re-animate-js 1.0.0 → 1.1.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/README.md +12 -6
- package/dist/common.d.ts +22 -0
- package/dist/common.d.ts.map +1 -1
- package/dist/common.js +36 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/useAnimateOnAction.d.ts +9 -9
- package/dist/useAnimateOnAction.d.ts.map +1 -1
- package/dist/useAnimateOnAction.js +33 -20
- package/dist/useAnimateOnChange.d.ts +9 -7
- package/dist/useAnimateOnChange.d.ts.map +1 -1
- package/dist/useAnimateOnChange.js +39 -39
- package/dist/useAnimateOnMount.d.ts +3 -7
- package/dist/useAnimateOnMount.d.ts.map +1 -1
- package/dist/useAnimateOnMount.js +16 -16
- package/dist/useAnimationRunner.d.ts +8 -11
- package/dist/useAnimationRunner.d.ts.map +1 -1
- package/dist/useAnimationRunner.js +78 -33
- package/lib/common.ts +71 -0
- package/lib/easing.ts +90 -0
- package/lib/index.ts +5 -0
- package/lib/useAnimateOnAction.ts +79 -0
- package/lib/useAnimateOnChange.ts +67 -0
- package/lib/useAnimateOnMount.ts +46 -0
- package/lib/useAnimationRunner.ts +155 -0
- package/package.json +7 -6
package/README.md
CHANGED
|
@@ -35,7 +35,11 @@ export const LoadingBar = () => {
|
|
|
35
35
|
};
|
|
36
36
|
```
|
|
37
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`).
|
|
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`). You can pass a new array or edit an existing one in place and re-render; either way the hooks read the current values (for example, `useAnimateOnChange` retargets mid-animation in both cases). Keep each array's length fixed for the lifetime of the hook instance, for `value` and `from` alike; to change it, remount the component (e.g. by changing its `key`). Behavior after a length change is undefined (for what `useAnimateOnChange` does, see below).
|
|
39
|
+
|
|
40
|
+
If a component is hidden mid-animation without unmounting (for example by React's `<Activity mode="hidden">`), its animation pauses and resumes when shown. The animation's clock keeps running while hidden, so a component shown after the duration has passed jumps to the target and fires `after` on its next frame.
|
|
41
|
+
|
|
42
|
+
The option and result types are exported for wrapper hooks: `UseAnimateOpts`, `UseAnimateOnMountOpts`, `UseAnimateOnActionOpts`, `UseAnimateResult`, `UseAnimateOnActionResult`, plus `Easable` and `EasingFunction`.
|
|
39
43
|
|
|
40
44
|
## API
|
|
41
45
|
|
|
@@ -45,8 +49,8 @@ Animates from `opts.from` to `value` once when the component mounts.
|
|
|
45
49
|
|
|
46
50
|
| Prop (in `opts`) | Type | Default | Description |
|
|
47
51
|
| --- | --- | --- | --- |
|
|
48
|
-
| `from` | `T` | `0` (scalar) / `Array(N).fill(0)` (array) | Origin of the animation. |
|
|
49
|
-
| `durationMs` | `number` | `1000` | Animation duration in milliseconds. |
|
|
52
|
+
| `from` | `T` | `0` (scalar) / `Array(N).fill(0)` (array) | Origin of the animation. Must have the same shape as `value`: a number for a scalar `value`, or an array of the same length for an array `value`. A mismatch throws. |
|
|
53
|
+
| `durationMs` | `number` | `1000` | Animation duration in milliseconds. `0`, negative, `NaN`, or `Infinity` jumps to `value` on the next frame. |
|
|
50
54
|
| `easingFunction` | `EasingFunction` | `Easings.linear` | Easing curve to apply. |
|
|
51
55
|
| `before` | `() => void` | — | Called once before the animation starts. |
|
|
52
56
|
| `after` | `() => void` | — | Called once after the animation finishes. |
|
|
@@ -78,13 +82,14 @@ export const PulseCounter = () => {
|
|
|
78
82
|
|
|
79
83
|
Same `opts` as `useAnimateOnMount`. Returns `{ animatedValue: T, isAnimating: boolean, trigger: () => void }`.
|
|
80
84
|
|
|
85
|
+
- Before the first `trigger`, `animatedValue` is the current `from` and follows changes to it.
|
|
81
86
|
- `trigger` has a stable identity across renders.
|
|
82
87
|
- Props are captured at the moment `trigger` is invoked; mid-flight prop changes do not disturb a running animation.
|
|
83
88
|
- Calling `trigger` mid-animation cancels the current run (no `after` for the cancelled run) and starts fresh from `from`.
|
|
84
89
|
|
|
85
90
|
### `useAnimateOnChange(value, opts?)`
|
|
86
91
|
|
|
87
|
-
Animates whenever `value` changes. No animation on mount. Mid-flight changes continue from the current exposed value (no snap-back) over a
|
|
92
|
+
Animates whenever `value` changes. No animation on mount. Mid-flight changes continue from the current exposed value (no snap-back) over a full `durationMs`, counted from the latest animation frame so the next frame already moves toward the new target.
|
|
88
93
|
|
|
89
94
|
```tsx
|
|
90
95
|
import { useAnimateOnChange } from "re-animate-js";
|
|
@@ -102,7 +107,7 @@ export const AnimatedScore = ({ score }: { score: number }) => {
|
|
|
102
107
|
| `before` | `() => void` | — | Fires once per animation start. |
|
|
103
108
|
| `after` | `() => void` | — | Fires once per completed run. Not fired for cancelled runs. |
|
|
104
109
|
|
|
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.
|
|
110
|
+
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. As with every hook, keep an array's length stable; changing it in place is unsupported: it logs an error once and does its best, animating the indices both arrays share and starting new indices at their target. Shrinking the array is undefined behavior: the exposed value may keep stale entries, possibly forever (for example, shrinking to `[]`).
|
|
106
111
|
|
|
107
112
|
### Animating arrays
|
|
108
113
|
|
|
@@ -147,10 +152,11 @@ Ready-to-use easing functions. Each family (except `linear`) exposes `in`, `out`
|
|
|
147
152
|
```bash
|
|
148
153
|
npm run build
|
|
149
154
|
npm run lint
|
|
155
|
+
npm run typecheck
|
|
150
156
|
npm test
|
|
151
157
|
```
|
|
152
158
|
|
|
153
|
-
|
|
159
|
+
`build` outputs compiled JS and type declarations to `dist/`. `typecheck` checks the library, tests and playground together (the build only covers the library).
|
|
154
160
|
|
|
155
161
|
## Playground
|
|
156
162
|
|
package/dist/common.d.ts
CHANGED
|
@@ -11,4 +11,26 @@ export type UseAnimateOpts = {
|
|
|
11
11
|
/** Fires once per animation that completes (never for cancelled runs) */
|
|
12
12
|
after?: () => void;
|
|
13
13
|
};
|
|
14
|
+
export type UseAnimateResult<T extends Easable> = {
|
|
15
|
+
/** The current animated value, in the same shape as the hook's `value`. */
|
|
16
|
+
animatedValue: T;
|
|
17
|
+
isAnimating: boolean;
|
|
18
|
+
};
|
|
19
|
+
export type AnimationRunParams = {
|
|
20
|
+
value: number[];
|
|
21
|
+
from: number[];
|
|
22
|
+
durationMs: number;
|
|
23
|
+
easingFunction: EasingFunction;
|
|
24
|
+
before?: () => void;
|
|
25
|
+
after?: () => void;
|
|
26
|
+
};
|
|
27
|
+
export declare const toArray: (v: Easable) => number[];
|
|
28
|
+
/** Converts the runner's internal array back to the caller's shape (scalar or array). */
|
|
29
|
+
export declare const fromArray: <T extends Easable>(arr: number[], isArray: boolean) => T;
|
|
30
|
+
export declare const elementWiseEqual: (a: number[], b: number[]) => boolean;
|
|
31
|
+
/** Origin array: the caller's `from` if given, otherwise all zeros matching `value`'s length. */
|
|
32
|
+
export declare const resolveFrom: (valueArr: number[], from: Easable | undefined) => number[];
|
|
33
|
+
export declare const assertSameLength: (from: number[], value: number[]) => void;
|
|
34
|
+
/** Builds runner params from hook options, applying defaults. */
|
|
35
|
+
export declare const resolveRunParams: (value: number[], from: number[], opts: UseAnimateOpts) => AnimationRunParams;
|
|
14
36
|
//# sourceMappingURL=common.d.ts.map
|
package/dist/common.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../lib/common.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,cAAc,
|
|
1
|
+
{"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../lib/common.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,cAAc,EAAW,MAAM,UAAU,CAAC;AAExD,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;AAEF,MAAM,MAAM,gBAAgB,CAAC,CAAC,SAAS,OAAO,IAAI;IAChD,2EAA2E;IAC3E,aAAa,EAAE,CAAC,CAAC;IACjB,WAAW,EAAE,OAAO,CAAC;CACtB,CAAC;AAEF,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,eAAO,MAAM,OAAO,GAAI,GAAG,OAAO,KAAG,MAAM,EAAkC,CAAC;AAE9E,yFAAyF;AACzF,eAAO,MAAM,SAAS,GAAI,CAAC,SAAS,OAAO,EAAE,KAAK,MAAM,EAAE,EAAE,SAAS,OAAO,KAAG,CAChD,CAAC;AAEhC,eAAO,MAAM,gBAAgB,GAAI,GAAG,MAAM,EAAE,EAAE,GAAG,MAAM,EAAE,KAAG,OAM3D,CAAC;AAEF,iGAAiG;AACjG,eAAO,MAAM,WAAW,GAAI,UAAU,MAAM,EAAE,EAAE,MAAM,OAAO,GAAG,SAAS,KAAG,MAAM,EACD,CAAC;AAElF,eAAO,MAAM,gBAAgB,GAAI,MAAM,MAAM,EAAE,EAAE,OAAO,MAAM,EAAE,KAAG,IAMlE,CAAC;AAEF,iEAAiE;AACjE,eAAO,MAAM,gBAAgB,GAC3B,OAAO,MAAM,EAAE,EACf,MAAM,MAAM,EAAE,EACd,MAAM,cAAc,KACnB,kBAOD,CAAC"}
|
package/dist/common.js
CHANGED
|
@@ -1,4 +1,39 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.DEFAULT_DURATION_MS = void 0;
|
|
3
|
+
exports.resolveRunParams = exports.assertSameLength = exports.resolveFrom = exports.elementWiseEqual = exports.fromArray = exports.toArray = exports.DEFAULT_DURATION_MS = void 0;
|
|
4
|
+
const easing_1 = require("./easing");
|
|
4
5
|
exports.DEFAULT_DURATION_MS = 1000;
|
|
6
|
+
const toArray = (v) => (Array.isArray(v) ? v : [v]);
|
|
7
|
+
exports.toArray = toArray;
|
|
8
|
+
/** Converts the runner's internal array back to the caller's shape (scalar or array). */
|
|
9
|
+
const fromArray = (arr, isArray) => (isArray ? arr : arr[0]);
|
|
10
|
+
exports.fromArray = fromArray;
|
|
11
|
+
const elementWiseEqual = (a, b) => {
|
|
12
|
+
if (a.length !== b.length)
|
|
13
|
+
return false;
|
|
14
|
+
for (let i = 0; i < a.length; i++) {
|
|
15
|
+
if (!Object.is(a[i], b[i]))
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
return true;
|
|
19
|
+
};
|
|
20
|
+
exports.elementWiseEqual = elementWiseEqual;
|
|
21
|
+
/** Origin array: the caller's `from` if given, otherwise all zeros matching `value`'s length. */
|
|
22
|
+
const resolveFrom = (valueArr, from) => from !== undefined ? (0, exports.toArray)(from) : new Array(valueArr.length).fill(0);
|
|
23
|
+
exports.resolveFrom = resolveFrom;
|
|
24
|
+
const assertSameLength = (from, value) => {
|
|
25
|
+
if (from.length !== value.length) {
|
|
26
|
+
throw new Error(`re-animate-js: \`from\` length (${from.length}) must match \`value\` length (${value.length})`);
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
exports.assertSameLength = assertSameLength;
|
|
30
|
+
/** Builds runner params from hook options, applying defaults. */
|
|
31
|
+
const resolveRunParams = (value, from, opts) => ({
|
|
32
|
+
value,
|
|
33
|
+
from,
|
|
34
|
+
durationMs: opts.durationMs ?? exports.DEFAULT_DURATION_MS,
|
|
35
|
+
easingFunction: opts.easingFunction ?? easing_1.Easings.linear,
|
|
36
|
+
before: opts.before,
|
|
37
|
+
after: opts.after,
|
|
38
|
+
});
|
|
39
|
+
exports.resolveRunParams = resolveRunParams;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
export type { Easable, UseAnimateOpts, UseAnimateResult } from './common';
|
|
1
2
|
export { type EasingFunction, Easings } from './easing';
|
|
2
|
-
export { useAnimateOnAction } from './useAnimateOnAction';
|
|
3
|
+
export { useAnimateOnAction, type UseAnimateOnActionOpts, type UseAnimateOnActionResult } from './useAnimateOnAction';
|
|
3
4
|
export { useAnimateOnChange } from './useAnimateOnChange';
|
|
4
|
-
export { useAnimateOnMount } from './useAnimateOnMount';
|
|
5
|
+
export { useAnimateOnMount, type UseAnimateOnMountOpts } from './useAnimateOnMount';
|
|
5
6
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +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;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../lib/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAC1E,OAAO,EAAE,KAAK,cAAc,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AACxD,OAAO,EAAE,kBAAkB,EAAE,KAAK,sBAAsB,EAAE,KAAK,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AACtH,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,iBAAiB,EAAE,KAAK,qBAAqB,EAAE,MAAM,qBAAqB,CAAC"}
|
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import { type Easable, type UseAnimateOpts } from "./common";
|
|
2
|
-
type UseAnimateOnActionOpts<T extends Easable> = UseAnimateOpts & {
|
|
1
|
+
import { type Easable, type UseAnimateOpts, type UseAnimateResult } from "./common";
|
|
2
|
+
export type UseAnimateOnActionOpts<T extends Easable> = UseAnimateOpts & {
|
|
3
3
|
/** Origin of the animation. Defaults to 0 (scalar) or Array(N).fill(0) (array). */
|
|
4
4
|
from?: T;
|
|
5
5
|
};
|
|
6
|
+
export type UseAnimateOnActionResult<T extends Easable> = UseAnimateResult<T> & {
|
|
7
|
+
/** Starts (or restarts) the animation. Stable across renders. */
|
|
8
|
+
trigger: () => void;
|
|
9
|
+
};
|
|
6
10
|
/**
|
|
7
11
|
* Animates a value (or array of values) from `from` to `value` when the
|
|
8
12
|
* returned `trigger` function is called. Configuration is captured at the
|
|
9
13
|
* moment `trigger` is invoked. Re-trigger snaps back to `from` and starts
|
|
10
|
-
* a fresh run.
|
|
14
|
+
* a fresh run. Until the first trigger, the exposed value is the current
|
|
15
|
+
* `from` (it follows changes to `from`).
|
|
11
16
|
*/
|
|
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 {};
|
|
17
|
+
export declare function useAnimateOnAction<T extends Easable>(value: T, opts?: UseAnimateOnActionOpts<T>): UseAnimateOnActionResult<T>;
|
|
18
18
|
//# sourceMappingURL=useAnimateOnAction.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAnimateOnAction.d.ts","sourceRoot":"","sources":["../lib/useAnimateOnAction.ts"],"names":[],"mappings":"AAEA,OAAO,
|
|
1
|
+
{"version":3,"file":"useAnimateOnAction.d.ts","sourceRoot":"","sources":["../lib/useAnimateOnAction.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,OAAO,EAMZ,KAAK,cAAc,EACnB,KAAK,gBAAgB,EACtB,MAAM,UAAU,CAAC;AAGlB,MAAM,MAAM,sBAAsB,CAAC,CAAC,SAAS,OAAO,IAAI,cAAc,GAAG;IACvE,mFAAmF;IACnF,IAAI,CAAC,EAAE,CAAC,CAAC;CACV,CAAC;AAEF,MAAM,MAAM,wBAAwB,CAAC,CAAC,SAAS,OAAO,IAAI,gBAAgB,CAAC,CAAC,CAAC,GAAG;IAC9E,iEAAiE;IACjE,OAAO,EAAE,MAAM,IAAI,CAAC;CACrB,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,OAAO,EAClD,KAAK,EAAE,CAAC,EACR,IAAI,GAAE,sBAAsB,CAAC,CAAC,CAAmC,GAChE,wBAAwB,CAAC,CAAC,CAAC,CA2C7B"}
|
|
@@ -3,35 +3,48 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.useAnimateOnAction = useAnimateOnAction;
|
|
4
4
|
const react_1 = require("react");
|
|
5
5
|
const common_1 = require("./common");
|
|
6
|
-
const easing_1 = require("./easing");
|
|
7
6
|
const useAnimationRunner_1 = require("./useAnimationRunner");
|
|
8
|
-
const toArray = (v) => (Array.isArray(v) ? v : [v]);
|
|
9
7
|
/**
|
|
10
8
|
* Animates a value (or array of values) from `from` to `value` when the
|
|
11
9
|
* returned `trigger` function is called. Configuration is captured at the
|
|
12
10
|
* moment `trigger` is invoked. Re-trigger snaps back to `from` and starts
|
|
13
|
-
* a fresh run.
|
|
11
|
+
* a fresh run. Until the first trigger, the exposed value is the current
|
|
12
|
+
* `from` (it follows changes to `from`).
|
|
14
13
|
*/
|
|
15
14
|
function useAnimateOnAction(value, opts = {}) {
|
|
16
15
|
const isArray = Array.isArray(value);
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
16
|
+
const { animatedValue, isAnimating, start } = (0, useAnimationRunner_1.useAnimationRunner)(() => (0, common_1.resolveFrom)((0, common_1.toArray)(value), opts.from));
|
|
17
|
+
// Until the first trigger the runner has nothing to show, so expose the
|
|
18
|
+
// current `from` directly. It's held in state and replaced only when its
|
|
19
|
+
// elements change, so its identity is stable across idle re-renders.
|
|
20
|
+
const [triggered, setTriggered] = (0, react_1.useState)(false);
|
|
21
|
+
const idleFrom = triggered ? undefined : (0, common_1.resolveFrom)((0, common_1.toArray)(value), opts.from);
|
|
22
|
+
// Copies, so the hook never shares an array with the caller's `from`.
|
|
23
|
+
const [idleShown, setIdleShown] = (0, react_1.useState)(() => idleFrom?.slice());
|
|
24
|
+
if (idleFrom && (!idleShown || !(0, common_1.elementWiseEqual)(idleShown, idleFrom))) {
|
|
25
|
+
// Adjusting state during render (React's "previous props" pattern).
|
|
26
|
+
setIdleShown(idleFrom.slice());
|
|
27
|
+
}
|
|
28
|
+
// Synced at commit, not during render, so a render React discards can't
|
|
29
|
+
// leak uncommitted props into the next trigger. An insertion effect runs
|
|
30
|
+
// before every layout effect in the commit, so a child's useLayoutEffect
|
|
31
|
+
// that calls trigger already sees this commit's props.
|
|
32
|
+
const latestRef = (0, react_1.useRef)({ value, opts });
|
|
33
|
+
(0, react_1.useInsertionEffect)(() => {
|
|
34
|
+
latestRef.current = { value, opts };
|
|
35
|
+
});
|
|
22
36
|
const trigger = (0, react_1.useCallback)(() => {
|
|
23
|
-
const {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
// Stable identity; reads latest props from ref.
|
|
37
|
+
const { value, opts } = latestRef.current;
|
|
38
|
+
const valueArr = (0, common_1.toArray)(value);
|
|
39
|
+
const fromArr = (0, common_1.resolveFrom)(valueArr, opts.from);
|
|
40
|
+
// Validate before switching display over to the runner.
|
|
41
|
+
(0, common_1.assertSameLength)(fromArr, valueArr);
|
|
42
|
+
setTriggered(true);
|
|
43
|
+
start((0, common_1.resolveRunParams)(valueArr, fromArr, opts));
|
|
44
|
+
// Stable identity; reads latest props from ref. `start` only touches
|
|
45
|
+
// refs and state setters, so the first-render instance stays valid.
|
|
33
46
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
34
47
|
}, []);
|
|
35
|
-
const
|
|
36
|
-
return { animatedValue:
|
|
48
|
+
const shown = triggered || !idleShown ? animatedValue : idleShown;
|
|
49
|
+
return { animatedValue: (0, common_1.fromArray)(shown, isArray), isAnimating, trigger };
|
|
37
50
|
}
|
|
@@ -1,14 +1,16 @@
|
|
|
1
|
-
import { type Easable, type UseAnimateOpts } from "./common";
|
|
1
|
+
import { type Easable, type UseAnimateOpts, type UseAnimateResult } from "./common";
|
|
2
2
|
/**
|
|
3
3
|
* Animates the exposed value whenever the `value` argument changes.
|
|
4
4
|
*
|
|
5
5
|
* Equality between renders is `Object.is` for scalars and length+element-wise
|
|
6
6
|
* `Object.is` for arrays. Mid-flight changes continue from the current
|
|
7
|
-
* exposed value (no snap-back)
|
|
8
|
-
* the
|
|
7
|
+
* exposed value (no snap-back) over a full duration, counted from the latest
|
|
8
|
+
* animation frame so the next frame already moves toward the new target.
|
|
9
|
+
*
|
|
10
|
+
* Changing an array's length is unsupported: it logs an error once, then does
|
|
11
|
+
* its best (shared indices animate, new indices start at their target).
|
|
12
|
+
* Shrinking is undefined behavior: stale entries may remain in the exposed
|
|
13
|
+
* value indefinitely (e.g. shrinking to `[]` never clears it).
|
|
9
14
|
*/
|
|
10
|
-
export declare function useAnimateOnChange<T extends Easable>(value: T, opts?: UseAnimateOpts):
|
|
11
|
-
animatedValue: T;
|
|
12
|
-
isAnimating: boolean;
|
|
13
|
-
};
|
|
15
|
+
export declare function useAnimateOnChange<T extends Easable>(value: T, opts?: UseAnimateOpts): UseAnimateResult<T>;
|
|
14
16
|
//# sourceMappingURL=useAnimateOnChange.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAnimateOnChange.d.ts","sourceRoot":"","sources":["../lib/useAnimateOnChange.ts"],"names":[],"mappings":"AAEA,OAAO,
|
|
1
|
+
{"version":3,"file":"useAnimateOnChange.d.ts","sourceRoot":"","sources":["../lib/useAnimateOnChange.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,OAAO,EAA0D,KAAK,cAAc,EAAE,KAAK,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAG5I;;;;;;;;;;;;GAYG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,OAAO,EAClD,KAAK,EAAE,CAAC,EACR,IAAI,GAAE,cAAmB,GACxB,gBAAgB,CAAC,CAAC,CAAC,CA6CrB"}
|
|
@@ -3,56 +3,56 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.useAnimateOnChange = useAnimateOnChange;
|
|
4
4
|
const react_1 = require("react");
|
|
5
5
|
const common_1 = require("./common");
|
|
6
|
-
const easing_1 = require("./easing");
|
|
7
6
|
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
7
|
/**
|
|
19
8
|
* Animates the exposed value whenever the `value` argument changes.
|
|
20
9
|
*
|
|
21
10
|
* Equality between renders is `Object.is` for scalars and length+element-wise
|
|
22
11
|
* `Object.is` for arrays. Mid-flight changes continue from the current
|
|
23
|
-
* exposed value (no snap-back)
|
|
24
|
-
* the
|
|
12
|
+
* exposed value (no snap-back) over a full duration, counted from the latest
|
|
13
|
+
* animation frame so the next frame already moves toward the new target.
|
|
14
|
+
*
|
|
15
|
+
* Changing an array's length is unsupported: it logs an error once, then does
|
|
16
|
+
* its best (shared indices animate, new indices start at their target).
|
|
17
|
+
* Shrinking is undefined behavior: stale entries may remain in the exposed
|
|
18
|
+
* value indefinitely (e.g. shrinking to `[]` never clears it).
|
|
25
19
|
*/
|
|
26
20
|
function useAnimateOnChange(value, opts = {}) {
|
|
27
21
|
const isArray = Array.isArray(value);
|
|
28
|
-
const valueArr = toArray(value);
|
|
29
|
-
const { animatedValue, isAnimating, start } = (0, useAnimationRunner_1.useAnimationRunner)(valueArr);
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
22
|
+
const valueArr = (0, common_1.toArray)(value);
|
|
23
|
+
const { animatedValue, isAnimating, start, getLatestValue } = (0, useAnimationRunner_1.useAnimationRunner)(() => valueArr);
|
|
24
|
+
// A copy, so in-place mutation of the caller's array still reads as a change.
|
|
25
|
+
// Lazy so it isn't re-copied on every animation-frame render.
|
|
26
|
+
const [initialCopy] = (0, react_1.useState)(() => valueArr.slice());
|
|
27
|
+
const prevValueRef = (0, react_1.useRef)(initialCopy);
|
|
28
|
+
const warnedRef = (0, react_1.useRef)(false);
|
|
33
29
|
(0, react_1.useEffect)(() => {
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
return;
|
|
37
|
-
}
|
|
38
|
-
if (elementWiseEqual(animatedValue, valueArr)) {
|
|
30
|
+
// Guards mount (including StrictMode's re-run) and any spurious re-run.
|
|
31
|
+
if ((0, common_1.elementWiseEqual)(prevValueRef.current, valueArr))
|
|
39
32
|
return;
|
|
33
|
+
prevValueRef.current = valueArr.slice();
|
|
34
|
+
// Latest frame, not the render snapshot: rAF may have written newer
|
|
35
|
+
// values between this render and the effect.
|
|
36
|
+
let from = getLatestValue();
|
|
37
|
+
if (from.length !== valueArr.length) {
|
|
38
|
+
if (!warnedRef.current) {
|
|
39
|
+
warnedRef.current = true;
|
|
40
|
+
console.error(`re-animate-js: useAnimateOnChange array length changed (${from.length} → ${valueArr.length}). ` +
|
|
41
|
+
"This is unsupported; remount the component (e.g. change its `key`) instead.");
|
|
42
|
+
}
|
|
43
|
+
const prev = from;
|
|
44
|
+
from = valueArr.map((v, i) => (i < prev.length ? prev[i] : v));
|
|
40
45
|
}
|
|
41
|
-
const
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
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.
|
|
46
|
+
const params = (0, common_1.resolveRunParams)(valueArr, from, opts);
|
|
47
|
+
// Already at the target (e.g. A→B→A before a frame fired): finish on the
|
|
48
|
+
// next frame through the normal completion path.
|
|
49
|
+
if ((0, common_1.elementWiseEqual)(from, valueArr))
|
|
50
|
+
params.durationMs = 0;
|
|
51
|
+
start(params);
|
|
52
|
+
// Re-run only when the value changes, not on every animation frame.
|
|
53
|
+
// Length goes first so a length change always differs at index 0 even
|
|
54
|
+
// though the deps array changes size (React warns; that case is unsupported).
|
|
54
55
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
55
|
-
}, valueArr);
|
|
56
|
-
|
|
57
|
-
return { animatedValue: out, isAnimating };
|
|
56
|
+
}, [valueArr.length, ...valueArr]);
|
|
57
|
+
return { animatedValue: (0, common_1.fromArray)(animatedValue, isArray), isAnimating };
|
|
58
58
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { type Easable, type UseAnimateOpts } from "./common";
|
|
2
|
-
type UseAnimateOnMountOpts<T extends Easable> = UseAnimateOpts & {
|
|
1
|
+
import { type Easable, type UseAnimateOpts, type UseAnimateResult } from "./common";
|
|
2
|
+
export type UseAnimateOnMountOpts<T extends Easable> = UseAnimateOpts & {
|
|
3
3
|
/** Origin of the animation. Defaults to 0 (scalar) or Array(N).fill(0) (array). */
|
|
4
4
|
from?: T;
|
|
5
5
|
};
|
|
@@ -9,9 +9,5 @@ type UseAnimateOnMountOpts<T extends Easable> = UseAnimateOpts & {
|
|
|
9
9
|
* Props are captured at mount time; subsequent prop changes are ignored.
|
|
10
10
|
* To re-run, remount the component (e.g. with a changing `key`).
|
|
11
11
|
*/
|
|
12
|
-
export declare function useAnimateOnMount<T extends Easable>(value: T, opts?: UseAnimateOnMountOpts<T>):
|
|
13
|
-
animatedValue: T;
|
|
14
|
-
isAnimating: boolean;
|
|
15
|
-
};
|
|
16
|
-
export {};
|
|
12
|
+
export declare function useAnimateOnMount<T extends Easable>(value: T, opts?: UseAnimateOnMountOpts<T>): UseAnimateResult<T>;
|
|
17
13
|
//# sourceMappingURL=useAnimateOnMount.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAnimateOnMount.d.ts","sourceRoot":"","sources":["../lib/useAnimateOnMount.ts"],"names":[],"mappings":"AAEA,OAAO,
|
|
1
|
+
{"version":3,"file":"useAnimateOnMount.d.ts","sourceRoot":"","sources":["../lib/useAnimateOnMount.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,OAAO,EAAqD,KAAK,cAAc,EAAE,KAAK,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAGvI,MAAM,MAAM,qBAAqB,CAAC,CAAC,SAAS,OAAO,IAAI,cAAc,GAAG;IACtE,mFAAmF;IACnF,IAAI,CAAC,EAAE,CAAC,CAAC;CACV,CAAC;AAEF;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,CAAC,SAAS,OAAO,EACjD,KAAK,EAAE,CAAC,EACR,IAAI,GAAE,qBAAqB,CAAC,CAAC,CAAkC,GAC9D,gBAAgB,CAAC,CAAC,CAAC,CA0BrB"}
|
|
@@ -3,9 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.useAnimateOnMount = useAnimateOnMount;
|
|
4
4
|
const react_1 = require("react");
|
|
5
5
|
const common_1 = require("./common");
|
|
6
|
-
const easing_1 = require("./easing");
|
|
7
6
|
const useAnimationRunner_1 = require("./useAnimationRunner");
|
|
8
|
-
const toArray = (v) => (Array.isArray(v) ? v : [v]);
|
|
9
7
|
/**
|
|
10
8
|
* Animates a value (or array of values) from `from` to `value` once on mount.
|
|
11
9
|
*
|
|
@@ -14,22 +12,24 @@ const toArray = (v) => (Array.isArray(v) ? v : [v]);
|
|
|
14
12
|
*/
|
|
15
13
|
function useAnimateOnMount(value, opts = {}) {
|
|
16
14
|
const isArray = Array.isArray(value);
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
|
|
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,
|
|
15
|
+
// Props are captured once at mount. Lazy so later renders (one per
|
|
16
|
+
// animation frame) don't rebuild arrays that would be thrown away.
|
|
17
|
+
const [params] = (0, react_1.useState)(() => {
|
|
18
|
+
const valueArr = (0, common_1.toArray)(value);
|
|
19
|
+
return (0, common_1.resolveRunParams)(valueArr, (0, common_1.resolveFrom)(valueArr, opts.from), opts);
|
|
27
20
|
});
|
|
21
|
+
const { animatedValue, isAnimating, start } = (0, useAnimationRunner_1.useAnimationRunner)(() => params.from);
|
|
22
|
+
// Refs survive effect teardown without a real unmount (StrictMode's
|
|
23
|
+
// simulated remount, a hidden-then-shown <Activity>), so the run starts once;
|
|
24
|
+
// the runner resumes it instead of replaying from `from`.
|
|
25
|
+
const startedRef = (0, react_1.useRef)(false);
|
|
28
26
|
(0, react_1.useEffect)(() => {
|
|
29
|
-
|
|
30
|
-
|
|
27
|
+
if (startedRef.current)
|
|
28
|
+
return;
|
|
29
|
+
startedRef.current = true;
|
|
30
|
+
start(params);
|
|
31
|
+
// Mount-once semantics; props captured at mount.
|
|
31
32
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
32
33
|
}, []);
|
|
33
|
-
|
|
34
|
-
return { animatedValue: out, isAnimating };
|
|
34
|
+
return { animatedValue: (0, common_1.fromArray)(animatedValue, isArray), isAnimating };
|
|
35
35
|
}
|
|
@@ -1,17 +1,14 @@
|
|
|
1
|
-
import { type
|
|
2
|
-
export type AnimationRunParams = {
|
|
3
|
-
value: number[];
|
|
4
|
-
from: number[];
|
|
5
|
-
durationMs: number;
|
|
6
|
-
easingFunction: EasingFunction;
|
|
7
|
-
before?: () => void;
|
|
8
|
-
after?: () => void;
|
|
9
|
-
};
|
|
1
|
+
import { type AnimationRunParams } from "./common";
|
|
10
2
|
export type AnimationRunner = {
|
|
11
3
|
animatedValue: number[];
|
|
12
4
|
isAnimating: boolean;
|
|
13
5
|
start: (params: AnimationRunParams) => void;
|
|
14
|
-
|
|
6
|
+
/** The most recently written value, which may be newer than the last rendered `animatedValue`. */
|
|
7
|
+
getLatestValue: () => number[];
|
|
15
8
|
};
|
|
16
|
-
|
|
9
|
+
/**
|
|
10
|
+
* @param getInitialValue Called once, on mount, for the starting value. A
|
|
11
|
+
* function so callers don't rebuild it on every animation-frame render.
|
|
12
|
+
*/
|
|
13
|
+
export declare const useAnimationRunner: (getInitialValue: () => number[]) => AnimationRunner;
|
|
17
14
|
//# sourceMappingURL=useAnimationRunner.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAnimationRunner.d.ts","sourceRoot":"","sources":["../lib/useAnimationRunner.ts"],"names":[],"mappings":"AAEA,OAAO,
|
|
1
|
+
{"version":3,"file":"useAnimationRunner.d.ts","sourceRoot":"","sources":["../lib/useAnimationRunner.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,kBAAkB,EAAsC,MAAM,UAAU,CAAC;AAGvF,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,kGAAkG;IAClG,cAAc,EAAE,MAAM,MAAM,EAAE,CAAC;CAChC,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,kBAAkB,GAAI,iBAAiB,MAAM,MAAM,EAAE,KAAG,eAyIpE,CAAC"}
|
|
@@ -2,30 +2,43 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.useAnimationRunner = void 0;
|
|
4
4
|
const react_1 = require("react");
|
|
5
|
+
const common_1 = require("./common");
|
|
5
6
|
const easing_1 = require("./easing");
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
};
|
|
15
|
-
const useAnimationRunner = (initialValue) => {
|
|
16
|
-
const [animatedValue, setAnimatedValue] = (0, react_1.useState)(initialValue);
|
|
7
|
+
/**
|
|
8
|
+
* @param getInitialValue Called once, on mount, for the starting value. A
|
|
9
|
+
* function so callers don't rebuild it on every animation-frame render.
|
|
10
|
+
*/
|
|
11
|
+
const useAnimationRunner = (getInitialValue) => {
|
|
12
|
+
// Copy so the runner never shares an array with the caller: otherwise an
|
|
13
|
+
// in-place edit of the caller's array would also rewrite "current".
|
|
14
|
+
const [animatedValue, setAnimatedValue] = (0, react_1.useState)(() => getInitialValue().slice());
|
|
17
15
|
const [isAnimating, setIsAnimating] = (0, react_1.useState)(false);
|
|
18
|
-
const latestValueRef = (0, react_1.useRef)(
|
|
16
|
+
const latestValueRef = (0, react_1.useRef)(animatedValue);
|
|
19
17
|
const rafIdRef = (0, react_1.useRef)(undefined);
|
|
20
18
|
const runTokenRef = (0, react_1.useRef)(0);
|
|
21
19
|
const mountedRef = (0, react_1.useRef)(true);
|
|
20
|
+
// The in-flight run's frame callback; cleared when the run ends or is cancelled.
|
|
21
|
+
const stepRef = (0, react_1.useRef)(undefined);
|
|
22
|
+
// True while that run waits for effects to be set up again: they were torn
|
|
23
|
+
// down without a real unmount (StrictMode's simulated remount, a hidden
|
|
24
|
+
// <Activity>), or the run was started while they were down.
|
|
25
|
+
const pausedRef = (0, react_1.useRef)(false);
|
|
26
|
+
// Timestamp of the in-flight run's latest frame. Cleared when the run ends
|
|
27
|
+
// or pauses, so a retarget after a long pause doesn't inherit a stale clock.
|
|
28
|
+
const lastFrameTimeRef = (0, react_1.useRef)(undefined);
|
|
22
29
|
(0, react_1.useEffect)(() => {
|
|
23
30
|
mountedRef.current = true;
|
|
31
|
+
if (pausedRef.current && stepRef.current) {
|
|
32
|
+
rafIdRef.current = requestAnimationFrame(stepRef.current);
|
|
33
|
+
}
|
|
34
|
+
pausedRef.current = false;
|
|
24
35
|
return () => {
|
|
25
36
|
mountedRef.current = false;
|
|
26
37
|
if (rafIdRef.current !== undefined) {
|
|
27
38
|
cancelAnimationFrame(rafIdRef.current);
|
|
28
39
|
rafIdRef.current = undefined;
|
|
40
|
+
pausedRef.current = true;
|
|
41
|
+
lastFrameTimeRef.current = undefined;
|
|
29
42
|
}
|
|
30
43
|
};
|
|
31
44
|
}, []);
|
|
@@ -33,41 +46,71 @@ const useAnimationRunner = (initialValue) => {
|
|
|
33
46
|
latestValueRef.current = next;
|
|
34
47
|
setAnimatedValue(next);
|
|
35
48
|
};
|
|
36
|
-
|
|
49
|
+
/** Cancels any scheduled frame. Returns true if a run was in flight. */
|
|
50
|
+
const cancel = () => {
|
|
51
|
+
runTokenRef.current++;
|
|
52
|
+
const wasRunning = stepRef.current !== undefined;
|
|
53
|
+
stepRef.current = undefined;
|
|
54
|
+
pausedRef.current = false;
|
|
37
55
|
if (rafIdRef.current !== undefined) {
|
|
38
56
|
cancelAnimationFrame(rafIdRef.current);
|
|
39
57
|
rafIdRef.current = undefined;
|
|
40
58
|
}
|
|
41
|
-
|
|
42
|
-
|
|
59
|
+
return wasRunning;
|
|
60
|
+
};
|
|
61
|
+
const start = (params) => {
|
|
62
|
+
const { durationMs, easingFunction, before, after } = params;
|
|
63
|
+
// Copy so later in-place mutation of the caller's arrays can't affect this run.
|
|
64
|
+
const value = params.value.slice();
|
|
65
|
+
const from = params.from.slice();
|
|
66
|
+
(0, common_1.assertSameLength)(from, value);
|
|
67
|
+
// A retarget mid-flight keeps the clock of the run it replaces: the new run
|
|
68
|
+
// counts from that run's last frame, so the very next frame moves. Starting
|
|
69
|
+
// the clock fresh would spend that frame standing still, and a value that
|
|
70
|
+
// changes about once per frame would never move at all.
|
|
71
|
+
const lastFrameTime = lastFrameTimeRef.current;
|
|
72
|
+
lastFrameTimeRef.current = undefined;
|
|
73
|
+
const wasRunning = cancel();
|
|
74
|
+
// Empty array: complete no-op (FR-013) — no callbacks, no rAF. Only clear
|
|
75
|
+
// isAnimating if this call cancelled an in-flight run.
|
|
43
76
|
if (value.length === 0) {
|
|
44
|
-
|
|
77
|
+
if (wasRunning)
|
|
78
|
+
setIsAnimating(false);
|
|
45
79
|
return;
|
|
46
80
|
}
|
|
47
|
-
const token =
|
|
81
|
+
const token = runTokenRef.current;
|
|
48
82
|
const span = new Array(value.length);
|
|
49
83
|
for (let i = 0; i < value.length; i++)
|
|
50
84
|
span[i] = value[i] - from[i];
|
|
51
85
|
// Seed write — skip if element-wise equal to current (mid-flight retarget case).
|
|
52
|
-
if (!elementWiseEqual(from, latestValueRef.current)) {
|
|
53
|
-
setValue(from
|
|
86
|
+
if (!(0, common_1.elementWiseEqual)(from, latestValueRef.current)) {
|
|
87
|
+
setValue(from);
|
|
54
88
|
}
|
|
55
89
|
setIsAnimating(true);
|
|
56
|
-
|
|
57
|
-
let startTime;
|
|
90
|
+
let startTime = wasRunning ? lastFrameTime : undefined;
|
|
58
91
|
const step = (timestamp) => {
|
|
59
92
|
if (token !== runTokenRef.current || !mountedRef.current)
|
|
60
93
|
return;
|
|
61
94
|
if (startTime === undefined)
|
|
62
95
|
startTime = timestamp;
|
|
96
|
+
lastFrameTimeRef.current = timestamp;
|
|
63
97
|
const elapsed = timestamp - startTime;
|
|
64
|
-
|
|
65
|
-
|
|
98
|
+
// Zero, negative, NaN and Infinity durations all jump to the end.
|
|
99
|
+
if (!(durationMs > 0 && Number.isFinite(durationMs)) || elapsed >= durationMs) {
|
|
100
|
+
setValue(value);
|
|
66
101
|
rafIdRef.current = undefined;
|
|
102
|
+
stepRef.current = undefined;
|
|
103
|
+
lastFrameTimeRef.current = undefined;
|
|
67
104
|
setIsAnimating(false);
|
|
68
105
|
after?.();
|
|
69
106
|
return;
|
|
70
107
|
}
|
|
108
|
+
// The first frame only fixes the clock; at elapsed 0 the value is still
|
|
109
|
+
// the seed, so writing it would just cost a re-render.
|
|
110
|
+
if (elapsed === 0) {
|
|
111
|
+
rafIdRef.current = requestAnimationFrame(step);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
71
114
|
const fraction = (0, easing_1.applyEasing)(easingFunction, elapsed / durationMs);
|
|
72
115
|
const next = new Array(value.length);
|
|
73
116
|
for (let i = 0; i < value.length; i++) {
|
|
@@ -76,16 +119,18 @@ const useAnimationRunner = (initialValue) => {
|
|
|
76
119
|
setValue(next);
|
|
77
120
|
rafIdRef.current = requestAnimationFrame(step);
|
|
78
121
|
};
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
122
|
+
stepRef.current = step;
|
|
123
|
+
// While effects are down, frames would bail on !mountedRef; wait for the
|
|
124
|
+
// setup effect to start the run instead.
|
|
125
|
+
if (mountedRef.current)
|
|
126
|
+
rafIdRef.current = requestAnimationFrame(step);
|
|
127
|
+
else
|
|
128
|
+
pausedRef.current = true;
|
|
129
|
+
// Fired after scheduling so a throwing `before` can't strand the run with
|
|
130
|
+
// isAnimating stuck true; the first frame still runs after it.
|
|
131
|
+
before?.();
|
|
88
132
|
};
|
|
89
|
-
|
|
133
|
+
const getLatestValue = () => latestValueRef.current;
|
|
134
|
+
return { animatedValue, isAnimating, start, getLatestValue };
|
|
90
135
|
};
|
|
91
136
|
exports.useAnimationRunner = useAnimationRunner;
|
package/lib/common.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { type EasingFunction, Easings } from "./easing";
|
|
2
|
+
|
|
3
|
+
export const DEFAULT_DURATION_MS = 1000;
|
|
4
|
+
|
|
5
|
+
export type Easable = number | number[];
|
|
6
|
+
|
|
7
|
+
export type UseAnimateOpts = {
|
|
8
|
+
/** Duration in ms; defaults to 1000 */
|
|
9
|
+
durationMs?: number;
|
|
10
|
+
/** Easing curve; defaults to linear */
|
|
11
|
+
easingFunction?: EasingFunction;
|
|
12
|
+
/** Fires once per animation that starts */
|
|
13
|
+
before?: () => void;
|
|
14
|
+
/** Fires once per animation that completes (never for cancelled runs) */
|
|
15
|
+
after?: () => void;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export type UseAnimateResult<T extends Easable> = {
|
|
19
|
+
/** The current animated value, in the same shape as the hook's `value`. */
|
|
20
|
+
animatedValue: T;
|
|
21
|
+
isAnimating: boolean;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export type AnimationRunParams = {
|
|
25
|
+
value: number[];
|
|
26
|
+
from: number[];
|
|
27
|
+
durationMs: number;
|
|
28
|
+
easingFunction: EasingFunction;
|
|
29
|
+
before?: () => void;
|
|
30
|
+
after?: () => void;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export const toArray = (v: Easable): number[] => (Array.isArray(v) ? v : [v]);
|
|
34
|
+
|
|
35
|
+
/** Converts the runner's internal array back to the caller's shape (scalar or array). */
|
|
36
|
+
export const fromArray = <T extends Easable>(arr: number[], isArray: boolean): T =>
|
|
37
|
+
(isArray ? arr : arr[0]) as T;
|
|
38
|
+
|
|
39
|
+
export const elementWiseEqual = (a: number[], b: number[]): boolean => {
|
|
40
|
+
if (a.length !== b.length) return false;
|
|
41
|
+
for (let i = 0; i < a.length; i++) {
|
|
42
|
+
if (!Object.is(a[i], b[i])) return false;
|
|
43
|
+
}
|
|
44
|
+
return true;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/** Origin array: the caller's `from` if given, otherwise all zeros matching `value`'s length. */
|
|
48
|
+
export const resolveFrom = (valueArr: number[], from: Easable | undefined): number[] =>
|
|
49
|
+
from !== undefined ? toArray(from) : new Array<number>(valueArr.length).fill(0);
|
|
50
|
+
|
|
51
|
+
export const assertSameLength = (from: number[], value: number[]): void => {
|
|
52
|
+
if (from.length !== value.length) {
|
|
53
|
+
throw new Error(
|
|
54
|
+
`re-animate-js: \`from\` length (${from.length}) must match \`value\` length (${value.length})`,
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/** Builds runner params from hook options, applying defaults. */
|
|
60
|
+
export const resolveRunParams = (
|
|
61
|
+
value: number[],
|
|
62
|
+
from: number[],
|
|
63
|
+
opts: UseAnimateOpts,
|
|
64
|
+
): AnimationRunParams => ({
|
|
65
|
+
value,
|
|
66
|
+
from,
|
|
67
|
+
durationMs: opts.durationMs ?? DEFAULT_DURATION_MS,
|
|
68
|
+
easingFunction: opts.easingFunction ?? Easings.linear,
|
|
69
|
+
before: opts.before,
|
|
70
|
+
after: opts.after,
|
|
71
|
+
});
|
package/lib/easing.ts
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
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
|
+
const c1 = 1.70158;
|
|
10
|
+
const c2 = c1 * 1.525;
|
|
11
|
+
const c3 = c1 + 1;
|
|
12
|
+
const c4 = (2 * Math.PI) / 3;
|
|
13
|
+
const c5 = (2 * Math.PI) / 4.5;
|
|
14
|
+
|
|
15
|
+
const n1 = 7.5625;
|
|
16
|
+
const d1 = 2.75;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* A collection of ready-to-use easing functions. Note that these have not been "clamped" so that
|
|
20
|
+
* f(0) = 0 and f(1) = 1; values may differ slightly due to floating point error. The algorithm in
|
|
21
|
+
* this library ensures clamped values, therefore these functions will work for this library but
|
|
22
|
+
* may be unsuitable outside of it.
|
|
23
|
+
*/
|
|
24
|
+
export const Easings = {
|
|
25
|
+
linear: ((x: number) => x) as EasingFunction,
|
|
26
|
+
sine: {
|
|
27
|
+
in: ((x: number) => 1 - Math.cos((x * Math.PI) / 2)) as EasingFunction,
|
|
28
|
+
out: ((x: number) => Math.sin((x * Math.PI) / 2)) as EasingFunction,
|
|
29
|
+
inOut: ((x: number) => -(Math.cos(x * Math.PI) - 1) / 2) as EasingFunction,
|
|
30
|
+
},
|
|
31
|
+
polynomial: (degree: number) => ({
|
|
32
|
+
in: ((x: number) => Math.pow(x, degree)) as EasingFunction,
|
|
33
|
+
out: ((x: number) => 1 - Math.pow(1 - x, degree)) as EasingFunction,
|
|
34
|
+
inOut: ((x: number) => x < 0.5 ? Math.pow(2, degree - 1) * Math.pow(x, degree) : 1 - Math.pow(-2 * x + 2, degree) / 2) as EasingFunction,
|
|
35
|
+
}),
|
|
36
|
+
exponential: {
|
|
37
|
+
in: ((x: number) => Math.pow(2, 10 * x - 10)) as EasingFunction,
|
|
38
|
+
out: ((x: number) => 1 - Math.pow(2, -10 * x)) as EasingFunction,
|
|
39
|
+
inOut: ((x: number) => x < 0.5 ? Math.pow(2, 20 * x - 10) / 2
|
|
40
|
+
: (2 - Math.pow(2, -20 * x + 10)) / 2) as EasingFunction,
|
|
41
|
+
},
|
|
42
|
+
circular: {
|
|
43
|
+
in: ((x: number) => 1 - Math.sqrt(1 - Math.pow(x, 2))) as EasingFunction,
|
|
44
|
+
out: ((x: number) => Math.sqrt(1 - Math.pow(x - 1, 2))) as EasingFunction,
|
|
45
|
+
inOut: ((x: number) => x < 0.5
|
|
46
|
+
? (1 - Math.sqrt(1 - Math.pow(2 * x, 2))) / 2
|
|
47
|
+
: (Math.sqrt(1 - Math.pow(-2 * x + 2, 2)) + 1) / 2) as EasingFunction,
|
|
48
|
+
},
|
|
49
|
+
back: {
|
|
50
|
+
in: ((x: number) => c3 * x * x * x - c1 * x * x) as EasingFunction,
|
|
51
|
+
out: ((x: number) => 1 + c3 * Math.pow(x - 1, 3) + c1 * Math.pow(x - 1, 2)) as EasingFunction,
|
|
52
|
+
inOut: ((x: number) => x < 0.5
|
|
53
|
+
? (Math.pow(2 * x, 2) * ((c2 + 1) * 2 * x - c2)) / 2
|
|
54
|
+
: (Math.pow(2 * x - 2, 2) * ((c2 + 1) * (x * 2 - 2) + c2) + 2) / 2) as EasingFunction,
|
|
55
|
+
},
|
|
56
|
+
elastic: {
|
|
57
|
+
in: ((x: number) => -Math.pow(2, 10 * x - 10) * Math.sin((x * 10 - 10.75) * c4)) as EasingFunction,
|
|
58
|
+
out: ((x: number) => Math.pow(2, -10 * x) * Math.sin((x * 10 - 0.75) * c4) + 1) as EasingFunction,
|
|
59
|
+
inOut: ((x: number) => x < 0.5
|
|
60
|
+
? -(Math.pow(2, 20 * x - 10) * Math.sin((20 * x - 11.125) * c5)) / 2
|
|
61
|
+
: (Math.pow(2, -20 * x + 10) * Math.sin((20 * x - 11.125) * c5)) / 2 + 1) as EasingFunction,
|
|
62
|
+
},
|
|
63
|
+
bounce: {
|
|
64
|
+
in: ((x: number) => 1 - Easings.bounce.out(1 - x)) as EasingFunction,
|
|
65
|
+
out: ((x: number) => {
|
|
66
|
+
if (x < 1 / d1) {
|
|
67
|
+
return n1 * x * x;
|
|
68
|
+
} else if (x < 2 / d1) {
|
|
69
|
+
return n1 * (x -= 1.5 / d1) * x + 0.75;
|
|
70
|
+
} else if (x < 2.5 / d1) {
|
|
71
|
+
return n1 * (x -= 2.25 / d1) * x + 0.9375;
|
|
72
|
+
} else {
|
|
73
|
+
return n1 * (x -= 2.625 / d1) * x + 0.984375;
|
|
74
|
+
}
|
|
75
|
+
}) as EasingFunction,
|
|
76
|
+
inOut: ((x: number) => x < 0.5
|
|
77
|
+
? (1 - Easings.bounce.out(1 - 2 * x)) / 2
|
|
78
|
+
: (1 + Easings.bounce.out(2 * x - 1)) / 2) as EasingFunction,
|
|
79
|
+
},
|
|
80
|
+
} as const;
|
|
81
|
+
|
|
82
|
+
export const applyEasing = (f: EasingFunction, x: number) => {
|
|
83
|
+
if (x <= 0) {
|
|
84
|
+
return 0;
|
|
85
|
+
} else if (x >= 1) {
|
|
86
|
+
return 1;
|
|
87
|
+
} else {
|
|
88
|
+
return f(x);
|
|
89
|
+
}
|
|
90
|
+
}
|
package/lib/index.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export type { Easable, UseAnimateOpts, UseAnimateResult } from './common';
|
|
2
|
+
export { type EasingFunction, Easings } from './easing';
|
|
3
|
+
export { useAnimateOnAction, type UseAnimateOnActionOpts, type UseAnimateOnActionResult } from './useAnimateOnAction';
|
|
4
|
+
export { useAnimateOnChange } from './useAnimateOnChange';
|
|
5
|
+
export { useAnimateOnMount, type UseAnimateOnMountOpts } from './useAnimateOnMount';
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { useCallback, useInsertionEffect, useRef, useState } from "react";
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
assertSameLength,
|
|
5
|
+
type Easable,
|
|
6
|
+
elementWiseEqual,
|
|
7
|
+
fromArray,
|
|
8
|
+
resolveFrom,
|
|
9
|
+
resolveRunParams,
|
|
10
|
+
toArray,
|
|
11
|
+
type UseAnimateOpts,
|
|
12
|
+
type UseAnimateResult,
|
|
13
|
+
} from "./common";
|
|
14
|
+
import { useAnimationRunner } from "./useAnimationRunner";
|
|
15
|
+
|
|
16
|
+
export type UseAnimateOnActionOpts<T extends Easable> = UseAnimateOpts & {
|
|
17
|
+
/** Origin of the animation. Defaults to 0 (scalar) or Array(N).fill(0) (array). */
|
|
18
|
+
from?: T;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export type UseAnimateOnActionResult<T extends Easable> = UseAnimateResult<T> & {
|
|
22
|
+
/** Starts (or restarts) the animation. Stable across renders. */
|
|
23
|
+
trigger: () => void;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Animates a value (or array of values) from `from` to `value` when the
|
|
28
|
+
* returned `trigger` function is called. Configuration is captured at the
|
|
29
|
+
* moment `trigger` is invoked. Re-trigger snaps back to `from` and starts
|
|
30
|
+
* a fresh run. Until the first trigger, the exposed value is the current
|
|
31
|
+
* `from` (it follows changes to `from`).
|
|
32
|
+
*/
|
|
33
|
+
export function useAnimateOnAction<T extends Easable>(
|
|
34
|
+
value: T,
|
|
35
|
+
opts: UseAnimateOnActionOpts<T> = {} as UseAnimateOnActionOpts<T>,
|
|
36
|
+
): UseAnimateOnActionResult<T> {
|
|
37
|
+
const isArray = Array.isArray(value);
|
|
38
|
+
|
|
39
|
+
const { animatedValue, isAnimating, start } = useAnimationRunner(() =>
|
|
40
|
+
resolveFrom(toArray(value), opts.from),
|
|
41
|
+
);
|
|
42
|
+
|
|
43
|
+
// Until the first trigger the runner has nothing to show, so expose the
|
|
44
|
+
// current `from` directly. It's held in state and replaced only when its
|
|
45
|
+
// elements change, so its identity is stable across idle re-renders.
|
|
46
|
+
const [triggered, setTriggered] = useState(false);
|
|
47
|
+
const idleFrom = triggered ? undefined : resolveFrom(toArray(value), opts.from);
|
|
48
|
+
// Copies, so the hook never shares an array with the caller's `from`.
|
|
49
|
+
const [idleShown, setIdleShown] = useState(() => idleFrom?.slice());
|
|
50
|
+
if (idleFrom && (!idleShown || !elementWiseEqual(idleShown, idleFrom))) {
|
|
51
|
+
// Adjusting state during render (React's "previous props" pattern).
|
|
52
|
+
setIdleShown(idleFrom.slice());
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Synced at commit, not during render, so a render React discards can't
|
|
56
|
+
// leak uncommitted props into the next trigger. An insertion effect runs
|
|
57
|
+
// before every layout effect in the commit, so a child's useLayoutEffect
|
|
58
|
+
// that calls trigger already sees this commit's props.
|
|
59
|
+
const latestRef = useRef({ value, opts });
|
|
60
|
+
useInsertionEffect(() => {
|
|
61
|
+
latestRef.current = { value, opts };
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
const trigger = useCallback(() => {
|
|
65
|
+
const { value, opts } = latestRef.current;
|
|
66
|
+
const valueArr = toArray(value);
|
|
67
|
+
const fromArr = resolveFrom(valueArr, opts.from);
|
|
68
|
+
// Validate before switching display over to the runner.
|
|
69
|
+
assertSameLength(fromArr, valueArr);
|
|
70
|
+
setTriggered(true);
|
|
71
|
+
start(resolveRunParams(valueArr, fromArr, opts));
|
|
72
|
+
// Stable identity; reads latest props from ref. `start` only touches
|
|
73
|
+
// refs and state setters, so the first-render instance stays valid.
|
|
74
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
75
|
+
}, []);
|
|
76
|
+
|
|
77
|
+
const shown = triggered || !idleShown ? animatedValue : idleShown;
|
|
78
|
+
return { animatedValue: fromArray<T>(shown, isArray), isAnimating, trigger };
|
|
79
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { useEffect, useRef, useState } from "react";
|
|
2
|
+
|
|
3
|
+
import { type Easable, elementWiseEqual, fromArray, resolveRunParams, toArray, type UseAnimateOpts, type UseAnimateResult } from "./common";
|
|
4
|
+
import { useAnimationRunner } from "./useAnimationRunner";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Animates the exposed value whenever the `value` argument changes.
|
|
8
|
+
*
|
|
9
|
+
* Equality between renders is `Object.is` for scalars and length+element-wise
|
|
10
|
+
* `Object.is` for arrays. Mid-flight changes continue from the current
|
|
11
|
+
* exposed value (no snap-back) over a full duration, counted from the latest
|
|
12
|
+
* animation frame so the next frame already moves toward the new target.
|
|
13
|
+
*
|
|
14
|
+
* Changing an array's length is unsupported: it logs an error once, then does
|
|
15
|
+
* its best (shared indices animate, new indices start at their target).
|
|
16
|
+
* Shrinking is undefined behavior: stale entries may remain in the exposed
|
|
17
|
+
* value indefinitely (e.g. shrinking to `[]` never clears it).
|
|
18
|
+
*/
|
|
19
|
+
export function useAnimateOnChange<T extends Easable>(
|
|
20
|
+
value: T,
|
|
21
|
+
opts: UseAnimateOpts = {},
|
|
22
|
+
): UseAnimateResult<T> {
|
|
23
|
+
const isArray = Array.isArray(value);
|
|
24
|
+
const valueArr = toArray(value);
|
|
25
|
+
|
|
26
|
+
const { animatedValue, isAnimating, start, getLatestValue } = useAnimationRunner(() => valueArr);
|
|
27
|
+
|
|
28
|
+
// A copy, so in-place mutation of the caller's array still reads as a change.
|
|
29
|
+
// Lazy so it isn't re-copied on every animation-frame render.
|
|
30
|
+
const [initialCopy] = useState(() => valueArr.slice());
|
|
31
|
+
const prevValueRef = useRef(initialCopy);
|
|
32
|
+
const warnedRef = useRef(false);
|
|
33
|
+
|
|
34
|
+
useEffect(() => {
|
|
35
|
+
// Guards mount (including StrictMode's re-run) and any spurious re-run.
|
|
36
|
+
if (elementWiseEqual(prevValueRef.current, valueArr)) return;
|
|
37
|
+
prevValueRef.current = valueArr.slice();
|
|
38
|
+
|
|
39
|
+
// Latest frame, not the render snapshot: rAF may have written newer
|
|
40
|
+
// values between this render and the effect.
|
|
41
|
+
let from = getLatestValue();
|
|
42
|
+
|
|
43
|
+
if (from.length !== valueArr.length) {
|
|
44
|
+
if (!warnedRef.current) {
|
|
45
|
+
warnedRef.current = true;
|
|
46
|
+
console.error(
|
|
47
|
+
`re-animate-js: useAnimateOnChange array length changed (${from.length} → ${valueArr.length}). ` +
|
|
48
|
+
"This is unsupported; remount the component (e.g. change its `key`) instead.",
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
const prev = from;
|
|
52
|
+
from = valueArr.map((v, i) => (i < prev.length ? prev[i] : v));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const params = resolveRunParams(valueArr, from, opts);
|
|
56
|
+
// Already at the target (e.g. A→B→A before a frame fired): finish on the
|
|
57
|
+
// next frame through the normal completion path.
|
|
58
|
+
if (elementWiseEqual(from, valueArr)) params.durationMs = 0;
|
|
59
|
+
start(params);
|
|
60
|
+
// Re-run only when the value changes, not on every animation frame.
|
|
61
|
+
// Length goes first so a length change always differs at index 0 even
|
|
62
|
+
// though the deps array changes size (React warns; that case is unsupported).
|
|
63
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
64
|
+
}, [valueArr.length, ...valueArr]);
|
|
65
|
+
|
|
66
|
+
return { animatedValue: fromArray<T>(animatedValue, isArray), isAnimating };
|
|
67
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { useEffect, useRef, useState } from "react";
|
|
2
|
+
|
|
3
|
+
import { type Easable, fromArray, resolveFrom, resolveRunParams, toArray, type UseAnimateOpts, type UseAnimateResult } from "./common";
|
|
4
|
+
import { useAnimationRunner } from "./useAnimationRunner";
|
|
5
|
+
|
|
6
|
+
export type UseAnimateOnMountOpts<T extends Easable> = UseAnimateOpts & {
|
|
7
|
+
/** Origin of the animation. Defaults to 0 (scalar) or Array(N).fill(0) (array). */
|
|
8
|
+
from?: T;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Animates a value (or array of values) from `from` to `value` once on mount.
|
|
13
|
+
*
|
|
14
|
+
* Props are captured at mount time; subsequent prop changes are ignored.
|
|
15
|
+
* To re-run, remount the component (e.g. with a changing `key`).
|
|
16
|
+
*/
|
|
17
|
+
export function useAnimateOnMount<T extends Easable>(
|
|
18
|
+
value: T,
|
|
19
|
+
opts: UseAnimateOnMountOpts<T> = {} as UseAnimateOnMountOpts<T>,
|
|
20
|
+
): UseAnimateResult<T> {
|
|
21
|
+
const isArray = Array.isArray(value);
|
|
22
|
+
|
|
23
|
+
// Props are captured once at mount. Lazy so later renders (one per
|
|
24
|
+
// animation frame) don't rebuild arrays that would be thrown away.
|
|
25
|
+
const [params] = useState(() => {
|
|
26
|
+
const valueArr = toArray(value);
|
|
27
|
+
return resolveRunParams(valueArr, resolveFrom(valueArr, opts.from), opts);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
const { animatedValue, isAnimating, start } = useAnimationRunner(() => params.from);
|
|
31
|
+
|
|
32
|
+
// Refs survive effect teardown without a real unmount (StrictMode's
|
|
33
|
+
// simulated remount, a hidden-then-shown <Activity>), so the run starts once;
|
|
34
|
+
// the runner resumes it instead of replaying from `from`.
|
|
35
|
+
const startedRef = useRef(false);
|
|
36
|
+
|
|
37
|
+
useEffect(() => {
|
|
38
|
+
if (startedRef.current) return;
|
|
39
|
+
startedRef.current = true;
|
|
40
|
+
start(params);
|
|
41
|
+
// Mount-once semantics; props captured at mount.
|
|
42
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
43
|
+
}, []);
|
|
44
|
+
|
|
45
|
+
return { animatedValue: fromArray<T>(animatedValue, isArray), isAnimating };
|
|
46
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { useEffect, useRef, useState } from "react";
|
|
2
|
+
|
|
3
|
+
import { type AnimationRunParams, assertSameLength, elementWiseEqual } from "./common";
|
|
4
|
+
import { applyEasing } from "./easing";
|
|
5
|
+
|
|
6
|
+
export type AnimationRunner = {
|
|
7
|
+
animatedValue: number[];
|
|
8
|
+
isAnimating: boolean;
|
|
9
|
+
start: (params: AnimationRunParams) => void;
|
|
10
|
+
/** The most recently written value, which may be newer than the last rendered `animatedValue`. */
|
|
11
|
+
getLatestValue: () => number[];
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @param getInitialValue Called once, on mount, for the starting value. A
|
|
16
|
+
* function so callers don't rebuild it on every animation-frame render.
|
|
17
|
+
*/
|
|
18
|
+
export const useAnimationRunner = (getInitialValue: () => number[]): AnimationRunner => {
|
|
19
|
+
// Copy so the runner never shares an array with the caller: otherwise an
|
|
20
|
+
// in-place edit of the caller's array would also rewrite "current".
|
|
21
|
+
const [animatedValue, setAnimatedValue] = useState<number[]>(() => getInitialValue().slice());
|
|
22
|
+
const [isAnimating, setIsAnimating] = useState(false);
|
|
23
|
+
|
|
24
|
+
const latestValueRef = useRef<number[]>(animatedValue);
|
|
25
|
+
const rafIdRef = useRef<number | undefined>(undefined);
|
|
26
|
+
const runTokenRef = useRef(0);
|
|
27
|
+
const mountedRef = useRef(true);
|
|
28
|
+
// The in-flight run's frame callback; cleared when the run ends or is cancelled.
|
|
29
|
+
const stepRef = useRef<FrameRequestCallback | undefined>(undefined);
|
|
30
|
+
// True while that run waits for effects to be set up again: they were torn
|
|
31
|
+
// down without a real unmount (StrictMode's simulated remount, a hidden
|
|
32
|
+
// <Activity>), or the run was started while they were down.
|
|
33
|
+
const pausedRef = useRef(false);
|
|
34
|
+
// Timestamp of the in-flight run's latest frame. Cleared when the run ends
|
|
35
|
+
// or pauses, so a retarget after a long pause doesn't inherit a stale clock.
|
|
36
|
+
const lastFrameTimeRef = useRef<number | undefined>(undefined);
|
|
37
|
+
|
|
38
|
+
useEffect(() => {
|
|
39
|
+
mountedRef.current = true;
|
|
40
|
+
if (pausedRef.current && stepRef.current) {
|
|
41
|
+
rafIdRef.current = requestAnimationFrame(stepRef.current);
|
|
42
|
+
}
|
|
43
|
+
pausedRef.current = false;
|
|
44
|
+
return () => {
|
|
45
|
+
mountedRef.current = false;
|
|
46
|
+
if (rafIdRef.current !== undefined) {
|
|
47
|
+
cancelAnimationFrame(rafIdRef.current);
|
|
48
|
+
rafIdRef.current = undefined;
|
|
49
|
+
pausedRef.current = true;
|
|
50
|
+
lastFrameTimeRef.current = undefined;
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
}, []);
|
|
54
|
+
|
|
55
|
+
const setValue = (next: number[]) => {
|
|
56
|
+
latestValueRef.current = next;
|
|
57
|
+
setAnimatedValue(next);
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
/** Cancels any scheduled frame. Returns true if a run was in flight. */
|
|
61
|
+
const cancel = (): boolean => {
|
|
62
|
+
runTokenRef.current++;
|
|
63
|
+
const wasRunning = stepRef.current !== undefined;
|
|
64
|
+
stepRef.current = undefined;
|
|
65
|
+
pausedRef.current = false;
|
|
66
|
+
if (rafIdRef.current !== undefined) {
|
|
67
|
+
cancelAnimationFrame(rafIdRef.current);
|
|
68
|
+
rafIdRef.current = undefined;
|
|
69
|
+
}
|
|
70
|
+
return wasRunning;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const start = (params: AnimationRunParams) => {
|
|
74
|
+
const { durationMs, easingFunction, before, after } = params;
|
|
75
|
+
// Copy so later in-place mutation of the caller's arrays can't affect this run.
|
|
76
|
+
const value = params.value.slice();
|
|
77
|
+
const from = params.from.slice();
|
|
78
|
+
|
|
79
|
+
assertSameLength(from, value);
|
|
80
|
+
|
|
81
|
+
// A retarget mid-flight keeps the clock of the run it replaces: the new run
|
|
82
|
+
// counts from that run's last frame, so the very next frame moves. Starting
|
|
83
|
+
// the clock fresh would spend that frame standing still, and a value that
|
|
84
|
+
// changes about once per frame would never move at all.
|
|
85
|
+
const lastFrameTime = lastFrameTimeRef.current;
|
|
86
|
+
lastFrameTimeRef.current = undefined;
|
|
87
|
+
const wasRunning = cancel();
|
|
88
|
+
|
|
89
|
+
// Empty array: complete no-op (FR-013) — no callbacks, no rAF. Only clear
|
|
90
|
+
// isAnimating if this call cancelled an in-flight run.
|
|
91
|
+
if (value.length === 0) {
|
|
92
|
+
if (wasRunning) setIsAnimating(false);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const token = runTokenRef.current;
|
|
97
|
+
const span = new Array<number>(value.length);
|
|
98
|
+
for (let i = 0; i < value.length; i++) span[i] = value[i] - from[i];
|
|
99
|
+
|
|
100
|
+
// Seed write — skip if element-wise equal to current (mid-flight retarget case).
|
|
101
|
+
if (!elementWiseEqual(from, latestValueRef.current)) {
|
|
102
|
+
setValue(from);
|
|
103
|
+
}
|
|
104
|
+
setIsAnimating(true);
|
|
105
|
+
|
|
106
|
+
let startTime: number | undefined = wasRunning ? lastFrameTime : undefined;
|
|
107
|
+
|
|
108
|
+
const step = (timestamp: number) => {
|
|
109
|
+
if (token !== runTokenRef.current || !mountedRef.current) return;
|
|
110
|
+
if (startTime === undefined) startTime = timestamp;
|
|
111
|
+
lastFrameTimeRef.current = timestamp;
|
|
112
|
+
|
|
113
|
+
const elapsed = timestamp - startTime;
|
|
114
|
+
|
|
115
|
+
// Zero, negative, NaN and Infinity durations all jump to the end.
|
|
116
|
+
if (!(durationMs > 0 && Number.isFinite(durationMs)) || elapsed >= durationMs) {
|
|
117
|
+
setValue(value);
|
|
118
|
+
rafIdRef.current = undefined;
|
|
119
|
+
stepRef.current = undefined;
|
|
120
|
+
lastFrameTimeRef.current = undefined;
|
|
121
|
+
setIsAnimating(false);
|
|
122
|
+
after?.();
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// The first frame only fixes the clock; at elapsed 0 the value is still
|
|
127
|
+
// the seed, so writing it would just cost a re-render.
|
|
128
|
+
if (elapsed === 0) {
|
|
129
|
+
rafIdRef.current = requestAnimationFrame(step);
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const fraction = applyEasing(easingFunction, elapsed / durationMs);
|
|
134
|
+
const next = new Array<number>(value.length);
|
|
135
|
+
for (let i = 0; i < value.length; i++) {
|
|
136
|
+
next[i] = from[i] + span[i] * fraction;
|
|
137
|
+
}
|
|
138
|
+
setValue(next);
|
|
139
|
+
rafIdRef.current = requestAnimationFrame(step);
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
stepRef.current = step;
|
|
143
|
+
// While effects are down, frames would bail on !mountedRef; wait for the
|
|
144
|
+
// setup effect to start the run instead.
|
|
145
|
+
if (mountedRef.current) rafIdRef.current = requestAnimationFrame(step);
|
|
146
|
+
else pausedRef.current = true;
|
|
147
|
+
// Fired after scheduling so a throwing `before` can't strand the run with
|
|
148
|
+
// isAnimating stuck true; the first frame still runs after it.
|
|
149
|
+
before?.();
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
const getLatestValue = () => latestValueRef.current;
|
|
153
|
+
|
|
154
|
+
return { animatedValue, isAnimating, start, getLatestValue };
|
|
155
|
+
};
|
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "re-animate-js",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "Lightweight React hooks for animating numeric values (or arrays of values) with configurable easing.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
7
|
-
"files": ["dist"],
|
|
7
|
+
"files": ["dist", "lib", "!lib/__tests__"],
|
|
8
8
|
"repository": {
|
|
9
9
|
"type": "git",
|
|
10
10
|
"url": "git+https://github.com/MattPutnam/re-animate-js.git"
|
|
@@ -13,8 +13,9 @@
|
|
|
13
13
|
"bugs": "https://github.com/MattPutnam/re-animate-js/issues",
|
|
14
14
|
"scripts": {
|
|
15
15
|
"prepare": "npm run build",
|
|
16
|
-
"build": "tsc",
|
|
16
|
+
"build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc",
|
|
17
17
|
"lint": "eslint .",
|
|
18
|
+
"typecheck": "tsc -p tsconfig.playground.json",
|
|
18
19
|
"demo": "vite",
|
|
19
20
|
"demo:build": "GITHUB_PAGES=true vite build",
|
|
20
21
|
"test": "vitest run"
|
|
@@ -26,16 +27,16 @@
|
|
|
26
27
|
"@eslint/js": "^10.0.1",
|
|
27
28
|
"@testing-library/dom": "^10.4.1",
|
|
28
29
|
"@testing-library/react": "^16.3.2",
|
|
29
|
-
"@types/react": "^19.
|
|
30
|
+
"@types/react": "^19.2.0",
|
|
30
31
|
"@types/react-dom": "^19.2.3",
|
|
31
32
|
"@vitejs/plugin-react": "^6.0.1",
|
|
32
|
-
"react": "^19.1.0",
|
|
33
33
|
"eslint": "^10.2.0",
|
|
34
34
|
"eslint-plugin-react-hooks": "^7.0.1",
|
|
35
35
|
"eslint-plugin-simple-import-sort": "^13.0.0",
|
|
36
36
|
"globals": "^17.5.0",
|
|
37
37
|
"jsdom": "^29.0.2",
|
|
38
|
-
"react
|
|
38
|
+
"react": "^19.2.0",
|
|
39
|
+
"react-dom": "^19.2.0",
|
|
39
40
|
"typescript": "^5.8.3",
|
|
40
41
|
"typescript-eslint": "^8.58.1",
|
|
41
42
|
"vite": "^8.0.8",
|