1 | import { useEffect, useMemo, useState } from 'react';
|
---|
2 | import { SpringSystem } from 'rebound';
|
---|
3 | var useSpring = function (targetValue, tension, friction) {
|
---|
4 | if (targetValue === void 0) { targetValue = 0; }
|
---|
5 | if (tension === void 0) { tension = 50; }
|
---|
6 | if (friction === void 0) { friction = 3; }
|
---|
7 | var _a = useState(null), spring = _a[0], setSpring = _a[1];
|
---|
8 | var _b = useState(targetValue), value = _b[0], setValue = _b[1];
|
---|
9 | // memoize listener to being able to unsubscribe later properly, otherwise
|
---|
10 | // listener fn will be different on each re-render and wouldn't unsubscribe properly.
|
---|
11 | var listener = useMemo(function () { return ({
|
---|
12 | onSpringUpdate: function (currentSpring) {
|
---|
13 | var newValue = currentSpring.getCurrentValue();
|
---|
14 | setValue(newValue);
|
---|
15 | },
|
---|
16 | }); }, []);
|
---|
17 | useEffect(function () {
|
---|
18 | if (!spring) {
|
---|
19 | var newSpring = new SpringSystem().createSpring(tension, friction);
|
---|
20 | newSpring.setCurrentValue(targetValue);
|
---|
21 | setSpring(newSpring);
|
---|
22 | newSpring.addListener(listener);
|
---|
23 | }
|
---|
24 | return function () {
|
---|
25 | if (spring) {
|
---|
26 | spring.removeListener(listener);
|
---|
27 | setSpring(null);
|
---|
28 | }
|
---|
29 | };
|
---|
30 | }, [tension, friction, spring]);
|
---|
31 | useEffect(function () {
|
---|
32 | if (spring) {
|
---|
33 | spring.setEndValue(targetValue);
|
---|
34 | }
|
---|
35 | }, [targetValue]);
|
---|
36 | return value;
|
---|
37 | };
|
---|
38 | export default useSpring;
|
---|