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