An open source design system that's fully customizable and agent ready
TypeScript
feat(core): createAnimator and useAnimator animate one element (#8653)
Christopher Chedeau871bc3d5e8cc
diff --git a/.changeset/public-animator.md b/.changeset/public-animator.mdnew file mode 100644index 0000000000..378452818e--- /dev/null+++ b/.changeset/public-animator.md@@ -0,0 +1,8 @@+---+'@astryxdesign/core': patch+'@astryxdesign/cli': patch+---++[feat] `createAnimator(element)` and its hook `useAnimator(ref)` animate one element with the motion Astryx's components use; the hook takes the element's ref, so a gesture hook can share the element. `animate` springs `x`, `y`, `scale`, `rotate` and `opacity` to a target on the state-change motion, `decay` coasts any of them from a release velocity, `set` jumps, `get` and `getVelocity` read, and `stop` halts; `animate` and `decay` return a promise. Reduce Motion is planned for every call. `createAnimator` is exported from the package root and `useAnimator` from `@astryxdesign/core/hooks`; the CLI's templates gain a playing-cards example of each.++@vjeuxdiff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.jsonindex 3e21c9b798..b209db8755 100644--- a/apps/sandbox/scripts/next-export-routes.json+++ b/apps/sandbox/scripts/next-export-routes.json@@ -61,6 +61,8 @@"/templates/","/templates/AlertDialogAsyncAction/","/templates/AlertDialogDeleteConfirmation/",+ "/templates/AnimatorPlayingCards/",+ "/templates/AnimatorPlayingCardsVanilla/","/templates/AppShellContentOnly/","/templates/AppShellMobileHookUsage/","/templates/AppShellShowcase/",diff --git a/docs/specs/AST-107-public-gesture-hooks/spec.md b/docs/specs/AST-107-public-gesture-hooks/spec.mdindex 9b2f6b4a8b..85fe7247c2 100644--- a/docs/specs/AST-107-public-gesture-hooks/spec.md+++ b/docs/specs/AST-107-public-gesture-hooks/spec.md@@ -108,7 +108,8 @@ animator2.destroy();`{state, translation, velocity}` as a drag on the element begins, changes,ends, or is cancelled. `axis` limits the drag to `'x'` or `'y'`. A finger,a mouse, and a pen all drive it (`spec:AST-094` FR43). It never- hands out a recognizer object, and it recognizes no press or long press.+ hands out a recognizer object, and it recognizes no press or long press. A+ cancelled pan reports `velocity` {0, 0}, so nothing flings on cancel.- **FR2 — `useDragToSnapPoints` settles an element on snap points.**`useDragToSnapPoints(ref, {axis, snapPoints, flickThreshold?, onSettle})`lets a drag move the element along `axis`, under@@ -150,7 +151,8 @@ animator2.destroy();curve is not offered. `animate` on a channel it does not know, any callbefore `ref` attaches, and any call after `destroy` do nothing and resolve atonce. A later `animate`, `decay`, `set`, or `stop` on a channel resolves that- channel's earlier promise where it stopped.+ channel's earlier promise where it stopped. A remount starts from the+ element's resting values; no animator values are kept after an unmount.- **FR4 — One hook per job.** `usePanGesture` does not do presses or longpresses, which `useLongPress` owns. `useAnimator` animates one element, and`useAnimatedLayout` animates an area (`spec:AST-105`). A component's own@@ -169,7 +171,10 @@ onSettle}) → {settleTo(index), destroy}`, and `createAnimator(element) →its factory and has no behavior of its own. `destroy` removes everylistener the factory added, and importing a factory does no DOM work, so itis safe on the server. No internal factory shares a public factory's name- (`architecture:react-component-runtime` INV13).+ (`architecture:react-component-runtime` INV13). `createPanGesture`'s+ `destroy()` during a drag reports `cancelled` once; `usePanGesture`'s+ unmount reports nothing (no callback after unmount). `decay` on `opacity`+ stops at 0 or 1.- **FR7 — Core and Lab use the public layer.** Wherever a public gesture ormotion API covers a component's job (the factories and hooks here,`createReorderable`, and `useAnimatedLayout`), Core and Lab components MUST@@ -272,6 +277,19 @@ factory that attaches to the element itself, with a thin hook, andRejected: a context menu reachable only through the `<ContextMenu>` wrapper.+### DEC-4 — Edge behaviors of the public animator and pan gesture++**Reference:** `spec:AST-107/DEC-4`+**Decider:** `cixzhang`, `2026-11-02`++A cancelled pan reports zero velocity; the factory's destroy() mid-drag+reports cancelled once and the hook's unmount reports nothing; an opacity+decay is clamped to 0–1; a remount starts from resting values.++Rejected: reporting the last velocity on cancel; callbacks after unmount;+unclamped opacity; keeping values across an unmount (a new keyed element+could inherit an off-screen position while still taking keyboard focus).+## Open questionsNone.diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.jsonindex 24f1d3591d..a7eb435b9c 100644--- a/internal/shadcn-registry/routes.lock.json+++ b/internal/shadcn-registry/routes.lock.json@@ -1961,6 +1961,11 @@"path": "examples/context-menu/bottom-sheet","aliases": []},+ {+ "name": "example-create-animator-playing-cards-in-plain-java-script",+ "path": "examples/create-animator/playing-cards-in-plain-java-script",+ "aliases": []+ },{"name": "example-date-input-clearable","path": "examples/date-input/clearable",@@ -3636,6 +3641,11 @@"path": "examples/typeahead/with-validation","aliases": []},+ {+ "name": "example-use-animator-playing-cards",+ "path": "examples/use-animator/playing-cards",+ "aliases": []+ },{"name": "example-use-app-shell-mobile-custom-mobile-trigger","path": "examples/use-app-shell-mobile/custom-mobile-trigger",@@ -3791,11 +3801,21 @@"path": "examples/visually-hidden/supplementary-context","aliases": []},+ {+ "name": "hook-create-animator",+ "path": "hooks/create-animator",+ "aliases": []+ },{"name": "hook-use-animated-layout","path": "hooks/use-animated-layout","aliases": []},+ {+ "name": "hook-use-animator",+ "path": "hooks/use-animator",+ "aliases": []+ },{"name": "hook-use-announce","path": "hooks/use-announce",diff --git a/packages/cli/assets/templates/blocks/components/createAnimator/AnimatorPlayingCardsVanilla.doc.mjs b/packages/cli/assets/templates/blocks/components/createAnimator/AnimatorPlayingCardsVanilla.doc.mjsnew file mode 100644index 0000000000..2573e34d27--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/createAnimator/AnimatorPlayingCardsVanilla.doc.mjs@@ -0,0 +1,14 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */+export const doc = {+ type: 'block',+ exampleFor: 'createAnimator',+ name: 'createAnimator — Playing cards in plain JavaScript',+ displayName: 'createAnimator — Playing cards in plain JavaScript',+ description:+ 'The playing card from the useAnimator example, built in plain JavaScript with createAnimator and pointer events: it follows a drag, springs back on a gentle release, flies off with momentum on a quick flick, and a button discards it from the keyboard. React only mounts it.',+ isReady: true,+ aspectRatio: 4 / 3,+ componentsUsed: [],+};diff --git a/packages/cli/assets/templates/blocks/components/createAnimator/AnimatorPlayingCardsVanilla.tsx b/packages/cli/assets/templates/blocks/components/createAnimator/AnimatorPlayingCardsVanilla.tsxnew file mode 100644index 0000000000..66fa59ecd5--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/createAnimator/AnimatorPlayingCardsVanilla.tsx@@ -0,0 +1,199 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {createAnimator} from '@astryxdesign/core';++const DECK = [+ {face: 'A\u2660', name: 'Ace of spades'},+ {face: 'K\u2665', name: 'King of hearts'},+ {face: 'Q\u2663', name: 'Queen of clubs'},+ {face: 'J\u2666', name: 'Jack of diamonds'},+];+/** A release faster than this (px/s) throws the card away. */+const THROW_SPEED = 1000;+/** The slowest throw, so a thrown card always leaves the table. */+const MIN_THROW = 1600;++/**+ * A deck on a table, in plain JavaScript: no React below this line. It+ * returns a function that takes it down again.+ */+function mountDeck(table: HTMLElement, discardButton: HTMLButtonElement) {+ let top = 0;+ const card = document.createElement('div');+ card.textContent = DECK[0].face;+ // An image's name is all a screen reader announces, so it names the card.+ card.setAttribute('role', 'img');+ card.setAttribute('aria-label', DECK[0].name);+ Object.assign(card.style, {+ width: '120px',+ height: '170px',+ display: 'grid',+ placeItems: 'center',+ font: 'bold 40px system-ui, sans-serif',+ // The theme's surface and text, so the rank reads in light and dark.+ borderRadius: 'var(--radius-container)',+ backgroundColor: 'var(--color-background-surface)',+ color: 'var(--color-text-primary)',+ boxShadow: '0 2px 8px var(--color-shadow)',+ touchAction: 'none',+ cursor: 'grab',+ userSelect: 'none',+ });+ // Announces each discard to screen readers.+ const status = document.createElement('div');+ status.setAttribute('aria-live', 'polite');+ Object.assign(status.style, {+ position: 'absolute',+ width: '1px',+ height: '1px',+ overflow: 'hidden',+ clipPath: 'inset(50%)',+ whiteSpace: 'nowrap',+ });+ table.append(card, status);+ const animator = createAnimator(card);+ // One discard at a time: a press while a card leaves deals no second card.+ let isDiscarding = false;++ // Announces the discard and deals the next card in place of the old one.+ async function dealNext() {+ status.textContent = `${DECK[top % DECK.length].name} discarded`;+ top += 1;+ const next = DECK[top % DECK.length];+ card.textContent = next.face;+ card.setAttribute('aria-label', next.name);+ animator.set({x: 0, y: 0, rotate: 0, scale: 0.9, opacity: 0});+ isDiscarding = false;+ await animator.animate({scale: 1, opacity: 1});+ }++ // Starts a discard unless one runs. It also ends a drag in progress: the+ // drag's next move would take the discard's motion over and drag the dealt+ // card.+ function startDiscard() {+ if (isDiscarding) {+ return false;+ }+ isDiscarding = true;+ origin = null;+ return true;+ }++ async function discard(vx: number, vy: number) {+ if (!startDiscard()) {+ return;+ }+ const speed = Math.hypot(vx, vy);+ const boost = speed < MIN_THROW ? MIN_THROW / Math.max(speed, 1) : 1;+ // The card coasts on while it fades; once it is gone, the next card is+ // dealt in place, which ends the coast. A coast continues the person's+ // throw, so Reduce Motion keeps it.+ void animator.decay({x: speed < 1 ? MIN_THROW : vx * boost, y: vy * boost});+ await animator.animate({opacity: 0});+ await dealNext();+ }++ // The drag: follow the pointer, then read the 80 ms before the release, so+ // a pointer that held still before letting go releases at rest.+ let origin: {x: number; y: number} | null = null;+ let samples: {t: number; x: number; y: number}[] = [];+ function onDown(event: PointerEvent) {+ // A leaving card takes no press. Pinning it would end its discard and deal+ // the next card under the finger.+ if (isDiscarding) {+ return;+ }+ card.setPointerCapture(event.pointerId);+ // Pins the card where it shows, so the drag starts there. Only the+ // position stops, so a card fading in keeps fading in.+ const {x, y, rotate} = animator.get();+ animator.set({x, y, rotate});+ origin = {x: event.clientX - x, y: event.clientY - y};+ samples = [];+ }+ function onMove(event: PointerEvent) {+ if (origin == null) {+ return;+ }+ const x = event.clientX - origin.x;+ const y = event.clientY - origin.y;+ samples.push({t: event.timeStamp, x, y});+ animator.set({x, y, rotate: x / 18});+ }+ // A cancelled pointer was not let go, so the card springs back.+ function onCancel() {+ if (origin == null) {+ return;+ }+ origin = null;+ void animator.animate({x: 0, y: 0, rotate: 0});+ }+ function onUp(event: PointerEvent) {+ if (origin == null) {+ return;+ }+ origin = null;+ const recent = samples.filter(s => event.timeStamp - s.t <= 80);+ const first = recent[0];+ const last = recent.at(-1);+ const seconds = last && first ? (last.t - first.t) / 1000 : 0;+ const vx = seconds > 0 && last && first ? (last.x - first.x) / seconds : 0;+ const vy = seconds > 0 && last && first ? (last.y - first.y) / seconds : 0;+ if (Math.abs(vx) > THROW_SPEED) {+ void discard(vx, vy);+ } else {+ void animator.animate(+ {x: 0, y: 0, rotate: 0},+ {velocity: {x: vx, y: vy}},+ );+ }+ }+ // The button moves the card off on the state-change motion: a planned+ // move, which Reduce Motion turns into a fade where the card is.+ async function discardWithButton() {+ if (!startDiscard()) {+ return;+ }+ await animator.animate({x: 400, opacity: 0});+ await dealNext();+ }+ const onDiscard = () => void discardWithButton();++ card.addEventListener('pointerdown', onDown);+ card.addEventListener('pointermove', onMove);+ card.addEventListener('pointerup', onUp);+ card.addEventListener('pointercancel', onCancel);+ discardButton.addEventListener('click', onDiscard);+ return () => {+ discardButton.removeEventListener('click', onDiscard);+ animator.destroy();+ card.remove();+ status.remove();+ };+}++/**+ * Mounts the deck when the wrapper attaches, and takes it down when it+ * detaches: its cleanup is the callback ref's.+ */+function mountTable(wrapper: HTMLDivElement | null) {+ if (wrapper == null) {+ return undefined;+ }+ const table = wrapper.firstElementChild as HTMLElement;+ const button = wrapper.querySelector('button') as HTMLButtonElement;+ return mountDeck(table, button);+}++export default function AnimatorPlayingCardsVanilla() {+ return (+ <div+ ref={mountTable}+ style={{display: 'grid', gap: 16, padding: 16, maxWidth: 360}}>+ <div style={{height: 200, display: 'grid', placeItems: 'center'}} />+ <button type="button">Discard the top card</button>+ </div>+ );+}diff --git a/packages/cli/assets/templates/blocks/components/useAnimator/AnimatorPlayingCards.doc.mjs b/packages/cli/assets/templates/blocks/components/useAnimator/AnimatorPlayingCards.doc.mjsnew file mode 100644index 0000000000..bcb27e22f6--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/useAnimator/AnimatorPlayingCards.doc.mjs@@ -0,0 +1,21 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */+export const doc = {+ type: 'block',+ exampleFor: 'useAnimator',+ name: 'useAnimator — Playing cards',+ displayName: 'useAnimator — Playing cards',+ description:+ 'A playing card that follows a drag: a gentle release springs it back on its release velocity, and a quick flick throws it away with momentum before the next card is dealt. A Discard button moves it off from the keyboard, fading it in place under Reduce Motion, and the discard is announced. Built only on the public useAnimator hook.',+ isReady: true,+ aspectRatio: 4 / 3,+ componentsUsed: [+ 'Card',+ 'Button',+ 'Layout',+ 'Text',+ 'VisuallyHidden',+ 'useAnimator',+ ],+};diff --git a/packages/cli/assets/templates/blocks/components/useAnimator/AnimatorPlayingCards.tsx b/packages/cli/assets/templates/blocks/components/useAnimator/AnimatorPlayingCards.tsxnew file mode 100644index 0000000000..3dd8e21ac7--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/useAnimator/AnimatorPlayingCards.tsx@@ -0,0 +1,210 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {useRef, useState} from 'react';+import type {PointerEvent} from 'react';+import {Button} from '@astryxdesign/core/Button';+import {Card} from '@astryxdesign/core/Card';+import {useAnimator} from '@astryxdesign/core/hooks';+import {HStack, VStack} from '@astryxdesign/core/Layout';+import {Text} from '@astryxdesign/core/Text';+import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';++const DECK = [+ {rank: 'A', suit: '\u2660', name: 'Ace of spades'},+ {rank: 'K', suit: '\u2665', name: 'King of hearts'},+ {rank: 'Q', suit: '\u2663', name: 'Queen of clubs'},+ {rank: 'J', suit: '\u2666', name: 'Jack of diamonds'},+];++/** A release faster than this (px/s) throws the card away. */+const THROW_SPEED = 1000;+/** The slowest throw, so a thrown card always leaves the table. */+const MIN_THROW = 1600;++interface Sample {+ t: number;+ x: number;+ y: number;+}++/**+ * The release velocity in px/s, over the 80 ms before the release: a finger+ * that held still before letting go releases at rest.+ */+function releaseVelocity(+ samples: Sample[],+ releasedAt: number,+): {x: number; y: number} {+ const recent = samples.filter(s => releasedAt - s.t <= 80);+ const first = recent[0];+ const last = recent.at(-1);+ if (last == null || first == null || last.t === first.t) {+ return {x: 0, y: 0};+ }+ const seconds = (last.t - first.t) / 1000;+ return {x: (last.x - first.x) / seconds, y: (last.y - first.y) / seconds};+}++export default function AnimatorPlayingCards() {+ const ref = useRef<HTMLDivElement>(null);+ const animator = useAnimator(ref);+ const [top, setTop] = useState(0);+ const [status, setStatus] = useState('');+ const drag = useRef<{start: Sample; samples: Sample[]} | null>(null);+ // One discard at a time: a press while a card leaves deals no second card.+ const discarding = useRef(false);+ const card = DECK[top % DECK.length];++ // Announces the discard and deals the next card in place of the old one.+ const dealNext = async () => {+ setStatus(`${card.name} discarded`);+ setTop(index => index + 1);+ animator.set({x: 0, y: 0, rotate: 0, scale: 0.9, opacity: 0});+ discarding.current = false;+ await animator.animate({scale: 1, opacity: 1});+ };++ // Starts a discard unless one runs. It also ends a drag in progress: the+ // drag's next move would take the discard's motion over and drag the dealt+ // card.+ const startDiscard = () => {+ if (discarding.current) {+ return false;+ }+ discarding.current = true;+ drag.current = null;+ return true;+ };++ // Throws the card away on its release velocity, then deals the next one.+ const discard = async (velocity: {x: number; y: number}) => {+ if (!startDiscard()) {+ return;+ }+ const speed = Math.hypot(velocity.x, velocity.y);+ const boost = speed < MIN_THROW ? MIN_THROW / Math.max(speed, 1) : 1;+ const throwX = speed < 1 ? MIN_THROW : velocity.x * boost;+ // The card coasts on while it fades; once it is gone, the next card is+ // dealt in place, which ends the coast. A coast continues the person's+ // throw, so Reduce Motion keeps it.+ void animator.decay({x: throwX, y: velocity.y * boost});+ await animator.animate({opacity: 0});+ await dealNext();+ };++ // The button moves the card off on the state-change motion: a planned+ // move, which Reduce Motion turns into a fade where the card is.+ const discardWithButton = async () => {+ if (!startDiscard()) {+ return;+ }+ await animator.animate({x: 400, opacity: 0});+ await dealNext();+ };++ const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {+ // A leaving card takes no press. Pinning it would end its discard and deal+ // the next card under the finger.+ if (discarding.current) {+ return;+ }+ event.currentTarget.setPointerCapture(event.pointerId);+ // Pins the card where it shows, so the drag starts there. Only the+ // position stops, so a card fading in keeps fading in.+ const {x, y, rotate} = animator.get();+ animator.set({x, y, rotate});+ const start = {+ t: event.timeStamp,+ x: event.clientX - x,+ y: event.clientY - y,+ };+ drag.current = {start, samples: []};+ };++ const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {+ const current = drag.current;+ if (current == null) {+ return;+ }+ const x = event.clientX - current.start.x;+ const y = event.clientY - current.start.y;+ current.samples.push({t: event.timeStamp, x, y});+ // The card follows the finger, turning a little with the drag.+ animator.set({x, y, rotate: x / 18});+ };++ // A cancelled pointer was not let go, so the card springs back.+ const onPointerCancel = () => {+ if (drag.current == null) {+ return;+ }+ drag.current = null;+ void animator.animate({x: 0, y: 0, rotate: 0});+ };++ const onPointerUp = (event: PointerEvent<HTMLDivElement>) => {+ const current = drag.current;+ drag.current = null;+ if (current == null) {+ return;+ }+ const velocity = releaseVelocity(current.samples, event.timeStamp);+ if (Math.abs(velocity.x) > THROW_SPEED) {+ void discard(velocity);+ } else {+ // A gentle release springs back, carrying on as it was let go.+ void animator.animate({x: 0, y: 0, rotate: 0}, {velocity});+ }+ };++ return (+ <VStack gap={4} style={{maxWidth: 360, padding: 16}}>+ <Text type="body">+ Drag the card and let go. A gentle release springs it back; a quick+ flick throws it away.+ </Text>+ <div style={{height: 200, display: 'grid', placeItems: 'center'}}>+ <Card+ ref={ref}+ width={120}+ minHeight={170}+ onPointerDown={onPointerDown}+ onPointerMove={onPointerMove}+ onPointerUp={onPointerUp}+ onPointerCancel={onPointerCancel}+ style={{touchAction: 'none', cursor: 'grab', userSelect: 'none'}}+ role="img"+ aria-label={card.name}>+ <VStack gap={1} hAlign="center" style={{paddingBlock: 40}}>+ <Text type="display-2" weight="bold">+ {card.rank}+ </Text>+ <Text type="display-3">{card.suit}</Text>+ </VStack>+ </Card>+ </div>+ <HStack gap={2}>+ <Button+ label={`Discard ${card.name}`}+ variant="secondary"+ onClick={() => void discardWithButton()}+ />+ <Button+ label="Shake"+ variant="ghost"+ onClick={() =>+ void animator.animate(+ {x: 0, rotate: 0},+ {velocity: {x: 900, rotate: 300}},+ )+ }+ />+ </HStack>+ <VisuallyHidden as="div" aria-live="polite">+ {status}+ </VisuallyHidden>+ </VStack>+ );+}diff --git a/packages/cli/foundation/doc-compiler/inputs.test.mjs b/packages/cli/foundation/doc-compiler/inputs.test.mjsindex 5673a5fa42..d62219b047 100644--- a/packages/cli/foundation/doc-compiler/inputs.test.mjs+++ b/packages/cli/foundation/doc-compiler/inputs.test.mjs@@ -97,6 +97,7 @@ describe('collectDocInputs over what this repo ships', () => {'NavMenu','Resizable','SyntaxTheme',+ 'createAnimator',]);});diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon-set.json b/packages/cli/test/__golden__/no-icon-set/search-icon-set.jsonindex 7536f0bfee..def019d8a7 100644--- a/packages/cli/test/__golden__/no-icon-set/search-icon-set.json+++ b/packages/cli/test/__golden__/no-icon-set/search-icon-set.json@@ -3,7 +3,7 @@"type": "search","data": {"query": "icon set",- "matchCount": 375,+ "matchCount": 376,"results": [{"domain": "doc",diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt b/packages/cli/test/__golden__/no-icon-set/search-icon-set.txtindex 58aa4db9ef..09f6742a78 100644--- a/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt+++ b/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt@@ -1,4 +1,4 @@-Results for "icon set" (20 of 375)+Results for "icon set" (20 of 376)name: authoring/building-blocks/templates/build-the-template/template-assets/template-iconssection: use-astryx-icondomain: docdiff --git a/packages/core/api-report.md b/packages/core/api-report.mdindex d407090e5c..b23935f5fb 100644--- a/packages/core/api-report.md+++ b/packages/core/api-report.md@@ -2855,6 +2855,7 @@ component VisuallyHidden(props: VisuallyHiddenProps)```texthook useAnimatedLayout: ({…}: UseAnimatedLayoutOptions) => AnimatedLayout+hook useAnimator: (ref: RefObject<HTMLElement | null>) => AnimatorHandlehook useAnnounce: ({…}?: UseAnnounceOptions) => AnnounceFnhook useAppShellMobile: () => AppShellMobileContextValuehook useAvatarGroup: () => AvatarGroupContextValue | null@@ -2978,6 +2979,7 @@ function compactDefinition: (points?: Readonly<Pick<WidthBreakpoints, 'md'>>) =>function compareTime: (a: ISOTimeString | undefined, b: ISOTimeString | undefined) => numberfunction composeEventHandlers: <E extends SyntheticEvent>(...handlers: (((event: E) => void) | undefined)[]) => (event: E) => voidfunction container: ({…}: ContainerOptions) => readonly [Readonly<{ readonly boxSizing: stylex.StyleXClassNameFor<"boxSizing", "border-box">; readonly paddingInlineStart: stylex.StyleXClassNameFor<"paddingIn … #72b9b91f+function createAnimator: (element: HTMLElement) => Animatorfunction createCodeLanguage: ({…}: CreateCodeLanguageOptions) => CodeLanguagefunction createISOTimeString: (value: string) => ISOTimeString | nullfunction createIncrementalState: <MathEnabled extends boolean = false>() => IncrementalState<MathEnabled>@@ -3498,6 +3500,27 @@ const typographyVars: stylex.VarGroup<Readonly<{ readonly '--font-family-body':interface AlertDialogProps extends BaseProps<HTMLDialogElement> (props of AlertDialog)interface AnimatedLayout[AREA]: () => Element | null+interface Animator extends AnimatorHandle+ animate: (target: AnimatorValues, options?: AnimatorAnimateOptions) => Promise<void>+ decay: (velocity: AnimatorDecayVelocity) => Promise<void>+ destroy: () => void+ get: () => AnimatorSnapshot+ getVelocity: () => AnimatorSnapshot+ set: (values: AnimatorValues) => void+ stop: () => void+interface AnimatorAnimateOptions+ velocity?: AnimatorValues+type AnimatorChannel = 'x' | 'y' | 'scale' | 'rotate' | 'opacity'+type AnimatorDecayVelocity = AnimatorValues+interface AnimatorHandle+ animate: (target: AnimatorValues, options?: AnimatorAnimateOptions) => Promise<void>+ decay: (velocity: AnimatorDecayVelocity) => Promise<void>+ get: () => AnimatorSnapshot+ getVelocity: () => AnimatorSnapshot+ set: (values: AnimatorValues) => void+ stop: () => void+type AnimatorSnapshot = Readonly<Record<AnimatorChannel, number>>+type AnimatorValues = Partial<Record<AnimatorChannel, number>>type AnnounceFn = (message: string, politeness?: AnnouncePoliteness) => voidtype AnnouncePoliteness = 'polite' | 'assertive'type AppShellBreakpoint = WidthBreakpointName | 'none'@@ -9104,6 +9127,7 @@ hasTextSelection (.)isMenuPressActivation (.)menuPressStep (.)useAnimatedLayout (.)+useAnimator (.)useAnnounce (.)useClickableContainer (.)useClipboard (.)diff --git a/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.test.ts b/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.test.tsindex 204086bd2c..f88dc63b3b 100644--- a/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.test.ts+++ b/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.test.ts@@ -13,7 +13,7 @@import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';import {motionRoleOf} from '../motion/roles';-import {createAnimator, type Animator} from '../motion/animator';+import {createMotionAnimator, type Animator} from '../motion/animator';import {solveSpring, toSpring} from '../motion/spring';import {cubicBezier} from '../motion/bezier';import {segmentedControl, springs} from '../motion/uikit';@@ -105,12 +105,12 @@ function setup(selected: string, {coarse = true}: {coarse?: boolean} = {}) {document.head.append(style);document.body.append(track);// A finger by default: Reduced Motion fades (design:reduced-motion DR2).- const animator: Animator = createAnimator(null, {+ const animator: Animator = createMotionAnimator(null, {now: () => clock,pseudoElement: '::before',});// The ::after: the lifted lens's shadow, or the surface fading out.- const afterAnimator: Animator = createAnimator(null, {+ const afterAnimator: Animator = createMotionAnimator(null, {now: () => clock,pseudoElement: '::after',initial: {opacity: 0},diff --git a/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts b/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.tsindex 0428ca171b..69e10fba73 100644--- a/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts+++ b/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts@@ -25,7 +25,7 @@ import {type RefObject,} from 'react';import {- createAnimator,+ createMotionAnimator,type AnimateOptions,type Animator,type MotionCurve,@@ -539,7 +539,7 @@ export class SegmentedSelectionMotion {private readonly after: Animator;constructor(- private readonly animator: Animator = createAnimator(null, {+ private readonly animator: Animator = createMotionAnimator(null, {pseudoElement: '::before',}),options: SegmentedSelectionMotionOptions = {},@@ -552,7 +552,10 @@ export class SegmentedSelectionMotion {this.now = options.now ?? defaultNow;this.after =options.afterAnimator ??- createAnimator(null, {pseudoElement: '::after', initial: {opacity: 0}});+ createMotionAnimator(null, {+ pseudoElement: '::after',+ initial: {opacity: 0},+ });}/** Attaches the radiogroup whose pseudo-elements are the lens (null detaches). */diff --git a/packages/core/src/Slider/sliderTouchController.ts b/packages/core/src/Slider/sliderTouchController.tsindex 7423076681..5d90e247e1 100644--- a/packages/core/src/Slider/sliderTouchController.ts+++ b/packages/core/src/Slider/sliderTouchController.ts@@ -29,7 +29,7 @@ import {TapGestureRecognizer} from '../gestures/TapGestureRecognizer';import type {PointerKind} from '../gestures/types';import {isRtlElement} from '../hooks/isRtlElement';import {- createAnimator,+ createMotionAnimator,type Animator,type MotionCurve,type MotionHandle,@@ -1186,7 +1186,7 @@ export class SliderTouchController {private animatorFor(element: HTMLElement): Animator {let animator = this.animators.get(element);if (animator == null) {- animator = createAnimator(element);+ animator = createMotionAnimator(element);this.animators.set(element, animator);}return animator;diff --git a/packages/core/src/Switch/useSwitchTouch.test.ts b/packages/core/src/Switch/useSwitchTouch.test.tsindex c8b2b3e44f..63fd79d077 100644--- a/packages/core/src/Switch/useSwitchTouch.test.ts+++ b/packages/core/src/Switch/useSwitchTouch.test.ts@@ -39,7 +39,7 @@ vi.mock('../motion/animator', async importOriginal => {const actual = await importOriginal<typeof AnimatorModule>();return {...actual,- createAnimator: (+ createMotionAnimator: (element: Element,options: {pseudoElement?: string} = {},) => {diff --git a/packages/core/src/Switch/useSwitchTouch.ts b/packages/core/src/Switch/useSwitchTouch.tsindex 0252a47587..2422dc0f47 100644--- a/packages/core/src/Switch/useSwitchTouch.ts+++ b/packages/core/src/Switch/useSwitchTouch.ts@@ -23,7 +23,7 @@ import type {GestureTouch} from '../gestures/types';import {isRtlElement} from '../hooks/isRtlElement';import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';import {- createAnimator,+ createMotionAnimator,type Animator,type MotionCurve,} from '../motion/animator';@@ -282,15 +282,15 @@ export class SwitchTouchController {return;}registerSwitchTable();- this.thumb = createAnimator(elements.thumb);+ this.thumb = createMotionAnimator(elements.thumb);// The layer rests clear (its class's opacity 0) while the visuals show// the value; from here its opacity is the animator's.- this.fade = createAnimator(elements.track, {+ this.fade = createMotionAnimator(elements.track, {pseudoElement: '::after',initial: {opacity: 0},});this.fade.set({opacity: 0});- this.shadow = createAnimator(elements.thumb, {+ this.shadow = createMotionAnimator(elements.thumb, {pseudoElement: '::after',initial: {opacity: 0},});diff --git a/packages/core/src/animator/__tests__/animatorBundle.ts b/packages/core/src/animator/__tests__/animatorBundle.tsnew file mode 100644index 0000000000..586ac9add9--- /dev/null+++ b/packages/core/src/animator/__tests__/animatorBundle.ts@@ -0,0 +1,14 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file animatorBundle.ts+ * @input The public animator and the math to check it against+ * @output Re-exports them as one entry point+ * @position The esbuild entry createAnimator.interaction.browser.spec.ts+ * bundles into its page (global `PublicAnimator`), and that global's type+ */++export {createAnimator} from '../createAnimator';+export {solveDecay} from '../../motion/decay';+export {solveSpring, toSpring} from '../../motion/spring';+export {springs} from '../../motion/uikit/springs';diff --git a/packages/core/src/animator/__tests__/createAnimator.interaction.browser.spec.ts b/packages/core/src/animator/__tests__/createAnimator.interaction.browser.spec.tsnew file mode 100644index 0000000000..45774a8a68--- /dev/null+++ b/packages/core/src/animator/__tests__/createAnimator.interaction.browser.spec.ts@@ -0,0 +1,222 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file createAnimator.interaction.browser.spec.ts+ * @input The public animator (createAnimator), bundled with esbuild onto a+ * blank fixture page. Chromium and WebKit run it on the phone profile, and+ * a desktop context gives a fine pointer.+ * @output Proof of the public animator in a real engine. `animate` plays the+ * `springs.stateChange` curve on screen, seeked frame by frame. It rests on+ * its target when its promise resolves. `decay` coasts to the analytic rest+ * of the normal deceleration. `stop` holds the box where it is. Under+ * Reduce Motion, a move cross-fades on a touch screen, and the box jumps+ * only while transparent. With a mouse, it lands at once.+ * @position Browser proof for animator/createAnimator.ts, run by+ * `pnpm test:interaction`; jsdom runs no animations+ */++import {fileURLToPath} from 'node:url';+import {expect, test, type Page} from '@playwright/test';+import {build} from 'esbuild';+import type * as Bundle from './animatorBundle';+import type {Animator} from '../createAnimator';++declare global {+ interface Window {+ PublicAnimator: typeof Bundle;+ card: Animator;+ }+}++let script = '';++test.beforeAll(async () => {+ const result = await build({+ entryPoints: [+ fileURLToPath(new URL('./animatorBundle.ts', import.meta.url)),+ ],+ bundle: true,+ write: false,+ format: 'iife',+ globalName: 'PublicAnimator',+ target: 'es2022',+ });+ script = result.outputFiles[0].text;+});++const TRAVEL = 300;++// A real navigation (not setContent): the page keeps its own window.+async function open(page: Page) {+ const html = `<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1">+<style>+ html, body { margin: 0; background: #fff; }+ #card { position: absolute; top: 40px; left: 0; width: 48px; height: 64px; background: #36c; border-radius: 6px; }+</style>+<div id="card"></div>+<script>${script}</script>+<script>window.card = PublicAnimator.createAnimator(document.getElementById('card'));</script>`;+ await page.route('http://animator.test/', async route =>+ route.fulfill({contentType: 'text/html', body: html}),+ );+ await page.goto('http://animator.test/');+}++/** The card's left edge on screen. */+async function left(page: Page): Promise<number> {+ return page.evaluate(+ () =>+ (document.getElementById('card') as HTMLElement).getBoundingClientRect()+ .left,+ );+}++test('animate plays the springs.stateChange curve on screen, seeked frame by frame', async ({+ page,+}) => {+ await open(page);+ const rows = await page.evaluate(async travel => {+ void window.card.animate({x: travel});+ // Let the browser commit the motion, then hold it to seek.+ await new Promise(requestAnimationFrame);+ await new Promise(requestAnimationFrame);+ const animations = document.getAnimations();+ for (const animation of animations) {+ animation.pause();+ }+ const {solveSpring, toSpring, springs} = window.PublicAnimator;+ const curve = solveSpring(toSpring(springs.stateChange), {+ from: 0,+ to: travel,+ });+ const card = document.getElementById('card') as HTMLElement;+ return [40, 120, 250, 400, 650].map(ms => {+ for (const animation of animations) {+ animation.currentTime = ms;+ }+ return {+ ms,+ onScreen: card.getBoundingClientRect().left,+ expected: curve.value(ms / 1000),+ };+ });+ }, TRAVEL);+ for (const {ms, onScreen, expected} of rows) {+ expect(Math.abs(onScreen - expected), `at ${ms} ms`).toBeLessThan(0.5);+ }+ // It moves: the samples are not all at one end.+ expect(rows[0].onScreen).toBeLessThan(rows[rows.length - 1].onScreen);+});++test('animate resolves with the card resting on its target', async ({page}) => {+ await open(page);+ await page.evaluate(async travel => {+ await window.card.animate({x: travel});+ }, TRAVEL);+ expect(await left(page)).toBeCloseTo(TRAVEL, 0);+ const values = await page.evaluate(() => window.card.get());+ expect(values.x).toBeCloseTo(TRAVEL, 3);+});++test('decay coasts to the rest of the normal deceleration', async ({page}) => {+ await open(page);+ const rest = await page.evaluate(async () => {+ await window.card.decay({x: 900});+ return window.PublicAnimator.solveDecay({from: 0, velocity: 900}).rest;+ });+ expect(Math.abs((await left(page)) - rest)).toBeLessThan(1);+});++test('stop holds the card where it is on screen', async ({page}) => {+ await open(page);+ const held = await page.evaluate(async travel => {+ void window.card.animate({x: travel});+ await new Promise(resolve => setTimeout(resolve, 150));+ // A busy machine can draw no frame in that time, and nothing moves+ // before one. Wait for the frame that commits the move, and the next.+ await new Promise(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(resolve)),+ );+ window.card.stop();+ return window.card.get().x;+ }, TRAVEL);+ expect(held).toBeGreaterThan(0);+ expect(held).toBeLessThan(TRAVEL);+ await page.waitForTimeout(400);+ expect(Math.abs((await left(page)) - held)).toBeLessThan(0.5);+});++test('under Reduce Motion on a touch screen, a move cross-fades: the card jumps only while transparent', async ({+ page,+}) => {+ await page.emulateMedia({reducedMotion: 'reduce'});+ await open(page);+ // Sampled every frame in real time. The travel lands with a style write at+ // the bottom of the fade, and no seek of the running animations shows it.+ // A first cross-fade warms the page up (a fresh WebKit page skips frames+ // for about 100 ms); the second, back home, is the one measured.+ const frames = await page.evaluate(async travel => {+ const card = document.getElementById('card') as HTMLElement;+ await window.card.animate({x: travel});+ const samples: {left: number; opacity: number}[] = [];+ let done = false;+ void window.card.animate({x: 0}).then(() => {+ done = true;+ });+ while (!done && samples.length < 120) {+ await new Promise(requestAnimationFrame);+ samples.push({+ left: card.getBoundingClientRect().left,+ opacity: Number(getComputedStyle(card).opacity),+ });+ }+ return samples;+ }, TRAVEL);+ // Never between the ends: the travel is substituted, not slowed.+ for (const {left: x} of frames) {+ expect(x === 0 || Math.abs(x - TRAVEL) < 0.5, `left ${x}`).toBe(true);+ }+ const jump = frames.findIndex(f => f.left === 0);+ expect(jump).toBeGreaterThan(0);+ // It fades out where it was, lands at the bottom of the fade, and fades+ // back in where it landed. It never shows moving, and it never brightens+ // before it lands.+ const before = frames.slice(0, jump).map(f => f.opacity);+ const after = frames.slice(jump).map(f => f.opacity);+ for (let i = 1; i < before.length; i++) {+ expect(before[i]).toBeLessThanOrEqual(before[i - 1] + 0.01);+ }+ for (let i = 1; i < after.length; i++) {+ expect(after[i]).toBeGreaterThanOrEqual(after[i - 1] - 0.01);+ }+ expect(Math.min(before[before.length - 1], after[0])).toBeLessThan(0.1);+ expect(frames[frames.length - 1].opacity).toBeCloseTo(1, 2);+});++test('under Reduce Motion with a mouse, a move lands at once', async ({+ browser,+}) => {+ const context = await browser.newContext({+ viewport: {width: 800, height: 600},+ hasTouch: false,+ isMobile: false,+ reducedMotion: 'reduce',+ });+ const page = await context.newPage();+ try {+ await open(page);+ const coarse = await page.evaluate(+ () => matchMedia('(pointer: coarse)').matches,+ );+ expect(coarse).toBe(false);+ const sameTask = await page.evaluate(travel => {+ void window.card.animate({x: travel});+ return (+ document.getElementById('card') as HTMLElement+ ).getBoundingClientRect().left;+ }, TRAVEL);+ expect(sameTask).toBeCloseTo(TRAVEL, 0);+ } finally {+ await context.close();+ }+});diff --git a/packages/core/src/animator/createAnimator.doc.mjs b/packages/core/src/animator/createAnimator.doc.mjsnew file mode 100644index 0000000000..47c2bc05a3--- /dev/null+++ b/packages/core/src/animator/createAnimator.doc.mjs@@ -0,0 +1,153 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').HookDoc} */+export const docs = {+ name: 'createAnimator',+ displayName: 'createAnimator',+ // A factory documented as a hook: listed with the utilities, beside its+ // hook, not as a tile in the components gallery.+ group: 'Utilities',+ keywords: [+ 'animate',+ 'animation',+ 'animator',+ 'spring',+ 'decay',+ 'momentum',+ 'fling',+ 'motion',+ 'transform',+ 'opacity',+ 'vanilla',+ 'factory',+ ],+ params: [+ {+ name: 'element',+ type: 'HTMLElement',+ description:+ 'The element to animate. The animator writes its `translate`, `scale`, `rotate` and `opacity`, and while it moves an inline `will-change` for them, merged with any it already has and restored 500 ms after its last motion; nothing else, so lay it out and style it as usual. Use one animator per element: two on one element overwrite each other.',+ required: true,+ },+ ],+ returns: [+ {+ name: 'animate',+ type: '(target: {x?, y?, scale?, rotate?, opacity?}, options?: {velocity?}) => Promise<void>',+ description:+ "Springs the given channels to `target` from wherever they are on screen, on the state-change motion Astryx's components use, and resolves when they arrive (or as soon as a later call takes them over). `x` and `y` are px, `scale` is 1 at the element's size, `rotate` is degrees and `opacity` runs from 0 to 1. Pass `velocity` (units per second, such as a drag's release velocity) to start with it; without it a channel keeps the velocity it has on screen, so interrupting a motion never jumps.",+ },+ {+ name: 'decay',+ type: '(velocity: {x?, y?, scale?, rotate?, opacity?}) => Promise<void>',+ description:+ "Coasts the given channels from a release velocity in their units per second, slowing as a scroll view's momentum does, and resolves when they stop (or as soon as a later call takes any of them over); opacity stops at 0 or 1. The distance follows from the velocity: use it to fling something away, then remove or reset it.",+ },+ {+ name: 'set',+ type: '(values: {x?, y?, scale?, rotate?, opacity?}) => void',+ description:+ 'Puts the given channels at these values at once, ending their motion: follow a finger with it, frame by frame.',+ },+ {+ name: 'get',+ type: '() => {x, y, scale, rotate, opacity}',+ description: "Every channel's value on screen now.",+ },+ {+ name: 'getVelocity',+ type: '() => {x, y, scale, rotate, opacity}',+ description:+ "Every channel's velocity on screen now, in units per second.",+ },+ {+ name: 'stop',+ type: '() => void',+ description: 'Halts every channel where it is on screen.',+ },+ {+ name: 'destroy',+ type: '() => void',+ description:+ 'Stops every motion and lets the element go; the element keeps the values it shows. Call it when you remove the element or no longer animate it.',+ },+ ],+ usage: {+ description:+ "Animates one element with the motion Astryx's own components use, without React. `animate` springs an element to new values on the state-change motion, `decay` flings it with the momentum of a released scroll view, and `set` moves it directly, so a card can follow a finger, snap back and be thrown away. Use the `useAnimator` hook in React. To animate an area's layout as its items change, use `useAnimatedLayout`; for what a component already animates, such as a sheet's detents or a carousel's snapping, use the component's own props.",+ bestPractices: [+ {+ guidance: true,+ description:+ 'Start every `animate` that follows a drag with the release velocity, so the element carries on as it was thrown.',+ },+ {+ guidance: true,+ description:+ 'Reach every state an animation shows without the animation too: a key, a button or a menu item that calls the same code.',+ },+ {+ guidance: true,+ description:+ '`await` the promise before removing an element you animate out, and call `destroy` once it is gone.',+ },+ {+ guidance: false,+ description:+ 'Read the element\u2019s position from layout while it moves: `get` gives the value on screen, wherever the motion runs.',+ },+ ],+ accessibility: [+ {+ name: 'Keyboard and assistive technology',+ category: 'Keyboard',+ description:+ 'An animator moves an element; it adds no way to act. Give every action an animation stands for a control a keyboard and a screen reader can reach, such as a button that discards a card, and have it call `animate`, which Reduce Motion turns into a fade in place. Keep `decay` for a throw the person made: Reduce Motion keeps the momentum of a coast, as it continues that throw. Keep focus on an element that stays on screen: move it before you fling its element away.',+ },+ {+ name: 'Reduce Motion',+ category: 'Content',+ criterion: '2.3.3 Animation from Interactions',+ description:+ 'When the person asks for reduced motion, every call is planned for them. On a touch screen a move or a scale becomes a short opacity cross-fade: the element fades out where it was and fades back in where it lands. With a mouse it lands at once. A decay of `x` and `y` keeps its momentum, as it continues the throw the person made; a decay of `scale`, `rotate` or `opacity` is planned like a move. No option turns this off.',+ },+ ],+ },+ relatedHooks: ['useAnimator', 'useAnimatedLayout'],+ importPath: '@astryxdesign/core',+ category: 'interaction',+};++/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */+export const docsDense = {+ description:+ "Animates one element (x, y, scale, rotate, opacity) with Astryx's motion, without React.",+ paramDescriptions: {+ element: 'The element to animate; one animator per element.',+ },+ returnDescriptions: {+ animate:+ '(target, {velocity?}) => Promise<void>; springs on the state-change motion.',+ decay:+ '({x?, y?, scale?, rotate?, opacity?}) => Promise<void>; coasts from a release velocity.',+ set: '(values) => void; jumps, ending motion.',+ get: '() => every value on screen.',+ getVelocity: '() => every velocity on screen.',+ stop: '() => void; halts where it is.',+ destroy: '() => void; lets the element go.',+ },+ usage: {+ description:+ 'Spring with animate, fling with decay, follow a finger with set. Reduce Motion: a cross-fade on touch, at once with a mouse; decay keeps its momentum.',+ bestPractices: [+ {+ guidance: true,+ description: 'Pass the release velocity to animate after a drag.',+ },+ {+ guidance: false,+ description: 'Read layout for the position mid-motion; use get.',+ },+ ],+ },+};diff --git a/packages/core/src/animator/createAnimator.server.test.ts b/packages/core/src/animator/createAnimator.server.test.tsnew file mode 100644index 0000000000..be450785ef--- /dev/null+++ b/packages/core/src/animator/createAnimator.server.test.ts@@ -0,0 +1,51 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file createAnimator.server.test.ts+ * @input vitest; esbuild and a plain Node process (no window, no document)+ * @output Checks `spec:AST-107` FR6: importing the factory or the hook does+ * no DOM work, so both are safe on the server+ * @position Testing; validates createAnimator.ts and hooks/useAnimator.ts+ */++import {execFileSync} from 'node:child_process';+import path from 'node:path';+import {describe, expect, it} from 'vitest';++/** Bundles `entry` and imports it in a fresh Node process; prints its export names. */+function importOnServer(entry: string): string[] {+ const out = execFileSync(+ process.execPath,+ [+ '--input-type=module',+ '-e',+ [+ "import {build} from 'esbuild';",+ `const result = await build({entryPoints: [${JSON.stringify(entry)}], bundle: true, write: false, format: 'esm', platform: 'node', logLevel: 'silent'});`,+ "const source = Buffer.from(result.outputFiles[0].text).toString('base64');",+ "if (typeof window !== 'undefined' || typeof document !== 'undefined') throw new Error('not a server');",+ "const mod = await import('data:text/javascript;base64,' + source);",+ 'process.stdout.write(JSON.stringify(Object.keys(mod).sort()));',+ ].join('\n'),+ ],+ {cwd: __dirname, encoding: 'utf8'},+ );+ return JSON.parse(out) as string[];+}++describe('the public animator on the server', () => {+ it('the factory imports with no window or document', () => {+ // The module also hands the hook its construction; the package root+ // re-exports `createAnimator` alone (publicSurface.test.ts).+ expect(importOnServer(path.join(__dirname, 'createAnimator.ts'))).toEqual([+ 'createAnimator',+ 'createAttachableAnimator',+ ]);+ });++ it('the hook imports with no window or document', () => {+ expect(+ importOnServer(path.join(__dirname, '..', 'hooks', 'useAnimator.ts')),+ ).toEqual(['useAnimator']);+ });+});diff --git a/packages/core/src/animator/createAnimator.test.ts b/packages/core/src/animator/createAnimator.test.tsnew file mode 100644index 0000000000..b3d79f0f99--- /dev/null+++ b/packages/core/src/animator/createAnimator.test.ts@@ -0,0 +1,519 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file createAnimator.test.ts+ * @input Vitest in jsdom, with a fake clock and fake frames, and the public+ * animator. A recording stand-in replaces Element.animate, since jsdom runs+ * no animations, and the spring and decay math checks the curves.+ * @output Checks `spec:AST-107` FR3 and FR6 for the factory, over every+ * method and channel. `animate` plays the `springs.stateChange` role from a+ * given or on-screen velocity. `decay` coasts on the normal deceleration.+ * It also covers `set`, `get`, `getVelocity`, `stop`, `destroy` and the+ * promises. Reduce Motion is checked on a coarse and a fine pointer, and the+ * handle exposes nothing internal.+ * @position Testing; the compositor run is proven in+ * __tests__/createAnimator.interaction.browser.spec.ts+ */++import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {solveDecay} from '../motion/decay';+import {solveSpring, toSpring} from '../motion/spring';+import {springs} from '../motion/uikit/springs';+import {+ createAnimator,+ type AnimatorChannel,+ type AnimatorValues,+} from './createAnimator';++interface Recorded {+ keyframes: Keyframe[];+ options: KeyframeAnimationOptions;+ startTime: number | null;+ cancelled: boolean;+ readonly playState: string;+ ready: Promise<unknown>;+ finish(): void;+ cancel(): void;+}++let recorded: Recorded[] = [];+const FRAME_MS = 16;++/** The person's settings, through matchMedia as the animator reads them. */+function stubMedia({reduced = false, coarse = false} = {}) {+ vi.stubGlobal('matchMedia', (query: string) => ({+ matches: query.includes('prefers-reduced-motion')+ ? reduced+ : query.includes('pointer: coarse')+ ? coarse+ : false,+ media: query,+ onchange: null,+ addEventListener: () => {},+ removeEventListener: () => {},+ addListener: () => {},+ removeListener: () => {},+ dispatchEvent: () => false,+ }));+}++beforeEach(() => {+ recorded = [];+ vi.useFakeTimers({+ toFake: [+ 'setTimeout',+ 'clearTimeout',+ 'setInterval',+ 'clearInterval',+ 'performance',+ 'requestAnimationFrame',+ 'cancelAnimationFrame',+ ],+ });+ stubMedia();+ // Like a browser: a new animation starts at the next frame.+ HTMLElement.prototype.animate = function (keyframes, options) {+ let start: number | null = null;+ let resolveReady: () => void = () => {};+ const animation: Recorded = {+ keyframes: keyframes as Keyframe[],+ options: options as KeyframeAnimationOptions,+ get startTime() {+ return start;+ },+ set startTime(value) {+ start = value;+ resolveReady();+ },+ cancelled: false,+ get playState() {+ return this.cancelled ? 'idle' : 'running';+ },+ ready: new Promise<void>(resolve => {+ resolveReady = resolve;+ }),+ finish() {},+ cancel() {+ this.cancelled = true;+ },+ };+ requestAnimationFrame(() => {+ if (start == null && !animation.cancelled) {+ start = performance.now();+ resolveReady();+ }+ });+ recorded.push(animation);+ return animation as unknown as Animation;+ };+});++afterEach(() => {+ vi.unstubAllGlobals();+ Reflect.deleteProperty(HTMLElement.prototype, 'animate');+ vi.useRealTimers();+});++async function advance(ms: number) {+ await vi.advanceTimersByTimeAsync(ms);+}++/** The time the browser started the latest animation, after its frame. */+async function started(): Promise<number> {+ await advance(FRAME_MS);+ const start = recorded.at(-1)?.startTime;+ if (start == null) {+ throw new Error('no animation started');+ }+ return start;+}++const STATE_CHANGE = toSpring(springs.stateChange);++function element(): HTMLElement {+ const box = document.createElement('div');+ document.body.append(box);+ return box;+}++describe('createAnimator', () => {+ it('hands out the six methods and destroy, and nothing of the motion module beneath', () => {+ const animator = createAnimator(element());+ expect(Object.keys(animator).sort()).toEqual(+ [+ 'animate',+ 'decay',+ 'destroy',+ 'get',+ 'getVelocity',+ 'set',+ 'stop',+ ].sort(),+ );+ for (const method of Object.values(animator)) {+ expect(typeof method).toBe('function');+ }+ animator.destroy();+ });++ it('reads every channel at rest: identity', () => {+ const animator = createAnimator(element());+ expect(animator.get()).toEqual({+ x: 0,+ y: 0,+ scale: 1,+ rotate: 0,+ opacity: 1,+ });+ expect(animator.getVelocity()).toEqual({+ x: 0,+ y: 0,+ scale: 0,+ rotate: 0,+ opacity: 0,+ });+ });++ it('animate plays the springs.stateChange role on each channel', async () => {+ const box = element();+ const animator = createAnimator(box);+ const target: Record<AnimatorChannel, number> = {+ x: 120,+ y: -80,+ scale: 1.5,+ rotate: 45,+ opacity: 0.25,+ };+ const from: Record<AnimatorChannel, number> = {+ x: 0,+ y: 0,+ scale: 1,+ rotate: 0,+ opacity: 1,+ };+ void animator.animate(target);+ const start = await started();+ await advance(150);+ const t = (performance.now() - start) / 1000;+ const now = animator.get();+ for (const channel of Object.keys(target) as AnimatorChannel[]) {+ const curve = solveSpring(STATE_CHANGE, {+ from: from[channel],+ to: target[channel],+ });+ expect(now[channel]).toBeCloseTo(curve.value(t), 6);+ expect(animator.getVelocity()[channel]).toBeCloseTo(curve.velocity(t), 4);+ // Moving, not there yet.+ expect(now[channel]).not.toBeCloseTo(target[channel], 2);+ }+ });++ it('animate starts from a given velocity, and otherwise from the one on screen', async () => {+ const animator = createAnimator(element());+ void animator.animate({x: 100}, {velocity: {x: 900}});+ const start = await started();+ await advance(100);+ const t = (performance.now() - start) / 1000;+ const withVelocity = solveSpring(STATE_CHANGE, {+ from: 0,+ to: 100,+ velocity: 900,+ });+ expect(animator.get().x).toBeCloseTo(withVelocity.value(t), 6);++ // Interrupted: the new spring keeps the velocity on screen.+ const before = animator.getVelocity().x;+ expect(before).not.toBe(0);+ void animator.animate({x: 0});+ expect(animator.getVelocity().x).toBeCloseTo(before, 4);+ });++ it('animate resolves once the channels arrive, with the values at the target', async () => {+ const animator = createAnimator(element());+ let done = false;+ void animator.animate({x: 60, opacity: 0.5}).then(() => {+ done = true;+ });+ await started();+ await advance(200);+ expect(done).toBe(false);+ await advance(3000);+ expect(done).toBe(true);+ expect(animator.get().x).toBeCloseTo(60, 3);+ expect(animator.get().opacity).toBeCloseTo(0.5, 3);+ });++ it('animate resolves early when a later call takes its channels over', async () => {+ const animator = createAnimator(element());+ let done = false;+ void animator.animate({x: 300}).then(() => {+ done = true;+ });+ await started();+ await advance(50);+ animator.set({x: 10});+ await advance(0);+ expect(done).toBe(true);+ expect(animator.get().x).toBe(10);+ });++ it('a later animate or decay on a channel resolves its earlier promise where it stopped', async () => {+ const animator = createAnimator(element());+ const settled: string[] = [];+ void animator.animate({x: 300}).then(() => settled.push('first animate'));+ await started();+ await advance(60);+ const before = animator.get().x;+ void animator.animate({x: -100}).then(() => settled.push('second animate'));+ await advance(0);+ expect(settled).toEqual(['first animate']);+ // The second picks up where the first stopped on screen.+ expect(animator.get().x).toBeCloseTo(before, 0);+ await advance(40);+ void animator.decay({x: 800}).then(() => settled.push('decay'));+ await advance(0);+ expect(settled).toEqual(['first animate', 'second animate']);+ await advance(40);+ void animator.animate({x: 0});+ await advance(0);+ expect(settled).toEqual(['first animate', 'second animate', 'decay']);+ });++ it('decay coasts x and y on the normal deceleration from the velocity', async () => {+ const animator = createAnimator(element());+ let done = false;+ void animator.decay({x: 1500, y: -600}).then(() => {+ done = true;+ });+ const start = await started();+ await advance(250);+ const t = (performance.now() - start) / 1000;+ const x = solveDecay({from: 0, velocity: 1500});+ const y = solveDecay({from: 0, velocity: -600});+ expect(animator.get().x).toBeCloseTo(x.value(t), 4);+ expect(animator.get().y).toBeCloseTo(y.value(t), 4);+ expect(animator.getVelocity().x).toBeCloseTo(x.velocity(t), 2);+ await advance(10_000);+ expect(done).toBe(true);+ // The rest is where the velocity alone carries it: no bounds.+ expect(animator.get().x).toBeCloseTo(x.rest, 0);+ expect(animator.get().y).toBeCloseTo(y.rest, 0);+ });++ it('decay coasts every channel it is given on the same momentum decay', async () => {+ const animator = createAnimator(element());+ let done = false;+ void animator.decay({scale: 0.8, rotate: 90}).then(() => {+ done = true;+ });+ const start = await started();+ await advance(250);+ const t = (performance.now() - start) / 1000;+ const scale = solveDecay({from: 1, velocity: 0.8});+ const rotate = solveDecay({from: 0, velocity: 90});+ expect(animator.get().scale).toBeCloseTo(scale.value(t), 4);+ expect(animator.get().rotate).toBeCloseTo(rotate.value(t), 3);+ await advance(10_000);+ expect(done).toBe(true);+ expect(animator.get().scale).toBeCloseTo(scale.rest, 3);+ expect(animator.get().rotate).toBeCloseTo(rotate.rest, 1);+ });++ it('a decay that coasts x with rotate resolves as soon as a later call takes x over, as animate does (spec:AST-107 FR3)', async () => {+ const animator = createAnimator(element());+ let done = false;+ void animator.decay({x: 1200, rotate: 90}).then(() => {+ done = true;+ });+ await started();+ await advance(50);+ // The rotate coast runs for seconds more; taking x over still ends the+ // call where it stopped.+ animator.set({x: 0});+ await advance(0);+ expect(done).toBe(true);+ expect(animator.get().x).toBe(0);+ });++ it('a decay that coasts x with rotate, left alone, resolves once both channels stop', async () => {+ const animator = createAnimator(element());+ let done = false;+ void animator.decay({x: 1200, rotate: 90}).then(() => {+ done = true;+ });+ await started();+ await advance(500);+ expect(done).toBe(false);+ await advance(10_000);+ expect(done).toBe(true);+ });++ it('an opacity coast stops at 0 or 1', async () => {+ const animator = createAnimator(element());+ animator.set({opacity: 0.5});+ void animator.decay({opacity: -5});+ await started();+ await advance(10_000);+ expect(animator.get().opacity).toBe(0);+ });++ it('set puts values in place at once and writes them to the element', () => {+ const box = element();+ const animator = createAnimator(box);+ animator.set({x: 40, y: 8, scale: 0.5, rotate: 90, opacity: 0.3});+ expect(animator.get()).toEqual({+ x: 40,+ y: 8,+ scale: 0.5,+ rotate: 90,+ opacity: 0.3,+ });+ expect(box.style.translate).toBe('40px 8px');+ expect(box.style.scale).toBe('0.5 0.5');+ expect(box.style.rotate).toBe('90deg');+ expect(box.style.opacity).toBe('0.3');+ });++ it('a call leaves the channels it is not given where they are', async () => {+ const animator = createAnimator(element());+ animator.set({y: 30, opacity: 0.5});+ void animator.animate({x: 100});+ await started();+ await advance(5000);+ expect(animator.get()).toMatchObject({x: 100, y: 30, opacity: 0.5});+ });++ it('stop halts every channel where it is on screen', async () => {+ const animator = createAnimator(element());+ let done = false;+ void animator.animate({x: 200, rotate: 30}).then(() => {+ done = true;+ });+ await started();+ await advance(120);+ animator.stop();+ const held = animator.get();+ await advance(2000);+ expect(animator.get()).toEqual(held);+ expect(held.x).toBeGreaterThan(0);+ expect(held.x).toBeLessThan(200);+ expect(animator.getVelocity().x).toBe(0);+ expect(done).toBe(true);+ });++ it('destroy stops everything; the animator does nothing after it', async () => {+ const box = element();+ const animator = createAnimator(box);+ void animator.animate({x: 200});+ await started();+ await advance(100);+ animator.destroy();+ expect(recorded.every(animation => animation.cancelled)).toBe(true);+ const count = recorded.length;+ await expect(animator.animate({x: 0})).resolves.toBeUndefined();+ await expect(animator.decay({x: 500})).resolves.toBeUndefined();+ await expect(animator.decay({scale: 1})).resolves.toBeUndefined();+ animator.set({y: 50});+ expect(() => animator.stop()).not.toThrow();+ expect(() => animator.destroy()).not.toThrow();+ expect(recorded.length).toBe(count);+ expect(animator.get().y).toBe(0);+ expect(animator.getVelocity().x).toBe(0);+ });++ it('destroy removes every listener it added (spec:AST-107 FR6)', async () => {+ const added = vi.spyOn(EventTarget.prototype, 'addEventListener');+ const removed = vi.spyOn(EventTarget.prototype, 'removeEventListener');+ try {+ const animator = createAnimator(element());+ void animator.animate({x: 200, opacity: 0.5});+ await started();+ await advance(100);+ animator.destroy();+ await advance(1000);+ expect(removed.mock.calls.length).toBe(added.mock.calls.length);+ } finally {+ added.mockRestore();+ removed.mockRestore();+ }+ });++ it('a channel it does not know is ignored: no throw, and a call with nothing it knows resolves at once', async () => {+ const box = element();+ const animator = createAnimator(box);+ const unknown = {width: 200, x: 30} as unknown as AnimatorValues;+ expect(() => animator.set(unknown)).not.toThrow();+ expect(animator.get()).toEqual({+ x: 30,+ y: 0,+ scale: 1,+ rotate: 0,+ opacity: 1,+ });+ expect(box.style.width).toBe('');+ await expect(+ animator.animate({height: 10} as unknown as AnimatorValues),+ ).resolves.toBeUndefined();+ await expect(+ animator.decay({height: 10} as unknown as AnimatorValues),+ ).resolves.toBeUndefined();+ expect(recorded).toEqual([]);+ });++ it('an empty call resolves at once and moves nothing', async () => {+ const animator = createAnimator(element());+ await expect(animator.animate({})).resolves.toBeUndefined();+ await expect(animator.decay({})).resolves.toBeUndefined();+ expect(recorded).toEqual([]);+ });++ describe('Reduce Motion (design:reduced-motion)', () => {+ it('on a coarse pointer, a move becomes a cross-fade: the travel lands while transparent', async () => {+ stubMedia({reduced: true, coarse: true});+ const animator = createAnimator(element());+ let done = false;+ void animator.animate({x: 200}).then(() => {+ done = true;+ });+ await started();+ const samples: {x: number; opacity: number}[] = [];+ for (let i = 0; i < 40; i++) {+ await advance(FRAME_MS);+ const {x, opacity} = animator.get();+ samples.push({x, opacity});+ }+ // Never a value between the ends: the move is substituted, not slowed.+ expect(samples.every(s => s.x === 0 || s.x === 200)).toBe(true);+ // It fades: opacity dips below 1, and the jump happens out of sight.+ expect(Math.min(...samples.map(s => s.opacity))).toBeLessThan(0.05);+ const jump = samples.findIndex(s => s.x === 200);+ expect(jump).toBeGreaterThan(0);+ expect(samples[jump].opacity).toBeLessThan(0.05);+ await advance(1000);+ expect(done).toBe(true);+ expect(animator.get()).toMatchObject({x: 200, opacity: 1});+ });++ it('on a fine pointer, a move lands at once', async () => {+ stubMedia({reduced: true, coarse: false});+ const animator = createAnimator(element());+ const finished = animator.animate({x: 200, scale: 2});+ expect(animator.get()).toMatchObject({x: 200, scale: 2});+ await advance(FRAME_MS);+ await expect(finished).resolves.toBeUndefined();+ });++ it('a release coast keeps its momentum: it continues the throw', async () => {+ stubMedia({reduced: true, coarse: true});+ const animator = createAnimator(element());+ void animator.decay({x: 1200});+ const start = await started();+ await advance(200);+ const t = (performance.now() - start) / 1000;+ expect(animator.get().x).toBeCloseTo(+ solveDecay({from: 0, velocity: 1200}).value(t),+ 4,+ );+ });+ });+});diff --git a/packages/core/src/animator/createAnimator.ts b/packages/core/src/animator/createAnimator.tsnew file mode 100644index 0000000000..c712bd9467--- /dev/null+++ b/packages/core/src/animator/createAnimator.ts@@ -0,0 +1,324 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file createAnimator.ts+ * @input An element; the internal motion animator (motion/animator.ts), the+ * `springs.stateChange` motion role and the momentum coast (motion/coast.ts)+ * @output The public animator: `createAnimator`, the `AnimatorHandle` it+ * returns, and their value types+ * @position Public entry point, re-exported from the package root. The+ * `useAnimator` hook wraps it. Importing it does no DOM work.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/animator/createAnimator.test.ts+ * - /packages/core/src/animator/createAnimator.doc.mjs+ * - /packages/core/src/hooks/useAnimator.ts+ */++import {+ createMotionAnimator,+ SETTLE_THRESHOLD,+ type Animator as MotionAnimator,+ type MotionCurve,+ type MotionProperty,+ type MotionValues,+} from '../motion/animator';+import {coast} from '../motion/coast';+import {solveDecay} from '../motion/decay';+import {registerSpringsTable, springs} from '../motion/uikit/springs';++/**+ * A channel the animator drives. `x` and `y` translate the element (px).+ * `scale` scales it about its transform origin (1 is its size). `rotate`+ * turns it (degrees, clockwise), and `opacity` fades it (0 to 1).+ */+export type AnimatorChannel = 'x' | 'y' | 'scale' | 'rotate' | 'opacity';++/**+ * Values by channel. A velocity uses the same keys, in units per second:+ * px/s, scale per second, deg/s, opacity per second.+ */+export type AnimatorValues = Partial<Record<AnimatorChannel, number>>;++/** Every channel's value (or velocity), as `get` and `getVelocity` read it. */+export type AnimatorSnapshot = Readonly<Record<AnimatorChannel, number>>;++/** Options of `AnimatorHandle.animate`. */+export interface AnimatorAnimateOptions {+ /**+ * Each channel's velocity at the start, such as a drag's release velocity.+ * A channel without one keeps the+ * velocity it has on screen, so an `animate` that interrupts another+ * carries on smoothly.+ */+ velocity?: AnimatorValues;+}++/**+ * A release velocity for `AnimatorHandle.decay`, per channel, in its units+ * per second. That is px/s for `x` and `y`, and degrees per second for+ * `rotate`. `scale` and `opacity` take their units per second.+ */+export type AnimatorDecayVelocity = AnimatorValues;++/**+ * Animates one element. Each method acts on the channels it is given and+ * leaves the others where they are.+ */+export interface AnimatorHandle {+ /**+ * Springs the given channels to `target` on the `springs.stateChange`+ * motion role, from wherever they are on screen. The promise resolves when+ * they arrive, or as soon as a later `animate`, `decay`, `set` or `stop`+ * takes any of them over.+ */+ animate(+ target: AnimatorValues,+ options?: AnimatorAnimateOptions,+ ): Promise<void>;+ /**+ * Coasts the given channels from a release velocity, slowing as a scroll+ * view's momentum does. It resolves when they stop, or when another call+ * takes them over. The distance follows from the velocity alone: there are+ * no bounds, except that opacity stops at 0 or 1.+ */+ decay(velocity: AnimatorDecayVelocity): Promise<void>;+ /**+ * Puts the given channels at these values at once, ending their motion:+ * the per-frame write of a drag.+ */+ set(values: AnimatorValues): void;+ /** Every channel's value on screen now. */+ get(): AnimatorSnapshot;+ /** Every channel's velocity on screen now, in units per second. */+ getVelocity(): AnimatorSnapshot;+ /** Halts every channel where it is on screen. */+ stop(): void;+}++/** What `createAnimator` returns: the handle, and `destroy`. */+export interface Animator extends AnimatorHandle {+ /**+ * Stops every motion and lets go of the element; the element keeps the+ * values it shows. The animator does nothing after this.+ */+ destroy(): void;+}++const CHANNELS: ReadonlyArray<AnimatorChannel> = [+ 'x',+ 'y',+ 'scale',+ 'rotate',+ 'opacity',+];++/** The values of the channels the public API names, and nothing else. */+function motionValues(values: AnimatorValues | undefined): MotionValues {+ const out: MotionValues = {};+ if (values == null) {+ return out;+ }+ for (const channel of CHANNELS) {+ const value = values[channel];+ if (typeof value === 'number' && Number.isFinite(value)) {+ out[channel] = value;+ }+ }+ return out;+}++/**+ * A coast from `from` at `velocity` on the momentum decay a scroll view+ * uses, ending at rest. The theme does not change this decay. An opacity+ * coast stops at 0 or 1.+ */+function momentum(+ from: number,+ velocity: number,+ threshold: number,+ isUnit: boolean,+): MotionCurve {+ const glide = solveDecay({from, velocity});+ const edge = !isUnit ? null : glide.rest < 0 ? 0 : glide.rest > 1 ? 1 : null;+ const hit = edge == null ? null : glide.timeToReach(edge);+ const duration = hit ?? glide.settleTime(threshold);+ const end = edge ?? glide.rest;+ return {+ duration,+ at: t => (t >= duration ? end : glide.value(t)),+ velocity: t => (t >= duration ? 0 : glide.velocity(t)),+ };+}++function snapshot(+ read: (channel: AnimatorChannel) => number,+): AnimatorSnapshot {+ return {+ x: read('x'),+ y: read('y'),+ scale: read('scale'),+ rotate: read('rotate'),+ opacity: read('opacity'),+ };+}++/**+ * Resolves once every motion of one call has finished, or as soon as any of+ * them is interrupted (`finished` resolves `false`). A later call that takes+ * over one channel ends the whole call where it stopped, as one `animate`+ * does. The other channels move on.+ */+async function settledOrTakenOver(+ moving: ReadonlyArray<Promise<boolean>>,+): Promise<void> {+ if (moving.length === 0) {+ return;+ }+ await new Promise<void>(resolve => {+ let left = moving.length;+ for (const finished of moving) {+ void finished.then(completed => {+ left -= 1;+ if (!completed || left === 0) {+ resolve();+ }+ });+ }+ });+}++/**+ * An animator whose element is attached later, through `attach`. It is the+ * one construction `createAnimator` and `useAnimator` share, so the hook has+ * no behavior of its own. Not exported from the package.+ */+export function createAttachableAnimator(): {+ readonly animator: Animator;+ readonly attach: (element: HTMLElement | null) => void;+} {+ const motion: MotionAnimator = createMotionAnimator(null);+ // Calls do nothing while no element is attached, before the ref attaches+ // or after it lets go. They also do nothing after destroy, and animate and+ // decay then resolve at once.+ let element: HTMLElement | null = null;+ let destroyed = false;+ const inactive = () => destroyed || element == null;+ const animator: Animator = {+ async animate(target, options) {+ const to = motionValues(target);+ if (inactive() || Object.keys(to).length === 0) {+ return;+ }+ // The role registry is written on first use, never on import.+ registerSpringsTable();+ const velocity = motionValues(options?.velocity);+ await motion.animate(to, {+ spring: springs.stateChange,+ ...(Object.keys(velocity).length > 0 ? {velocity} : {}),+ }).finished;+ },+ async decay(velocity) {+ if (inactive()) {+ return;+ }+ const given = motionValues(velocity);+ // The translate axes coast as a throw, which Reduce Motion lets+ // continue. The others coast as a transition, which it replaces.+ const translate = coast(motion, {x: given.x, y: given.y});+ const others: Partial<Record<MotionProperty | 'scale', MotionCurve>> = {};+ for (const channel of ['scale', 'rotate', 'opacity'] as const) {+ const v0 = given[channel];+ if (v0 != null) {+ const property = channel === 'scale' ? 'scaleX' : channel;+ others[channel] = momentum(+ motion.get(property),+ v0,+ SETTLE_THRESHOLD[property],+ channel === 'opacity',+ );+ }+ }+ const moving: Promise<boolean>[] = [];+ if (Object.keys(translate).length > 0) {+ moving.push(motion.decay(translate).finished);+ }+ if (Object.keys(others).length > 0) {+ moving.push(motion.play(others).finished);+ }+ await settledOrTakenOver(moving);+ },+ set(values) {+ if (!inactive()) {+ motion.set(motionValues(values));+ }+ },+ get() {+ return snapshot(channel => motion.get(channel));+ },+ getVelocity() {+ return snapshot(channel => motion.getVelocity(channel));+ },+ stop() {+ if (!inactive()) {+ motion.stop();+ }+ },+ destroy() {+ if (!destroyed) {+ destroyed = true;+ // Halts every channel where it shows, so the element keeps those+ // values and nothing reads as moving, then lets go of it.+ motion.stop();+ motion.dispose();+ }+ },+ };+ return {+ animator,+ attach: next => {+ if (destroyed || next === element) {+ return;+ }+ if (element != null) {+ // The old node takes its values with it, so the next node, or a+ // remount, starts at rest.+ motion.attach(null);+ motion.stop();+ motion.set(motionValues(REST));+ }+ element = next;+ motion.attach(next);+ },+ };+}++/** A new or remounted element starts from these values. */+const REST = {x: 0, y: 0, scale: 1, rotate: 0, opacity: 1} as const;++/**+ * Animates `element` with the motion Core uses. `animate` springs channels to+ * a target on the state-change motion, and `decay` coasts them from a release+ * velocity. `set` jumps them, `get` and `getVelocity` read them, `stop` halts+ * them, and `destroy` lets the element go. Under Reduce Motion every call is+ * planned. A move becomes a short cross-fade on a touch screen, and it lands+ * at once with a mouse.+ *+ * Use one animator per element: two on one element overwrite each other.+ *+ * @example+ * ```+ * const card = document.querySelector('.card');+ * const animator = createAnimator(card);+ * await animator.animate({x: 0, rotate: 0}, {velocity: {x: -900}});+ * animator.decay({x: 2400});+ * animator.destroy();+ * ```+ */+export function createAnimator(element: HTMLElement): Animator {+ const {animator, attach} = createAttachableAnimator();+ attach(element);+ return animator;+}diff --git a/packages/core/src/animator/playingCardsTemplates.test.tsx b/packages/core/src/animator/playingCardsTemplates.test.tsxnew file mode 100644index 0000000000..56868b0662--- /dev/null+++ b/packages/core/src/animator/playingCardsTemplates.test.tsx@@ -0,0 +1,356 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file playingCardsTemplates.test.tsx+ * @input The CLI's two playing-card examples of the public animator, each+ * rendered with a recording animator in place of the real one.+ * @output Tests of each example's release and press logic. A drag held still+ * springs back, and so does a cancelled drag. A thrown card's successor is+ * dealt and announced once the thrown card has faded. The Discard button+ * uses `animate`, never `decay`, so Reduce Motion fades the card in place+ * (`design:reduced-motion` DR2). The card is an image with its name. One+ * card leaves at a time, a leaving card takes no press, and a press during+ * a fade-in moves only the card's position.+ * @position The examples ship to products through the CLI, so their logic is+ * checked here, beside the animator they demonstrate.+ */++import type {ComponentType} from 'react';+import {act, render, screen} from '@testing-library/react';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';++// The examples live in the CLI's templates, outside Core's type-checked+// sources, so they load at run time; the CLI type-checks them itself.+const TEMPLATES = '../../../cli/assets/templates/blocks/components';+async function loadExample(file: string): Promise<ComponentType> {+ const module = (await import(/* @vite-ignore */ `${TEMPLATES}/${file}`)) as {+ default: ComponentType;+ };+ return module.default;+}+const AnimatorPlayingCards = await loadExample(+ 'useAnimator/AnimatorPlayingCards',+);+const AnimatorPlayingCardsVanilla = await loadExample(+ 'createAnimator/AnimatorPlayingCardsVanilla',+);++const recorder = vi.hoisted(() => {+ const state = {+ calls: [] as {method: string; values?: unknown}[],+ // The fades still running, oldest first.+ fades: [] as (() => void)[],+ finishFade: () => {+ state.fades.shift()?.();+ },+ };+ const animator = {+ animate: async (values: {opacity?: number}) => {+ state.calls.push({method: 'animate', values});+ if (values.opacity != null) {+ // A new opacity target takes over a running fade, which then+ // resolves, as the animator's does. The new fade, out or in, runs+ // until the test finishes it.+ for (const finish of state.fades.splice(0)) {+ finish();+ }+ await new Promise<void>(resolve => {+ state.fades.push(resolve);+ });+ }+ },+ // A thrown card coasts for seconds: this one never stops on its own.+ decay: async (values: unknown) => {+ state.calls.push({method: 'decay', values});+ await new Promise<void>(() => {});+ },+ set: (values: unknown) => {+ state.calls.push({method: 'set', values});+ },+ get: () => ({x: 0, y: 0, scale: 1, rotate: 0, opacity: 1}),+ getVelocity: () => ({x: 0, y: 0, scale: 0, rotate: 0, opacity: 0}),+ // A stop ends every running motion, which resolves its promise, as the+ // animator's does.+ stop: () => {+ state.calls.push({method: 'stop'});+ for (const finish of state.fades.splice(0)) {+ finish();+ }+ },+ destroy: () => {+ state.calls.push({method: 'destroy'});+ },+ };+ return {state, animator};+});++vi.mock('@astryxdesign/core/hooks', async importOriginal => ({+ ...(await importOriginal<object>()),+ useAnimator: () => recorder.animator,+}));+vi.mock('@astryxdesign/core', async importOriginal => ({+ ...(await importOriginal<object>()),+ createAnimator: () => recorder.animator,+}));++/** Dispatches a pointer event at a given time stamp (ms). */+function pointer(+ target: Element,+ type: 'pointerdown' | 'pointermove' | 'pointerup' | 'pointercancel',+ x: number,+ t: number,+) {+ const event = new MouseEvent(type, {+ bubbles: true,+ cancelable: true,+ clientX: x,+ clientY: 0,+ });+ Object.defineProperty(event, 'pointerId', {value: 1});+ Object.defineProperty(event, 'timeStamp', {value: t});+ act(() => {+ target.dispatchEvent(event);+ });+}++/** A 150 px drag over 100 ms, released at `releasedAt`. */+function drag(card: Element, releasedAt: number) {+ pointer(card, 'pointerdown', 0, 1000);+ for (let step = 1; step <= 10; step++) {+ pointer(card, 'pointermove', step * 15, 1000 + step * 10);+ }+ pointer(card, 'pointerup', 150, releasedAt);+}++const methods = () => recorder.state.calls.map(call => call.method);++const EXAMPLES = [+ {+ name: 'the useAnimator example',+ mount: () => render(<AnimatorPlayingCards />),+ card: () => screen.getByRole('img', {name: 'Ace of spades'}),+ discardButton: 'Discard Ace of spades',+ announced: 'Ace of spades discarded',+ },+ {+ name: 'the createAnimator example',+ mount: () => render(<AnimatorPlayingCardsVanilla />),+ card: () => screen.getByRole('img', {name: 'Ace of spades'}),+ discardButton: 'Discard the top card',+ announced: 'Ace of spades discarded',+ },+];++describe.each(EXAMPLES)('$name', ({mount, card, discardButton, announced}) => {+ beforeEach(() => {+ recorder.state.calls = [];+ recorder.state.fades = [];+ HTMLElement.prototype.setPointerCapture = () => {};+ });+ afterEach(() => {+ Reflect.deleteProperty(HTMLElement.prototype, 'setPointerCapture');+ });++ it('a drag held still for 600 ms before its release springs back, not thrown', () => {+ mount();+ drag(card(), 1100 + 600);+ expect(methods()).not.toContain('decay');+ expect(recorder.state.calls.at(-1)).toMatchObject({+ method: 'animate',+ values: {x: 0, y: 0, rotate: 0},+ });+ });++ it('a drag that the browser cancels springs back, even after fast moves', () => {+ mount();+ const target = card();+ pointer(target, 'pointerdown', 0, 1000);+ for (let step = 1; step <= 10; step++) {+ pointer(target, 'pointermove', step * 15, 1000 + step * 10);+ }+ pointer(target, 'pointercancel', 150, 1100);+ expect(methods()).not.toContain('decay');+ expect(recorder.state.calls.at(-1)).toMatchObject({+ method: 'animate',+ values: {x: 0, y: 0, rotate: 0},+ });+ });++ it('a flick deals and announces the next card once the thrown one fades, during its coast', async () => {+ mount();+ drag(card(), 1100);+ expect(methods()).toContain('decay');+ expect(screen.queryByText(announced)).toBeNull();+ await act(async () => {+ recorder.state.finishFade();+ });+ expect(screen.getByText(announced)).toBeTruthy();+ expect(recorder.state.calls).toContainEqual({+ method: 'set',+ values: {x: 0, y: 0, rotate: 0, scale: 0.9, opacity: 0},+ });+ });++ it('the Discard button moves the card off with animate, never decay, so Reduce Motion fades it in place (design:reduced-motion DR2)', async () => {+ mount();+ act(() => {+ screen.getByRole('button', {name: discardButton}).click();+ });+ // A coast keeps its momentum under Reduce Motion, as a person's throw;+ // a button's move is planned, so it fades where it is.+ expect(methods()).not.toContain('decay');+ expect(recorder.state.calls[0]).toEqual({+ method: 'animate',+ values: {x: 400, opacity: 0},+ });+ await act(async () => {+ recorder.state.finishFade();+ });+ expect(screen.getByText(announced)).toBeTruthy();+ });++ it('a Discard press mid-drag ends the drag: later moves neither cut the discard short nor move the dealt card', async () => {+ mount();+ const target = card();+ pointer(target, 'pointerdown', 0, 1000);+ pointer(target, 'pointermove', 20, 1010);+ act(() => {+ screen.getByRole('button', {name: discardButton}).click();+ });+ const atDiscard = recorder.state.calls.length;+ // The finger moves on and lifts while the card leaves.+ pointer(target, 'pointermove', 60, 1020);+ pointer(target, 'pointerup', 60, 1030);+ expect(recorder.state.calls.slice(atDiscard)).toEqual([]);+ await act(async () => {+ while (recorder.state.fades.length > 0) {+ recorder.state.finishFade();+ await Promise.resolve();+ }+ });+ expect(deals()).toHaveLength(1);+ });++ it('a press on the card being dealt moves only its position: its fade-in runs on', async () => {+ mount();+ act(() => {+ screen.getByRole('button', {name: discardButton}).click();+ });+ await act(async () => {+ recorder.state.finishFade();+ });+ // The next card is fading in.+ expect(recorder.state.fades).toHaveLength(1);+ const dealt = screen.getByRole('img', {name: 'King of hearts'});+ pointer(dealt, 'pointerdown', 0, 1000);+ pointer(dealt, 'pointermove', 40, 1010);+ expect(recorder.state.fades).toHaveLength(1);+ expect(methods()).not.toContain('stop');+ expect(recorder.state.calls.at(-1)).toMatchObject({+ method: 'set',+ values: {x: 40},+ });+ });++ it('names the dealt card by its rank and suit', async () => {+ mount();+ act(() => {+ screen.getByRole('button', {name: discardButton}).click();+ });+ await act(async () => {+ recorder.state.finishFade();+ });+ expect(screen.getByRole('img', {name: 'King of hearts'})).toBeTruthy();+ });+});++/** The `set` calls that deal a card. */+const deals = () =>+ recorder.state.calls.filter(+ call =>+ call.method === 'set' && (call.values as {scale?: number}).scale === 0.9,+ );++describe.each(EXAMPLES)(+ '$name, one discard at a time',+ ({mount, card, discardButton}) => {+ beforeEach(() => {+ recorder.state.calls = [];+ recorder.state.fades = [];+ HTMLElement.prototype.setPointerCapture = () => {};+ });+ afterEach(() => {+ Reflect.deleteProperty(HTMLElement.prototype, 'setPointerCapture');+ });++ it('a second Discard press while the card leaves deals one card, not two', async () => {+ mount();+ const button = screen.getByRole('button', {name: discardButton});+ act(() => {+ button.click();+ });+ act(() => {+ button.click();+ });+ await act(async () => {+ while (recorder.state.fades.length > 0) {+ recorder.state.finishFade();+ await Promise.resolve();+ }+ });+ expect(deals()).toHaveLength(1);+ });++ it('a press on a card that is leaving is ignored: its fade runs on, and one card is dealt after it', async () => {+ mount();+ act(() => {+ screen.getByRole('button', {name: discardButton}).click();+ });+ // A finger lands on the leaving card and moves.+ pointer(card(), 'pointerdown', 0, 1000);+ pointer(card(), 'pointermove', 40, 1010);+ expect(methods()).not.toContain('stop');+ expect(methods()).not.toContain('set');+ await act(async () => {+ while (recorder.state.fades.length > 0) {+ recorder.state.finishFade();+ await Promise.resolve();+ }+ });+ expect(deals()).toHaveLength(1);+ });++ it('a Discard press while a flicked card fades deals one card, not two', async () => {+ mount();+ drag(card(), 1100);+ act(() => {+ screen.getByRole('button', {name: discardButton}).click();+ });+ await act(async () => {+ while (recorder.state.fades.length > 0) {+ recorder.state.finishFade();+ await Promise.resolve();+ }+ });+ expect(deals()).toHaveLength(1);+ });+ },+);++describe('the createAnimator example', () => {+ it('colours its card from the theme\u2019s surface and text tokens, so it reads in a dark theme', () => {+ render(<AnimatorPlayingCardsVanilla />);+ const {style} = screen.getByRole('img', {name: 'Ace of spades'});+ expect(style.backgroundColor).toBe('var(--color-background-surface)');+ expect(style.color).toBe('var(--color-text-primary)');+ });++ it('takes its deck down when it unmounts', () => {+ recorder.state.calls = [];+ const {unmount} = render(<AnimatorPlayingCardsVanilla />);+ expect(screen.getByRole('img', {name: 'Ace of spades'})).toBeTruthy();+ unmount();+ expect(screen.queryByRole('img')).toBeNull();+ expect(methods()).toContain('destroy');+ });+});diff --git a/packages/core/src/animator/publicSurface.test.ts b/packages/core/src/animator/publicSurface.test.tsnew file mode 100644index 0000000000..00babbcb42--- /dev/null+++ b/packages/core/src/animator/publicSurface.test.ts@@ -0,0 +1,72 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file publicSurface.test.ts+ * @input The package root, the hooks barrel, Core's package.json+ * @output Checks `spec:AST-107` FR4 and FR6 for the animator. The package+ * root hands out `createAnimator`, and only the root does, since one API+ * has one entry. The hooks barrel hands out `useAnimator` and nothing of+ * the motion module beneath. No internal factory takes the public+ * factory's name.+ * @position Public API test; enforced by Vitest and Core typecheck+ */++import fs from 'node:fs';+import path from 'node:path';+import {describe, expect, it} from 'vitest';+import * as root from '..';+import * as hooks from '../hooks';++const SRC = path.join(__dirname, '..');++/** Names of the motion module beneath the public animator. */+const INTERNAL = [+ 'createMotionAnimator',+ 'createAttachableAnimator',+ 'animatorFor',+ 'coast',+ 'resolveMotion',+ 'registerSpringsTable',+ 'springs',+];++describe('the public animator surface', () => {+ it('the package root exports createAnimator, and nothing of the motion module', () => {+ expect(typeof root.createAnimator).toBe('function');+ for (const name of INTERNAL) {+ expect(root).not.toHaveProperty(name);+ }+ });++ it('the hooks barrel exports useAnimator, and nothing of the motion module', () => {+ expect(typeof hooks.useAnimator).toBe('function');+ for (const name of INTERNAL) {+ expect(hooks).not.toHaveProperty(name);+ }+ });++ it('the package root names createAnimator and re-exports no motion or gesture module whole', () => {+ const source = fs.readFileSync(path.join(SRC, 'index.ts'), 'utf8');+ expect(source).toContain("from './animator/createAnimator';");+ // A public factory may be named from its module, as createPanGesture is+ // from gestures/; the runtime case above keeps the internals out.+ expect(source).not.toMatch(/export \* from '\.\/(motion|gestures)(\/|')/);+ });++ it('createAnimator ships from the package root only: no `./animator` subpath (one API, one entry)', () => {+ const pkg = JSON.parse(+ fs.readFileSync(path.join(SRC, '..', 'package.json'), 'utf8'),+ ) as {exports: Record<string, unknown>};+ expect(Object.keys(pkg.exports)).not.toContain('./animator');+ expect(fs.existsSync(path.join(__dirname, 'index.ts'))).toBe(false);+ });++ it('no internal factory takes the public factory\u2019s name', () => {+ const motion = fs.readFileSync(+ path.join(SRC, 'motion', 'animator.ts'),+ 'utf8',+ );+ expect(motion).not.toMatch(/export function createAnimator\b/);+ expect(motion).toMatch(/export function createMotionAnimator\b/);+ });+});diff --git a/packages/core/src/gestures/__tests__/browser/presentedFixture.ts b/packages/core/src/gestures/__tests__/browser/presentedFixture.tsindex 84e24830d4..cc28188bf1 100644--- a/packages/core/src/gestures/__tests__/browser/presentedFixture.ts+++ b/packages/core/src/gestures/__tests__/browser/presentedFixture.ts@@ -22,7 +22,7 @@* @position Browser fixture of presentedHitTesting.interaction.browser.spec.ts; test-only*/-import {createAnimator} from '../../../motion/animator';+import {createMotionAnimator} from '../../../motion/animator';import {presentedOffsetOf} from '../../../motion/presentation';import {GestureHost} from '../../GestureHost';import {PanGestureRecognizer} from '../../PanGestureRecognizer';@@ -101,7 +101,7 @@ const TRAVEL = 444;*/const SPRING = {response: 6, dampingRatio: 1} as const;-const animator = createAnimator(sheet);+const animator = createMotionAnimator(sheet);const drawn = (target: Element): DOMRect =>Element.prototype.getBoundingClientRect.call(target);diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.tsindex 051bca2be4..bc42af899e 100644--- a/packages/core/src/hooks/index.ts+++ b/packages/core/src/hooks/index.ts@@ -133,6 +133,8 @@ export type {UseInteractiveRoleOptions,} from './useInteractiveRole';+export {useAnimator} from './useAnimator';+export {useLongPress} from './useLongPress';export type {UseLongPressOptions, UseLongPressHandlers} from './useLongPress';diff --git a/packages/core/src/hooks/useAnimator.doc.mjs b/packages/core/src/hooks/useAnimator.doc.mjsnew file mode 100644index 0000000000..591fcfd252--- /dev/null+++ b/packages/core/src/hooks/useAnimator.doc.mjs@@ -0,0 +1,109 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').HookDoc} */+export const docs = {+ name: 'useAnimator',+ displayName: 'useAnimator',+ keywords: [+ 'animate',+ 'animation',+ 'animator',+ 'spring',+ 'decay',+ 'momentum',+ 'fling',+ 'motion',+ 'transform',+ 'opacity',+ 'drag',+ 'card',+ ],+ params: [+ {+ name: 'ref',+ type: 'RefObject<HTMLElement | null>',+ description:+ 'The ref of the one element to animate, the same ref you pass to the element: another hook, such as a gesture hook, can take it too, so a drag and an animation share one element. After every render the animator follows the element behind it. When the element unmounts its motion stops and its values return to rest, so a remount starts at rest, and so does a node that replaces it. Before the element mounts, and while it is unmounted, every call does nothing and `animate` and `decay` resolve at once.',+ required: true,+ },+ ],+ returns: [+ {+ name: 'animator',+ type: 'AnimatorHandle',+ description:+ "The element's animator, the same object on every render: `animate(target, {velocity?})` springs channels to a target on the state-change motion Astryx's components use, `decay(velocity)` coasts them from a release velocity, `set(values)` jumps them, `get()` and `getVelocity()` read them, and `stop()` halts them. The channels are `x` and `y` (px), `scale` (1 at the element's size), `rotate` (degrees) and `opacity` (0 to 1). `animate` and `decay` return a promise that resolves when the motion ends. Calling it never re-renders the component. Calls before the ref attaches do nothing and resolve at once.",+ },+ ],+ usage: {+ description:+ "Animates one element with the motion Astryx's own components use. Call `animator.animate` to spring an element to new values on the state-change motion, `animator.decay` to fling it with the momentum of a released scroll view, and `animator.set` to move it directly, so a card can follow a finger, snap back and be thrown away. To animate an area's layout as its items change, use `useAnimatedLayout`; for what a component already animates, such as a sheet's detents or a carousel's snapping, use the component's own props. Outside React, use `createAnimator`.",+ bestPractices: [+ {+ guidance: true,+ description:+ 'Call the animator from event handlers and effects: it lives outside render, so animating never re-renders the component.',+ },+ {+ guidance: true,+ description:+ 'Start every `animate` that follows a drag with the release velocity, so the element carries on as it was thrown.',+ },+ {+ guidance: true,+ description:+ 'Reach every state an animation shows without the animation too: a key, a button or a menu item that calls the same code.',+ },+ {+ guidance: false,+ description:+ 'Keep the animated values in React state: read them with `animator.get()` when you need them.',+ },+ ],+ accessibility: [+ {+ name: 'Keyboard and assistive technology',+ category: 'Keyboard',+ description:+ 'An animator moves an element; it adds no way to act. Give every action an animation stands for a control a keyboard and a screen reader can reach, such as a button that discards a card, and have it call `animate`, which Reduce Motion turns into a fade in place. Keep `decay` for a throw the person made: Reduce Motion keeps the momentum of a coast, as it continues that throw. Keep focus on an element that stays on screen: move it before you fling its element away.',+ },+ {+ name: 'Reduce Motion',+ category: 'Content',+ criterion: '2.3.3 Animation from Interactions',+ description:+ 'When the person asks for reduced motion, every call is planned for them. On a touch screen a move or a scale becomes a short opacity cross-fade: the element fades out where it was and fades back in where it lands. With a mouse it lands at once. A decay of `x` and `y` keeps its momentum, as it continues the throw the person made; a decay of `scale`, `rotate` or `opacity` is planned like a move. No option turns this off.',+ },+ ],+ },+ relatedHooks: ['useAnimatedLayout'],+ importPath: '@astryxdesign/core/hooks',+ category: 'interaction',+};++/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */+export const docsDense = {+ description:+ "Animates the element behind ref (x, y, scale, rotate, opacity) with Astryx's motion; returns the animator.",+ paramDescriptions: {+ ref: 'The element ref; share it with a gesture hook to drag and animate one element.',+ },+ returnDescriptions: {+ animator:+ 'animate(target, {velocity?}), decay(velocity), set, get, getVelocity, stop; stable, never re-renders.',+ },+ usage: {+ description:+ 'Spring with animate, fling with decay, follow a finger with set. Reduce Motion: a cross-fade on touch, at once with a mouse; decay keeps its momentum.',+ bestPractices: [+ {+ guidance: true,+ description: 'Pass the release velocity to animate after a drag.',+ },+ {+ guidance: false,+ description: 'Keep animated values in state; read animator.get().',+ },+ ],+ },+};diff --git a/packages/core/src/hooks/useAnimator.test.tsx b/packages/core/src/hooks/useAnimator.test.tsxnew file mode 100644index 0000000000..9d53d5c07a--- /dev/null+++ b/packages/core/src/hooks/useAnimator.test.tsx@@ -0,0 +1,196 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useAnimator.test.tsx+ * @input vitest (jsdom), React Testing Library, the public hook and factory+ * @output Checks `spec:AST-107` FR3 and FR6 for the hook. `useAnimator(ref)`+ * takes the caller's element ref and returns one animator, the factory's+ * handle and nothing more. An animator used before its element mounts does+ * nothing and resolves at once. It follows the element behind the ref when+ * the node is replaced, and the new node starts at rest. An unmount drops+ * the values, and a remount starts at rest.+ * Another hook can share the element through the same ref. Animating causes+ * no re-render, and the hook module has no behavior of its own.+ * @position Testing; validates useAnimator.ts+ */++import fs from 'node:fs';+import path from 'node:path';+import {act, render} from '@testing-library/react';+import {useEffect, useRef} from 'react';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import type {AnimatorHandle} from '../animator/createAnimator';+import {useAnimator} from './useAnimator';++beforeEach(() => {+ HTMLElement.prototype.animate = function () {+ return {+ startTime: null,+ playState: 'running',+ ready: new Promise(() => {}),+ cancel: vi.fn(),+ } as unknown as Animation;+ };+});++afterEach(() => {+ Reflect.deleteProperty(HTMLElement.prototype, 'animate');+});++function Probe({+ box,+ onRender,+ show = true,+}: {+ box: {current: AnimatorHandle | null};+ onRender?: () => void;+ show?: boolean;+}) {+ const ref = useRef<HTMLDivElement>(null);+ const animator = useAnimator(ref);+ box.current = animator;+ onRender?.();+ return show ? <div data-testid="target" ref={ref} /> : null;+}++describe('useAnimator', () => {+ it('takes the element ref and returns one animator for the component\u2019s lifetime, and never re-renders while animating', () => {+ const animators = new Set<AnimatorHandle>();+ let renders = 0;+ function Counter({label}: {label: string}) {+ const ref = useRef<HTMLButtonElement>(null);+ const animator = useAnimator(ref);+ animators.add(animator);+ renders += 1;+ return (+ <button+ type="button"+ ref={ref}+ onClick={() => void animator.animate({x: 20})}>+ {label}+ </button>+ );+ }+ const {getByRole, rerender} = render(<Counter label="Card" />);+ rerender(<Counter label="Card again" />);+ const after = renders;+ act(() => {+ getByRole('button').click();+ });+ expect(renders).toBe(after);+ expect(animators.size).toBe(1);+ });++ it('returns the handle\u2019s six methods, and nothing else: no ref and no destroy of its own', () => {+ const box: {current: AnimatorHandle | null} = {current: null};+ render(<Probe box={box} />);+ const animator = box.current!;+ expect(Object.keys(animator).sort()).toEqual(+ ['animate', 'decay', 'get', 'getVelocity', 'set', 'stop'].sort(),+ );+ for (const method of Object.keys(animator)) {+ expect(+ typeof (animator as unknown as Record<string, unknown>)[method],+ ).toBe('function');+ }+ });++ it('an animator used before its element mounts does nothing and resolves at once', async () => {+ const box: {current: AnimatorHandle | null} = {current: null};+ const {rerender, getByTestId} = render(<Probe box={box} show={false} />);+ const animator = box.current!;+ // Unattached: no element yet, so nothing happens and nothing throws.+ animator.set({x: 30, opacity: 0.4});+ animator.stop();+ expect(animator.get()).toMatchObject({x: 0, opacity: 1});+ let resolved = 0;+ await Promise.all([+ animator.animate({y: 10}).then(() => resolved++),+ animator.decay({x: 900}).then(() => resolved++),+ ]);+ expect(resolved).toBe(2);+ rerender(<Probe box={box} show />);+ const target = getByTestId('target');+ expect(animator.get()).toMatchObject({x: 0, y: 0, opacity: 1});+ // Attached, it works.+ animator.set({x: 30});+ expect(target.style.translate).toBe('30px 0px');+ });++ it('an unmount lets the element go and drops the values; a remount starts at rest', async () => {+ const box: {current: AnimatorHandle | null} = {current: null};+ const {rerender, getByTestId} = render(<Probe box={box} />);+ const animator = box.current!;+ animator.set({x: 12, rotate: 5});+ rerender(<Probe box={box} show={false} />);+ // With no element attached, a call does nothing.+ animator.set({x: 24});+ await act(async () => {+ await Promise.resolve();+ });+ expect(animator.get()).toMatchObject({x: 0, rotate: 0});+ rerender(<Probe box={box} show />);+ expect(['', 'none', '0px 0px']).toContain(+ getByTestId('target').style.translate,+ );+ expect(['', 'none', '0deg']).toContain(getByTestId('target').style.rotate);+ });++ it('follows the element behind the ref when the node is replaced, and the new node starts at rest (architecture:react-component-runtime INV6)', () => {+ const box: {current: AnimatorHandle | null} = {current: null};+ function Swapped({id}: {id: string}) {+ const ref = useRef<HTMLDivElement>(null);+ const animator = useAnimator(ref);+ box.current = animator;+ return <div key={id} data-testid={id} ref={ref} />;+ }+ const {rerender, getByTestId} = render(<Swapped id="first" />);+ const animator = box.current!;+ animator.set({x: 8});+ expect(getByTestId('first').style.translate).toBe('8px 0px');+ rerender(<Swapped id="second" />);+ // The new node starts at rest, and the next call moves it.+ expect(['', 'none', '0px 0px']).toContain(+ getByTestId('second').style.translate,+ );+ animator.set({x: 16});+ expect(getByTestId('second').style.translate).toBe('16px 0px');+ });++ it('shares its element with another hook through the same ref: a drag and an animation on one element', () => {+ const box: {current: AnimatorHandle | null} = {current: null};+ let seen: Element | null = null;+ function Shared() {+ const ref = useRef<HTMLDivElement>(null);+ const animator = useAnimator(ref);+ box.current = animator;+ // Another hook reads the same ref, as a gesture hook does.+ useEffect(() => {+ seen = ref.current;+ });+ return <div data-testid="shared" ref={ref} />;+ }+ const {getByTestId} = render(<Shared />);+ expect(seen).toBe(getByTestId('shared'));+ box.current!.set({y: 4});+ expect(getByTestId('shared').style.translate).toBe('0px 4px');+ });++ it('delegates entirely to the factory: the hook module holds no behavior of its own', () => {+ const source = fs.readFileSync(+ path.join(__dirname, 'useAnimator.ts'),+ 'utf8',+ );+ const imports = [...source.matchAll(/from '([^']+)'/g)].map(m => m[1]);+ expect(imports.sort()).toEqual([+ '../animator/createAnimator',+ './useAttachment',+ 'react',+ ]);+ // One construction, the factory's. The hook only wires the caller's ref+ // to it, through the attach lifecycle the gesture hooks share.+ expect(source).toContain('createAttachableAnimator()');+ expect(source).toContain('useAttachment(ref, attach, null)');+ expect(source).not.toMatch(/\bmotion\//);+ });+});diff --git a/packages/core/src/hooks/useAnimator.ts b/packages/core/src/hooks/useAnimator.tsnew file mode 100644index 0000000000..ea2db99df3--- /dev/null+++ b/packages/core/src/hooks/useAnimator.ts@@ -0,0 +1,67 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useAnimator.ts+ * @input React (useState), the element ref the caller owns, the public+ * animator factory (animator/createAnimator.ts) and useAttachment+ * @output Exports `useAnimator(ref)`: the public animator for the element+ * behind `ref`+ * @position Public hook, exported from `@astryxdesign/core/hooks`. A thin+ * wrapper over `createAnimator` with no behavior of its own.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/hooks/useAnimator.test.tsx+ * - /packages/core/src/hooks/useAnimator.doc.mjs+ */++import {useState, type RefObject} from 'react';+import {+ createAttachableAnimator,+ type AnimatorHandle,+} from '../animator/createAnimator';+import {useAttachment} from './useAttachment';++/**+ * Animates the element behind `ref` with the motion Core uses. Call+ * `animate`, `decay`, `set`, `get`, `getVelocity` or `stop` on the returned+ * animator from event handlers and effects. Pass the same `ref` to a gesture+ * hook to drag and animate one element.+ *+ * The hook makes the animator once, and animating never re-renders the+ * component. After each commit, the animator follows the element behind+ * `ref`, also a node that replaces it. An unmount stops running motion and+ * drops the values. A remount, or a node that replaces the element, starts+ * at rest. While no element is attached, every call does nothing, and+ * `animate` and `decay` resolve at once.+ *+ * @example+ * ```+ * const ref = useRef<HTMLDivElement>(null);+ * const animator = useAnimator(ref);+ * return (+ * <div ref={ref} onClick={() => animator.animate({scale: 1.2})}>+ * Card+ * </div>+ * );+ * ```+ */+export function useAnimator(+ ref: RefObject<HTMLElement | null>,+): AnimatorHandle {+ const [{handle, attach}] = useState(() => {+ const {animator, attach: attachElement} = createAttachableAnimator();+ // The handle without `destroy`: the hook owns the element's lifetime.+ const {destroy: _destroy, ...handle} = animator;+ return {+ handle,+ attach: (element: HTMLElement) => {+ attachElement(element);+ return () => attachElement(null);+ },+ };+ });+ useAttachment(ref, attach, null);+ return handle;+}diff --git a/packages/core/src/hooks/useAttachment.ts b/packages/core/src/hooks/useAttachment.tsindex 77a1d8b4be..591e0c124d 100644--- a/packages/core/src/hooks/useAttachment.ts+++ b/packages/core/src/hooks/useAttachment.ts@@ -9,7 +9,7 @@* @output Exports useAttachment and useAttachmentPair (two elements): they keep* the attach function bound to the nodes the refs hold across commits* @position Internal React helper, not in hooks/index.ts: the one attach and- * release lifecycle of the gesture hooks and the pager+ * release lifecycle of the gesture hooks, the pager and useAnimator** SYNC: When modified, update gestures/__tests__/useGestureRecognizer.test.tsx,* gestures/__tests__/useFingerScroll.test.tsx anddiff --git a/packages/core/src/hooks/usePager.test.ts b/packages/core/src/hooks/usePager.test.tsindex 8b786a7c0b..46831b156e 100644--- a/packages/core/src/hooks/usePager.test.ts+++ b/packages/core/src/hooks/usePager.test.ts@@ -17,7 +17,7 @@ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';import {GestureHost} from '../gestures/GestureHost';import {PanGestureRecognizer} from '../gestures/PanGestureRecognizer';import {ManualClock} from '../gestures/__tests__/harness';-import {createAnimator, type Animator} from '../motion/animator';+import {createMotionAnimator, type Animator} from '../motion/animator';import {solveAnimatedPageScroll, solvePaging} from '../motion/paging';import type * as motionResolution from '../motion/resolveMotion';import {resolveMotion} from '../motion/resolveMotion';@@ -305,7 +305,7 @@ function setup(options: Partial<PagerOptions> = {}, rtl = false): Fixture {value: WIDTH,configurable: true,});- const animator = createAnimator(track, {+ const animator = createMotionAnimator(track, {now: () => now,requestFrame: callback => {frameQueue.push(callback);@@ -1259,7 +1259,7 @@ describe('createPager', () => {// (DR3). The drag itself follows the pointer.function reducedPager(f: Fixture, defaultIndex: number, coarse: boolean) {stubMedia(true, coarse);- const reduced = createAnimator(f.track, {+ const reduced = createMotionAnimator(f.track, {now: () => now,requestFrame: callback => {frameQueue.push(callback);@@ -1928,7 +1928,7 @@ function setupChildren(value: WIDTH,configurable: true,});- const animator = createAnimator(track, {+ const animator = createMotionAnimator(track, {now: () => now,requestFrame: callback => {frameQueue.push(callback);@@ -2461,7 +2461,7 @@ describe('pre-review fixes', () => {configurable: true,});const host = {attach: () => () => {}} as unknown as GestureHost;- const animator = createAnimator(track, {+ const animator = createMotionAnimator(track, {now: () => now,requestFrame: callback => {frameQueue.push(callback);diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex e768052a92..a616f32872 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -173,6 +173,19 @@ export * from './Outline';// Overflow listexport * from './OverflowList';+// Animating one element: from the package root only, since one API has one+// entry. Its hook ships from './hooks'.+export {+ createAnimator,+ type Animator,+ type AnimatorAnimateOptions,+ type AnimatorChannel,+ type AnimatorDecayVelocity,+ type AnimatorHandle,+ type AnimatorSnapshot,+ type AnimatorValues,+} from './animator/createAnimator';+// Hooksexport * from './hooks';diff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.mdindex 4a21eb3f43..5c81bb7ae5 100644--- a/packages/core/src/motion/README.md+++ b/packages/core/src/motion/README.md@@ -64,7 +64,7 @@ the timings that decide who gets a touch are not roles.## Animator```-import {createAnimator} from '../motion/animator';+import {createMotionAnimator} from '../motion/animator';import {coast} from '../motion/coast';import {solveSpringTowardRamp, toSpring} from '../motion/spring';import {resolveMotion} from '../motion/resolveMotion';@@ -73,7 +73,7 @@ import {registerSpringsTable, springs} from '../motion/uikit';// Once, so the springs are registered as their roles:registerSpringsTable();-const animator = createAnimator(sheet);+const animator = createMotionAnimator(sheet);// The animator plays a motion role (spec:AST-094 FR4), its table value, as the// per-role tables stay internal (DEC-15); math on a spring reads the role with// resolveMotion.@@ -170,7 +170,7 @@ await handle.finished; // true if it ran to the end, false if interrupted- `animatorFor(element)` returns the one animator for an element, so codethat animates it from several places (a swipe on x, a removal on y)composes in one `translate` track.-- `createAnimator(dialog, {pseudoElement: '::backdrop'})` drives a+- `createMotionAnimator(dialog, {pseudoElement: '::backdrop'})` drives apseudo-element; with no inline style to hold it, a static filling animationholds its end value until the next animation replaces it, while thepseudo-element exists. A dialog's `::backdrop` is made again each time thediff --git a/packages/core/src/motion/__tests__/animator.interaction.browser.spec.ts b/packages/core/src/motion/__tests__/animator.interaction.browser.spec.tsindex 8702fa3786..d1b46d3124 100644--- a/packages/core/src/motion/__tests__/animator.interaction.browser.spec.ts+++ b/packages/core/src/motion/__tests__/animator.interaction.browser.spec.ts@@ -109,7 +109,7 @@ async function open(page: Page) {</style><div id="box"></div><script>${script}</script>-<script>window.animator = Motion.createAnimator(document.getElementById('box'));</script>`;+<script>window.animator = Motion.createMotionAnimator(document.getElementById('box'));</script>`;await page.route('http://motion.test/', async route =>route.fulfill({contentType: 'text/html', body: html}),);@@ -374,7 +374,7 @@ test('a frame painted before the compositor has the curve shows the element wherdocument.body.append(element);return {element,- animator: Motion.createAnimator(element, now ? {now} : {}),+ animator: Motion.createMotionAnimator(element, now ? {now} : {}),};};const x = (element: HTMLElement) =>@@ -910,7 +910,7 @@ test('a role variable set on a scope changes nothing while touch motion stays inconst report: Record<string, {worst: number; lowest: number}> = {};for (const id of ['plain', 'themed'] as const) {const element = document.getElementById(id) as HTMLElement;- const animator = Motion.createAnimator(element);+ const animator = Motion.createMotionAnimator(element);animator.set({y: 300});const handle = animator.animate({y: 0}, {spring: Motion.springs.settle});await handle.started;@@ -1014,7 +1014,7 @@ test('a fade-in on an element its stylesheet hides stays visible once it retireselement.style.cssText ='position:absolute;top:120px;left:0;width:48px;height:48px;background:#c63';document.body.append(element);- const animator = Motion.createAnimator(element);+ const animator = Motion.createMotionAnimator(element);animator.set({opacity: 0});animator.animate({opacity: 1}, {spring});await new Promise<void>(resolve => {@@ -1086,7 +1086,7 @@ test('a dialog\u2019s ::backdrop plays the curve and holds its end state', asyncconst dialog = document.createElement('dialog');document.body.append(dialog);dialog.showModal();- const backdrop = Motion.createAnimator(dialog, {+ const backdrop = Motion.createMotionAnimator(dialog, {pseudoElement: '::backdrop',});backdrop.set({opacity: 0});diff --git a/packages/core/src/motion/__tests__/motionBundle.ts b/packages/core/src/motion/__tests__/motionBundle.tsindex 0c5447b6f5..874fb5e2a8 100644--- a/packages/core/src/motion/__tests__/motionBundle.ts+++ b/packages/core/src/motion/__tests__/motionBundle.ts@@ -8,7 +8,7 @@* (global `Motion`), and the type of that global*/-export {createAnimator} from '../animator';+export {createMotionAnimator} from '../animator';export {solveSpring, toSpring} from '../spring';export {registerSpringsTable, springs} from '../uikit/springs';export {motionRoleOf} from '../roles';diff --git a/packages/core/src/motion/animator.test.ts b/packages/core/src/motion/animator.test.tsindex da166eef64..f52f2cbb86 100644--- a/packages/core/src/motion/animator.test.ts+++ b/packages/core/src/motion/animator.test.ts@@ -19,7 +19,7 @@ import path from 'node:path';import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';import {animatorFor,- createAnimator,+ createMotionAnimator,END_HOLD_MS,PROMOTION_LINGER_MS,type AnimatorOptions,@@ -205,7 +205,7 @@ function setup({}: AnimatorOptions & {reduced?: boolean; coarse?: boolean} = {}) {stubMedia(reduced, coarse);const element = document.createElement('div');- const animator = createAnimator(element, {+ const animator = createMotionAnimator(element, {now: () => clock,requestFrame,...options,@@ -2071,11 +2071,11 @@ describe('promotion: a compositing layer while it moves', () => {.mock.calls.filter(([read]) => read === node).length;const removed = document.createElement('div');document.body.append(removed);- createAnimator(removed, {now: () => clock, requestFrame});+ createMotionAnimator(removed, {now: () => clock, requestFrame});removed.remove();const kept = document.createElement('div');document.body.append(kept);- createAnimator(kept, {now: () => clock, requestFrame});+ createMotionAnimator(kept, {now: () => clock, requestFrame});await vi.advanceTimersByTimeAsync(0);expect(readsOf(removed)).toBe(0);// A node still in the document is read, once, in that task.@@ -2089,7 +2089,7 @@ describe('promotion: a compositing layer while it moves', () => {stylesheet['will-change'] = 'transform, opacity';stubMedia(false, false);const element = document.createElement('div');- const animator = createAnimator(element, {+ const animator = createMotionAnimator(element, {now: () => clock,requestFrame,});@@ -2834,7 +2834,7 @@ describe('Reduced Motion (design:reduced-motion)', () => {it('a running dip survives any re-attach, so the move never passes in view', async () => {const halfway = async (- animator: ReturnType<typeof createAnimator>,+ animator: ReturnType<typeof createMotionAnimator>,start: number,): Promise<number> => {// The plan lands by timer: step the clock to the landing.@@ -4171,7 +4171,7 @@ describe('pseudoElement: a dialog\u2019s ::backdrop', () => {describe('attach', () => {it('keeps state without an element and resumes the curve on attach', () => {- const animator = createAnimator(null, {+ const animator = createMotionAnimator(null, {now: () => clock,});animator.animate({x: 300}, {spring: springs.settle});@@ -4262,7 +4262,7 @@ describe('attach', () => {it('writes nothing for channels at identity', () => {const element = document.createElement('div');- createAnimator(element);+ createMotionAnimator(element);expect(element.getAttribute('style')).toBeNull();});});diff --git a/packages/core/src/motion/animator.ts b/packages/core/src/motion/animator.tsindex dbe6bdd362..0a3fb468dd 100644--- a/packages/core/src/motion/animator.ts+++ b/packages/core/src/motion/animator.ts@@ -4,11 +4,12 @@* @file animator.ts* @input An element, target values, and a spring, momentum curves (coast.ts)* or any closed-form curve- * @output Exports `createAnimator`: a compositor animator for translate,- * rotate, scale and opacity, with presentation values and velocities read- * from the analytic curves, velocity-preserving retargeting, freeze-in-place- * `stop`, completion promises, a shared clock, and UIKit's Reduced Motion- * substitution; plus its option, handle and transition types+ * @output Exports `createMotionAnimator`, a compositor animator for+ * translate, rotate, scale and opacity, and its option, handle and+ * transition types. It reads presentation values and velocities from the+ * analytic curves. It retargets with the velocity kept, freezes in place on+ * `stop`, and gives completion promises, a shared clock, and UIKit's+ * Reduced Motion substitution.* @position Motion foundation (DOM). Internal to core: components use it for* every touch-presentation animation; not exported from the package entry*@@ -297,7 +298,7 @@ export interface MotionCurve {}/**- * Options of `createAnimator`.+ * Options of `createMotionAnimator`.*//** How `set` puts values in place. */export interface SetOptions {@@ -815,7 +816,7 @@ export function animatorFor(const key = options.pseudoElement ?? '';let animator = byPseudo.get(key);if (animator == null) {- animator = createAnimator(element, options);+ animator = createMotionAnimator(element, options);byPseudo.set(key, animator);}return animator;@@ -932,7 +933,7 @@ const REDUCED_TRANSITION: SpringTransition = {** @example* ```- * const animator = createAnimator(sheet);+ * const animator = createMotionAnimator(sheet);* // finger lifts at 1200 px/s heading for the detent at 0 (a component* // passes the spring of its motion role):* animator.animate({y: 0}, {spring: {response: 0.45, dampingRatio: 0.9}, velocity: {y: 1200}});@@ -941,7 +942,7 @@ const REDUCED_TRANSITION: SpringTransition = {* animator.stop(['y']);* ```*/-export function createAnimator(+export function createMotionAnimator(element: HTMLElement | null,options: AnimatorOptions = {},): Animator {diff --git a/packages/core/src/motion/resolveMotion.test.ts b/packages/core/src/motion/resolveMotion.test.tsindex b2a1502081..cf5a306761 100644--- a/packages/core/src/motion/resolveMotion.test.ts+++ b/packages/core/src/motion/resolveMotion.test.ts@@ -12,7 +12,7 @@*/import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';-import {createAnimator} from './animator';+import {createMotionAnimator} from './animator';import {coast} from './coast';import {resolveMotion} from './resolveMotion';import {solveSpring, toSpring} from './spring';@@ -93,7 +93,7 @@ describe('resolveMotion while the per-role tables stay internal (DEC-15)', () =>describe('the animator', () => {it("plays the table's spring even where a scope sets the role's variable", () => {const child = scoped({'--motion-springs-settle': '0.8s 0.3'});- const animator = createAnimator(child, {now: () => 0});+ const animator = createMotionAnimator(child, {now: () => 0});animator.set({y: 300});animator.animate({y: 0}, {spring: springs.settle}, {at: 0});const table = solveSpring(toSpring(springs.settle), {from: 300, to: 0});@@ -104,7 +104,7 @@ describe('the animator', () => {});it('a coast plays the table edge spring whatever a scope sets: scroll.bounce is no role', () => {const child = scoped({'--motion-scroll-bounce': '0.8s 0.3'});- const animator = createAnimator(child, {now: () => 0});+ const animator = createMotionAnimator(child, {now: () => 0});animator.set({x: 60});// Released past the edge: straight back on the edge spring.animator.decay(diff --git a/scripts/motion-node-load.test.mjs b/scripts/motion-node-load.test.mjsindex d6b9b15aac..2005604556 100644--- a/scripts/motion-node-load.test.mjs+++ b/scripts/motion-node-load.test.mjs@@ -28,7 +28,7 @@ const coreSrc = path.join(root, 'packages/core/src');* the press paint's styles).*/const ENTRY = `-export {createAnimator, animatorFor, SETTLE_THRESHOLD} from './motion/animator';+export {createMotionAnimator, animatorFor, SETTLE_THRESHOLD} from './motion/animator';export {reducedMotionFade} from './motion/reducedMotion';export {resolveMotion} from './motion/resolveMotion';export {solveSpring, toSpring} from './motion/spring';@@ -98,10 +98,10 @@ describe('the touch motion foundation in plain Node', () => {'-e',`const m = await import(${JSON.stringify(pathToFileURL(file).href)});m.registerSpringsTable();- const animator = m.createAnimator(null);+ const animator = m.createMotionAnimator(null);const pan = new m.PanGestureRecognizer({});console.log(JSON.stringify({- createAnimator: typeof m.createAnimator,+ createMotionAnimator: typeof m.createMotionAnimator,set: typeof animator.set,sheet: m.springs.sheetPresent != null,pan: typeof pan.state,@@ -110,7 +110,7 @@ describe('the touch motion foundation in plain Node', () => {{encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe']},);expect(JSON.parse(out.trim().split('\n').at(-1))).toEqual({- createAnimator: 'function',+ createMotionAnimator: 'function',set: 'function',sheet: true,pan: 'string',