From 025e68bd072dc2bbfcc04f49eb63780b234636f7 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 2 Nov 2026 23:09:29 -0800 Subject: [PATCH] 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, along with its callers in the Slider's and the Switch's touch controllers, the SegmentedControl's selection motion and the pager's tests, 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), a leaving card takes no press, a discard ends a drag in progress, and a press on a card fading in moves only its position; 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. When the element behind useAnimator's ref unmounts, or a node replaces it, the animator's values return to rest, so a remount or a new node starts from the element's resting values. AST-107 records the owner's decision on four edge behaviors of the public animator and pan gesture (DEC-4): FR1 and FR6 state that a cancelled pan reports zero velocity, how the pan factory's destroy and the hook's unmount report, and that an opacity decay stops at 0 or 1; FR3 states the remount. --- .changeset/public-animator.md | 8 + apps/sandbox/scripts/next-export-routes.json | 2 + .../AST-107-public-gesture-hooks/spec.md | 24 +- internal/shadcn-registry/routes.lock.json | 20 + .../AnimatorPlayingCardsVanilla.doc.mjs | 14 + .../AnimatorPlayingCardsVanilla.tsx | 199 +++++++ .../useAnimator/AnimatorPlayingCards.doc.mjs | 21 + .../useAnimator/AnimatorPlayingCards.tsx | 210 +++++++ .../foundation/doc-compiler/inputs.test.mjs | 1 + .../no-icon-set/search-icon-set.json | 2 +- .../no-icon-set/search-icon-set.txt | 2 +- packages/core/api-report.md | 24 + .../useSegmentedSelectionMotion.test.ts | 6 +- .../useSegmentedSelectionMotion.ts | 9 +- .../core/src/Slider/sliderTouchController.ts | 4 +- .../core/src/Switch/useSwitchTouch.test.ts | 2 +- packages/core/src/Switch/useSwitchTouch.ts | 8 +- .../src/animator/__tests__/animatorBundle.ts | 14 + ...createAnimator.interaction.browser.spec.ts | 222 ++++++++ .../core/src/animator/createAnimator.doc.mjs | 153 ++++++ .../animator/createAnimator.server.test.ts | 51 ++ .../core/src/animator/createAnimator.test.ts | 519 ++++++++++++++++++ packages/core/src/animator/createAnimator.ts | 324 +++++++++++ .../animator/playingCardsTemplates.test.tsx | 356 ++++++++++++ .../core/src/animator/publicSurface.test.ts | 72 +++ .../__tests__/browser/presentedFixture.ts | 4 +- packages/core/src/hooks/index.ts | 2 + packages/core/src/hooks/useAnimator.doc.mjs | 109 ++++ packages/core/src/hooks/useAnimator.test.tsx | 196 +++++++ packages/core/src/hooks/useAnimator.ts | 67 +++ packages/core/src/hooks/useAttachment.ts | 2 +- packages/core/src/hooks/usePager.test.ts | 10 +- packages/core/src/index.ts | 13 + packages/core/src/motion/README.md | 6 +- .../animator.interaction.browser.spec.ts | 10 +- .../core/src/motion/__tests__/motionBundle.ts | 2 +- packages/core/src/motion/animator.test.ts | 16 +- packages/core/src/motion/animator.ts | 19 +- .../core/src/motion/resolveMotion.test.ts | 6 +- scripts/motion-node-load.test.mjs | 8 +- 40 files changed, 2678 insertions(+), 59 deletions(-) create mode 100644 .changeset/public-animator.md create mode 100644 packages/cli/assets/templates/blocks/components/createAnimator/AnimatorPlayingCardsVanilla.doc.mjs create mode 100644 packages/cli/assets/templates/blocks/components/createAnimator/AnimatorPlayingCardsVanilla.tsx create mode 100644 packages/cli/assets/templates/blocks/components/useAnimator/AnimatorPlayingCards.doc.mjs create mode 100644 packages/cli/assets/templates/blocks/components/useAnimator/AnimatorPlayingCards.tsx create mode 100644 packages/core/src/animator/__tests__/animatorBundle.ts create mode 100644 packages/core/src/animator/__tests__/createAnimator.interaction.browser.spec.ts create mode 100644 packages/core/src/animator/createAnimator.doc.mjs create mode 100644 packages/core/src/animator/createAnimator.server.test.ts create mode 100644 packages/core/src/animator/createAnimator.test.ts create mode 100644 packages/core/src/animator/createAnimator.ts create mode 100644 packages/core/src/animator/playingCardsTemplates.test.tsx create mode 100644 packages/core/src/animator/publicSurface.test.ts create mode 100644 packages/core/src/hooks/useAnimator.doc.mjs create mode 100644 packages/core/src/hooks/useAnimator.test.tsx create mode 100644 packages/core/src/hooks/useAnimator.ts diff --git a/.changeset/public-animator.md b/.changeset/public-animator.md new file mode 100644 index 0000000000000..378452818eeb3 --- /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. + +@vjeux diff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.json index 6716cbcda9015..ae110bc7ac18a 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.md index 9b2f6b4a8b069..85fe7247c2e27 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 call before `ref` attaches, and any call after `destroy` do nothing and resolve at once. 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 long presses, 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 every listener the factory added, and importing a factory does no DOM work, so it is 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 or motion 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, and Rejected: a context menu reachable only through the `` 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 questions None. diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json index 0612525a49021..0c7d8d4bb4c79 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", @@ -3776,11 +3786,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.mjs new file mode 100644 index 0000000000000..2573e34d272c7 --- /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.tsx new file mode 100644 index 0000000000000..66fa59ecd5ea7 --- /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 ( +
+
+ +
+ ); +} diff --git a/packages/cli/assets/templates/blocks/components/useAnimator/AnimatorPlayingCards.doc.mjs b/packages/cli/assets/templates/blocks/components/useAnimator/AnimatorPlayingCards.doc.mjs new file mode 100644 index 0000000000000..bcb27e22f62ca --- /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.tsx new file mode 100644 index 0000000000000..3dd8e21ac706d --- /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(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) => { + // 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) => { + 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) => { + 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 ( + + + Drag the card and let go. A gentle release springs it back; a quick + flick throws it away. + +
+ + + + {card.rank} + + {card.suit} + + +
+ +