diff --git a/.changeset/public-pan-gesture.md b/.changeset/public-pan-gesture.md new file mode 100644 index 0000000000000..a08c674648917 --- /dev/null +++ b/.changeset/public-pan-gesture.md @@ -0,0 +1,8 @@ +--- +'@astryxdesign/core': patch +'@astryxdesign/cli': patch +--- + +[feature] `createPanGesture(element, {axis?, onPan})` and `usePanGesture(ref, {axis?, onPan})` report a drag on an element as values: `onPan` gets `{state, translation, velocity}` as the drag begins, changes, ends at the release, or is cancelled, and a finger, a mouse and a pen all drive it. A mouse or pen drag that starts on selectable text selects it instead; give text the drag should move `user-select: none`. `axis` limits the drag to `'x'` or `'y'`; a drag along the other axis is not reported. `translation` counts from where the drag began, so an element that follows it does not jump, and `velocity` at `ended` is the release velocity in pixels per second. The drag claims its touch at UIKit's 10 pt and leaves presses and long presses alone. `destroy()` removes every listener; the hook creates one pan for the element behind `ref` and destroys it at unmount. + +@vjeux diff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.json index 2e82f3b49da91..4d99e7f0f5a95 100644 --- a/apps/sandbox/scripts/next-export-routes.json +++ b/apps/sandbox/scripts/next-export-routes.json @@ -470,6 +470,8 @@ "/templates/PaginationPageSize/", "/templates/PaginationVariants/", "/templates/PaginationWithTable/", + "/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 6f912c9749055..4f883ab3810bf 100644 --- a/internal/shadcn-registry/routes.lock.json +++ b/internal/shadcn-registry/routes.lock.json @@ -1966,6 +1966,11 @@ "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", @@ -3766,6 +3771,11 @@ "path": "examples/use-overflow/editor-toolbar", "aliases": [] }, + { + "name": "example-use-pan-gesture-a-playing-card", + "path": "examples/use-pan-gesture/a-playing-card", + "aliases": [] + }, { "name": "example-use-popover-quick-actions", "path": "examples/use-popover/quick-actions", @@ -3881,6 +3891,11 @@ "path": "hooks/create-animator", "aliases": [] }, + { + "name": "hook-create-pan-gesture", + "path": "hooks/create-pan-gesture", + "aliases": [] + }, { "name": "hook-use-animated-layout", "path": "hooks/use-animated-layout", @@ -4061,6 +4076,11 @@ "path": "hooks/use-overflow", "aliases": [] }, + { + "name": "hook-use-pan-gesture", + "path": "hooks/use-pan-gesture", + "aliases": [] + }, { "name": "hook-use-popover", "path": "hooks/use-popover", diff --git a/packages/cli/api/template/pan-playing-card.test.tsx b/packages/cli/api/template/pan-playing-card.test.tsx new file mode 100644 index 0000000000000..a31e6c2a337bc --- /dev/null +++ b/packages/cli/api/template/pan-playing-card.test.tsx @@ -0,0 +1,338 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +// @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. + * @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. + * @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 {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 = { + state: 'began' | 'changed' | 'ended' | 'cancelled'; + translation: {x: number; y: number}; + velocity: {x: number; y: number}; +}; +// 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, +})); +vi.mock('@astryxdesign/core/hooks', () => ({ + usePanGesture: ( + _ref: unknown, + options: {onPan: (event: PanEvent) => void}, + ) => { + 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; + }, + }; + }, +})); + +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. + window.matchMedia = ((query: string) => ({ + matches: false, + media: query, + addEventListener: () => {}, + removeEventListener: () => {}, + })) as unknown as typeof window.matchMedia; +}); + +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 () => { + const container = document.createElement('div'); + document.body.append(container); + const root = createRoot(container); + await act(async () => { + root.render(createElement(PanPlayingCardVanilla)); + }); + expect(container.querySelector('[role="img"]')).not.toBeNull(); + const destroyed = pan.destroyed; + 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('[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(); + }); + }); + + /** 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('[role="img"]'); + if (button == null || card == null) { + throw new Error('the block renders no Discard button or top card'); + } + return {root, button, card}; + } + + const at = (x: number) => ({x, y: 0}); + + 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 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(`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(`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(`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('[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(`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 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(); + }); + }); + } +}); diff --git a/packages/cli/assets/templates/blocks/components/createPanGesture/PanPlayingCardVanilla.doc.mjs b/packages/cli/assets/templates/blocks/components/createPanGesture/PanPlayingCardVanilla.doc.mjs new file mode 100644 index 0000000000000..ab9e7dc478372 --- /dev/null +++ b/packages/cli/assets/templates/blocks/components/createPanGesture/PanPlayingCardVanilla.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: '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 new file mode 100644 index 0000000000000..82ae04178ca42 --- /dev/null +++ b/packages/cli/assets/templates/blocks/components/createPanGesture/PanPlayingCardVanilla.tsx @@ -0,0 +1,156 @@ +// 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 ( +
+
+ +
+ ); +} diff --git a/packages/cli/assets/templates/blocks/components/usePanGesture/PanPlayingCard.doc.mjs b/packages/cli/assets/templates/blocks/components/usePanGesture/PanPlayingCard.doc.mjs new file mode 100644 index 0000000000000..1932ca01c7eff --- /dev/null +++ b/packages/cli/assets/templates/blocks/components/usePanGesture/PanPlayingCard.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: 'usePanGesture', + name: 'usePanGesture — A playing card', + displayName: 'usePanGesture — A playing card', + 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.', + isReady: true, + aspectRatio: 4 / 3, + componentsUsed: [], +}; diff --git a/packages/cli/assets/templates/blocks/components/usePanGesture/PanPlayingCard.tsx b/packages/cli/assets/templates/blocks/components/usePanGesture/PanPlayingCard.tsx new file mode 100644 index 0000000000000..d42ff395ba8cc --- /dev/null +++ b/packages/cli/assets/templates/blocks/components/usePanGesture/PanPlayingCard.tsx @@ -0,0 +1,143 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +import {useRef, useState} from 'react'; +import {flushSync} from 'react-dom'; +import {usePanGesture} from '@astryxdesign/core/hooks'; + +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'; + +export default function PanPlayingCard() { + const card = useRef(null); + const [top, setTop] = useState(0); + const [announcement, setAnnouncement] = useState(''); + /** 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`; + } + + function discard(direction: number) { + const element = card.current; + // One throw at a time: a second Discard during it would deal twice. + if (element == null || throwing.current) { + 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 = () => { + 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'; + }; + if (element.style.transition === 'none') { + deal(); + } else { + element.addEventListener('transitionend', deal, {once: true}); + } + } + + // 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. + if (state === 'began') { + ignoringDrag.current = throwing.current; + } + if (ignoringDrag.current) { + return; + } + if (state === 'began' || state === 'changed') { + 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); + } + }, + }); + + return ( +
+
+
+ {DECK[top % DECK.length].face} +
+
+ {/* The drag's keyboard and assistive-technology path (WCAG 2.5.7). */} + +
+ {announcement} +
+
+ ); +} diff --git a/packages/cli/foundation/doc-compiler/inputs.test.mjs b/packages/cli/foundation/doc-compiler/inputs.test.mjs index d62219b047cfb..56e328dc9960f 100644 --- a/packages/cli/foundation/doc-compiler/inputs.test.mjs +++ b/packages/cli/foundation/doc-compiler/inputs.test.mjs @@ -98,6 +98,7 @@ describe('collectDocInputs over what this repo ships', () => { 'Resizable', 'SyntaxTheme', 'createAnimator', + 'createPanGesture', ]); }); diff --git a/packages/core/api-report.md b/packages/core/api-report.md index dfebb429057af..e67337f88e39f 100644 --- a/packages/core/api-report.md +++ b/packages/core/api-report.md @@ -2931,6 +2931,7 @@ hook useOutlineFromDOM: (containerRef: React.RefObject) => O hook useOutlineFromMarkdown: (markdown: string, options?: ParseOutlineFromMarkdownOptions) => OutlineItem[] hook useOverflow: (itemCount: number, options?: UseOverflowOptions) => UseOverflowReturn hook useOverlay: ({…}?: UseOverlayOptions) => UseOverlayResult +hook usePanGesture: (ref: RefObject, options: PanGestureOptions) => void hook usePopover: (options?: UsePopoverOptions) => UsePopoverReturn hook usePowerSearchConfig: >(definitions: D, configName?: string) => { config: PowerSearchConfig; applyFilters: >(filters: ReadonlyArray, data: ReadonlyArray) => T[] } hook usePressFeedback: () => typeof pressableProps @@ -2995,6 +2996,7 @@ function createAnimator: (element: HTMLElement) => Animator function createCodeLanguage: ({…}: CreateCodeLanguageOptions) => CodeLanguage function createISOTimeString: (value: string) => ISOTimeString | null function createIncrementalState: () => IncrementalState +function createPanGesture: (element: Element, options: PanGestureOptions) => PanGesture function createPowerSearchConfig: >(definitions: D, configName?: string) => { config: PowerSearchConfig; applyFilters: >(filters: ReadonlyArray, data: ReadonlyArray) => T[] } function createStaticSource: (items: T[], options?: CreateStaticSourceOptions) => SearchSource function dateToISO: (pd: PlainDate) => ISODateString @@ -4927,6 +4929,16 @@ interface PaginationVariantMap input: true none: true pages: true +interface PanGesture + destroy: () => void +interface PanGestureEvent + state: PanGestureState + translation: { x: number; y: number } + velocity: { x: number; y: number } +interface PanGestureOptions + axis?: 'x' | 'y' + onPan: (event: PanGestureEvent) => void +type PanGestureState = 'began' | 'changed' | 'ended' | 'cancelled' type ParseOptions = readonly []> = CommonParseOptions & { math?: false | undefined } interface ParseOutlineFromMarkdownOptions isFinal?: boolean @@ -9098,6 +9110,10 @@ MenuPressEvent (.) MenuPressGesture (.) MenuPressPointerType (.) MenuPressStep (.) +PanGesture (.) +PanGestureEvent (.) +PanGestureOptions (.) +PanGestureState (.) ScrollAxis (.) ScrollAxisState (.) ScrollKeyboardAccess (.) @@ -9168,6 +9184,7 @@ useMediaQuery (.) useMenuPress (.) useMergedRefs (.) useOverflow (.) +usePanGesture (.) usePressFeedback (.) useScrollLock (.) useScrollOverflow (.) diff --git a/packages/core/src/Drawer/Drawer.tsx b/packages/core/src/Drawer/Drawer.tsx index 7607542b045f4..92b392f430371 100644 --- a/packages/core/src/Drawer/Drawer.tsx +++ b/packages/core/src/Drawer/Drawer.tsx @@ -72,7 +72,9 @@ import { shadowVars, } from '../theme/tokens.stylex'; import type {DialogPurpose} from '../Dialog'; -import {useFocusTrap, useMergedRefs, useScrollLock} from '../hooks'; +import {useFocusTrap} from '../hooks/useFocusTrap'; +import {useMergedRefs} from '../hooks/useMergedRefs'; +import {useScrollLock} from '../hooks/useScrollLock'; import {LayerDepthProvider, useLayerDismissal} from '../Layer'; import {layerTextReset} from '../Layer/layerTextReset.stylex'; import {layerStructureReset} from '../Layer/layerStructureReset.stylex'; diff --git a/packages/core/src/gestures/README.md b/packages/core/src/gestures/README.md index cb603f434f6af..fa28133a0f8d3 100644 --- a/packages/core/src/gestures/README.md +++ b/packages/core/src/gestures/README.md @@ -2,7 +2,8 @@ A gesture recognizer system with UIKit's semantics, for the touch presentations of Astryx core components. Components import it from -`../gestures`; nothing here is exported from the package. +`../gestures`. The package exports only `createPanGesture` and its types from +here. UIKit is the reference throughout: the same recognizer states, the same conflict rules, the same thresholds (from `../motion/uikit/gestures.ts`, each diff --git a/packages/core/src/gestures/__tests__/browser/fixture.ts b/packages/core/src/gestures/__tests__/browser/fixture.ts index b10c5beddde52..d61cd87d76a32 100644 --- a/packages/core/src/gestures/__tests__/browser/fixture.ts +++ b/packages/core/src/gestures/__tests__/browser/fixture.ts @@ -14,6 +14,7 @@ * test-only */ +import {createPanGesture} from '../../createPanGesture'; import {getGestureHost} from '../../GestureHost'; import type {GestureRecognizer} from '../../GestureRecognizer'; import {LongPressGestureRecognizer} from '../../LongPressGestureRecognizer'; @@ -163,6 +164,7 @@ document.body.innerHTML = `
feed row (tap)
feed content
+
public pan (drag sideways)
page
passive control at the page's end
`; @@ -280,6 +282,19 @@ for (const id of ['edgeZone', 'edgeWide', 'edgeZoneRtl', 'edgeWideRtl']) { record(edge, () => ({x: edge.translation().x})); host.attach(element(id), edge); } +// The public pan (spec:AST-107 FR1): a drag reported as values, on its axis. +createPanGesture(element('publicPan'), { + axis: 'x', + onPan: ({state, translation}) => { + window.__gestures.push({ + name: 'publicPan', + state, + time: performance.now(), + x: translation.x, + y: translation.y, + }); + }, +}); // A control with no recognizer of its own (no blocking listener): only a // press consumer, under pan-y, as a passive switch is. diff --git a/packages/core/src/gestures/__tests__/browser/gestures.interaction.browser.spec.ts b/packages/core/src/gestures/__tests__/browser/gestures.interaction.browser.spec.ts index 6625e96a0734f..d68dfa7b095ca 100644 --- a/packages/core/src/gestures/__tests__/browser/gestures.interaction.browser.spec.ts +++ b/packages/core/src/gestures/__tests__/browser/gestures.interaction.browser.spec.ts @@ -411,6 +411,7 @@ test('only elements whose recognizers claim a moving touch carry a blocking touc 'card', 'onePan', 'kept', + 'publicPan', 'authorNone', 'authorPanY', 'authorPinchZoom', @@ -575,6 +576,123 @@ test('a one-way overlay pan keeps its direction from the page, and leaves the ot expect(states(await log(page), 'card')).toEqual(['failed', 'possible']); }); +test('the public pan reports a finger\u2019s drag along its axis as values (spec:AST-107 FR1)', async ({ + page, + browserName, +}) => { + const driver = await open(page, browserName); + await page.evaluate(() => { + document.getElementById('publicPan')?.scrollIntoView({block: 'center'}); + }); + const start = await center(page, 'publicPan'); + await driver.play(drag(start, {x: start.x + 120, y: start.y + 6})); + const entries = (await log(page)).filter(entry => entry.name === 'publicPan'); + expect(entries[0]?.state).toBe('began'); + expect(entries.at(-1)?.state).toBe('ended'); + // Nothing across its axis. + expect(entries.every(entry => entry.y === 0)).toBe(true); + // As in UIKit, the travel the drag needed to begin is not part of it. + expect( + entries.filter(entry => entry.state === 'changed').at(-1)?.x, + ).toBeCloseTo(120 - 10, 0); +}); + +test('the public pan is driven by a mouse drag and a pen drag where the primary pointer is fine (spec:AST-107 FR1, AST-094 FR43)', async ({ + browser, + browserName, +}) => { + // A desktop context: a fine primary pointer and no touch. + const context = await browser.newContext({ + hasTouch: false, + isMobile: false, + viewport: {width: 800, height: 900}, + }); + try { + const page = await context.newPage(); + await page.goto('about:blank'); + await page.setContent( + '', + ); + await page.addScriptTag({content: bundle}); + await page.evaluate(() => { + document.getElementById('publicPan')?.scrollIntoView({block: 'center'}); + }); + const start = await center(page, 'publicPan'); + const publicPan = async () => + (await log(page)) + .filter(entry => entry.name === 'publicPan') + .map(entry => entry.state); + // A mouse drag. + await page.mouse.move(start.x, start.y); + await page.mouse.down(); + for (let step = 1; step <= 8; step++) { + await page.mouse.move(start.x + step * 15, start.y + 2); + } + await page.mouse.up(); + const byMouse = await publicPan(); + expect(byMouse[0]).toBe('began'); + expect(byMouse.at(-1)).toBe('ended'); + await clearLog(page); + // A pen drag, where the engine can make one (Chromium's input domain). + if (browserName === 'chromium') { + const cdp = await context.newCDPSession(page); + const pen = async ( + type: 'mousePressed' | 'mouseMoved' | 'mouseReleased', + x: number, + buttons: number, + ): Promise => { + await cdp.send('Input.dispatchMouseEvent', { + type, + x, + y: start.y, + button: 'left', + buttons, + clickCount: 1, + pointerType: 'pen', + }); + }; + await pen('mousePressed', start.x, 1); + for (let step = 1; step <= 8; step++) { + await pen('mouseMoved', start.x + step * 15, 1); + } + await pen('mouseReleased', start.x + 120, 0); + const byPen = await publicPan(); + expect(byPen[0]).toBe('began'); + expect(byPen.at(-1)).toBe('ended'); + } + } finally { + await context.close(); + } +}); + +test('a tap, a long press and a drag across its axis on the public pan report nothing (spec:AST-107 FR1)', async ({ + page, + browserName, +}) => { + const driver = await open(page, browserName); + await page.evaluate(() => { + document.getElementById('publicPan')?.scrollIntoView({block: 'center'}); + }); + const at = await center(page, 'publicPan'); + const finger = {...at, id: 1}; + // A tap. + await driver.play([ + {t: 0, down: [finger]}, + {t: 60, down: []}, + ]); + // A long press: still well past the long-press duration. + await driver.play([ + {t: 0, down: [finger]}, + {t: 800, down: [finger]}, + {t: 816, down: []}, + ]); + // A drag across its axis. + await driver.play(drag(at, {x: at.x, y: at.y + 60}, 20)); + expect((await log(page)).filter(entry => entry.name === 'publicPan')).toEqual( + [], + ); +}); + test('a held finger turns text selection off only where the hold does something (a pan that asks), until it lifts; a press-tracked control, a mouse and other pans keep native selection (spec:AST-094 FR41)', async ({ page, browserName, @@ -2514,6 +2632,7 @@ test.describe('where the primary pointer is fine', () => { 'edgeWide', 'edgeZoneRtl', 'edgeWideRtl', + 'publicPan', 'slider', 'switchRow', 'onePan', diff --git a/packages/core/src/gestures/__tests__/createPanGesture.test.tsx b/packages/core/src/gestures/__tests__/createPanGesture.test.tsx new file mode 100644 index 0000000000000..3a2a6689d835a --- /dev/null +++ b/packages/core/src/gestures/__tests__/createPanGesture.test.tsx @@ -0,0 +1,490 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file createPanGesture.test.tsx + * @input createPanGesture and usePanGesture driven by touches through the + * document's gesture host + * @output Tests for spec:AST-107 FR1 and FR6. A drag is reported as values, + * on each axis, and as cancelled. A press or a long press reports nothing. + * One API works at two layers. Destroy leaves no listener. + * @position Tests of the public pan factory and its hook + */ + +import {act, render} from '@testing-library/react'; +import {StrictMode, useRef, useState} from 'react'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import { + createPanGesture, + type PanGestureEvent, + type PanGestureOptions, +} from '../createPanGesture'; +import {usePanGesture} from '../../hooks/usePanGesture'; +import {armClickGuard, disarmClickGuard} from '../../utils/clickGuard'; +import {coarsePrimaryPointer} from './harness'; + +function touch( + type: string, + target: EventTarget, + contact: {id: number; x: number; y: number}, + time: number, + isLift = false, +): Event { + const event = new Event(type, {bubbles: true, cancelable: true}); + const entry = { + identifier: contact.id, + clientX: contact.x, + clientY: contact.y, + target, + }; + Object.defineProperty(event, 'changedTouches', {value: [entry]}); + Object.defineProperty(event, 'touches', {value: isLift ? [] : [entry]}); + Object.defineProperty(event, 'timeStamp', {value: time}); + target.dispatchEvent(event); + return event; +} + +// The document's host outlives a test, so event times only move forward. +let clock = 0; +function later(): number { + clock += 10_000; + return clock; +} + +/** A finger dragging from (10, 10) by `dx`, `dy` in four 16 ms steps, then lifting. */ +function drag( + target: Element, + dx: number, + dy: number, + {lift = true, start = later()}: {lift?: boolean; start?: number} = {}, +): number { + const id = 1; + touch('touchstart', target, {id, x: 10, y: 10}, start); + for (let step = 1; step <= 4; step++) { + touch( + 'touchmove', + target, + {id, x: 10 + (dx * step) / 4, y: 10 + (dy * step) / 4}, + start + step * 16, + ); + } + if (lift) { + touch('touchend', target, {id, x: 10 + dx, y: 10 + dy}, start + 80, true); + } + return start; +} + +/** A drag through Pointer Events only, as a mouse or a pen makes it. */ +function pointerDrag( + target: Element, + pointerType: 'mouse' | 'pen', + dx: number, +): void { + const start = later(); + const send = (type: string, x: number, time: number, buttons: number) => { + const event = new PointerEvent(type, { + bubbles: true, + cancelable: true, + composed: true, + pointerId: 7, + pointerType, + clientX: x, + clientY: 10, + button: 0, + buttons, + }); + Object.defineProperty(event, 'timeStamp', {value: time}); + target.dispatchEvent(event); + }; + send('pointerdown', 10, start, 1); + for (let step = 1; step <= 4; step++) { + send('pointermove', 10 + (dx * step) / 4, start + step * 16, 1); + } + send('pointerup', 10 + dx, start + 80, 0); +} + +/** The states in order, a run of 'changed' counted once. */ +function phases(events: PanGestureEvent[]): string[] { + return events + .map(event => event.state) + .filter((state, index, all) => index === 0 || state !== all[index - 1]); +} + +/** Every listener added to the document, the window and `element`, net of removals. */ +function trackListeners(element?: Element): () => number { + const live = new Map(); + const restores: (() => void)[] = []; + const targets: EventTarget[] = + element == null ? [document, window] : [document, window, element]; + for (const target of targets) { + const add = target.addEventListener.bind(target); + const remove = target.removeEventListener.bind(target); + const key = ( + type: string, + listener: unknown, + options?: boolean | EventListenerOptions, + ) => { + const capture = + typeof options === 'boolean' ? options : options?.capture === true; + return `${target === document ? 'd' : target === window ? 'w' : 'e'}:${type}:${capture}:${listenerId(listener)}`; + }; + target.addEventListener = ( + type: string, + listener: EventListenerOrEventListenerObject | null, + options?: boolean | AddEventListenerOptions, + ) => { + live.set(key(type, listener, options), 1); + add(type, listener, options); + }; + target.removeEventListener = ( + type: string, + listener: EventListenerOrEventListenerObject | null, + options?: boolean | EventListenerOptions, + ) => { + live.delete(key(type, listener, options)); + remove(type, listener, options); + }; + restores.push(() => { + target.addEventListener = add; + target.removeEventListener = remove; + }); + } + afterEachRestore.push(...restores); + return () => live.size; +} + +const ids = new WeakMap(); +let nextId = 0; +function listenerId(listener: unknown): number { + if ( + listener == null || + (typeof listener !== 'object' && typeof listener !== 'function') + ) { + return -1; + } + let id = ids.get(listener); + if (id == null) { + id = nextId++; + ids.set(listener, id); + } + return id; +} + +const afterEachRestore: (() => void)[] = []; +let restorePointer: () => void = () => {}; +const surfaces: HTMLElement[] = []; +const destroys: (() => void)[] = []; + +function surface(): HTMLElement { + const element = document.createElement('div'); + document.body.append(element); + surfaces.push(element); + return element; +} + +function pan(element: Element, options: PanGestureOptions) { + const gesture = createPanGesture(element, options); + destroys.push(() => gesture.destroy()); + return gesture; +} + +// A phone: the document's host listens only where the pointer is coarse. +beforeEach(() => { + restorePointer = coarsePrimaryPointer(); +}); +afterEach(() => { + for (const destroy of destroys.splice(0)) { + destroy(); + } + for (const element of surfaces.splice(0)) { + element.remove(); + } + for (const restore of afterEachRestore.splice(0)) { + restore(); + } + restorePointer(); + vi.useRealTimers(); +}); + +describe('createPanGesture (spec:AST-107 FR1, FR6)', () => { + it('reports a horizontal drag as began, changed and ended values, and hands out no recognizer', () => { + const element = surface(); + const events: PanGestureEvent[] = []; + const gesture = pan(element, { + axis: 'x', + onPan: event => events.push(event), + }); + expect(Object.keys(gesture)).toEqual(['destroy']); + drag(element, 40, 0); + expect(phases(events)).toEqual(['began', 'changed', 'ended']); + for (const event of events) { + // Exactly the record's values (spec:AST-107 FR1): no pointer kind. + expect(Object.keys(event).sort()).toEqual([ + 'state', + 'translation', + 'velocity', + ]); + expect(event.translation.y).toBe(0); + expect(event.velocity.y).toBe(0); + } + // The threshold's travel is not part of the translation: the step that + // reached 10 px begins the drag at 0, as UIKit's pan does. + expect(events[0].translation.x).toBe(0); + expect(events.at(-1)?.translation.x).toBe(30); + expect(events.at(-1)?.velocity.x).toBeGreaterThan(0); + }); + + it('is driven by a finger, a mouse and a pen alike (spec:AST-107 FR1, AST-094 FR43)', () => { + const element = surface(); + const events: PanGestureEvent[] = []; + pan(element, {axis: 'x', onPan: event => events.push(event)}); + drag(element, 60, 0); + expect(phases(events)).toEqual(['began', 'changed', 'ended']); + for (const pointerType of ['mouse', 'pen'] as const) { + events.length = 0; + pointerDrag(element, pointerType, 60); + expect(phases(events)).toEqual(['began', 'changed', 'ended']); + } + }); + + it('reports a vertical drag on the y axis, with nothing across it', () => { + const element = surface(); + const events: PanGestureEvent[] = []; + pan(element, {axis: 'y', onPan: event => events.push(event)}); + drag(element, 4, 40); + expect(phases(events)).toEqual(['began', 'changed', 'ended']); + for (const event of events) { + expect(event.translation.x).toBe(0); + expect(event.velocity.x).toBe(0); + } + expect(events.at(-1)?.translation.y).toBe(30); + expect(events.at(-1)?.velocity.y).toBeGreaterThan(0); + }); + + it('reports nothing for a drag off its axis', () => { + const element = surface(); + const onPan = vi.fn(); + pan(element, {axis: 'x', onPan}); + drag(element, 0, 40); + expect(onPan).not.toHaveBeenCalled(); + }); + + it('reports both axes without an axis', () => { + const element = surface(); + const events: PanGestureEvent[] = []; + pan(element, {onPan: event => events.push(event)}); + drag(element, 40, 20); + expect(events.at(-1)?.state).toBe('ended'); + expect(events.at(-1)?.translation.x).toBeGreaterThan(0); + expect(events.at(-1)?.translation.y).toBeGreaterThan(0); + }); + + it('reports a cancelled drag as cancelled, with no velocity', () => { + const element = surface(); + const events: PanGestureEvent[] = []; + pan(element, {axis: 'x', onPan: event => events.push(event)}); + const start = drag(element, 40, 0, {lift: false}); + touch('touchcancel', element, {id: 1, x: 50, y: 10}, start + 96, true); + expect(phases(events)).toEqual(['began', 'changed', 'cancelled']); + expect(events.at(-1)?.velocity).toEqual({x: 0, y: 0}); + }); + + it('reports nothing for a press or a long press', () => { + vi.useFakeTimers(); + const element = surface(); + const onPan = vi.fn(); + pan(element, {axis: 'x', onPan}); + // A press: down and up in place. + const press = later(); + touch('touchstart', element, {id: 1, x: 10, y: 10}, press); + touch('touchend', element, {id: 1, x: 10, y: 10}, press + 80, true); + // A long press: a finger held still well past the long-press duration. + const hold = later(); + touch('touchstart', element, {id: 2, x: 10, y: 10}, hold); + vi.advanceTimersByTime(1000); + touch('touchend', element, {id: 2, x: 11, y: 10}, hold + 1000, true); + expect(onPan).not.toHaveBeenCalled(); + }); + + it('removes every listener it added on destroy, and a destroy mid-drag cancels the drag once', () => { + const element = surface(); + const live = trackListeners(element); + const before = live(); + const events: PanGestureEvent[] = []; + const gesture = createPanGesture(element, { + axis: 'x', + onPan: event => events.push(event), + }); + const start = drag(element, 40, 0, {lift: false}); + gesture.destroy(); + expect(phases(events)).toEqual(['began', 'changed', 'cancelled']); + expect(live()).toBe(before); + // Nothing reaches it any more. + touch('touchmove', element, {id: 1, x: 80, y: 10}, start + 120); + touch('touchend', element, {id: 1, x: 80, y: 10}, start + 136, true); + const reported = events.length; + drag(element, 40, 0); + expect(events).toHaveLength(reported); + // A second destroy does nothing. + gesture.destroy(); + expect(live()).toBe(before); + }); +}); + +describe('createPanGesture on the server (spec:AST-107 FR6)', () => { + it('does no DOM work at import', async () => { + vi.resetModules(); + const touched: string[] = []; + const realDocument: Document = document; + const realMatchMedia: typeof window.matchMedia = window.matchMedia; + const documentDescriptor = Object.getOwnPropertyDescriptor( + globalThis, + 'document', + ); + const matchMediaDescriptor = Object.getOwnPropertyDescriptor( + window, + 'matchMedia', + ); + Object.defineProperty(globalThis, 'document', { + configurable: true, + get(): Document { + touched.push('document'); + return realDocument; + }, + }); + Object.defineProperty(window, 'matchMedia', { + configurable: true, + get(): typeof window.matchMedia { + touched.push('matchMedia'); + return realMatchMedia; + }, + }); + try { + const module = await import('../createPanGesture'); + expect(typeof module.createPanGesture).toBe('function'); + const hooks = await import('../../hooks/usePanGesture'); + expect(typeof hooks.usePanGesture).toBe('function'); + } finally { + if (documentDescriptor) { + Object.defineProperty(globalThis, 'document', documentDescriptor); + } + if (matchMediaDescriptor) { + Object.defineProperty(window, 'matchMedia', matchMediaDescriptor); + } + } + expect(touched).toEqual([]); + }); +}); + +function Draggable({ + axis, + onPan, +}: { + axis?: 'x' | 'y'; + onPan: (event: PanGestureEvent) => void; +}) { + const ref = useRef(null); + usePanGesture(ref, {axis, onPan}); + return
; +} + +describe('usePanGesture (spec:AST-107 FR1, FR6)', () => { + it('reports what its factory reports, through the latest onPan', () => { + const first = vi.fn(); + const events: PanGestureEvent[] = []; + const {getByTestId, rerender} = render( + , + ); + rerender( events.push(event)} />); + drag(getByTestId('surface'), 40, 0); + expect(first).not.toHaveBeenCalled(); + expect(phases(events)).toEqual(['began', 'changed', 'ended']); + expect(events.at(-1)?.translation).toEqual({x: 30, y: 0}); + }); + + it('calls onPan from no effect: a drag in progress at unmount ends without a cancelled event (architecture:react-component-runtime INV2)', () => { + const events: PanGestureEvent[] = []; + const {getByTestId, unmount} = render( + events.push(event)} />, + ); + drag(getByTestId('surface'), 40, 0, {lift: false}); + expect(phases(events)).toEqual(['began', 'changed']); + unmount(); + expect(phases(events)).toEqual(['began', 'changed']); + }); + + it('calls onPan from no effect: a drag in progress when the axis changes ends without a cancelled event (architecture:react-component-runtime INV2)', () => { + const events: PanGestureEvent[] = []; + const onPan = (event: PanGestureEvent) => events.push(event); + const {getByTestId, rerender} = render( + , + ); + drag(getByTestId('surface'), 40, 0, {lift: false}); + expect(phases(events)).toEqual(['began', 'changed']); + rerender(); + expect(phases(events)).toEqual(['began', 'changed']); + }); + + it('attaches once under StrictMode and removes every listener at unmount', () => { + const events: PanGestureEvent[] = []; + const holder = document.createElement('div'); + document.body.append(holder); + surfaces.push(holder); + // React keeps its own root listeners on the container after unmount. + // The page's once-per-document listeners go in first, so the count is + // the pan's alone. They are React's own and the click guard's window + // click listener. The guard keeps that listener once a gesture first arms + // it (utils/clickGuard.ts). + const warmup = document.createElement('div'); + document.body.append(warmup); + surfaces.push(warmup); + render(
, {container: warmup}).unmount(); + armClickGuard(document); + disarmClickGuard(document); + const live = trackListeners(); + const before = live(); + const {getByTestId, unmount} = render( + + events.push(event)} /> + , + {container: holder}, + ); + drag(getByTestId('surface'), 40, 0); + expect(phases(events)).toEqual(['began', 'changed', 'ended']); + unmount(); + // The drag's claimed lift armed the click guard. The guard outlives the + // pan on purpose: it swallows the browser's click after the lift, until + // the next press or its window ends. End it here. + disarmClickGuard(document); + expect(live()).toBe(before); + }); + + it('follows the element when the ref moves to a new node', () => { + const events: PanGestureEvent[] = []; + function Swapping() { + const ref = useRef(null); + const [which, setWhich] = useState<'a' | 'b'>('a'); + usePanGesture(ref, {axis: 'x', onPan: event => events.push(event)}); + return ( + <> + + {which === 'a' ? ( +
+ ) : ( +
+ )} + + ); + } + const {getByTestId, getByRole} = render(); + const first = getByTestId('a'); + act(() => { + getByRole('button').click(); + }); + drag(first, 40, 0); + expect(events).toHaveLength(0); + drag(getByTestId('b'), 40, 0); + expect(phases(events)).toEqual(['began', 'changed', 'ended']); + }); +}); diff --git a/packages/core/src/gestures/createPanGesture.doc.mjs b/packages/core/src/gestures/createPanGesture.doc.mjs new file mode 100644 index 0000000000000..97dd5a8dbeda7 --- /dev/null +++ b/packages/core/src/gestures/createPanGesture.doc.mjs @@ -0,0 +1,145 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** @type {import('@astryxdesign/cli/authoring').HookDoc} */ +export const docs = { + name: 'createPanGesture', + displayName: 'createPanGesture', + // A factory documented as a hook: listed with the utilities, beside its + // hook, not as a tile in the components gallery. + group: 'Utilities', + keywords: [ + 'pan', + 'drag', + 'gesture', + 'touch', + 'swipe', + 'translation', + 'velocity', + 'pointer', + 'vanilla', + 'factory', + ], + params: [ + { + name: 'element', + type: 'Element', + description: + 'The element to drag. The pan writes the `touch-action` its axis needs on it and nothing else; it moves nothing itself.', + required: true, + }, + { + name: 'options', + type: 'PanGestureOptions', + description: 'Configuration object.', + required: true, + }, + { + name: 'options.axis', + type: "'x' | 'y'", + description: + 'Limits the drag to one axis. A drag along the other axis is not reported, and that component of every value reads 0, so a scroll across it stays the page’s. Omit it to report both axes; a finger’s scroll that starts on the element then moves the element instead of the page. A trackpad scroll still scrolls the page.', + required: false, + }, + { + name: 'options.onPan', + type: '(event: PanGestureEvent) => void', + description: + "Called with `{state, translation, velocity}` as the drag begins, changes, ends at the release, or is cancelled. `state` is 'began', 'changed', 'ended' or 'cancelled'. `translation` is the movement since the drag began, in pixels, without the travel the drag needed to begin, so an element that follows it does not jump. `velocity` is in pixels per second; at 'ended' it is the release velocity, 0 when the finger rested before lifting, and at 'cancelled' it is 0.", + required: true, + }, + ], + returns: [ + { + name: 'destroy', + type: '() => void', + description: + 'Removes every listener the pan added and its `touch-action`. A drag in progress is cancelled: `onPan` hears `cancelled`.', + }, + ], + 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`.", + bestPractices: [ + { + guidance: true, + description: + 'Move the element from `translation` added to where it was when the drag began, so it moves with the finger from the moment the drag claims it.', + }, + { + guidance: true, + description: + 'At `ended`, hand `velocity` to the animation that settles the element, so a flick carries on at the speed it was released.', + }, + { + guidance: true, + description: + 'Call `destroy` when the element leaves the page, so no listener outlives it.', + }, + { + guidance: false, + description: + 'Read the element’s layout on every `changed` event to place it; `translation` already says where the finger is.', + }, + ], + accessibility: [ + { + name: 'Keyboard and assistive technology', + category: 'Keyboard', + criterion: '2.5.7 Dragging Movements', + description: + 'A drag has no keyboard or assistive-technology path of its own: whatever the drag does needs another way to do it, such as buttons, arrow keys or a menu.', + }, + { + name: 'Reduce Motion', + category: 'Content', + criterion: '2.3.3 Animation from Interactions', + description: + 'The pan moves nothing itself, so Reduce Motion applies to the motion you drive from it: a settle or a throw goes to its end without travel when the person asks for reduced motion.', + }, + ], + }, + relatedHooks: ['usePanGesture'], + importPath: '@astryxdesign/core', + category: 'interaction', +}; + +/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */ +export const docsDense = { + description: + 'Reports a drag on an element as values ({state, translation, velocity}), without React; a finger, a mouse and a pen all drive it, though a mouse or pen drag on selectable text selects it instead (give that text user-select: none). Returns {destroy}.', + paramDescriptions: { + element: 'element to drag; the pan writes only its touch-action.', + options: 'config object.', + 'options.axis': + "'x' | 'y': limit to one axis; the other is never reported and reads 0.", + 'options.onPan': + "({state, translation, velocity}): state 'began' | 'changed' | 'ended' | 'cancelled'; translation px since the drag began (no jump); velocity px/s, release velocity at 'ended', 0 at 'cancelled'.", + }, + returnDescriptions: { + destroy: + '() => void; removes every listener and the touch-action, cancels a drag in progress.', + }, + usage: { + description: + 'Drag as values without React, for a surface you move. Claims at UIKit’s 10 pt. No keyboard path of its own (WCAG 2.5.7); Reduce Motion applies to what you animate. Prefer component props (BottomSheet snapPoints, Carousel hasSnap); in React, usePanGesture.', + bestPractices: [ + { + guidance: true, + description: + 'Move from translation + the offset at began, so the element moves with the finger from the claim.', + }, + { + guidance: true, + description: 'Hand the ended velocity to the settling animation.', + }, + { + guidance: true, + description: 'Call destroy when the element leaves the page.', + }, + { + guidance: false, + description: 'Read layout on every changed event; use translation.', + }, + ], + }, +}; diff --git a/packages/core/src/gestures/createPanGesture.ts b/packages/core/src/gestures/createPanGesture.ts new file mode 100644 index 0000000000000..0c9026c46a9e9 --- /dev/null +++ b/packages/core/src/gestures/createPanGesture.ts @@ -0,0 +1,107 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file createPanGesture.ts + * @input An element and a pan listener + * @output Exports createPanGesture and its types: the public pan factory + * @position Public face of packages/core/src/gestures. It reports a drag as + * values and hands out no recognizer; `usePanGesture` is its React layer. + * Importing it does no DOM work. + * SYNC: When modified, update ../hooks/usePanGesture.ts, its .doc.mjs and + * __tests__/createPanGesture.test.tsx. + */ + +import {getGestureHost} from './GestureHost'; +import {PanGestureRecognizer} from './PanGestureRecognizer'; +import type {Point} from './types'; + +/** Where a drag is: it began, moved, ended at the release, or was cancelled. */ +export type PanGestureState = 'began' | 'changed' | 'ended' | 'cancelled'; + +export interface PanGestureEvent { + state: PanGestureState; + /** + * Movement since the drag began, in CSS px. The travel the drag needed to + * begin is not part of it, so an element that follows it does not jump. + */ + translation: {x: number; y: number}; + /** + * Velocity in px/s. At `ended` it is the release velocity, 0 when the + * finger rested before lifting; at `cancelled` it is 0. + */ + velocity: {x: number; y: number}; +} + +export interface PanGestureOptions { + /** Limit the drag to one axis: a drag along the other is not reported, and that component reads 0. */ + axis?: 'x' | 'y'; + /** Called as the drag begins, changes, ends, or is cancelled. */ + onPan: (event: PanGestureEvent) => void; +} + +export interface PanGesture { + /** Remove every listener the pan added; a drag in progress is cancelled. */ + destroy(): void; +} + +const ZERO = {x: 0, y: 0}; + +/** + * Report drags on `element` as values. The drag claims its touch at UIKit's + * 10 pt, as `UIPanGestureRecognizer` does, so a tap stays a tap. The pan sets + * the element's `touch-action` for the axis. + * @example + * ``` + * const pan = createPanGesture(card, { + * axis: 'x', + * onPan: ({state, translation}) => { + * card.style.translate = state === 'changed' ? `${translation.x}px` : ''; + * }, + * }); + * // Later: + * pan.destroy(); + * ``` + */ +export function createPanGesture( + element: Element, + options: PanGestureOptions, +): PanGesture { + const {axis, onPan} = options; + const recognizer = new PanGestureRecognizer({ + name: 'pan', + direction: axis === 'x' ? 'horizontal' : axis === 'y' ? 'vertical' : 'any', + }); + const along = (point: Point) => + axis === 'x' + ? {x: point.x, y: 0} + : axis === 'y' + ? {x: 0, y: point.y} + : {x: point.x, y: point.y}; + recognizer.addListener(() => { + const state = recognizer.state; + if ( + state !== 'began' && + state !== 'changed' && + state !== 'ended' && + state !== 'cancelled' + ) { + return; + } + onPan({ + state, + translation: along(recognizer.translation()), + velocity: + state === 'cancelled' ? {...ZERO} : along(recognizer.velocity()), + }); + }); + let detach: (() => void) | null = getGestureHost( + element.ownerDocument, + ).attach(element, recognizer); + return { + destroy() { + const current = detach; + detach = null; + current?.(); + }, + }; +} diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.ts index bc42af899e95c..56636015cb466 100644 --- a/packages/core/src/hooks/index.ts +++ b/packages/core/src/hooks/index.ts @@ -150,3 +150,11 @@ export type { ContainerRevealOptions, ContentRevealOptions, } from './useContainerReveal'; + +export {usePanGesture} from './usePanGesture'; +export type { + PanGesture, + PanGestureEvent, + PanGestureOptions, + PanGestureState, +} from '../gestures/createPanGesture'; diff --git a/packages/core/src/hooks/usePanGesture.doc.mjs b/packages/core/src/hooks/usePanGesture.doc.mjs new file mode 100644 index 0000000000000..5b5b4df82b709 --- /dev/null +++ b/packages/core/src/hooks/usePanGesture.doc.mjs @@ -0,0 +1,159 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** @type {import('@astryxdesign/cli/authoring').HookDoc} */ +export const docs = { + name: 'usePanGesture', + displayName: 'usePanGesture', + keywords: [ + 'pan', + 'drag', + 'gesture', + 'touch', + 'swipe', + 'translation', + 'velocity', + 'pointer', + 'createPanGesture', + 'uikit', + ], + params: [ + { + name: 'ref', + type: 'RefObject', + description: + 'The element to drag. The hook creates one pan for the element behind the ref, creates a new one when the ref moves to another node or `axis` changes, and destroys it at unmount; a drag in progress then ends without a `cancelled` event, since an effect never calls `onPan`.', + required: true, + }, + { + name: 'options', + type: 'PanGestureOptions', + description: 'Configuration object.', + required: true, + }, + { + name: 'options.axis', + type: "'x' | 'y'", + description: + 'Limits the drag to one axis. A drag along the other axis is not reported, and that component of every value reads 0. Omit it to report both axes.', + required: false, + }, + { + name: 'options.onPan', + type: '(event: PanGestureEvent) => void', + description: + "Called with `{state, translation, velocity}` as the drag begins, changes, ends at the release, or is cancelled. `state` is 'began', 'changed', 'ended' or 'cancelled'. `translation` is the movement since the drag began, in pixels: the travel the drag needed to begin is not part of it, so an element that follows it does not jump. `velocity` is in pixels per second; at 'ended' it is the release velocity (0 when the finger rested before lifting), and at 'cancelled' it is 0. Read through a ref: a new function each render re-creates nothing.", + required: true, + }, + ], + returns: [ + { + name: 'void', + type: 'void', + description: + 'Nothing: the hook hands out no recognizer. Without React, `createPanGesture(element, options)` takes the same options and returns `{destroy}`, which removes every listener it added and cancels a drag in progress.', + }, + ], + usage: { + description: + 'Reports a drag on an element as values, 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. With `axis`, a scroll across that axis that starts on the element stays the page’s; without it, the pan takes a drag in any direction, so a finger’s scroll that starts on the element moves the element instead of the page. A trackpad scroll still scrolls the page. The hook is a thin layer over `createPanGesture`, the same API for code without React. A drag has no keyboard or assistive-technology path of its own: whatever the drag does needs another way to do it, such as buttons or arrow keys (WCAG 2.5.7). The pan moves nothing itself, so Reduce Motion applies to the motion you drive from it: honor the user’s reduced-motion setting in the animation that moves the element. Where a component already offers the behavior, use its prop instead: BottomSheet’s `snapPoints`, Carousel’s `hasSnap`.', + bestPractices: [ + { + guidance: true, + description: + 'Move the element from `translation` added to where it was when the drag began, so it moves with the finger from the moment the drag claims it.', + }, + { + guidance: true, + description: + 'At `ended`, hand `velocity` to the animation that settles the element, so a flick carries on at the speed it was released.', + }, + { + guidance: true, + description: + 'Give every drag another way to do the same thing from a keyboard and from assistive technology, such as buttons, arrow keys or a menu.', + }, + { + guidance: true, + description: + "Use a component's own prop when it covers the job: BottomSheet's `snapPoints` for a sheet, Carousel's `hasSnap` for paging.", + }, + { + 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.', + }, + { + guidance: false, + description: + 'Recognize taps or long presses with it; `useLongPress` and the components’ own press handling own those.', + }, + ], + accessibility: [ + { + name: 'Keyboard and assistive technology', + category: 'Keyboard', + criterion: '2.5.7 Dragging Movements', + description: + 'A drag has no keyboard or assistive-technology path of its own: whatever the drag does needs another way to do it, such as buttons, arrow keys or a menu.', + }, + { + name: 'Reduce Motion', + category: 'Content', + criterion: '2.3.3 Animation from Interactions', + description: + 'The pan moves nothing itself, so Reduce Motion applies to the motion you drive from it: a settle or a throw goes to its end without travel when the person asks for reduced motion.', + }, + ], + }, + relatedComponents: ['BottomSheet', 'Carousel'], + relatedHooks: ['useLongPress', 'createPanGesture'], + importPath: '@astryxdesign/core/hooks', + category: 'interaction', +}; + +/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */ +export const docsDense = { + description: + 'Reports a drag as values ({state, translation, velocity}) for a surface you move yourself; a finger, a mouse and a pen all drive it, though a mouse or pen drag on selectable text selects it instead (give that text user-select: none). Claims at UIKit’s 10 pt; taps, presses and long presses are never a pan, and with axis a scroll across it stays the page’s. Thin layer over createPanGesture(element, options) → {destroy}. No keyboard path of its own: give the drag another way (WCAG 2.5.7). Reduce Motion: honor it in the animation you drive. Prefer BottomSheet snapPoints / Carousel hasSnap when they fit.', + paramDescriptions: { + ref: 'element to drag; one pan per node, re-created when the ref moves, destroyed at unmount.', + options: 'config object.', + 'options.axis': + "'x' | 'y': limit to one axis; the other is never reported and reads 0.", + 'options.onPan': + "({state, translation, velocity}): state 'began' | 'changed' | 'ended' | 'cancelled'; translation px since the drag began (threshold travel excluded, no jump); velocity px/s, release velocity at 'ended', 0 at 'cancelled'. Read through a ref.", + }, + returnDescriptions: { + void: 'nothing (no recognizer). createPanGesture returns {destroy}: removes every listener, cancels a drag in progress.', + }, + usage: { + description: + 'Drag as values for a card, a drawer handle, any surface you move. Thin layer over createPanGesture. No keyboard path of its own (WCAG 2.5.7); Reduce Motion applies to what you animate. Prefer component props (BottomSheet snapPoints, Carousel hasSnap).', + bestPractices: [ + { + guidance: true, + description: + 'Move from translation + the offset at began, so the element moves with the finger from the claim.', + }, + { + guidance: true, + description: 'Hand the ended velocity to the settling animation.', + }, + { + guidance: true, + description: + 'Give every drag a keyboard and assistive-technology alternative.', + }, + { + guidance: true, + description: "Use a component's own prop when it covers the job.", + }, + { + guidance: false, + description: + 'Set React state on every changed event; write the style in onPan.', + }, + {guidance: false, description: 'Recognize taps or long presses with it.'}, + ], + }, +}; diff --git a/packages/core/src/hooks/usePanGesture.ts b/packages/core/src/hooks/usePanGesture.ts new file mode 100644 index 0000000000000..f4d2899fc9ae9 --- /dev/null +++ b/packages/core/src/hooks/usePanGesture.ts @@ -0,0 +1,69 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file usePanGesture.ts + * @input An element ref and pan options + * @output Exports usePanGesture: the React layer of createPanGesture + * @position Public hook in packages/core/src/hooks. It delegates entirely to + * createPanGesture, through Core's attachment owner (useAttachment). It + * keeps one pan for the element behind `ref`, re-created when the node or + * the axis changes, and destroyed at unmount. `onPan` is read through a + * ref, so a new function each render re-creates nothing. A drag costs no + * React render. + * SYNC: When modified, update usePanGesture.doc.mjs and + * ../gestures/__tests__/createPanGesture.test.tsx. + */ + +import {useRef, type RefObject} from 'react'; +import { + createPanGesture, + type PanGestureOptions, +} from '../gestures/createPanGesture'; +import {useAttachment} from './useAttachment'; + +/** + * Report drags on the element behind `ref` as values. + * @example + * ``` + * const ref = useRef(null); + * usePanGesture(ref, { + * axis: 'x', + * onPan: ({state, translation}) => { + * ref.current!.style.translate = + * state === 'changed' ? `${translation.x}px` : ''; + * }, + * }); + * ``` + */ +export function usePanGesture( + ref: RefObject, + options: PanGestureOptions, +): void { + const {axis, onPan} = options; + // Keep the latest listener without re-creating the pan on every render. + const onPanRef = useRef(onPan); + onPanRef.current = onPan; + // An effect never calls `onPan`. So a drag in progress ends with no event + // when the node or the axis changes, or at unmount. + useAttachment( + ref, + element => { + let isForwarding = true; + const gesture = createPanGesture(element, { + axis, + onPan: event => { + if (isForwarding) { + onPanRef.current(event); + } + }, + }); + return () => { + isForwarding = false; + gesture.destroy(); + }; + }, + axis, + ); +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index a616f32872495..3ed448fa5cbfa 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -189,6 +189,8 @@ export { // Hooks export * from './hooks'; +export {createPanGesture} from './gestures/createPanGesture'; + // Utilities export * from './utils'; diff --git a/scripts/touch-support-bundle.test.mjs b/scripts/touch-support-bundle.test.mjs index 76ebf5bc5b09f..5055c2b77b8b9 100644 --- a/scripts/touch-support-bundle.test.mjs +++ b/scripts/touch-support-bundle.test.mjs @@ -206,6 +206,8 @@ const GESTURE_USERS = new Set([ 'SideNav', 'TimeInput', 'TopNav', + // The public pan, which the root's createPanGesture shares. + 'hooks: usePanGesture', ]); /** Public imports that carry no gesture code, whatever the list above says. */