Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

docs(core): open the pan hook pages with a minimal draggable box (#9928)

Christopher Chedeaudf15de7fc394
diff --git a/.changeset/pan-gesture-draggable-box-examples.md b/.changeset/pan-gesture-draggable-box-examples.md
new file mode 100644
index 0000000000..e3242a3eac
--- /dev/null
+++ b/.changeset/pan-gesture-draggable-box-examples.md
@@ -0,0 +1,8 @@
+---
+'@astryxdesign/core': patch
+'@astryxdesign/cli': patch
+---
+
+[docs] The `usePanGesture` page opens with a draggable box in two forms side by side: the hook and `createPanGesture`, which takes any element, with the same StyleX styles and Astryx tokens. The playing card follows as the advanced example. The `createPanGesture` page points to that example, and the `usePanGesture` guidance warns against holding the drag offset in a large component's state.
+
+@vjeux
diff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.json
index 015c01b26e..40d2bb7902 100644
--- a/apps/sandbox/scripts/next-export-routes.json
+++ b/apps/sandbox/scripts/next-export-routes.json
@@ -470,8 +470,8 @@
"/templates/PaginationPageSize/",
"/templates/PaginationVariants/",
"/templates/PaginationWithTable/",
+ "/templates/PanDraggableBox/",
"/templates/PanPlayingCard/",
- "/templates/PanPlayingCardVanilla/",
"/templates/PopoverBottomSheetAlternative/",
"/templates/PopoverConfirmAction/",
"/templates/PopoverFilterPanel/",
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index b8da3bf073..2ca075faec 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -1966,11 +1966,6 @@
"path": "examples/create-animator/playing-cards-in-plain-java-script",
"aliases": []
},
- {
- "name": "example-create-pan-gesture-a-playing-card-without-react",
- "path": "examples/create-pan-gesture/a-playing-card-without-react",
- "aliases": []
- },
{
"name": "example-date-input-clearable",
"path": "examples/date-input/clearable",
@@ -3782,8 +3777,13 @@
"aliases": []
},
{
- "name": "example-use-pan-gesture-a-playing-card",
- "path": "examples/use-pan-gesture/a-playing-card",
+ "name": "example-use-pan-gesture-a-draggable-box",
+ "path": "examples/use-pan-gesture/a-draggable-box",
+ "aliases": []
+ },
+ {
+ "name": "example-use-pan-gesture-a-playing-card-advanced",
+ "path": "examples/use-pan-gesture/a-playing-card-advanced",
"aliases": []
},
{
diff --git a/packages/cli/api/template/pan-draggable-box.test.tsx b/packages/cli/api/template/pan-draggable-box.test.tsx
new file mode 100644
index 0000000000..8553887b01
--- /dev/null
+++ b/packages/cli/api/template/pan-draggable-box.test.tsx
@@ -0,0 +1,197 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @vitest-environment jsdom
+
+/**
+ * @file Behavior test for the draggable-box pan block.
+ * @input The shipped PanDraggableBox block, rendered in jsdom with the pans,
+ * StyleX and the Astryx components stubbed. It shows one box with
+ * usePanGesture and one with createPanGesture.
+ * @output Guards that each box follows its own drag through its StyleX drag
+ * style and springs back when it is let go. A person who reduces motion gets
+ * no spring. The createPanGesture pan comes down with the block.
+ * @position CLI template regression coverage; runs in the node test project,
+ * under jsdom for this file.
+ */
+
+import {act, createElement, type ReactNode} from 'react';
+import {createRoot} from 'react-dom/client';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import PanDraggableBox from '../../assets/templates/blocks/components/usePanGesture/PanDraggableBox';
+
+type PanEvent = {
+ state: 'began' | 'changed' | 'ended' | 'cancelled';
+ translation: {x: number; y: number};
+ velocity: {x: number; y: number};
+};
+type Listener = (event: PanEvent) => void;
+// The stubbed pans keep each form's listener, so a case can drive one drag.
+const pan = vi.hoisted(() => ({
+ hook: null as null | ((event: PanEvent) => void),
+ factory: null as null | ((event: PanEvent) => void),
+ destroyed: 0,
+}));
+// This project does not compile StyleX. The stub merges a style list into one
+// object on `data-style`, so a case reads the styles the block applies.
+const style = vi.hoisted(() => ({
+ attribute: (...styles: unknown[]) => ({
+ 'data-style': JSON.stringify(
+ Object.assign({}, ...styles.flat(Infinity).filter(Boolean)),
+ ),
+ }),
+}));
+vi.mock('@stylexjs/stylex', () => ({
+ create: (styles: object) => styles,
+ props: style.attribute,
+}));
+vi.mock('@astryxdesign/core/Card', () => ({
+ Card: ({
+ xstyle,
+ children,
+ ref,
+ }: {
+ xstyle: unknown;
+ children: ReactNode;
+ ref: unknown;
+ }) =>
+ createElement(
+ 'div',
+ {ref, role: 'group', ...style.attribute(xstyle)},
+ children,
+ ),
+}));
+vi.mock('@astryxdesign/core/Center', () => ({
+ Center: (props: {children: ReactNode}) =>
+ createElement('div', null, props.children),
+}));
+vi.mock('@astryxdesign/core/HStack', () => ({
+ HStack: (props: {children: ReactNode}) =>
+ createElement('div', null, props.children),
+}));
+vi.mock('@astryxdesign/core/theme/tokens.stylex', () => ({
+ colorVars: {},
+ durationVars: {'--duration-medium': 'var(--duration-medium)'},
+ easeVars: {'--ease-move': 'var(--ease-move)'},
+ radiusVars: {},
+}));
+vi.mock('@astryxdesign/core/hooks', () => ({
+ usePanGesture: (_ref: unknown, options: {onPan: Listener}) => {
+ pan.hook = options.onPan;
+ },
+}));
+vi.mock('@astryxdesign/core', () => ({
+ createPanGesture: (_element: unknown, options: {onPan: Listener}) => {
+ pan.factory = options.onPan;
+ return {
+ destroy: () => {
+ pan.destroyed += 1;
+ },
+ };
+ },
+}));
+
+const reactActEnvironment = globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean};
+
+beforeEach(() => {
+ reactActEnvironment.IS_REACT_ACT_ENVIRONMENT = true;
+});
+
+afterEach(() => {
+ document.body.innerHTML = '';
+});
+
+type Styles = {
+ translate?: string;
+ userSelect?: string;
+ transition?: {
+ default: string;
+ '@media (prefers-reduced-motion: reduce)': string;
+ };
+};
+
+async function mount() {
+ const container = document.createElement('div');
+ document.body.append(container);
+ const root = createRoot(container);
+ await act(async () => {
+ root.render(createElement(PanDraggableBox));
+ });
+ // The hook's box comes first, then the factory's.
+ const boxes = [...container.querySelectorAll<HTMLElement>('[role="group"]')];
+ const styles = (index: number) =>
+ JSON.parse(boxes[index]?.getAttribute('data-style') ?? '{}') as Styles;
+ return {root, boxes, styles};
+}
+
+const at = (x: number, y = 0) => ({x, y});
+
+async function send(listener: Listener | null, event: PanEvent) {
+ await act(async () => {
+ listener?.(event);
+ });
+}
+
+describe('the draggable-box pan block', () => {
+ it('shows the same box twice, each named by the API that makes its pan', async () => {
+ const {root, boxes} = await mount();
+ expect(boxes.map(box => box.textContent)).toEqual([
+ 'usePanGesture',
+ 'createPanGesture',
+ ]);
+ await act(async () => {
+ root.unmount();
+ });
+ });
+
+ for (const [name, index, listener] of [
+ ['usePanGesture', 0, () => pan.hook],
+ ['createPanGesture', 1, () => pan.factory],
+ ] as const) {
+ it(`follows a drag, then springs back when it is let go (${name})`, async () => {
+ const {root, styles} = await mount();
+ await send(listener(), {
+ state: 'began',
+ translation: at(0),
+ velocity: at(0),
+ });
+ await send(listener(), {
+ state: 'changed',
+ translation: at(30, 12),
+ velocity: at(400),
+ });
+ const held = styles(index);
+ expect(held.translate).toBe('30px 12px');
+ // A mouse drag moves the box instead of selecting its text.
+ expect(held.userSelect).toBe('none');
+ expect(held.transition).toBeUndefined();
+ // The other box stays where it is.
+ expect(styles(1 - index).translate).toBe('0px 0px');
+ await send(listener(), {
+ state: 'ended',
+ translation: at(30, 12),
+ velocity: at(0),
+ });
+ const released = styles(index);
+ expect(released.translate).toBe('0px 0px');
+ // At the theme's duration and easing for a move.
+ expect(released.transition?.default).toBe(
+ 'translate var(--duration-medium) var(--ease-move)',
+ );
+ // A person who reduces motion sees it back at once.
+ expect(
+ released.transition?.['@media (prefers-reduced-motion: reduce)'],
+ ).toBe('none');
+ await act(async () => {
+ root.unmount();
+ });
+ });
+ }
+
+ it('takes the createPanGesture pan down with the block', async () => {
+ const {root} = await mount();
+ const destroyed = pan.destroyed;
+ await act(async () => {
+ root.unmount();
+ });
+ expect(pan.destroyed).toBe(destroyed + 1);
+ });
+});
diff --git a/packages/cli/api/template/pan-playing-card.test.tsx b/packages/cli/api/template/pan-playing-card.test.tsx
index a31e6c2a33..245e7bcc4d 100644
--- a/packages/cli/api/template/pan-playing-card.test.tsx
+++ b/packages/cli/api/template/pan-playing-card.test.tsx
@@ -2,22 +2,22 @@
// @vitest-environment jsdom
/**
- * @file Behavior test for the two playing-card pan blocks.
- * @input The shipped PanPlayingCard (usePanGesture) and PanPlayingCardVanilla
- * (createPanGesture) blocks, rendered in jsdom with the pan itself stubbed.
+ * @file Behavior test for the playing-card pan blocks.
+ * @input The shipped PanPlayingCard (usePanGesture) block, rendered in jsdom
+ * with the pan, StyleX, the announcer and the Astryx components stubbed.
* @output Guards the keyboard path: a second Discard while the first throw
- * still runs deals one card, not two, in both blocks. Guards the card's
- * theme colors, and a throw that a drag beginning during it leaves running.
- * Guards that the next face is in place before the card is visible again.
+ * still runs deals one card, not two. Guards a throw that a drag beginning
+ * during it leaves running. Guards the card's name and each discard's
+ * announcement. It also checks that the next face is in place before the
+ * card is at rest again.
* @position CLI template regression coverage; runs in the node test project,
* under jsdom for this file. The pan is stubbed because the Discard button
* is the drag's keyboard path and never goes through it.
*/
-import {act, createElement, type ComponentType} from 'react';
+import {act, createElement, type ReactNode} from 'react';
import {createRoot} from 'react-dom/client';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-import PanPlayingCardVanilla from '../../assets/templates/blocks/components/createPanGesture/PanPlayingCardVanilla';
import PanPlayingCard from '../../assets/templates/blocks/components/usePanGesture/PanPlayingCard';
type PanEvent = {
@@ -25,11 +25,88 @@ type PanEvent = {
translation: {x: number; y: number};
velocity: {x: number; y: number};
};
+type Styles = {
+ translate?: string;
+ opacity?: number;
+ transition?: object;
+ userSelect?: string;
+};
// The stubbed pan keeps the block's listener, so a case can drive a drag.
const pan = vi.hoisted(() => ({
onPan: null as null | ((event: PanEvent) => void),
destroyed: 0,
}));
+// This project does not compile StyleX. The stub merges a style list into one
+// object on `data-style`. The card stub records each render's name and
+// styles, so a case reads what the block shows and in what order.
+const stub = vi.hoisted(() => ({
+ attribute: (...styles: unknown[]) => ({
+ 'data-style': JSON.stringify(
+ Object.assign({}, ...styles.flat(Infinity).filter(Boolean)),
+ ),
+ }),
+ renders: [] as Array<{name: string; styles: Styles}>,
+ announced: [] as string[],
+}));
+// jsdom runs no transitions. The stubs give each throw one animation per
+// moving property, and a case runs the next frame and settles them by hand.
+const motion = vi.hoisted(() => ({
+ frames: [] as Array<() => void>,
+ running: 2,
+ settle: [] as Array<(ended: boolean) => void>,
+}));
+vi.mock('@stylexjs/stylex', () => ({
+ create: (styles: object) => styles,
+ props: stub.attribute,
+}));
+vi.mock('@astryxdesign/core/Card', () => ({
+ Card: ({
+ xstyle,
+ children,
+ ref,
+ ...rest
+ }: {
+ xstyle: unknown;
+ children: ReactNode;
+ ref: unknown;
+ 'aria-label': string;
+ }) => {
+ const attribute = stub.attribute(xstyle);
+ stub.renders.push({
+ name: rest['aria-label'],
+ styles: JSON.parse(attribute['data-style']) as Styles,
+ });
+ return createElement('div', {ref, ...rest, ...attribute}, children);
+ },
+}));
+vi.mock('@astryxdesign/core/Center', () => ({
+ Center: ({xstyle, children}: {xstyle?: unknown; children: ReactNode}) =>
+ createElement('div', stub.attribute(xstyle), children),
+}));
+vi.mock('@astryxdesign/core/VStack', () => ({
+ VStack: ({children}: {children: ReactNode}) =>
+ createElement('div', null, children),
+}));
+vi.mock('@astryxdesign/core/Text', () => ({
+ Text: ({children}: {children: ReactNode}) =>
+ createElement('span', null, children),
+}));
+vi.mock('@astryxdesign/core/Button', () => ({
+ Button: ({label, onClick}: {label: string; onClick: () => void}) =>
+ createElement('button', {type: 'button', onClick}, label),
+}));
+vi.mock('@astryxdesign/core/theme/tokens.stylex', () => ({
+ colorVars: {'--color-neutral': 'var(--color-neutral)'},
+ durationVars: {
+ '--duration-medium': 'var(--duration-medium)',
+ '--duration-exit': 'var(--duration-exit)',
+ },
+ easeVars: {
+ '--ease-move': 'var(--ease-move)',
+ '--ease-exit': 'var(--ease-exit)',
+ },
+ radiusVars: {'--radius-container': 'var(--radius-container)'},
+}));
vi.mock('@astryxdesign/core/hooks', () => ({
usePanGesture: (
_ref: unknown,
@@ -37,26 +114,34 @@ vi.mock('@astryxdesign/core/hooks', () => ({
) => {
pan.onPan = options.onPan;
},
-}));
-vi.mock('@astryxdesign/core', () => ({
- createPanGesture: (
- _element: unknown,
- options: {onPan: (event: PanEvent) => void},
- ) => {
- pan.onPan = options.onPan;
- return {
- destroy: () => {
- pan.destroyed += 1;
- },
- };
+ useAnnounce: () => (message: string) => {
+ stub.announced.push(message);
},
}));
-
const reactActEnvironment = globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean};
beforeEach(() => {
reactActEnvironment.IS_REACT_ACT_ENVIRONMENT = true;
- // Motion allowed: a discard throws the card and deals at its transitionend.
+ stub.renders.length = 0;
+ stub.announced.length = 0;
+ motion.frames.length = 0;
+ motion.settle.length = 0;
+ motion.running = 2;
+ window.requestAnimationFrame = callback => {
+ motion.frames.push(() => callback(0));
+ return motion.frames.length;
+ };
+ Element.prototype.getAnimations = () =>
+ Array.from({length: motion.running}, () => {
+ const finished = new Promise((resolve, reject) => {
+ motion.settle.push(ended =>
+ ended ? resolve(undefined) : reject(new Error('cancelled')),
+ );
+ });
+ return {finished} as unknown as Animation;
+ });
+ // Motion allowed: a discard throws the card and deals once its transitions
+ // settle.
window.matchMedia = ((query: string) => ({
matches: false,
media: query,
@@ -69,270 +154,242 @@ afterEach(() => {
document.body.innerHTML = '';
});
-describe('the plain-JavaScript pan block', () => {
- it('mounts its deck with its wrapper and takes it down, pan included, when it unmounts', async () => {
+describe('the playing-card pan block', () => {
+ /** Render the block; return its Discard button, top card and styles. */
+ async function renderBlock() {
const container = document.createElement('div');
document.body.append(container);
const root = createRoot(container);
await act(async () => {
- root.render(createElement(PanPlayingCardVanilla));
+ root.render(createElement(PanPlayingCard));
+ });
+ const button = container.querySelector('button');
+ const card = container.querySelector<HTMLElement>('[role="img"]');
+ if (button == null || card == null) {
+ throw new Error('the block renders no Discard button or top card');
+ }
+ const styles = () =>
+ JSON.parse(card.getAttribute('data-style') ?? '{}') as Styles;
+ return {root, button, card, styles, container};
+ }
+
+ const at = (x: number) => ({x, y: 0});
+
+ /** Runs the frame after a throw starts, then ends or cancels its motion. */
+ function settleThrow(ended = true) {
+ for (const frame of motion.frames.splice(0)) {
+ frame();
+ }
+ for (const settle of motion.settle.splice(0)) {
+ settle(ended);
+ }
+ }
+
+ async function send(...events: PanEvent[]) {
+ await act(async () => {
+ for (const event of events) {
+ pan.onPan?.(event);
+ }
});
- expect(container.querySelector('[role="img"]')).not.toBeNull();
- const destroyed = pan.destroyed;
+ }
+
+ it("paints the stage in the theme's neutral wash, so the card reads in light and dark themes", async () => {
+ const {root, card} = await renderBlock();
+ const stage = JSON.parse(
+ card.parentElement?.getAttribute('data-style') ?? '{}',
+ ) as {backgroundColor?: string};
+ expect(stage.backgroundColor).toBe('var(--color-neutral)');
await act(async () => {
root.unmount();
});
- expect(container.querySelector('[role="img"]')).toBeNull();
- expect(pan.destroyed).toBe(destroyed + 1);
});
-});
-describe('the playing-card pan blocks', () => {
- for (const [name, Block] of [
- ['usePanGesture', PanPlayingCard],
- ['createPanGesture', PanPlayingCardVanilla],
- ] as ReadonlyArray<[string, ComponentType]>) {
- it(`paints the card in the theme's surface and text colors, so its face reads in dark mode too (${name})`, async () => {
- const container = document.createElement('div');
- document.body.append(container);
- const root = createRoot(container);
- await act(async () => {
- root.render(createElement(Block));
- });
- const card = container.querySelector<HTMLElement>('[role="img"]');
- if (card == null) {
- throw new Error('the block renders no top card');
- }
- expect({
- background: card.style.backgroundColor,
- color: card.style.color,
- }).toEqual({
- background: 'var(--color-background-surface)',
- color: 'var(--color-text-primary)',
- });
- await act(async () => {
- root.unmount();
- });
+ it("deals the next card's face in the same render that brings the card back to rest, so no frame paints the discarded card back at the centre", async () => {
+ const {root, button} = await renderBlock();
+ await act(async () => {
+ button.click();
});
-
- /** Render the block; return its Discard button and top card. */
- async function renderBlock() {
- const container = document.createElement('div');
- document.body.append(container);
- const root = createRoot(container);
- await act(async () => {
- root.render(createElement(Block));
- });
- const button = container.querySelector('button');
- const card = container.querySelector<HTMLElement>('[role="img"]');
- if (button == null || card == null) {
- throw new Error('the block renders no Discard button or top card');
- }
- return {root, button, card};
+ const thrownAt = stub.renders.length;
+ await act(async () => {
+ settleThrow();
+ });
+ const after = stub.renders.slice(thrownAt);
+ // Every render after the throw shows the next card, at rest and visible.
+ expect(after.length).toBeGreaterThan(0);
+ for (const render of after) {
+ expect(render.name).toBe('King of hearts');
+ expect(render.styles.opacity).toBeUndefined();
+ expect(render.styles.translate).toBe('0px 0px');
}
+ await act(async () => {
+ root.unmount();
+ });
+ });
- const at = (x: number) => ({x, y: 0});
+ it('ignores the rest of a drag that began during a throw: the next card stays at rest and is not discarded', async () => {
+ const {root, button, card, styles} = await renderBlock();
+ await act(async () => {
+ button.click();
+ pan.onPan?.({state: 'began', translation: at(5), velocity: at(0)});
+ settleThrow();
+ });
+ expect(card.textContent).toBe('K\u2665');
+ // The drag outlives the throw.
+ await send({state: 'changed', translation: at(40), velocity: at(0)});
+ expect(styles().translate).toBe('0px 0px');
+ await send({state: 'ended', translation: at(90), velocity: at(2000)});
+ expect({face: card.textContent, opacity: styles().opacity}).toEqual({
+ face: 'K\u2665',
+ opacity: undefined,
+ });
+ await act(async () => {
+ root.unmount();
+ });
+ });
- it(`deals the next card's face before the thrown card returns to rest, so no frame paints the discarded card back at the centre (${name})`, async () => {
- const {root, button, card} = await renderBlock();
- // The face the page holds when the card turns visible again. jsdom
- // keeps the opacity accessor on the declaration's prototype.
- const facesAtReset: string[] = [];
- const declaration = Object.getPrototypeOf(card.style) as object;
- const opacity = Object.getOwnPropertyDescriptor(declaration, 'opacity');
- if (opacity?.set == null) {
- throw new Error('jsdom has no opacity accessor to watch');
- }
- const setOpacity = opacity.set;
- Object.defineProperty(declaration, 'opacity', {
- ...opacity,
- set(this: CSSStyleDeclaration, value: string) {
- if (value === '1') {
- facesAtReset.push(card.textContent ?? '');
- }
- setOpacity.call(this, value);
- },
- });
- try {
- await act(async () => {
- button.click();
- card.dispatchEvent(new Event('transitionend'));
- });
- } finally {
- Object.defineProperty(declaration, 'opacity', opacity);
- }
- expect(facesAtReset).toEqual(['K\u2665']);
- await act(async () => {
- root.unmount();
- });
+ it('ignores the rest of a drag a throw starts during: the next card stays at rest and is not discarded', async () => {
+ const {root, button, card, styles} = await renderBlock();
+ await send(
+ {state: 'began', translation: at(5), velocity: at(0)},
+ {state: 'changed', translation: at(20), velocity: at(0)},
+ );
+ expect(styles().translate).toBe('20px 0px');
+ // A mouse drag moves the card instead of selecting its face.
+ expect(styles().userSelect).toBe('none');
+ // Discard, from another finger or the keyboard, mid-drag.
+ await act(async () => {
+ button.click();
+ settleThrow();
+ });
+ expect(card.textContent).toBe('K\u2665');
+ await send(
+ {state: 'changed', translation: at(60), velocity: at(0)},
+ {state: 'ended', translation: at(90), velocity: at(2000)},
+ );
+ expect({
+ face: card.textContent,
+ opacity: styles().opacity,
+ translate: styles().translate,
+ }).toEqual({face: 'K\u2665', opacity: undefined, translate: '0px 0px'});
+ await act(async () => {
+ root.unmount();
});
+ });
- it(`ignores the rest of a drag that began during a throw: the next card stays at rest and is not discarded (${name})`, async () => {
- const {root, button, card} = await renderBlock();
- await act(async () => {
- button.click();
- pan.onPan?.({state: 'began', translation: at(5), velocity: at(0)});
- card.dispatchEvent(new Event('transitionend'));
- });
- expect(card.textContent).toBe('K\u2665');
- // The drag outlives the throw.
- await act(async () => {
- pan.onPan?.({state: 'changed', translation: at(40), velocity: at(0)});
- });
- expect(card.style.translate).toBe('0px 0px');
- await act(async () => {
- pan.onPan?.({state: 'ended', translation: at(90), velocity: at(2000)});
- });
- expect({face: card.textContent, opacity: card.style.opacity}).toEqual({
- face: 'K\u2665',
- opacity: '1',
- });
- await act(async () => {
- root.unmount();
- });
+ it('follows the next drag after an ignored one', async () => {
+ const {root, button, styles} = await renderBlock();
+ await act(async () => {
+ button.click();
+ pan.onPan?.({state: 'began', translation: at(5), velocity: at(0)});
+ settleThrow();
+ pan.onPan?.({state: 'ended', translation: at(30), velocity: at(0)});
});
+ await send(
+ {state: 'began', translation: at(5), velocity: at(0)},
+ {state: 'changed', translation: at(25), velocity: at(0)},
+ );
+ expect(styles().translate).toBe('25px 0px');
+ await act(async () => {
+ root.unmount();
+ });
+ });
- it(`ignores the rest of a drag a throw starts during: the next card stays at rest and is not discarded (${name})`, async () => {
- const {root, button, card} = await renderBlock();
- await act(async () => {
- pan.onPan?.({state: 'began', translation: at(5), velocity: at(0)});
- pan.onPan?.({state: 'changed', translation: at(20), velocity: at(0)});
- });
- expect(card.style.translate).toBe('20px 0px');
- // Discard, from another finger or the keyboard, mid-drag.
- await act(async () => {
- button.click();
- card.dispatchEvent(new Event('transitionend'));
- });
- expect(card.textContent).toBe('K\u2665');
- await act(async () => {
- pan.onPan?.({state: 'changed', translation: at(60), velocity: at(0)});
- pan.onPan?.({state: 'ended', translation: at(90), velocity: at(2000)});
- });
- expect({
- face: card.textContent,
- opacity: card.style.opacity,
- translate: card.style.translate,
- }).toEqual({face: 'K\u2665', opacity: '1', translate: '0px 0px'});
- await act(async () => {
- root.unmount();
- });
+ it('keeps a throw running through a drag that begins during it, so the next card is dealt', async () => {
+ const {root, button, card, styles} = await renderBlock();
+ await act(async () => {
+ button.click();
+ });
+ const thrown = styles();
+ expect(thrown.opacity).toBe(0);
+ expect(thrown.translate).toBe('160px 0px');
+ // A drag begins during the throw and ends slowly. Changing the card's
+ // transition then would cancel the throw in a browser, so its end would
+ // never deal the next card.
+ await send(
+ {state: 'began', translation: at(5), velocity: at(0)},
+ {state: 'changed', translation: at(40), velocity: at(0)},
+ {state: 'ended', translation: at(40), velocity: at(0)},
+ );
+ expect(styles()).toEqual(thrown);
+ await act(async () => {
+ settleThrow();
+ });
+ expect({face: card.textContent, opacity: styles().opacity}).toEqual({
+ face: 'K\u2665',
+ opacity: undefined,
});
+ await act(async () => {
+ root.unmount();
+ });
+ });
- it(`follows the next drag after an ignored one (${name})`, async () => {
- const {root, button, card} = await renderBlock();
- await act(async () => {
- button.click();
- pan.onPan?.({state: 'began', translation: at(5), velocity: at(0)});
- card.dispatchEvent(new Event('transitionend'));
- pan.onPan?.({state: 'ended', translation: at(30), velocity: at(0)});
- });
- await act(async () => {
- pan.onPan?.({state: 'began', translation: at(5), velocity: at(0)});
- pan.onPan?.({state: 'changed', translation: at(25), velocity: at(0)});
- });
- expect(card.style.translate).toBe('25px 0px');
- await act(async () => {
- root.unmount();
- });
+ it('names the top card by its rank and suit, as an image, and announces each discard by name', async () => {
+ const {root, button, card} = await renderBlock();
+ expect({
+ role: card.getAttribute('role'),
+ name: card.getAttribute('aria-label'),
+ face: card.textContent,
+ }).toEqual({role: 'img', name: 'Ace of spades', face: 'A\u2660'});
+ await act(async () => {
+ button.click();
+ settleThrow();
});
+ expect({
+ name: card.getAttribute('aria-label'),
+ face: card.textContent,
+ announced: stub.announced,
+ }).toEqual({
+ name: 'King of hearts',
+ face: 'K\u2665',
+ announced: ['Ace of spades discarded'],
+ });
+ await act(async () => {
+ root.unmount();
+ });
+ });
- it(`keeps a throw running through a drag that begins during it, so the next card is dealt (${name})`, async () => {
- const container = document.createElement('div');
- document.body.append(container);
- const root = createRoot(container);
- await act(async () => {
- root.render(createElement(Block));
- });
- const button = container.querySelector('button');
- const card = container.querySelector<HTMLElement>('[role="img"]');
- if (button == null || card == null) {
- throw new Error('the block renders no Discard button or top card');
- }
- await act(async () => {
- button.click();
- });
- const thrown = {
- transition: card.style.transition,
- translate: card.style.translate,
- };
- expect(thrown.transition).not.toBe('none');
- // A drag begins during the throw and ends slowly. Writing the card's
- // transition then would cancel the throw in a browser, so its end would
- // never deal the next card.
- await act(async () => {
- const at = (x: number) => ({x, y: 0});
- pan.onPan?.({state: 'began', translation: at(5), velocity: at(0)});
- pan.onPan?.({state: 'changed', translation: at(40), velocity: at(0)});
- pan.onPan?.({state: 'ended', translation: at(40), velocity: at(0)});
- });
- expect({
- transition: card.style.transition,
- translate: card.style.translate,
- }).toEqual(thrown);
- await act(async () => {
- card.dispatchEvent(new Event('transitionend'));
- });
- expect({face: card.textContent, opacity: card.style.opacity}).toEqual({
- face: 'K\u2665',
- opacity: '1',
- });
- await act(async () => {
- root.unmount();
- });
+ it("deals the next card at once when a stylesheet stops the throw's transitions", async () => {
+ motion.running = 0;
+ const {root, button, card} = await renderBlock();
+ await act(async () => {
+ button.click();
+ });
+ expect(card.textContent).toBe('A\u2660');
+ await act(async () => {
+ settleThrow();
+ });
+ expect(card.textContent).toBe('K\u2665');
+ await act(async () => {
+ root.unmount();
});
+ });
- it(`names the top card by its rank and suit, as an image, and announces each discard by name (${name})`, async () => {
- const {root, button, card} = await renderBlock();
- expect({
- role: card.getAttribute('role'),
- name: card.getAttribute('aria-label'),
- face: card.textContent,
- }).toEqual({role: 'img', name: 'Ace of spades', face: 'A\u2660'});
- await act(async () => {
- button.click();
- card.dispatchEvent(new Event('transitionend'));
- });
- expect({
- name: card.getAttribute('aria-label'),
- face: card.textContent,
- announced: document.querySelector('[aria-live="polite"]')?.textContent,
- }).toEqual({
- name: 'King of hearts',
- face: 'K\u2665',
- announced: 'Ace of spades discarded',
- });
- await act(async () => {
- root.unmount();
- });
+ it("deals the next card when the throw's transitions are cancelled", async () => {
+ const {root, button, card} = await renderBlock();
+ await act(async () => {
+ button.click();
+ settleThrow(false);
+ });
+ expect(card.textContent).toBe('K\u2665');
+ await act(async () => {
+ root.unmount();
});
+ });
- it(`deals one card for a second Discard pressed while the first throw runs (${name})`, async () => {
- const container = document.createElement('div');
- document.body.append(container);
- const root = createRoot(container);
- await act(async () => {
- root.render(createElement(Block));
- });
- const button = container.querySelector('button');
- const card = container.querySelector('[role="img"]');
- if (button == null || card == null) {
- throw new Error('the block renders no Discard button or top card');
- }
- expect(card.textContent).toBe('A\u2660');
- await act(async () => {
- button.click();
- button.click();
- });
- // The throw's two transitions end one after the other.
- await act(async () => {
- card.dispatchEvent(new Event('transitionend'));
- card.dispatchEvent(new Event('transitionend'));
- });
- expect(card.textContent).toBe('K\u2665');
- await act(async () => {
- root.unmount();
- });
+ it('deals one card for a second Discard pressed while the first throw runs', async () => {
+ const {root, button, card} = await renderBlock();
+ expect(card.textContent).toBe('A\u2660');
+ await act(async () => {
+ button.click();
+ button.click();
});
- }
+ // The throw's two transitions both end.
+ await act(async () => {
+ settleThrow();
+ });
+ expect(card.textContent).toBe('K\u2665');
+ await act(async () => {
+ root.unmount();
+ });
+ });
});
diff --git a/packages/cli/assets/templates/blocks/components/createPanGesture/PanPlayingCardVanilla.doc.mjs b/packages/cli/assets/templates/blocks/components/createPanGesture/PanPlayingCardVanilla.doc.mjs
deleted file mode 100644
index ab9e7dc478..0000000000
--- a/packages/cli/assets/templates/blocks/components/createPanGesture/PanPlayingCardVanilla.doc.mjs
+++ /dev/null
@@ -1,14 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
-export const doc = {
- type: 'block',
- exampleFor: 'createPanGesture',
- name: 'createPanGesture — A playing card without React',
- displayName: 'createPanGesture — A playing card without React',
- description:
- 'A playing card built in plain JavaScript with createPanGesture: it follows a drag from a finger, a mouse or a pen, snaps back on a gentle release, flies off 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/createPanGesture/PanPlayingCardVanilla.tsx b/packages/cli/assets/templates/blocks/components/createPanGesture/PanPlayingCardVanilla.tsx
deleted file mode 100644
index 82ae04178c..0000000000
--- a/packages/cli/assets/templates/blocks/components/createPanGesture/PanPlayingCardVanilla.tsx
+++ /dev/null
@@ -1,156 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-'use client';
-
-import {createPanGesture} 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;
-/** How far a thrown card travels before the next one is dealt, px. */
-const THROW_DISTANCE = 480;
-const SETTLE = 'translate 300ms cubic-bezier(0.2, 0.9, 0.3, 1.2)';
-const THROW = 'translate 250ms ease-in, opacity 250ms ease-in';
-
-/**
- * A deck on a table, in plain JavaScript: no React below this line. The pan
- * reports the drag; the card's own style moves it. Returns a function that
- * takes it down again.
- */
-function mountDeck(table: HTMLElement, discardButton: HTMLButtonElement) {
- let top = 0;
- /** A throw is in flight: the next card is dealt when it ends. */
- let isThrowing = false;
- /** The drag in progress met a throw: the rest of it moves nothing. */
- let isIgnoringDrag = false;
- const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
- 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',
- borderRadius: '12px',
- backgroundColor: 'var(--color-background-surface)',
- color: 'var(--color-text-primary)',
- boxShadow: '0 2px 8px rgb(0 0 0 / 0.2)',
- 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);
-
- /** Move the card, with a transition unless the person reduces motion. */
- function moveTo(x: number, y: number, transition: string) {
- card.style.transition = reduceMotion.matches ? 'none' : transition;
- card.style.translate = `${x}px ${y}px`;
- }
-
- function discard(direction: number) {
- // One throw at a time: a second Discard during it would deal twice.
- if (isThrowing) {
- return;
- }
- isThrowing = true;
- // The drag in progress, if any, moves nothing more.
- isIgnoringDrag = true;
- moveTo(direction * THROW_DISTANCE, 0, THROW);
- card.style.opacity = '0';
- const deal = () => {
- isThrowing = false;
- status.textContent = `${DECK[top % DECK.length].name} discarded`;
- top += 1;
- card.textContent = DECK[top % DECK.length].face;
- card.setAttribute('aria-label', DECK[top % DECK.length].name);
- moveTo(0, 0, 'none');
- card.style.opacity = '1';
- };
- if (reduceMotion.matches) {
- deal();
- } else {
- card.addEventListener('transitionend', deal, {once: true});
- }
- }
-
- const pan = createPanGesture(card, {
- onPan: ({state, translation, velocity}) => {
- // A drag that meets a throw is ignored to its end. Its moves would
- // cancel the throw's transitions, and the next card would jump to it.
- if (state === 'began') {
- isIgnoringDrag = isThrowing;
- }
- if (isIgnoringDrag) {
- return;
- }
- if (state === 'began' || state === 'changed') {
- // Follows the finger: translation leaves out the travel the drag
- // needed to begin, so the card does not jump.
- moveTo(translation.x, translation.y, 'none');
- } else if (state === 'ended' && Math.abs(velocity.x) > THROW_SPEED) {
- discard(Math.sign(velocity.x));
- } else {
- moveTo(0, 0, SETTLE);
- }
- },
- });
- // The drag's keyboard and assistive-technology path (WCAG 2.5.7).
- const onDiscard = () => discard(1);
- discardButton.addEventListener('click', onDiscard);
- return () => {
- discardButton.removeEventListener('click', onDiscard);
- pan.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 PanPlayingCardVanilla() {
- return (
- <div
- ref={mountTable}
- style={{display: 'grid', gap: 16, padding: 16, maxWidth: 360}}>
- <div
- style={{
- height: 200,
- display: 'grid',
- placeItems: 'center',
- overflow: 'hidden',
- }}
- />
- <button type="button">Discard the top card</button>
- </div>
- );
-}
diff --git a/packages/cli/assets/templates/blocks/components/usePanGesture/PanDraggableBox.doc.mjs b/packages/cli/assets/templates/blocks/components/usePanGesture/PanDraggableBox.doc.mjs
new file mode 100644
index 0000000000..6dd395aadd
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/usePanGesture/PanDraggableBox.doc.mjs
@@ -0,0 +1,15 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'usePanGesture',
+ alsoExampleFor: ['createPanGesture'],
+ name: 'usePanGesture — A draggable box',
+ displayName: 'usePanGesture — A draggable box',
+ description:
+ 'The smallest pan example, in two forms side by side: the usePanGesture hook and the createPanGesture factory. The factory takes any element, React or not. Each card names its API, follows a drag from a finger, a mouse or a pen, and springs back, with the same StyleX styles. A starting point for a draggable tile, a swipe or any drag-and-release gesture.',
+ isReady: true,
+ aspectRatio: 4 / 3,
+ componentsUsed: ['Card', 'Center', 'HStack'],
+};
diff --git a/packages/cli/assets/templates/blocks/components/usePanGesture/PanDraggableBox.tsx b/packages/cli/assets/templates/blocks/components/usePanGesture/PanDraggableBox.tsx
new file mode 100644
index 0000000000..a67d1ef84e
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/usePanGesture/PanDraggableBox.tsx
@@ -0,0 +1,98 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {useCallback, useRef, useState, type Ref} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {createPanGesture} from '@astryxdesign/core';
+import {Card} from '@astryxdesign/core/Card';
+import {Center} from '@astryxdesign/core/Center';
+import {HStack} from '@astryxdesign/core/HStack';
+import {usePanGesture, type PanGestureEvent} from '@astryxdesign/core/hooks';
+import {
+ colorVars,
+ durationVars,
+ easeVars,
+ radiusVars,
+} from '@astryxdesign/core/theme/tokens.stylex';
+
+const styles = stylex.create({
+ // A wash under the stage, so the box on top reads in light and dark themes.
+ stage: {
+ backgroundColor: colorVars['--color-neutral'],
+ borderRadius: radiusVars['--radius-container'],
+ },
+ box: {cursor: 'grab', userSelect: 'none'},
+ // Let go, the box springs back, unless the person reduces motion.
+ springBack: {
+ transition: {
+ default: `translate ${durationVars['--duration-medium']} ${easeVars['--ease-move']}`,
+ '@media (prefers-reduced-motion: reduce)': 'none',
+ },
+ },
+ drag: (x: number, y: number) => ({translate: `${x}px ${y}px`}),
+});
+
+type Drag = {x: number; y: number; held: boolean};
+const REST: Drag = {x: 0, y: 0, held: false};
+
+/** The box follows a held drag and goes back to rest when it ends. */
+function nextDrag({state, translation}: PanGestureEvent): Drag {
+ const held = state === 'began' || state === 'changed';
+ return held ? {...translation, held} : REST;
+}
+
+/** The same stage and card for both forms; the card names its API. */
+function DraggableBox(props: {
+ name: string;
+ ref: Ref<HTMLDivElement>;
+ drag: Drag;
+}) {
+ const {name, ref, drag} = props;
+ return (
+ <Center width="min(280px, 80vw)" height={180} xstyle={styles.stage}>
+ <Card
+ ref={ref}
+ padding={6}
+ elevation="med"
+ xstyle={[
+ styles.box,
+ styles.drag(drag.x, drag.y),
+ !drag.held && styles.springBack,
+ ]}>
+ {name}
+ </Card>
+ </Center>
+ );
+}
+
+function WithHook() {
+ const box = useRef<HTMLDivElement>(null);
+ const [drag, setDrag] = useState(REST);
+ usePanGesture(box, {onPan: event => setDrag(nextDrag(event))});
+ return <DraggableBox name="usePanGesture" ref={box} drag={drag} />;
+}
+
+function WithFactory() {
+ const [drag, setDrag] = useState(REST);
+ // A callback ref: its cleanup takes the pan down with the box.
+ const draggable = useCallback((box: HTMLDivElement | null) => {
+ if (box == null) {
+ return undefined;
+ }
+ const pan = createPanGesture(box, {
+ onPan: event => setDrag(nextDrag(event)),
+ });
+ return () => pan.destroy();
+ }, []);
+ return <DraggableBox name="createPanGesture" ref={draggable} drag={drag} />;
+}
+
+export default function PanDraggableBox() {
+ return (
+ <HStack gap={6} wrap="wrap" justify="center">
+ <WithHook />
+ <WithFactory />
+ </HStack>
+ );
+}
diff --git a/packages/cli/assets/templates/blocks/components/usePanGesture/PanPlayingCard.doc.mjs b/packages/cli/assets/templates/blocks/components/usePanGesture/PanPlayingCard.doc.mjs
index 1932ca01c7..958726a2af 100644
--- a/packages/cli/assets/templates/blocks/components/usePanGesture/PanPlayingCard.doc.mjs
+++ b/packages/cli/assets/templates/blocks/components/usePanGesture/PanPlayingCard.doc.mjs
@@ -4,11 +4,11 @@
export const doc = {
type: 'block',
exampleFor: 'usePanGesture',
- name: 'usePanGesture — A playing card',
- displayName: 'usePanGesture — A playing card',
+ name: 'usePanGesture — A playing card (advanced)',
+ displayName: 'usePanGesture — A playing card (advanced)',
description:
- 'A playing card built with usePanGesture: it follows a drag from a finger, a mouse or a pen with no render per move, snaps back on a gentle release, flies off on a quick flick, and a button discards it from the keyboard.',
+ 'An advanced usePanGesture example: a playing card follows a drag, settles back on a gentle release and flies off on a quick flick, while a Discard button deals the next card from the keyboard and announces it. Drag, settle and throw are StyleX styles driven by React state. A pattern for swipe-to-dismiss, card decks and flick gestures.',
isReady: true,
aspectRatio: 4 / 3,
- componentsUsed: [],
+ componentsUsed: ['Button', 'Card', 'Center', 'Text', 'VStack'],
};
diff --git a/packages/cli/assets/templates/blocks/components/usePanGesture/PanPlayingCard.tsx b/packages/cli/assets/templates/blocks/components/usePanGesture/PanPlayingCard.tsx
index d42ff395ba..cb6cd8666e 100644
--- a/packages/cli/assets/templates/blocks/components/usePanGesture/PanPlayingCard.tsx
+++ b/packages/cli/assets/templates/blocks/components/usePanGesture/PanPlayingCard.tsx
@@ -3,8 +3,19 @@
'use client';
import {useRef, useState} from 'react';
-import {flushSync} from 'react-dom';
-import {usePanGesture} from '@astryxdesign/core/hooks';
+import * as stylex from '@stylexjs/stylex';
+import {Button} from '@astryxdesign/core/Button';
+import {Card} from '@astryxdesign/core/Card';
+import {Center} from '@astryxdesign/core/Center';
+import {useAnnounce, usePanGesture} from '@astryxdesign/core/hooks';
+import {Text} from '@astryxdesign/core/Text';
+import {VStack} from '@astryxdesign/core/VStack';
+import {
+ colorVars,
+ durationVars,
+ easeVars,
+ radiusVars,
+} from '@astryxdesign/core/theme/tokens.stylex';
const DECK = [
{face: 'A\u2660', name: 'Ace of spades'},
@@ -14,32 +25,48 @@ const DECK = [
];
/** A release faster than this (px/s) throws the card away. */
const THROW_SPEED = 1000;
-/** How far a thrown card travels before the next one is dealt, px. */
-const THROW_DISTANCE = 480;
-const SETTLE = 'translate 300ms cubic-bezier(0.2, 0.9, 0.3, 1.2)';
-const THROW = 'translate 250ms ease-in, opacity 250ms ease-in';
+/** How far a thrown card travels while it fades, px. */
+const THROW_DISTANCE = 160;
+const EXIT = `${durationVars['--duration-exit']} ${easeVars['--ease-exit']}`;
+
+const styles = stylex.create({
+ // A wash under the stage, so the card on top reads in light and dark themes.
+ stage: {
+ backgroundColor: colorVars['--color-neutral'],
+ borderRadius: radiusVars['--radius-container'],
+ overflow: 'hidden',
+ },
+ card: {cursor: 'grab', userSelect: 'none'},
+ // A gentle release settles the card back, unless the person reduces motion.
+ settle: {
+ transition: {
+ default: `translate ${durationVars['--duration-medium']} ${easeVars['--ease-move']}`,
+ '@media (prefers-reduced-motion: reduce)': 'none',
+ },
+ },
+ // A flick throws it off to one side as it fades.
+ thrown: {
+ opacity: 0,
+ transition: {
+ default: `translate ${EXIT}, opacity ${EXIT}`,
+ '@media (prefers-reduced-motion: reduce)': 'none',
+ },
+ },
+ drag: (x: number, y: number) => ({translate: `${x}px ${y}px`}),
+});
+
+type Pose = {x: number; y: number; motion: 'rest' | 'settle' | 'thrown'};
export default function PanPlayingCard() {
const card = useRef<HTMLDivElement>(null);
const [top, setTop] = useState(0);
- const [announcement, setAnnouncement] = useState('');
+ const [pose, setPose] = useState<Pose>({x: 0, y: 0, motion: 'rest'});
+ const announce = useAnnounce();
/** A throw is in flight: the next card is dealt when it ends. */
const throwing = useRef(false);
/** The drag in progress met a throw: the rest of it moves nothing. */
const ignoringDrag = useRef(false);
-
- /** Move the card, with a transition unless the person reduces motion. */
- function moveTo(x: number, y: number, transition: string) {
- const element = card.current;
- if (element == null) {
- return;
- }
- const reduced = window.matchMedia(
- '(prefers-reduced-motion: reduce)',
- ).matches;
- element.style.transition = reduced ? 'none' : transition;
- element.style.translate = `${x}px ${y}px`;
- }
+ const shown = DECK[top % DECK.length];
function discard(direction: number) {
const element = card.current;
@@ -48,33 +75,31 @@ export default function PanPlayingCard() {
return;
}
throwing.current = true;
- // The drag in progress, if any, moves nothing more.
ignoringDrag.current = true;
- moveTo(direction * THROW_DISTANCE, 0, THROW);
- element.style.opacity = '0';
- const deal = () => {
+ setPose({x: direction * THROW_DISTANCE, y: 0, motion: 'thrown'});
+ // The next card's face and its place at the center commit together.
+ const dealNext = () => {
throwing.current = false;
- // Commit the next card's face first. A reset before that paints the
- // discarded card back at the centre for one frame.
- flushSync(() => {
- setAnnouncement(`${DECK[top % DECK.length].name} discarded`);
- setTop(value => value + 1);
- });
- moveTo(0, 0, 'none');
- element.style.opacity = '1';
+ announce(`${shown.name} discarded`);
+ setTop(value => value + 1);
+ setPose({x: 0, y: 0, motion: 'rest'});
};
- if (element.style.transition === 'none') {
- deal();
- } else {
- element.addEventListener('transitionend', deal, {once: true});
+ if (matchMedia('(prefers-reduced-motion: reduce)').matches) {
+ dealNext();
+ return;
}
+ // Once the throw's style applies, deal when its transitions settle: at
+ // the theme's duration, or at once when a stylesheet stops them.
+ requestAnimationFrame(() => {
+ const ends = element.getAnimations().map(animation => animation.finished);
+ void Promise.allSettled(ends).then(dealNext);
+ });
}
- // The drag writes the card's style in onPan: no render per move.
usePanGesture(card, {
onPan: ({state, translation, velocity}) => {
- // A drag that meets a throw is ignored to its end. Its moves would
- // cancel the throw's transitions, and the next card would jump to it.
+ // A drag that meets a throw is ignored to its end, or the next card
+ // would jump to it.
if (state === 'began') {
ignoringDrag.current = throwing.current;
}
@@ -82,62 +107,41 @@ export default function PanPlayingCard() {
return;
}
if (state === 'began' || state === 'changed') {
- moveTo(translation.x, translation.y, 'none');
+ setPose({...translation, motion: 'rest'});
} else if (state === 'ended' && Math.abs(velocity.x) > THROW_SPEED) {
discard(Math.sign(velocity.x));
} else {
- moveTo(0, 0, SETTLE);
+ setPose({x: 0, y: 0, motion: 'settle'});
}
},
});
return (
- <div style={{display: 'grid', gap: 16, padding: 16, maxWidth: 360}}>
- <div
- style={{
- height: 200,
- display: 'grid',
- placeItems: 'center',
- overflow: 'hidden',
- }}>
- <div
+ <VStack gap={4} padding={4} width="min(360px, 80vw)">
+ <Center height={280} xstyle={styles.stage}>
+ <Card
ref={card}
// An image's name is all a screen reader announces, so it names the
// card.
role="img"
- aria-label={DECK[top % DECK.length].name}
- style={{
- width: 120,
- height: 170,
- display: 'grid',
- placeItems: 'center',
- font: 'bold 40px system-ui, sans-serif',
- borderRadius: 12,
- backgroundColor: 'var(--color-background-surface)',
- color: 'var(--color-text-primary)',
- boxShadow: '0 2px 8px rgb(0 0 0 / 0.2)',
- cursor: 'grab',
- userSelect: 'none',
- }}>
- {DECK[top % DECK.length].face}
- </div>
- </div>
+ aria-label={shown.name}
+ width={80}
+ height={112}
+ elevation="med"
+ xstyle={[
+ styles.card,
+ styles.drag(pose.x, pose.y),
+ pose.motion !== 'rest' && styles[pose.motion],
+ ]}>
+ <Center height="100%">
+ <Text size="3xl" weight="bold">
+ {shown.face}
+ </Text>
+ </Center>
+ </Card>
+ </Center>
{/* The drag's keyboard and assistive-technology path (WCAG 2.5.7). */}
- <button type="button" onClick={() => discard(1)}>
- Discard the top card
- </button>
- <div
- aria-live="polite"
- style={{
- position: 'absolute',
- width: 1,
- height: 1,
- overflow: 'hidden',
- clipPath: 'inset(50%)',
- whiteSpace: 'nowrap',
- }}>
- {announcement}
- </div>
- </div>
+ <Button label="Discard the top card" onClick={() => discard(1)} />
+ </VStack>
);
}
diff --git a/packages/core/src/gestures/createPanGesture.doc.mjs b/packages/core/src/gestures/createPanGesture.doc.mjs
index 97dd5a8dbe..f233f593a1 100644
--- a/packages/core/src/gestures/createPanGesture.doc.mjs
+++ b/packages/core/src/gestures/createPanGesture.doc.mjs
@@ -58,7 +58,7 @@ export const docs = {
],
usage: {
description:
- "Reports a drag on an element as values, without React, for a surface the product moves itself: a card that follows the finger, a drawer pulled by its handle. A finger, a mouse and a pen all drive it. A mouse or pen drag that starts on selectable text selects that text, and the pan reports nothing. Give that text `user-select: none`. The drag claims its touch at UIKit’s 10 pt, as `UIPanGestureRecognizer` does, so a tap stays a tap and a press or a long press is never reported as a pan. Use the `usePanGesture` hook in React. Where a component already offers the behavior, use its prop instead: BottomSheet's `snapPoints`, Carousel's `hasSnap`.",
+ "Reports a drag on an element as values, without React, for a surface the product moves itself: a card that follows the finger, a drawer pulled by its handle. A finger, a mouse and a pen all drive it. A mouse or pen drag that starts on selectable text selects that text, and the pan reports nothing. Give that text `user-select: none`. The drag claims its touch at UIKit’s 10 pt, as `UIPanGestureRecognizer` does, so a tap stays a tap and a press or a long press is never reported as a pan. Use the `usePanGesture` hook in React. Where a component already offers the behavior, use its prop instead: BottomSheet's `snapPoints`, Carousel's `hasSnap`. Its example is on the usePanGesture page: one draggable box, made once with the hook and once with createPanGesture.",
bestPractices: [
{
guidance: true,
diff --git a/packages/core/src/hooks/usePanGesture.doc.mjs b/packages/core/src/hooks/usePanGesture.doc.mjs
index 5b5b4df82b..41c27e4012 100644
--- a/packages/core/src/hooks/usePanGesture.doc.mjs
+++ b/packages/core/src/hooks/usePanGesture.doc.mjs
@@ -80,7 +80,7 @@ export const docs = {
{
guidance: false,
description:
- 'Set a new React state on every `changed` event; write the element’s style in `onPan` instead, so a drag costs no render.',
+ 'Hold the drag offset in a large component’s state: each `changed` event renders the component that holds it.',
},
{
guidance: false,
@@ -150,8 +150,7 @@ export const docsDense = {
},
{
guidance: false,
- description:
- 'Set React state on every changed event; write the style in onPan.',
+ description: 'Hold the drag offset in a large component’s state.',
},
{guidance: false, description: 'Recognize taps or long presses with it.'},
],