Skip to content

Commit 6d3d599

Browse files
committed
feat(core): createAnimator and useAnimator animate one element
The public animator (spec:AST-107 FR3, FR6): createAnimator(element) over the internal animator, with animate, decay, set, get, getVelocity, stop and destroy, from the package root; and useAnimator(ref), which takes the element's ref like the gesture hooks, so a gesture hook can share the element, and returns the animator. After every commit the hook follows the element behind the ref, through the attach lifecycle the gesture hooks share (useAttachment). The internal factory is renamed createMotionAnimator, so no internal factory shares a public factory's name. Docs, a changeset, and playing-cards templates in React and plain JavaScript, with their registrations. In both templates the card is an image named by its rank and suit, renamed on each deal; one card leaves at a time (a Discard press while a card leaves deals no second card); and a drag the browser cancels springs back. The plain-JavaScript example mounts its deck from a callback ref on its wrapper, whose cleanup takes it down. The core API report gains the animator's rows.
1 parent 5a455f5 commit 6d3d599

33 files changed

Lines changed: 2516 additions & 38 deletions

‎.changeset/public-animator.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
'@astryxdesign/core': patch
3+
'@astryxdesign/cli': patch
4+
---
5+
6+
[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.
7+
8+
@vjeux

‎apps/sandbox/scripts/next-export-routes.json‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@
6161
"/templates/",
6262
"/templates/AlertDialogAsyncAction/",
6363
"/templates/AlertDialogDeleteConfirmation/",
64+
"/templates/AnimatorPlayingCards/",
65+
"/templates/AnimatorPlayingCardsVanilla/",
6466
"/templates/AppShellContentOnly/",
6567
"/templates/AppShellMobileHookUsage/",
6668
"/templates/AppShellShowcase/",

‎internal/shadcn-registry/routes.lock.json‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1959,6 +1959,11 @@
19591959
"path": "examples/context-menu/bottom-sheet",
19601960
"aliases": []
19611961
},
1962+
{
1963+
"name": "example-create-animator-playing-cards-in-plain-java-script",
1964+
"path": "examples/create-animator/playing-cards-in-plain-java-script",
1965+
"aliases": []
1966+
},
19621967
{
19631968
"name": "example-date-input-clearable",
19641969
"path": "examples/date-input/clearable",
@@ -3634,6 +3639,11 @@
36343639
"path": "examples/typeahead/with-validation",
36353640
"aliases": []
36363641
},
3642+
{
3643+
"name": "example-use-animator-playing-cards",
3644+
"path": "examples/use-animator/playing-cards",
3645+
"aliases": []
3646+
},
36373647
{
36383648
"name": "example-use-app-shell-mobile-custom-mobile-trigger",
36393649
"path": "examples/use-app-shell-mobile/custom-mobile-trigger",
@@ -3769,11 +3779,21 @@
37693779
"path": "examples/visually-hidden/supplementary-context",
37703780
"aliases": []
37713781
},
3782+
{
3783+
"name": "hook-create-animator",
3784+
"path": "hooks/create-animator",
3785+
"aliases": []
3786+
},
37723787
{
37733788
"name": "hook-use-animated-layout",
37743789
"path": "hooks/use-animated-layout",
37753790
"aliases": []
37763791
},
3792+
{
3793+
"name": "hook-use-animator",
3794+
"path": "hooks/use-animator",
3795+
"aliases": []
3796+
},
37773797
{
37783798
"name": "hook-use-announce",
37793799
"path": "hooks/use-announce",
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// Copyright (c) Meta Platforms, Inc. and affiliates.
2+
3+
/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
4+
export const doc = {
5+
type: 'block',
6+
exampleFor: 'createAnimator',
7+
name: 'createAnimator — Playing cards in plain JavaScript',
8+
displayName: 'createAnimator — Playing cards in plain JavaScript',
9+
description:
10+
'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.',
11+
isReady: true,
12+
aspectRatio: 4 / 3,
13+
componentsUsed: [],
14+
};
Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
// Copyright (c) Meta Platforms, Inc. and affiliates.
2+
3+
'use client';
4+
5+
import {createAnimator} from '@astryxdesign/core';
6+
7+
const DECK = [
8+
{face: 'A\u2660', name: 'Ace of spades'},
9+
{face: 'K\u2665', name: 'King of hearts'},
10+
{face: 'Q\u2663', name: 'Queen of clubs'},
11+
{face: 'J\u2666', name: 'Jack of diamonds'},
12+
];
13+
/** A release faster than this (px/s) throws the card away. */
14+
const THROW_SPEED = 1000;
15+
/** The slowest throw, so a thrown card always leaves the table. */
16+
const MIN_THROW = 1600;
17+
18+
/**
19+
* A deck on a table, in plain JavaScript: no React below this line. It
20+
* returns a function that takes it down again.
21+
*/
22+
function mountDeck(table: HTMLElement, discardButton: HTMLButtonElement) {
23+
let top = 0;
24+
const card = document.createElement('div');
25+
card.textContent = DECK[0].face;
26+
// An image's name is all a screen reader announces, so it names the card.
27+
card.setAttribute('role', 'img');
28+
card.setAttribute('aria-label', DECK[0].name);
29+
Object.assign(card.style, {
30+
width: '120px',
31+
height: '170px',
32+
display: 'grid',
33+
placeItems: 'center',
34+
font: 'bold 40px system-ui, sans-serif',
35+
// The theme's surface and text, so the rank reads in light and dark.
36+
borderRadius: 'var(--radius-container)',
37+
backgroundColor: 'var(--color-background-surface)',
38+
color: 'var(--color-text-primary)',
39+
boxShadow: '0 2px 8px var(--color-shadow)',
40+
touchAction: 'none',
41+
cursor: 'grab',
42+
userSelect: 'none',
43+
});
44+
// Announces each discard to screen readers.
45+
const status = document.createElement('div');
46+
status.setAttribute('aria-live', 'polite');
47+
Object.assign(status.style, {
48+
position: 'absolute',
49+
width: '1px',
50+
height: '1px',
51+
overflow: 'hidden',
52+
clipPath: 'inset(50%)',
53+
whiteSpace: 'nowrap',
54+
});
55+
table.append(card, status);
56+
const animator = createAnimator(card);
57+
// One discard at a time: a press while a card leaves deals no second card.
58+
let isDiscarding = false;
59+
60+
// Announces the discard and deals the next card in place of the old one.
61+
async function dealNext() {
62+
status.textContent = `${DECK[top % DECK.length].name} discarded`;
63+
top += 1;
64+
const next = DECK[top % DECK.length];
65+
card.textContent = next.face;
66+
card.setAttribute('aria-label', next.name);
67+
animator.set({x: 0, y: 0, rotate: 0, scale: 0.9, opacity: 0});
68+
isDiscarding = false;
69+
await animator.animate({scale: 1, opacity: 1});
70+
}
71+
72+
async function discard(vx: number, vy: number) {
73+
if (isDiscarding) {
74+
return;
75+
}
76+
isDiscarding = true;
77+
const speed = Math.hypot(vx, vy);
78+
const boost = speed < MIN_THROW ? MIN_THROW / Math.max(speed, 1) : 1;
79+
// The card coasts on while it fades; once it is gone, the next card is
80+
// dealt in place, which ends the coast. A coast continues the person's
81+
// throw, so Reduce Motion keeps it.
82+
void animator.decay({x: speed < 1 ? MIN_THROW : vx * boost, y: vy * boost});
83+
await animator.animate({opacity: 0});
84+
await dealNext();
85+
}
86+
87+
// The drag: follow the pointer, then read the 80 ms before the release, so
88+
// a pointer that held still before letting go releases at rest.
89+
let origin: {x: number; y: number} | null = null;
90+
let samples: {t: number; x: number; y: number}[] = [];
91+
function onDown(event: PointerEvent) {
92+
card.setPointerCapture(event.pointerId);
93+
animator.stop();
94+
const {x, y} = animator.get();
95+
origin = {x: event.clientX - x, y: event.clientY - y};
96+
samples = [];
97+
}
98+
function onMove(event: PointerEvent) {
99+
if (origin == null) {
100+
return;
101+
}
102+
const x = event.clientX - origin.x;
103+
const y = event.clientY - origin.y;
104+
samples.push({t: event.timeStamp, x, y});
105+
animator.set({x, y, rotate: x / 18});
106+
}
107+
// A cancelled pointer was not let go, so the card springs back.
108+
function onCancel() {
109+
if (origin == null) {
110+
return;
111+
}
112+
origin = null;
113+
void animator.animate({x: 0, y: 0, rotate: 0});
114+
}
115+
function onUp(event: PointerEvent) {
116+
if (origin == null) {
117+
return;
118+
}
119+
origin = null;
120+
const recent = samples.filter(s => event.timeStamp - s.t <= 80);
121+
const first = recent[0];
122+
const last = recent.at(-1);
123+
const seconds = last && first ? (last.t - first.t) / 1000 : 0;
124+
const vx = seconds > 0 && last && first ? (last.x - first.x) / seconds : 0;
125+
const vy = seconds > 0 && last && first ? (last.y - first.y) / seconds : 0;
126+
if (Math.abs(vx) > THROW_SPEED) {
127+
void discard(vx, vy);
128+
} else {
129+
void animator.animate(
130+
{x: 0, y: 0, rotate: 0},
131+
{velocity: {x: vx, y: vy}},
132+
);
133+
}
134+
}
135+
// The button moves the card off on the state-change motion: a planned
136+
// move, which Reduce Motion turns into a fade where the card is.
137+
async function discardWithButton() {
138+
if (isDiscarding) {
139+
return;
140+
}
141+
isDiscarding = true;
142+
await animator.animate({x: 400, opacity: 0});
143+
await dealNext();
144+
}
145+
const onDiscard = () => void discardWithButton();
146+
147+
card.addEventListener('pointerdown', onDown);
148+
card.addEventListener('pointermove', onMove);
149+
card.addEventListener('pointerup', onUp);
150+
card.addEventListener('pointercancel', onCancel);
151+
discardButton.addEventListener('click', onDiscard);
152+
return () => {
153+
discardButton.removeEventListener('click', onDiscard);
154+
animator.destroy();
155+
card.remove();
156+
status.remove();
157+
};
158+
}
159+
160+
/**
161+
* Mounts the deck when the wrapper attaches, and takes it down when it
162+
* detaches: its cleanup is the callback ref's.
163+
*/
164+
function mountTable(wrapper: HTMLDivElement | null) {
165+
if (wrapper == null) {
166+
return undefined;
167+
}
168+
const table = wrapper.firstElementChild as HTMLElement;
169+
const button = wrapper.querySelector('button') as HTMLButtonElement;
170+
return mountDeck(table, button);
171+
}
172+
173+
export default function AnimatorPlayingCardsVanilla() {
174+
return (
175+
<div
176+
ref={mountTable}
177+
style={{display: 'grid', gap: 16, padding: 16, maxWidth: 360}}>
178+
<div style={{height: 200, display: 'grid', placeItems: 'center'}} />
179+
<button type="button">Discard the top card</button>
180+
</div>
181+
);
182+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Copyright (c) Meta Platforms, Inc. and affiliates.
2+
3+
/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
4+
export const doc = {
5+
type: 'block',
6+
exampleFor: 'useAnimator',
7+
name: 'useAnimator — Playing cards',
8+
displayName: 'useAnimator — Playing cards',
9+
description:
10+
'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.',
11+
isReady: true,
12+
aspectRatio: 4 / 3,
13+
componentsUsed: [
14+
'Card',
15+
'Button',
16+
'Layout',
17+
'Text',
18+
'VisuallyHidden',
19+
'useAnimator',
20+
],
21+
};

0 commit comments

Comments
 (0)