-
Notifications
You must be signed in to change notification settings - Fork 1
/
spring.ts
55 lines (50 loc) · 1.39 KB
/
spring.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
export default function Spring(
initialPosition = 0,
{ stiffness = 200, damping = 10, precision = 100 } = {}
) {
let position = initialPosition;
let endPosition = 0;
let secPerFrame = 1 / 60;
let velocity = 0;
let onUpdate = v => {};
let onRest = v => {};
let raf;
const interpolate = () => {
const distance = endPosition - position;
const acceleration = stiffness * distance - damping * velocity;
const newVelocity = velocity + acceleration * secPerFrame;
const newPosition = position + newVelocity * secPerFrame;
const isComplete =
Math.abs(newVelocity) < 1 / precision &&
Math.abs(newPosition - endPosition) < 1 / precision;
position = isComplete ? endPosition : newPosition;
velocity = newVelocity;
onUpdate(position);
if (!isComplete) raf = requestAnimationFrame(interpolate);
else onRest(position);
};
return {
setValue: (v = 0) => {
cancelAnimationFrame(raf);
position = endPosition = v;
onUpdate(position);
},
transitionTo: (v = 0) => {
cancelAnimationFrame(raf);
endPosition = v;
raf = requestAnimationFrame(interpolate);
},
onUpdate: (fn = v => {}) => {
onUpdate = fn;
fn(position);
},
onRest: (fn = v => {}) => {
onRest = fn;
},
destroy: () => {
cancelAnimationFrame(raf);
onUpdate = () => {};
onRest = () => {};
}
};
}