re-animate-js 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Matt Putnam
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,163 @@
1
+ # re-animate-js
2
+
3
+ A lightweight React hook library for animating numeric values (or arrays of numeric values) with configurable easing.
4
+
5
+ ## Introduction
6
+
7
+ Animations are great. They can draw attention to important areas of the application, smooth transitions to help the user maintain context, or just make things look snazzy. And it's really great when you can implement your animations in CSS - they perform well and there's lots of support out there. But sometimes, what you really need to do is animate the property of a React component, especially if the source is closed.
8
+
9
+ `re-animate-js` solves this problem. With one simple hook, you can have any numeric parameter slide from one value to another over time. If you have a lot of values that you need to animate in sync, you can pass them as an array. Arbitrary easing functions are supported, with many of the most common ones built in. Pass in `before` and `after` functions if you need to run additional logic when the animation runs.
10
+
11
+ Play around with it [in the live demo](https://mattputnam.github.io/re-animate-js/)
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ npm install re-animate-js
17
+ ```
18
+
19
+ Peer dependency: `react` ^19.
20
+
21
+ ## Usage
22
+
23
+ ```tsx
24
+ import { useAnimateOnMount, Easings } from "re-animate-js";
25
+ import { ProgressBar } from "./ProgressBar";
26
+
27
+ export const LoadingBar = () => {
28
+ const { animatedValue } = useAnimateOnMount(100, {
29
+ from: 0,
30
+ durationMs: 1500,
31
+ easingFunction: Easings.sine.inOut,
32
+ });
33
+
34
+ return <ProgressBar percentage={animatedValue} />;
35
+ };
36
+ ```
37
+
38
+ All hooks share the same shape: `useAnimateXxx(value, opts?)`. The first argument is the value being animated (or, for `useAnimateOnChange`, the value being driven). Pass a `number` to get a `number` back; pass a `number[]` to get a `number[]` of the same length back. Array inputs animate every element on a single shared rAF cycle (one `before`, one `after`, one `isAnimating`).
39
+
40
+ ## API
41
+
42
+ ### `useAnimateOnMount(value, opts?)`
43
+
44
+ Animates from `opts.from` to `value` once when the component mounts.
45
+
46
+ | Prop (in `opts`) | Type | Default | Description |
47
+ | --- | --- | --- | --- |
48
+ | `from` | `T` | `0` (scalar) / `Array(N).fill(0)` (array) | Origin of the animation. |
49
+ | `durationMs` | `number` | `1000` | Animation duration in milliseconds. |
50
+ | `easingFunction` | `EasingFunction` | `Easings.linear` | Easing curve to apply. |
51
+ | `before` | `() => void` | — | Called once before the animation starts. |
52
+ | `after` | `() => void` | — | Called once after the animation finishes. |
53
+
54
+ Returns `{ animatedValue: T, isAnimating: boolean }`. Props are captured at mount; subsequent prop changes are ignored. Remount via a changing `key` to re-run.
55
+
56
+ ### `useAnimateOnAction(value, opts?)`
57
+
58
+ Same animation semantics as `useAnimateOnMount`, but fires when the caller invokes the returned `trigger` function. Does not animate on mount.
59
+
60
+ ```tsx
61
+ import { useAnimateOnAction, Easings } from "re-animate-js";
62
+
63
+ export const PulseCounter = () => {
64
+ const { animatedValue, isAnimating, trigger } = useAnimateOnAction(100, {
65
+ from: 0,
66
+ durationMs: 400,
67
+ easingFunction: Easings.sine.inOut,
68
+ });
69
+
70
+ return (
71
+ <>
72
+ <button onClick={trigger} disabled={isAnimating}>Pulse</button>
73
+ <div>{animatedValue.toFixed(1)}</div>
74
+ </>
75
+ );
76
+ };
77
+ ```
78
+
79
+ Same `opts` as `useAnimateOnMount`. Returns `{ animatedValue: T, isAnimating: boolean, trigger: () => void }`.
80
+
81
+ - `trigger` has a stable identity across renders.
82
+ - Props are captured at the moment `trigger` is invoked; mid-flight prop changes do not disturb a running animation.
83
+ - Calling `trigger` mid-animation cancels the current run (no `after` for the cancelled run) and starts fresh from `from`.
84
+
85
+ ### `useAnimateOnChange(value, opts?)`
86
+
87
+ Animates whenever `value` changes. No animation on mount. Mid-flight changes continue from the current exposed value (no snap-back) over a fresh full `durationMs`.
88
+
89
+ ```tsx
90
+ import { useAnimateOnChange } from "re-animate-js";
91
+
92
+ export const AnimatedScore = ({ score }: { score: number }) => {
93
+ const { animatedValue } = useAnimateOnChange(score, { durationMs: 400 });
94
+ return <div>{animatedValue.toFixed(0)}</div>;
95
+ };
96
+ ```
97
+
98
+ | Prop (in `opts`) | Type | Default | Description |
99
+ | --- | --- | --- | --- |
100
+ | `durationMs` | `number` | `1000` | Duration of each run. |
101
+ | `easingFunction` | `EasingFunction` | `Easings.linear` | Easing curve. |
102
+ | `before` | `() => void` | — | Fires once per animation start. |
103
+ | `after` | `() => void` | — | Fires once per completed run. Not fired for cancelled runs. |
104
+
105
+ No `from` — origin is always the current exposed value. Returns `{ animatedValue: T, isAnimating: boolean }`. Equality between renders is `Object.is` for scalars and length-and-element-wise `Object.is` for arrays. For arrays, length must remain stable for the lifetime of the hook instance.
106
+
107
+ ### Animating arrays
108
+
109
+ Pass a `number[]` as the first argument to any of the three hooks. All elements share one animation cycle:
110
+
111
+ ```tsx
112
+ import { useAnimateOnChange } from "re-animate-js";
113
+
114
+ export const MovingPoints = ({ xs }: { xs: number[] }) => {
115
+ const { animatedValue } = useAnimateOnChange(xs, { durationMs: 300 });
116
+ return (
117
+ <svg>
118
+ {animatedValue.map((x, i) => (
119
+ <circle key={i} cx={x} cy={i * 10} r={3} />
120
+ ))}
121
+ </svg>
122
+ );
123
+ };
124
+ ```
125
+
126
+ This is more efficient and synchronization-safe compared to calling the hook N times — a single `requestAnimationFrame` per visible frame drives all elements.
127
+
128
+ ### `Easings`
129
+
130
+ Ready-to-use easing functions. Each family (except `linear`) exposes `in`, `out`, and `inOut` variants:
131
+
132
+ - `linear`
133
+ - `sine`
134
+ - `polynomial(degree)` — call with a degree, e.g. `Easings.polynomial(3).inOut`
135
+ - `exponential`
136
+ - `circular`
137
+ - `back`
138
+ - `elastic`
139
+ - `bounce`
140
+
141
+ ### `EasingFunction`
142
+
143
+ `(x: number) => number` where `x` is in `[0, 1]`. Custom easing functions are supported — pass any function satisfying this signature to `easingFunction`.
144
+
145
+ ## Development
146
+
147
+ ```bash
148
+ npm run build
149
+ npm run lint
150
+ npm test
151
+ ```
152
+
153
+ Outputs compiled JS and type declarations to `dist/`.
154
+
155
+ ## Playground
156
+
157
+ To play with the hooks interactively:
158
+
159
+ ```bash
160
+ npm run demo
161
+ ```
162
+
163
+ This opens a local Vite dev server with one tab per hook. Each demo gives you sliders for value/`from`/duration, a dropdown for easing, and a code snippet that mirrors the current control values. The playground source lives under `playground/` and is excluded from the published package.
@@ -0,0 +1,14 @@
1
+ import { type EasingFunction } from "./easing";
2
+ export declare const DEFAULT_DURATION_MS = 1000;
3
+ export type Easable = number | number[];
4
+ export type UseAnimateOpts = {
5
+ /** Duration in ms; defaults to 1000 */
6
+ durationMs?: number;
7
+ /** Easing curve; defaults to linear */
8
+ easingFunction?: EasingFunction;
9
+ /** Fires once per animation that starts */
10
+ before?: () => void;
11
+ /** Fires once per animation that completes (never for cancelled runs) */
12
+ after?: () => void;
13
+ };
14
+ //# sourceMappingURL=common.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../lib/common.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,UAAU,CAAC;AAE/C,eAAO,MAAM,mBAAmB,OAAO,CAAC;AAExC,MAAM,MAAM,OAAO,GAAG,MAAM,GAAG,MAAM,EAAE,CAAC;AAExC,MAAM,MAAM,cAAc,GAAG;IAC3B,uCAAuC;IACvC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,uCAAuC;IACvC,cAAc,CAAC,EAAE,cAAc,CAAC;IAChC,2CAA2C;IAC3C,MAAM,CAAC,EAAE,MAAM,IAAI,CAAC;IACpB,yEAAyE;IACzE,KAAK,CAAC,EAAE,MAAM,IAAI,CAAC;CACpB,CAAC"}
package/dist/common.js ADDED
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_DURATION_MS = void 0;
4
+ exports.DEFAULT_DURATION_MS = 1000;
@@ -0,0 +1,53 @@
1
+ /**
2
+ * An easing function defines the shape of the animation transition. It is a function of type
3
+ * `number => number`, where both input and output range from 0 to 1, representing the fraction
4
+ * of the animation that is complete. It is required that f(0) = 0 and f(1) = 1. The function is
5
+ * not defined for inputs outside of [0, 1]. Outputs may extend outside of [0, 1].
6
+ */
7
+ export type EasingFunction = (x: number) => number;
8
+ /**
9
+ * A collection of ready-to-use easing functions. Note that these have not been "clamped" so that
10
+ * f(0) = 0 and f(1) = 1; values may differ slightly due to floating point error. The algorithm in
11
+ * this library ensures clamped values, therefore these functions will work for this library but
12
+ * may be unsuitable outside of it.
13
+ */
14
+ export declare const Easings: {
15
+ readonly linear: EasingFunction;
16
+ readonly sine: {
17
+ readonly in: EasingFunction;
18
+ readonly out: EasingFunction;
19
+ readonly inOut: EasingFunction;
20
+ };
21
+ readonly polynomial: (degree: number) => {
22
+ in: EasingFunction;
23
+ out: EasingFunction;
24
+ inOut: EasingFunction;
25
+ };
26
+ readonly exponential: {
27
+ readonly in: EasingFunction;
28
+ readonly out: EasingFunction;
29
+ readonly inOut: EasingFunction;
30
+ };
31
+ readonly circular: {
32
+ readonly in: EasingFunction;
33
+ readonly out: EasingFunction;
34
+ readonly inOut: EasingFunction;
35
+ };
36
+ readonly back: {
37
+ readonly in: EasingFunction;
38
+ readonly out: EasingFunction;
39
+ readonly inOut: EasingFunction;
40
+ };
41
+ readonly elastic: {
42
+ readonly in: EasingFunction;
43
+ readonly out: EasingFunction;
44
+ readonly inOut: EasingFunction;
45
+ };
46
+ readonly bounce: {
47
+ readonly in: EasingFunction;
48
+ readonly out: EasingFunction;
49
+ readonly inOut: EasingFunction;
50
+ };
51
+ };
52
+ export declare const applyEasing: (f: EasingFunction, x: number) => number;
53
+ //# sourceMappingURL=easing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"easing.d.ts","sourceRoot":"","sources":["../lib/easing.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;AAWnD;;;;;GAKG;AACH,eAAO,MAAM,OAAO;qBACY,cAAc;;qBAEc,cAAc;sBACjB,cAAc;wBACP,cAAc;;kCAEvD,MAAM;YACmB,cAAc;aACL,cAAc;eACuD,cAAc;;;qBAGvF,cAAc;sBACb,cAAc;wBAEpB,cAAc;;;qBAGA,cAAc;sBACb,cAAc;wBAGhB,cAAc;;;qBAGnB,cAAc;sBACa,cAAc;wBAGpB,cAAc;;;qBAGH,cAAc;sBACf,cAAc;wBAGlB,cAAc;;;qBAGvC,cAAc;sBAW9D,cAAc;wBAG4B,cAAc;;CAExD,CAAC;AAEX,eAAO,MAAM,WAAW,GAAI,GAAG,cAAc,EAAE,GAAG,MAAM,WAQvD,CAAA"}
package/dist/easing.js ADDED
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.applyEasing = exports.Easings = void 0;
4
+ const c1 = 1.70158;
5
+ const c2 = c1 * 1.525;
6
+ const c3 = c1 + 1;
7
+ const c4 = (2 * Math.PI) / 3;
8
+ const c5 = (2 * Math.PI) / 4.5;
9
+ const n1 = 7.5625;
10
+ const d1 = 2.75;
11
+ /**
12
+ * A collection of ready-to-use easing functions. Note that these have not been "clamped" so that
13
+ * f(0) = 0 and f(1) = 1; values may differ slightly due to floating point error. The algorithm in
14
+ * this library ensures clamped values, therefore these functions will work for this library but
15
+ * may be unsuitable outside of it.
16
+ */
17
+ exports.Easings = {
18
+ linear: ((x) => x),
19
+ sine: {
20
+ in: ((x) => 1 - Math.cos((x * Math.PI) / 2)),
21
+ out: ((x) => Math.sin((x * Math.PI) / 2)),
22
+ inOut: ((x) => -(Math.cos(x * Math.PI) - 1) / 2),
23
+ },
24
+ polynomial: (degree) => ({
25
+ in: ((x) => Math.pow(x, degree)),
26
+ out: ((x) => 1 - Math.pow(1 - x, degree)),
27
+ inOut: ((x) => x < 0.5 ? Math.pow(2, degree - 1) * Math.pow(x, degree) : 1 - Math.pow(-2 * x + 2, degree) / 2),
28
+ }),
29
+ exponential: {
30
+ in: ((x) => Math.pow(2, 10 * x - 10)),
31
+ out: ((x) => 1 - Math.pow(2, -10 * x)),
32
+ inOut: ((x) => x < 0.5 ? Math.pow(2, 20 * x - 10) / 2
33
+ : (2 - Math.pow(2, -20 * x + 10)) / 2),
34
+ },
35
+ circular: {
36
+ in: ((x) => 1 - Math.sqrt(1 - Math.pow(x, 2))),
37
+ out: ((x) => Math.sqrt(1 - Math.pow(x - 1, 2))),
38
+ inOut: ((x) => x < 0.5
39
+ ? (1 - Math.sqrt(1 - Math.pow(2 * x, 2))) / 2
40
+ : (Math.sqrt(1 - Math.pow(-2 * x + 2, 2)) + 1) / 2),
41
+ },
42
+ back: {
43
+ in: ((x) => c3 * x * x * x - c1 * x * x),
44
+ out: ((x) => 1 + c3 * Math.pow(x - 1, 3) + c1 * Math.pow(x - 1, 2)),
45
+ inOut: ((x) => x < 0.5
46
+ ? (Math.pow(2 * x, 2) * ((c2 + 1) * 2 * x - c2)) / 2
47
+ : (Math.pow(2 * x - 2, 2) * ((c2 + 1) * (x * 2 - 2) + c2) + 2) / 2),
48
+ },
49
+ elastic: {
50
+ in: ((x) => -Math.pow(2, 10 * x - 10) * Math.sin((x * 10 - 10.75) * c4)),
51
+ out: ((x) => Math.pow(2, -10 * x) * Math.sin((x * 10 - 0.75) * c4) + 1),
52
+ inOut: ((x) => x < 0.5
53
+ ? -(Math.pow(2, 20 * x - 10) * Math.sin((20 * x - 11.125) * c5)) / 2
54
+ : (Math.pow(2, -20 * x + 10) * Math.sin((20 * x - 11.125) * c5)) / 2 + 1),
55
+ },
56
+ bounce: {
57
+ in: ((x) => 1 - exports.Easings.bounce.out(1 - x)),
58
+ out: ((x) => {
59
+ if (x < 1 / d1) {
60
+ return n1 * x * x;
61
+ }
62
+ else if (x < 2 / d1) {
63
+ return n1 * (x -= 1.5 / d1) * x + 0.75;
64
+ }
65
+ else if (x < 2.5 / d1) {
66
+ return n1 * (x -= 2.25 / d1) * x + 0.9375;
67
+ }
68
+ else {
69
+ return n1 * (x -= 2.625 / d1) * x + 0.984375;
70
+ }
71
+ }),
72
+ inOut: ((x) => x < 0.5
73
+ ? (1 - exports.Easings.bounce.out(1 - 2 * x)) / 2
74
+ : (1 + exports.Easings.bounce.out(2 * x - 1)) / 2),
75
+ },
76
+ };
77
+ const applyEasing = (f, x) => {
78
+ if (x <= 0) {
79
+ return 0;
80
+ }
81
+ else if (x >= 1) {
82
+ return 1;
83
+ }
84
+ else {
85
+ return f(x);
86
+ }
87
+ };
88
+ exports.applyEasing = applyEasing;
@@ -0,0 +1,5 @@
1
+ export { type EasingFunction, Easings } from './easing';
2
+ export { useAnimateOnAction } from './useAnimateOnAction';
3
+ export { useAnimateOnChange } from './useAnimateOnChange';
4
+ export { useAnimateOnMount } from './useAnimateOnMount';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../lib/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,cAAc,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AACxD,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useAnimateOnMount = exports.useAnimateOnChange = exports.useAnimateOnAction = exports.Easings = void 0;
4
+ var easing_1 = require("./easing");
5
+ Object.defineProperty(exports, "Easings", { enumerable: true, get: function () { return easing_1.Easings; } });
6
+ var useAnimateOnAction_1 = require("./useAnimateOnAction");
7
+ Object.defineProperty(exports, "useAnimateOnAction", { enumerable: true, get: function () { return useAnimateOnAction_1.useAnimateOnAction; } });
8
+ var useAnimateOnChange_1 = require("./useAnimateOnChange");
9
+ Object.defineProperty(exports, "useAnimateOnChange", { enumerable: true, get: function () { return useAnimateOnChange_1.useAnimateOnChange; } });
10
+ var useAnimateOnMount_1 = require("./useAnimateOnMount");
11
+ Object.defineProperty(exports, "useAnimateOnMount", { enumerable: true, get: function () { return useAnimateOnMount_1.useAnimateOnMount; } });
@@ -0,0 +1,18 @@
1
+ import { type Easable, type UseAnimateOpts } from "./common";
2
+ type UseAnimateOnActionOpts<T extends Easable> = UseAnimateOpts & {
3
+ /** Origin of the animation. Defaults to 0 (scalar) or Array(N).fill(0) (array). */
4
+ from?: T;
5
+ };
6
+ /**
7
+ * Animates a value (or array of values) from `from` to `value` when the
8
+ * returned `trigger` function is called. Configuration is captured at the
9
+ * moment `trigger` is invoked. Re-trigger snaps back to `from` and starts
10
+ * a fresh run.
11
+ */
12
+ export declare function useAnimateOnAction<T extends Easable>(value: T, opts?: UseAnimateOnActionOpts<T>): {
13
+ animatedValue: T;
14
+ isAnimating: boolean;
15
+ trigger: () => void;
16
+ };
17
+ export {};
18
+ //# sourceMappingURL=useAnimateOnAction.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useAnimateOnAction.d.ts","sourceRoot":"","sources":["../lib/useAnimateOnAction.ts"],"names":[],"mappings":"AAEA,OAAO,EAAuB,KAAK,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,UAAU,CAAC;AAIlF,KAAK,sBAAsB,CAAC,CAAC,SAAS,OAAO,IAAI,cAAc,GAAG;IAChE,mFAAmF;IACnF,IAAI,CAAC,EAAE,CAAC,CAAC;CACV,CAAC;AAIF;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,OAAO,EAClD,KAAK,EAAE,CAAC,EACR,IAAI,GAAE,sBAAsB,CAAC,CAAC,CAAmC,GAChE;IAAE,aAAa,EAAE,CAAC,CAAC;IAAC,WAAW,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,MAAM,IAAI,CAAA;CAAE,CA2BjE"}
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useAnimateOnAction = useAnimateOnAction;
4
+ const react_1 = require("react");
5
+ const common_1 = require("./common");
6
+ const easing_1 = require("./easing");
7
+ const useAnimationRunner_1 = require("./useAnimationRunner");
8
+ const toArray = (v) => (Array.isArray(v) ? v : [v]);
9
+ /**
10
+ * Animates a value (or array of values) from `from` to `value` when the
11
+ * returned `trigger` function is called. Configuration is captured at the
12
+ * moment `trigger` is invoked. Re-trigger snaps back to `from` and starts
13
+ * a fresh run.
14
+ */
15
+ function useAnimateOnAction(value, opts = {}) {
16
+ const isArray = Array.isArray(value);
17
+ const valueArr = toArray(value);
18
+ const fromArr = opts.from !== undefined ? toArray(opts.from) : new Array(valueArr.length).fill(0);
19
+ const { animatedValue, isAnimating, start } = (0, useAnimationRunner_1.useAnimationRunner)(fromArr);
20
+ const latestRef = (0, react_1.useRef)({ valueArr, fromArr, opts });
21
+ latestRef.current = { valueArr, fromArr, opts };
22
+ const trigger = (0, react_1.useCallback)(() => {
23
+ const { valueArr, fromArr, opts } = latestRef.current;
24
+ start({
25
+ value: valueArr,
26
+ from: fromArr,
27
+ durationMs: opts.durationMs ?? common_1.DEFAULT_DURATION_MS,
28
+ easingFunction: opts.easingFunction ?? easing_1.Easings.linear,
29
+ before: opts.before,
30
+ after: opts.after,
31
+ });
32
+ // Stable identity; reads latest props from ref.
33
+ // eslint-disable-next-line react-hooks/exhaustive-deps
34
+ }, []);
35
+ const out = (isArray ? animatedValue : animatedValue[0]);
36
+ return { animatedValue: out, isAnimating, trigger };
37
+ }
@@ -0,0 +1,14 @@
1
+ import { type Easable, type UseAnimateOpts } from "./common";
2
+ /**
3
+ * Animates the exposed value whenever the `value` argument changes.
4
+ *
5
+ * Equality between renders is `Object.is` for scalars and length+element-wise
6
+ * `Object.is` for arrays. Mid-flight changes continue from the current
7
+ * exposed value (no snap-back). For arrays, length MUST remain stable for
8
+ * the lifetime of a hook instance (FR-009).
9
+ */
10
+ export declare function useAnimateOnChange<T extends Easable>(value: T, opts?: UseAnimateOpts): {
11
+ animatedValue: T;
12
+ isAnimating: boolean;
13
+ };
14
+ //# sourceMappingURL=useAnimateOnChange.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useAnimateOnChange.d.ts","sourceRoot":"","sources":["../lib/useAnimateOnChange.ts"],"names":[],"mappings":"AAEA,OAAO,EAAuB,KAAK,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,UAAU,CAAC;AAclF;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,OAAO,EAClD,KAAK,EAAE,CAAC,EACR,IAAI,GAAE,cAAmB,GACxB;IAAE,aAAa,EAAE,CAAC,CAAC;IAAC,WAAW,EAAE,OAAO,CAAA;CAAE,CAsC5C"}
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useAnimateOnChange = useAnimateOnChange;
4
+ const react_1 = require("react");
5
+ const common_1 = require("./common");
6
+ const easing_1 = require("./easing");
7
+ const useAnimationRunner_1 = require("./useAnimationRunner");
8
+ const toArray = (v) => (Array.isArray(v) ? v : [v]);
9
+ const elementWiseEqual = (a, b) => {
10
+ if (a.length !== b.length)
11
+ return false;
12
+ for (let i = 0; i < a.length; i++) {
13
+ if (!Object.is(a[i], b[i]))
14
+ return false;
15
+ }
16
+ return true;
17
+ };
18
+ /**
19
+ * Animates the exposed value whenever the `value` argument changes.
20
+ *
21
+ * Equality between renders is `Object.is` for scalars and length+element-wise
22
+ * `Object.is` for arrays. Mid-flight changes continue from the current
23
+ * exposed value (no snap-back). For arrays, length MUST remain stable for
24
+ * the lifetime of a hook instance (FR-009).
25
+ */
26
+ function useAnimateOnChange(value, opts = {}) {
27
+ const isArray = Array.isArray(value);
28
+ const valueArr = toArray(value);
29
+ const { animatedValue, isAnimating, start } = (0, useAnimationRunner_1.useAnimationRunner)(valueArr);
30
+ const firstRenderRef = (0, react_1.useRef)(true);
31
+ const optsRef = (0, react_1.useRef)(opts);
32
+ optsRef.current = opts;
33
+ (0, react_1.useEffect)(() => {
34
+ if (firstRenderRef.current) {
35
+ firstRenderRef.current = false;
36
+ return;
37
+ }
38
+ if (elementWiseEqual(animatedValue, valueArr)) {
39
+ return;
40
+ }
41
+ const o = optsRef.current;
42
+ start({
43
+ value: valueArr,
44
+ from: animatedValue,
45
+ durationMs: o.durationMs ?? common_1.DEFAULT_DURATION_MS,
46
+ easingFunction: o.easingFunction ?? easing_1.Easings.linear,
47
+ before: o.before,
48
+ after: o.after,
49
+ });
50
+ // Effect intentionally depends on `valueArr` element-wise: spreading
51
+ // exploits React's per-element Object.is dep comparison. Length is
52
+ // assumed stable per FR-009. `animatedValue`, `start`, and opts are
53
+ // intentionally excluded — see hook docstring.
54
+ // eslint-disable-next-line react-hooks/exhaustive-deps
55
+ }, valueArr);
56
+ const out = (isArray ? animatedValue : animatedValue[0]);
57
+ return { animatedValue: out, isAnimating };
58
+ }
@@ -0,0 +1,17 @@
1
+ import { type Easable, type UseAnimateOpts } from "./common";
2
+ type UseAnimateOnMountOpts<T extends Easable> = UseAnimateOpts & {
3
+ /** Origin of the animation. Defaults to 0 (scalar) or Array(N).fill(0) (array). */
4
+ from?: T;
5
+ };
6
+ /**
7
+ * Animates a value (or array of values) from `from` to `value` once on mount.
8
+ *
9
+ * Props are captured at mount time; subsequent prop changes are ignored.
10
+ * To re-run, remount the component (e.g. with a changing `key`).
11
+ */
12
+ export declare function useAnimateOnMount<T extends Easable>(value: T, opts?: UseAnimateOnMountOpts<T>): {
13
+ animatedValue: T;
14
+ isAnimating: boolean;
15
+ };
16
+ export {};
17
+ //# sourceMappingURL=useAnimateOnMount.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useAnimateOnMount.d.ts","sourceRoot":"","sources":["../lib/useAnimateOnMount.ts"],"names":[],"mappings":"AAEA,OAAO,EAAuB,KAAK,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,UAAU,CAAC;AAIlF,KAAK,qBAAqB,CAAC,CAAC,SAAS,OAAO,IAAI,cAAc,GAAG;IAC/D,mFAAmF;IACnF,IAAI,CAAC,EAAE,CAAC,CAAC;CACV,CAAC;AAIF;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,CAAC,SAAS,OAAO,EACjD,KAAK,EAAE,CAAC,EACR,IAAI,GAAE,qBAAqB,CAAC,CAAC,CAAkC,GAC9D;IAAE,aAAa,EAAE,CAAC,CAAC;IAAC,WAAW,EAAE,OAAO,CAAA;CAAE,CAyB5C"}
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useAnimateOnMount = useAnimateOnMount;
4
+ const react_1 = require("react");
5
+ const common_1 = require("./common");
6
+ const easing_1 = require("./easing");
7
+ const useAnimationRunner_1 = require("./useAnimationRunner");
8
+ const toArray = (v) => (Array.isArray(v) ? v : [v]);
9
+ /**
10
+ * Animates a value (or array of values) from `from` to `value` once on mount.
11
+ *
12
+ * Props are captured at mount time; subsequent prop changes are ignored.
13
+ * To re-run, remount the component (e.g. with a changing `key`).
14
+ */
15
+ function useAnimateOnMount(value, opts = {}) {
16
+ const isArray = Array.isArray(value);
17
+ const valueArr = toArray(value);
18
+ const fromArr = opts.from !== undefined ? toArray(opts.from) : new Array(valueArr.length).fill(0);
19
+ const { animatedValue, isAnimating, start } = (0, useAnimationRunner_1.useAnimationRunner)(fromArr);
20
+ const propsRef = (0, react_1.useRef)({
21
+ value: valueArr,
22
+ from: fromArr,
23
+ durationMs: opts.durationMs ?? common_1.DEFAULT_DURATION_MS,
24
+ easingFunction: opts.easingFunction ?? easing_1.Easings.linear,
25
+ before: opts.before,
26
+ after: opts.after,
27
+ });
28
+ (0, react_1.useEffect)(() => {
29
+ start(propsRef.current);
30
+ // Mount-once semantics; props captured at mount via ref.
31
+ // eslint-disable-next-line react-hooks/exhaustive-deps
32
+ }, []);
33
+ const out = (isArray ? animatedValue : animatedValue[0]);
34
+ return { animatedValue: out, isAnimating };
35
+ }
@@ -0,0 +1,17 @@
1
+ import { type EasingFunction } from "./easing";
2
+ export type AnimationRunParams = {
3
+ value: number[];
4
+ from: number[];
5
+ durationMs: number;
6
+ easingFunction: EasingFunction;
7
+ before?: () => void;
8
+ after?: () => void;
9
+ };
10
+ export type AnimationRunner = {
11
+ animatedValue: number[];
12
+ isAnimating: boolean;
13
+ start: (params: AnimationRunParams) => void;
14
+ stop: () => void;
15
+ };
16
+ export declare const useAnimationRunner: (initialValue: number[]) => AnimationRunner;
17
+ //# sourceMappingURL=useAnimationRunner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useAnimationRunner.d.ts","sourceRoot":"","sources":["../lib/useAnimationRunner.ts"],"names":[],"mappings":"AAEA,OAAO,EAAe,KAAK,cAAc,EAAE,MAAM,UAAU,CAAC;AAE5D,MAAM,MAAM,kBAAkB,GAAG;IAC/B,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,cAAc,EAAE,cAAc,CAAC;IAC/B,MAAM,CAAC,EAAE,MAAM,IAAI,CAAC;IACpB,KAAK,CAAC,EAAE,MAAM,IAAI,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAC5B,aAAa,EAAE,MAAM,EAAE,CAAC;IACxB,WAAW,EAAE,OAAO,CAAC;IACrB,KAAK,EAAE,CAAC,MAAM,EAAE,kBAAkB,KAAK,IAAI,CAAC;IAC5C,IAAI,EAAE,MAAM,IAAI,CAAC;CAClB,CAAC;AAUF,eAAO,MAAM,kBAAkB,GAAI,cAAc,MAAM,EAAE,KAAG,eAwF3D,CAAC"}
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useAnimationRunner = void 0;
4
+ const react_1 = require("react");
5
+ const easing_1 = require("./easing");
6
+ const elementWiseEqual = (a, b) => {
7
+ if (a.length !== b.length)
8
+ return false;
9
+ for (let i = 0; i < a.length; i++) {
10
+ if (!Object.is(a[i], b[i]))
11
+ return false;
12
+ }
13
+ return true;
14
+ };
15
+ const useAnimationRunner = (initialValue) => {
16
+ const [animatedValue, setAnimatedValue] = (0, react_1.useState)(initialValue);
17
+ const [isAnimating, setIsAnimating] = (0, react_1.useState)(false);
18
+ const latestValueRef = (0, react_1.useRef)(initialValue);
19
+ const rafIdRef = (0, react_1.useRef)(undefined);
20
+ const runTokenRef = (0, react_1.useRef)(0);
21
+ const mountedRef = (0, react_1.useRef)(true);
22
+ (0, react_1.useEffect)(() => {
23
+ mountedRef.current = true;
24
+ return () => {
25
+ mountedRef.current = false;
26
+ if (rafIdRef.current !== undefined) {
27
+ cancelAnimationFrame(rafIdRef.current);
28
+ rafIdRef.current = undefined;
29
+ }
30
+ };
31
+ }, []);
32
+ const setValue = (next) => {
33
+ latestValueRef.current = next;
34
+ setAnimatedValue(next);
35
+ };
36
+ const start = (params) => {
37
+ if (rafIdRef.current !== undefined) {
38
+ cancelAnimationFrame(rafIdRef.current);
39
+ rafIdRef.current = undefined;
40
+ }
41
+ const { value, from, durationMs, easingFunction, before, after } = params;
42
+ // Empty array: complete no-op (FR-013) — no callbacks, no rAF, no setState.
43
+ if (value.length === 0) {
44
+ runTokenRef.current++;
45
+ return;
46
+ }
47
+ const token = ++runTokenRef.current;
48
+ const span = new Array(value.length);
49
+ for (let i = 0; i < value.length; i++)
50
+ span[i] = value[i] - from[i];
51
+ // Seed write — skip if element-wise equal to current (mid-flight retarget case).
52
+ if (!elementWiseEqual(from, latestValueRef.current)) {
53
+ setValue(from.slice());
54
+ }
55
+ setIsAnimating(true);
56
+ before?.();
57
+ let startTime;
58
+ const step = (timestamp) => {
59
+ if (token !== runTokenRef.current || !mountedRef.current)
60
+ return;
61
+ if (startTime === undefined)
62
+ startTime = timestamp;
63
+ const elapsed = timestamp - startTime;
64
+ if (durationMs <= 0 || elapsed >= durationMs) {
65
+ setValue(value.slice());
66
+ rafIdRef.current = undefined;
67
+ setIsAnimating(false);
68
+ after?.();
69
+ return;
70
+ }
71
+ const fraction = (0, easing_1.applyEasing)(easingFunction, elapsed / durationMs);
72
+ const next = new Array(value.length);
73
+ for (let i = 0; i < value.length; i++) {
74
+ next[i] = from[i] + span[i] * fraction;
75
+ }
76
+ setValue(next);
77
+ rafIdRef.current = requestAnimationFrame(step);
78
+ };
79
+ rafIdRef.current = requestAnimationFrame(step);
80
+ };
81
+ const stop = () => {
82
+ runTokenRef.current++;
83
+ if (rafIdRef.current !== undefined) {
84
+ cancelAnimationFrame(rafIdRef.current);
85
+ rafIdRef.current = undefined;
86
+ }
87
+ setIsAnimating(false);
88
+ };
89
+ return { animatedValue, isAnimating, start, stop };
90
+ };
91
+ exports.useAnimationRunner = useAnimationRunner;
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "re-animate-js",
3
+ "version": "1.0.0",
4
+ "description": "Lightweight React hooks for animating numeric values (or arrays of values) with configurable easing.",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "files": ["dist"],
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/MattPutnam/re-animate-js.git"
11
+ },
12
+ "homepage": "https://mattputnam.github.io/re-animate-js/",
13
+ "bugs": "https://github.com/MattPutnam/re-animate-js/issues",
14
+ "scripts": {
15
+ "prepare": "npm run build",
16
+ "build": "tsc",
17
+ "lint": "eslint .",
18
+ "demo": "vite",
19
+ "demo:build": "GITHUB_PAGES=true vite build",
20
+ "test": "vitest run"
21
+ },
22
+ "keywords": ["react", "hooks", "animation", "easing", "interpolate", "requestAnimationFrame"],
23
+ "author": "Matt Putnam",
24
+ "license": "MIT",
25
+ "devDependencies": {
26
+ "@eslint/js": "^10.0.1",
27
+ "@testing-library/dom": "^10.4.1",
28
+ "@testing-library/react": "^16.3.2",
29
+ "@types/react": "^19.1.0",
30
+ "@types/react-dom": "^19.2.3",
31
+ "@vitejs/plugin-react": "^6.0.1",
32
+ "react": "^19.1.0",
33
+ "eslint": "^10.2.0",
34
+ "eslint-plugin-react-hooks": "^7.0.1",
35
+ "eslint-plugin-simple-import-sort": "^13.0.0",
36
+ "globals": "^17.5.0",
37
+ "jsdom": "^29.0.2",
38
+ "react-dom": "^19.1.0",
39
+ "typescript": "^5.8.3",
40
+ "typescript-eslint": "^8.58.1",
41
+ "vite": "^8.0.8",
42
+ "vitest": "^4.1.4"
43
+ },
44
+ "peerDependencies": {
45
+ "react": "^19.0.0"
46
+ }
47
+ }