From ebaa99eb6aec93964c83634cbc11a05d24a1b751 Mon Sep 17 00:00:00 2001 From: Humberto Virtudes <22264642+humbertovirtudes@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:55:54 -0800 Subject: [PATCH] feat(core): a Lab collection that runs its own reorder mode shares List's reorder parts A new internal entry, @astryxdesign/core/internal/reorder-mode, gives Lab the parts of List's reorder: the mode hint, which now offers Up and Down or Left and Right, the strings, the pointer input with a finger's hold, the edge autoscroll, the drop bounds and the preview copy. internal/reorder gains mountReorderStarter, so a reorderable object's start(key) reaches such a collection. List's session uses the same parts, so List does not change. The catalog gains Move left and Move right. --- .changeset/reorder-internal-shared-parts.md | 7 + docs/specs/components/List/List.spec.md | 24 + packages/core/locales/en.json | 8 + packages/core/package.json | 5 + packages/core/src/List/ReorderModeHint.tsx | 200 ++++++ packages/core/src/List/listReorderContext.ts | 14 + packages/core/src/List/listReorderEngine.tsx | 571 +++--------------- packages/core/src/List/reorderAutoscroll.ts | 41 ++ packages/core/src/List/reorderMessages.ts | 73 +++ packages/core/src/List/reorderPointer.ts | 239 ++++++++ packages/core/src/List/reorderScrollWatch.ts | 130 ++++ packages/core/src/internal/reorder-mode.ts | 45 ++ packages/core/src/internal/reorder.ts | 39 +- .../core/src/internal/reorderShared.test.tsx | 253 ++++++++ .../motion/animatedLayout.boundary.test.ts | 2 + packages/core/src/motion/inertClone.ts | 33 +- scripts/sync-exports.js | 1 + 17 files changed, 1181 insertions(+), 504 deletions(-) create mode 100644 .changeset/reorder-internal-shared-parts.md create mode 100644 packages/core/src/List/ReorderModeHint.tsx create mode 100644 packages/core/src/List/reorderAutoscroll.ts create mode 100644 packages/core/src/List/reorderMessages.ts create mode 100644 packages/core/src/List/reorderPointer.ts create mode 100644 packages/core/src/List/reorderScrollWatch.ts create mode 100644 packages/core/src/internal/reorder-mode.ts create mode 100644 packages/core/src/internal/reorderShared.test.tsx diff --git a/.changeset/reorder-internal-shared-parts.md b/.changeset/reorder-internal-shared-parts.md new file mode 100644 index 0000000000000..17e8872b70c4c --- /dev/null +++ b/.changeset/reorder-internal-shared-parts.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: a new internal entry, `@astryxdesign/core/internal/reorder-mode`, reserved for Astryx's own packages, gives a collection that runs its own reorder mode the parts a List's uses: its mode hint, along either axis, its strings, its pointer input with a finger's hold, its edge autoscroll, scroll watch and bounds, the preview copy, and the text it names items by. The internal reorder entry gains a way for the object's `start(key)` to reach such a collection. The catalog gains Move left and Move right for the hint's inline moves. The entry is not part of the public API. Apps see no change. + +@humbertovirtudes diff --git a/docs/specs/components/List/List.spec.md b/docs/specs/components/List/List.spec.md index 4018fad06fcc2..8d6a151231e6b 100644 --- a/docs/specs/components/List/List.spec.md +++ b/docs/specs/components/List/List.spec.md @@ -20,6 +20,7 @@ verified_by: packages/core/src/List/listLayoutUpdates.test.tsx, packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts, packages/core/src/List/__tests__/ListReorder.test.tsx, + packages/core/src/internal/reorderShared.test.tsx, packages/core/src/List/__tests__/ListReorderLayout.test.tsx, packages/core/src/List/__tests__/ListReorderTouch.interaction.browser.spec.ts, packages/core/src/List/__tests__/ListReorderPointer.interaction.browser.spec.ts, @@ -116,6 +117,29 @@ Consumer migration instructions belong in consumer docs and release notes. through `@astryxdesign/core/internal/reorder`. It tells whether an element is a reorder handle, so a Lab collection that puts the handle beside its own controls tells them apart: ListInput's field focus skips the handle. +- The parts of List's reorder that a Lab collection running its own reorder + mode shares, through the internal entry + `@astryxdesign/core/internal/reorder-mode` (`internal/reorder-mode.ts`): + - the mode's hint, `ReorderModeHint` (`List/ReorderModeHint.tsx`), with + Move up and Move down on the block axis or Move left and Move right on + the inline axis; + - its strings, `reorderMessagesFrom` (`List/reorderMessages.ts`); + - its pointer input, `attachReorderMouse` and `attachReorderHold` + (`List/reorderPointer.ts`): a mouse, or a pen where the primary pointer + is fine, drags at once; a finger, or a pen where it is coarse, after the + hold; + - its edge autoscroll, `reorderAutoscroll` (`List/reorderAutoscroll.ts`) + with `autoscrollStep`, and its watch of the scroller, + `watchReorderScroll` (`List/reorderScrollWatch.ts`), which folds a + scroll the drag did not cause into the drag in a later frame; + - its drop bounds, `movableRange`, and its preview copy, `previewCopyOf` + with the bare box `bareCopyOf` it falls back to, and + `paintedBackground`; + - the text it names an item's handle by, `getNodeText`. + + `mountReorderStarter`, in `@astryxdesign/core/internal/reorder`, lets the + object's `start(key)` reach that collection (`spec:AST-103` FR4a). + - `@astryxdesign/core/internal/reorderHandle.stylex` holds the reorder handle's grip and reach sizes (`grip`, `targetReach`, `touchReach`), which List, ListInput and TransferList share. It is internal, like the other diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json index 61913b75c2e14..e2de779e0bee9 100644 --- a/packages/core/locales/en.json +++ b/packages/core/locales/en.json @@ -651,6 +651,14 @@ "defaultMessage": "Move down", "description": "Accessible label of the down-arrow button in the hint a List row's reorder mode shows: it moves the row one place down, as the Down arrow key does." }, + "@astryx.list.reorderMoveLeft": { + "defaultMessage": "Move left", + "description": "Accessible label of the left-arrow button in the hint that reorder mode shows for items in a row, such as a Table's columns: it moves the item one place to the left, as the Left arrow key does." + }, + "@astryx.list.reorderMoveRight": { + "defaultMessage": "Move right", + "description": "Accessible label of the right-arrow button in the hint that reorder mode shows for items in a row, such as a Table's columns: it moves the item one place to the right, as the Right arrow key does." + }, "@astryx.list.reorderDone": { "defaultMessage": "Done", "description": "Button in the hint a List row's reorder mode shows: it ends the mode and keeps the moves, as Escape does." diff --git a/packages/core/package.json b/packages/core/package.json index 4d435d32f6535..cfcc37625ad92 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -849,6 +849,11 @@ "types": "./dist/internal/reorder.d.ts", "default": "./dist/internal/reorder.js" }, + "./internal/reorder-mode": { + "source": "./src/internal/reorder-mode.ts", + "types": "./dist/internal/reorder-mode.d.ts", + "default": "./dist/internal/reorder-mode.js" + }, "./internal/reorderHandle.stylex": { "source": "./src/internal/reorderHandle.stylex.ts", "types": "./dist/internal/reorderHandle.stylex.d.ts", diff --git a/packages/core/src/List/ReorderModeHint.tsx b/packages/core/src/List/ReorderModeHint.tsx new file mode 100644 index 0000000000000..e510db1e1eb6f --- /dev/null +++ b/packages/core/src/List/ReorderModeHint.tsx @@ -0,0 +1,200 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file ReorderModeHint.tsx + * @input The handle of the item in reorder mode, its collection's axis, and + * Core's keyboard hint layer (hooks/anchoredHint.tsx) + * @output `ReorderModeHint`: reorder mode's hint, anchored below the start of + * the handle. Its glyphs and Done are buttons that do what their keys do + * @position Rendered by List's reorder session (List/listReorderEngine.tsx), + * and by Lab collections through `@astryxdesign/core/internal/reorder-mode` + */ + +import {useRef, type ReactNode} from 'react'; +import * as stylex from '@stylexjs/stylex'; +import {anchoredHintStyles, renderAnchoredHint} from '../hooks/anchoredHint'; +import {useCommittedRef} from '../hooks/useCommittedRef'; +import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; +import english from '../i18n/generated-english/List/ReorderModeHint.generated'; +import { + registerEnglishFallback, + useComponentTranslator, +} from '../i18n/useComponentTranslator'; +import {touchHitAreaStyles} from '../internal/touchHitArea.stylex'; +import {Kbd} from '../Kbd/Kbd'; +import {useLayer} from '../Layer/useLayer'; +import {useLayerDismissal} from '../Layer/useLayerDismissal'; +import {spacingVars} from '../theme/tokens.stylex'; +import {focusOutlineProps} from '../utils/focusOutline.stylex'; +import {useTouchHitArea} from '../utils/touchHitArea'; + +registerEnglishFallback(english); + +/** A move reorder mode's hint offers: one place in a direction on screen. */ +export type ReorderHintMove = 'up' | 'down' | 'left' | 'right'; + +/** What `ReorderModeHint` takes. */ +export interface ReorderModeHintProps { + /** The handle of the item in reorder mode, or null outside the mode. */ + readonly target: HTMLElement | null; + /** + * The axis the collection orders along: `block` offers Up and Down, + * `inline` offers Left and Right. + */ + readonly axis: 'block' | 'inline'; + /** Does what the move's arrow key does. */ + readonly onMove: (move: ReorderHintMove) => void; + /** Ends reorder mode, as Escape does. */ + readonly onDone: () => void; + /** Receives the hint's element, which holds its buttons. */ + readonly onHintElement?: (element: HTMLElement | null) => void; +} + +const styles = stylex.create({ + // A glyph or Done: the hint's text, with nothing of a button's own, the + // same size under every pointer. A finger's 44 px target is the shared + // touch hit layer, which stops short of a neighbouring target. + button: { + position: 'relative', + display: 'inline-flex', + alignItems: 'center', + justifyContent: 'center', + margin: 0, + padding: 0, + borderWidth: 0, + borderRadius: 4, + backgroundColor: 'transparent', + color: 'inherit', + fontFamily: 'inherit', + fontSize: 'inherit', + lineHeight: 'inherit', + cursor: { + default: 'pointer', + ':is(:disabled,[aria-disabled="true"])': 'default', + }, + }, + done: { + paddingInline: spacingVars['--spacing-1'], + }, +}); + +/** + * One of the hint's buttons: it never takes the focus from the handle (a + * press does not move it), and does what its key does. + */ +function HintButton({ + label, + onPress, + isText = false, + children, +}: { + label?: string; + onPress: () => void; + isText?: boolean; + children: ReactNode; +}) { + // A finger's target: the shared touch hit area grows the button's hit + // layer where the primary pointer is coarse. + const hitAreaRef = useTouchHitArea(true); + return ( + + ); +} + +/** + * Reorder mode's hint. It is anchored below the start of the handle whose + * item is in the mode, in Core's keyboard hint's layer and theme roles. It + * shows the moves for the collection's axis and Done until the mode ends. + * Each move is a button that does what its key does, and the focus stays on + * the handle. Done ends the mode as Escape does. So a pointer or a finger + * can reorder by tapping the handle, the moves, then Done. + */ +export function ReorderModeHint({ + target, + axis, + onMove, + onDone, + onHintElement, +}: ReorderModeHintProps): ReactNode { + const t = useComponentTranslator(); + const layer = useLayer({mode: 'context'}); + // The latest layer handle, for the effect below, which re-runs only when + // the mode's item changes. + const layerRef = useCommittedRef(layer); + const hintRef = useRef(null); + // External system: the hint's popover in the top layer (useLayer), + // anchored to the handle of the item in reorder mode. Shown while that + // item is in the mode; hidden and unanchored when the mode ends or moves on. + useIsomorphicLayoutEffect(() => { + if (target == null) { + return undefined; + } + const shown = layerRef.current; + shown.ref(target); + shown.show(); + return () => { + shown.hide(); + shown.ref(null); + }; + }, [target]); + // The shared dismissal stack. While the hint is up, an Escape that reaches + // the stack, with the focus in the hint, ends reorder mode. A layer below + // it, such as a Dialog, stays open. The handle claims its own Escape first. + useLayerDismissal({ + isActive: target != null, + onDismiss: onDone, + getContainer: () => hintRef.current, + }); + const [back, forward]: ReadonlyArray = + axis === 'block' ? ['up', 'down'] : ['left', 'right']; + return renderAnchoredHint( + layer, + target == null ? null : ( + { + hintRef.current = element; + onHintElement?.(element); + }} + {...stylex.props(anchoredHintStyles.keys)}> + onMove(back)}> + + + onMove(forward)}> + + + + {t('@astryx.list.reorderDone')} + + + ), + {isInteractive: true}, + ); +} diff --git a/packages/core/src/List/listReorderContext.ts b/packages/core/src/List/listReorderContext.ts index edf9943014a34..14ee703902891 100644 --- a/packages/core/src/List/listReorderContext.ts +++ b/packages/core/src/List/listReorderContext.ts @@ -212,6 +212,12 @@ export interface ReorderRows { holds(element: Element, container: HTMLElement): boolean; } +/** A collection that starts reorder mode for one of its items, by key. */ +export interface ReorderStarter { + /** Starts reorder mode for the item with `key`; returns whether it did. */ + startByKey(key: Key): boolean; +} + /** The machinery a reorderable object carries. */ export interface ListReorderEngine { /** @@ -230,6 +236,14 @@ export interface ListReorderEngine { * one mounted last if several. */ start(options: ListReorderOptions, key: Key): void; + /** + * Lets `start` reach a collection that runs its own reorder mode, mounted + * with the object with `options`. Returns the removal. + */ + mountStarter( + options: ListReorderOptions, + starter: ReorderStarter, + ): () => void; } /** What a reorderable object holds (reorderable/createReorderable.ts). */ diff --git a/packages/core/src/List/listReorderEngine.tsx b/packages/core/src/List/listReorderEngine.tsx index c2db89e722169..35e60a70caef3 100644 --- a/packages/core/src/List/listReorderEngine.tsx +++ b/packages/core/src/List/listReorderEngine.tsx @@ -7,9 +7,11 @@ * @input A List's element and its reorderable object's options, through * List/listReorderContext.ts. Also the reorder model (List/reorderModel.ts), * the touch layer (List/ListReorderTouch.ts) and the row moves of - * utils/rowMotion.ts. Also the edge autoscroll, the touch presentation, - * the shared announcer, and the anchored hint that Core's keyboard hints - * share (hooks/anchoredHint.tsx) + * utils/rowMotion.ts. Also the reorder parts it shares with Lab + * collections: autoscroll, scroll watch, strings, pointer input and mode + * hint (List/reorderAutoscroll.ts, List/reorderScrollWatch.ts, + * List/reorderMessages.ts, List/reorderPointer.ts, List/ReorderModeHint.tsx), + * the touch presentation and the shared announcer * @output `listReorderEngine`, the machinery a reorderable object carries: * the reorder session of a List, its Host and its handle. A drag from a * handle leaves the rows in place. The row dims where it is, and a preview @@ -67,37 +69,24 @@ */ import { - useRef, useSyncExternalStore, type Key, type KeyboardEvent, type ReactNode, } from 'react'; -import * as stylex from '@stylexjs/stylex'; import type {StyleXStyles} from '@stylexjs/stylex'; -import {useCommittedRef} from '../hooks/useCommittedRef'; import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; import { useAnnounce, type AnnounceFn, type AnnouncePoliteness, } from '../hooks/useAnnounce'; -import type {TranslatorFn} from '../i18n/useTranslator'; import { registerEnglishFallback, useComponentTranslator, } from '../i18n/useComponentTranslator'; import english from '../i18n/generated-english/List/listReorderEngine.generated'; -import {useLayer} from '../Layer/useLayer'; -import {useLayerDismissal} from '../Layer/useLayerDismissal'; -import {Kbd} from '../Kbd/Kbd'; -import {anchoredHintStyles, renderAnchoredHint} from '../hooks/anchoredHint'; -import {spacingVars} from '../theme/tokens.stylex'; -import {focusOutlineProps} from '../utils/focusOutline.stylex'; -import type {LongPressGestureRecognizer} from '../gestures/LongPressGestureRecognizer'; -import {VelocityTracker} from '../gestures/VelocityTracker'; -import {inertClone, paintedBackground} from '../motion/inertClone'; -import {reorder} from '../motion/uikit/reorder'; +import {paintedBackground, previewCopyOf} from '../motion/inertClone'; import {reducedMotionCrossFade} from '../motion/uikit/timing'; import { animatorFor, @@ -106,13 +95,16 @@ import { motionOf, releaseMotion, } from '../utils/rowMotion'; -import {edgeAutoscroll, type EdgeAutoscroll} from '../utils/edgeAutoscroll'; -import {msSinceInput} from '../utils/inputAge'; -import {subscribeInput} from '../utils/inputStream'; +import type {EdgeAutoscroll} from '../utils/edgeAutoscroll'; +import {reorderAutoscroll} from './reorderAutoscroll'; +import { + watchReorderScroll, + type ReorderScrollWatch, +} from './reorderScrollWatch'; +import {ReorderModeHint} from './ReorderModeHint'; +import {reorderMessagesFrom, type ReorderMessages} from './reorderMessages'; import {nearestScroller} from '../utils/scrollingAncestor'; import {useTouchPresentation} from '../utils/touchPresentation'; -import {useTouchHitArea} from '../utils/touchHitArea'; -import {touchHitAreaStyles} from '../internal/touchHitArea.stylex'; import {createDevWarnings, devWarn} from '../utils/devWarning'; import {observeMutations} from '../utils/sharedMutationObserver'; import {isLeaving, markLeaving} from '../privateAttributes/leaving.stylex'; @@ -150,13 +142,15 @@ import { reorderRowLayout, reorderRowStyle, } from './ListReorderHandle'; -import {attachTouchHold, touchMotion} from './ListReorderTouch'; +import {touchMotion} from './ListReorderTouch'; +import {attachReorderHold, attachReorderMouse} from './reorderPointer'; import type { ListReorderContextValue, ListReorderEngine, ListReorderOptions, ListReorderSession, ReorderRows, + ReorderStarter, } from './listReorderContext'; import { autoscrollStep, @@ -173,7 +167,7 @@ registerEnglishFallback(english); * button itself. The date wheel's mouse drag uses the same value * (DateInput/usePointerDragScroll.ts `DRAG_SLOP`); a test keeps them equal. */ -export const MOUSE_DRAG_SLOP = 4; +export {MOUSE_DRAG_SLOP} from './reorderPointer'; /** Moves under half a pixel are layout noise. */ const MIN_MOVE_PX = 0.5; @@ -189,15 +183,12 @@ const START_FOCUS_CLAIM_MS = 150; * The sessions each reorderable object (by its options) is mounted on, in * the order they mounted: `start` uses the last. */ -const sessionsByOptions = new WeakMap< - ListReorderOptions, - ListReorderController[] ->(); +const sessionsByOptions = new WeakMap(); /** Records `controller` as mounted with `options`; returns the removal. */ function mountSession( options: ListReorderOptions, - controller: ListReorderController, + controller: ReorderStarter, ): () => void { const sessions = sessionsByOptions.get(options) ?? []; sessionsByOptions.set(options, [ @@ -339,23 +330,6 @@ function overlay(element: HTMLElement): HTMLElement { return element; } -/** - * A copy of `row` that takes no part in the page (`inertClone`). It has no - * ids, names or form, so a copied checked radio leaves the row's checked. A - * row holding a canvas that reads back empty is not copied: its bare box is. - */ -function previewCopyOf(row: HTMLElement): HTMLElement { - const copy = inertClone(row); - if (copy != null) { - return copy; - } - const box = row.cloneNode(false) as HTMLElement; - for (const name of ['id', 'data-testid', 'name', 'for', 'autofocus']) { - box.removeAttribute(name); - } - return box; -} - /** * Makes `preview`, a copy of the dragged row, its preview at its place, with * the same reduced emphasis as the row and no elevation. It only writes. @@ -558,19 +532,8 @@ interface DragSession { readonly background: string | null; /** The preview's offset from its row's place, as last written. */ previewOffset: number; - /** - * A scroll the engine did not cause moved the scroller since its offset - * was last read (`syncScroll`). - */ - scrollStale: boolean; - /** The engine's own scroll still waits for its scroll event. */ - ownScroll: boolean; - /** The engine wrote since the last frame that renders its writes. */ - wrote: boolean; - /** A fold waits for a later frame (`foldInFrame`). */ - foldArmed: boolean; - /** Stops watching the scroller's scroll events. */ - stopScrollWatch: () => void; + /** The watch of the scroller for a scroll the engine did not cause. */ + readonly scrollWatch: ReorderScrollWatch; } /** The inline values a drag overrides until its rows rest. */ @@ -633,62 +596,6 @@ interface PendingAnnouncement { readonly politeness: AnnouncePoliteness | undefined; } -/** The strings the controller announces, from the translator. */ -interface ReorderMessages { - /** - * A row's place in reorder mode: its name, place and count. Also the names - * of the rows before and after it, null at the top or the end. - */ - place: ( - label: string, - position: number, - total: number, - previous: string | null, - next: string | null, - ) => string; - /** A reorder mode move refused by the row that stays where it would go. */ - refused: (label: string) => string; - /** A row's name when it shows no text: its place. */ - itemAt: (position: number) => string; - /** Reorder mode ended: the row's name and its place. */ - modeDone: (label: string, position: number, total: number) => string; - pickedUp: (position: number, total: number) => string; - dropped: (position: number, total: number) => string; - cancelled: (position: number, total: number) => string; -} - -function messagesFrom(t: TranslatorFn): ReorderMessages { - return { - place: (label, position, total, previous, next) => - previous == null - ? t('@astryx.list.reorderPlaceTop', {label, position, total, next}) - : next == null - ? t('@astryx.list.reorderPlaceEnd', { - label, - position, - total, - previous, - }) - : t('@astryx.list.reorderPlace', { - label, - position, - total, - previous, - next, - }), - refused: label => t('@astryx.list.reorderRefused', {label}), - itemAt: position => t('@astryx.list.reorderItemAt', {position}), - modeDone: (label, position, total) => - t('@astryx.list.reorderModeDone', {label, position, total}), - pickedUp: (position, total) => - t('@astryx.list.reorderPickedUp', {position, total}), - dropped: (position, total) => - t('@astryx.list.reorderDropped', {position, total}), - cancelled: (position, total) => - t('@astryx.list.reorderCancelled', {position, total}), - }; -} - /** What a gesture listener hands the controller. */ export interface ReorderGestureEvent { readonly state: 'began' | 'changed' | 'ended' | 'cancelled'; @@ -703,23 +610,6 @@ export interface ReorderGestureEvent { readonly time?: number; } -/** A long press's state as a reorder gesture's; null while it waits. */ -function gestureStateOf( - recognizer: LongPressGestureRecognizer, -): ReorderGestureEvent['state'] | null { - switch (recognizer.state) { - case 'began': - case 'changed': - case 'ended': - case 'cancelled': - return recognizer.state; - case 'failed': - return 'cancelled'; - case 'possible': - return null; - } -} - /** * The reorder session of one List. One instance per List; its listeners are * on the list, and every handle in it reports its keys here. @@ -831,19 +721,6 @@ export class ListReorderController implements ListReorderSession { return this.presentation === 'uikit'; } - /** - * Whether a pointer drags from a handle without a hold: a mouse, or a pen - * where the primary pointer is fine. A finger, and a pen where the primary - * pointer is coarse, keep the hold. The touch presentation is the coarse - * primary pointer. - */ - private dragsAtOnce(pointerType: string): boolean { - return ( - pointerType === 'mouse' || - (pointerType === 'pen' && this.presentation !== 'uikit') - ); - } - /** * Records a row's handle and the row's item key (ListItem `itemKey`); * returns the removal. A row moves only with a handle recorded here. Its @@ -1261,86 +1138,32 @@ export class ListReorderController implements ListReorderSession { if (list == null) { return () => {}; } - const onPointerDown = (event: PointerEvent) => { - if (!this.dragsAtOnce(event.pointerType) || event.button !== 0) { - return; - } - const handle = this.handleOf(event.target); - if (handle == null) { - return; - } - this.endMouse?.(); - this.draggedHandle = null; - const {pointerId, clientX: x, clientY: y} = event; - let isDragging = false; - // The pointer's velocity, for the glide a release hands it to. - const velocity = new VelocityTracker(); - velocity.add(x, y, event.timeStamp); - const end = () => { - list.removeEventListener('pointermove', onMove); - list.removeEventListener('pointerup', onUp); - list.removeEventListener('pointercancel', onCancel); - list.removeEventListener('lostpointercapture', onCancel); - if (handle.hasPointerCapture?.(pointerId)) { - handle.releasePointerCapture(pointerId); - } - if (this.endMouse === end) { - this.endMouse = null; - } - }; - const onMove = (move: PointerEvent) => { - if (move.pointerId !== pointerId) { - return; - } - velocity.add(move.clientX, move.clientY, move.timeStamp); - if (!isDragging) { - if ( - Math.hypot(move.clientX - x, move.clientY - y) < MOUSE_DRAG_SLOP - ) { - return; + // The touch presentation is the coarse primary pointer. + const mouse = attachReorderMouse( + list, + () => this.presentation === 'uikit', + { + handleOf: target => this.handleOf(target), + onPress: () => { + this.draggedHandle = null; + }, + onGesture: (handle, event) => { + if (event.state === 'began') { + this.draggedHandle = handle; } - isDragging = true; - this.draggedHandle = handle; - this.gesture(this.rowOf(handle), {state: 'began', y}); - } - this.gesture(null, {state: 'changed', y: move.clientY}); - }; - const onUp = (up: PointerEvent) => { - if (up.pointerId !== pointerId) { - return; - } - end(); - if (isDragging) { - velocity.add(up.clientX, up.clientY, up.timeStamp); - this.gesture(null, { - state: 'ended', - y: up.clientY, - velocity: velocity.velocity(up.timeStamp).y, - // The release on the motion clock, from the pointer's own stamp. - time: motionNow() - msSinceInput(up.timeStamp, up), + this.gesture(event.state === 'began' ? this.rowOf(handle) : null, { + state: event.state, + y: event.y, + velocity: event.velocity?.y, + time: event.time, }); - } - }; - const onCancel = (cancel: PointerEvent) => { - if (cancel.pointerId !== pointerId) { - return; - } - end(); - if (isDragging) { - this.gesture(null, {state: 'cancelled', y: cancel.clientY}); - } - }; - list.addEventListener('pointermove', onMove); - list.addEventListener('pointerup', onUp); - list.addEventListener('pointercancel', onCancel); - list.addEventListener('lostpointercapture', onCancel); - handle.setPointerCapture?.(pointerId); - this.endMouse = end; - }; - list.addEventListener('pointerdown', onPointerDown); + }, + }, + ); + this.endMouse = () => mouse.endPress(); return () => { - this.endMouse?.(); - list.removeEventListener('pointerdown', onPointerDown); + mouse.detach(); + this.endMouse = null; }; } @@ -1355,47 +1178,20 @@ export class ListReorderController implements ListReorderSession { if (list == null) { return () => {}; } - let held: HTMLElement | null = null; - // The finger's velocity, for the glide a release hands it to. - const velocity = new VelocityTracker(); - return attachTouchHold( - list, - isCoarsePointer ? ['touch', 'pen'] : ['touch'], - target => { - const handle = this.handleOf(target); - if (handle != null) { - held = handle; - } - return handle != null; - }, - recognizer => { - const state = gestureStateOf(recognizer); - if (state === 'began') { - this.draggedHandle = held; - velocity.reset(); - } - // One sample per event, at the event's time. - const touch = recognizer.trackedTouches[0]; - if (touch != null && state != null && state !== 'cancelled') { - velocity.add(touch.x, touch.y, touch.time); - } - if (state != null) { - this.gesture(state === 'began' ? this.rowOf(held) : null, { - state, - y: recognizer.location().y, - velocity: - state === 'ended' && touch != null - ? velocity.velocity(touch.time).y - : undefined, - // A tracked touch keeps the time of its last move, which can be - // long before the lift. The recognizer ends in the lift's own - // task, so now is the lift. - time: state === 'ended' ? motionNow() : undefined, - }); + return attachReorderHold(list, isCoarsePointer, { + handleOf: target => this.handleOf(target), + onGesture: (handle, event) => { + if (event.state === 'began') { + this.draggedHandle = handle; } + this.gesture(event.state === 'began' ? this.rowOf(handle) : null, { + state: event.state, + y: event.y, + velocity: event.velocity?.y, + time: event.time, + }); }, - target => this.handleOf(target) != null, - ); + }); } // --- Pointer drags --------------------------------------------------- @@ -1537,13 +1333,7 @@ export class ListReorderController implements ListReorderSession { scroller, scrolled: 0, lastY: y, - edge: edgeAutoscroll({ - intervalMs: reorder.autoscroll.tickMs, - // UIKit's run-loop timer: a late fire catches up one tick, and a - // longer stall is skipped. Engines fire a 20 ms interval every 20 to - // 25 ms. - catchUp: true, - now: motionNow, + edge: reorderAutoscroll({ step: () => this.edgeStep(session), apply: delta => this.scrollBy(session, delta), }), @@ -1552,14 +1342,14 @@ export class ListReorderController implements ListReorderSession { preview, background, previewOffset: 0, - scrollStale: false, - ownScroll: false, - wrote: true, - foldArmed: false, - stopScrollWatch: () => {}, + // A wheel or a key scroll folds into the drag in a later frame. + scrollWatch: watchReorderScroll(scroller.element, () => { + if (this.session === session) { + this.track(session.lastY); + } + }), }; this.session = session; - session.stopScrollWatch = this.watchScroll(session); // Rows still sliding from an earlier drag go to their places. this.moveTo(dragged); this.track(y); @@ -1590,11 +1380,11 @@ export class ListReorderController implements ListReorderSession { if (session == null) { return; } - if (session.scrollStale) { + if (session.scrollWatch.takeStale()) { this.syncScroll(session); } session.lastY = y; - session.wrote = true; + session.scrollWatch.noteWrite(); const {geometry, dragged} = session; const row = geometry.rows[dragged]; const origin = session.origin - session.scrolled; @@ -1666,7 +1456,7 @@ export class ListReorderController implements ListReorderSession { if (this.session !== session) { return 0; } - if (session.scrollStale) { + if (session.scrollWatch.takeStale()) { this.syncScroll(session); } const {geometry, dragged} = session; @@ -1691,94 +1481,17 @@ export class ListReorderController implements ListReorderSession { scroller.element.scrollTop = next; session.scrolled += moved; scroller.position = next; - // Its scroll event comes in the next frame, before that frame's - // callbacks. A write that moves nothing sends none. - session.ownScroll = true; - requestAnimationFrame(() => { - session.ownScroll = false; - }); + session.scrollWatch.noteOwnScroll(); this.track(session.lastY); return moved; } - /** - * Watches the scroller for a scroll the engine did not cause, such as a - * wheel or a key. A later frame folds it in (`armFold`). - */ - private watchScroll(session: DragSession): () => void { - const doc = session.list.ownerDocument; - const view = doc.defaultView; - if (view == null) { - return () => {}; - } - const {element} = session.scroller; - const page = doc.scrollingElement ?? doc.documentElement; - // The page's own scroll is reported on the document. - const own = element === page ? doc : element; - // A scroll around the list's scroller can move it on screen too, as when - // a wheel at the end of a box scrolls the page. - const isAround = (target: EventTarget) => - own !== doc && - (target === doc || - (target instanceof Element && - target !== element && - target.contains(element))); - return subscribeInput(view, 'scroll', event => { - const {target} = event; - if ( - target == null || - this.session !== session || - (target !== own && !isAround(target)) - ) { - return; - } - if (target === own && session.ownScroll) { - session.ownScroll = false; - return; - } - session.scrollStale = true; - this.armFold(session); - }); - } - - /** - * Folds a scroll into the drag in the next frame without a move or a tick. - * The writes made so far render first, so its one read forces no layout. - */ - private armFold(session: DragSession): void { - if (session.foldArmed) { - return; - } - session.foldArmed = true; - requestAnimationFrame(() => { - // Everything written so far renders after this frame's callbacks. - session.wrote = false; - requestAnimationFrame(() => this.foldInFrame(session)); - }); - } - - private foldInFrame(session: DragSession): void { - session.foldArmed = false; - if (this.session !== session || !session.scrollStale) { - return; - } - if (session.wrote) { - // The engine wrote in this frame, so the read waits another frame. - session.wrote = false; - session.foldArmed = true; - requestAnimationFrame(() => this.foldInFrame(session)); - return; - } - this.track(session.lastY); - } - /** * Reads the scroller's offset once and adds what a scroll the engine did * not cause moved to the drag. It runs before any write in its frame or * task. */ private syncScroll(session: DragSession): void { - session.scrollStale = false; const {scroller} = session; const {element} = scroller; const position = element.scrollTop; @@ -1812,12 +1525,13 @@ export class ListReorderController implements ListReorderSession { if (session == null) { return; } - if (session.scrollStale) { + if (session.scrollWatch.takeStale()) { + this.syncScroll(session); this.track(session.lastY); } this.session = null; this.stopAutoscroll(session); - session.stopScrollWatch(); + session.scrollWatch.stop(); const {geometry, dragged, position, rows, list} = session; const element = rows[dragged]; // Where the preview is now: on the commit the dragged row glides from @@ -1878,7 +1592,7 @@ export class ListReorderController implements ListReorderSession { } this.session = null; this.stopAutoscroll(session); - session.stopScrollWatch(); + session.scrollWatch.stop(); // Nothing moved: the preview and the line go and the row is itself again // at once. this.clearOverlays(session); @@ -2517,7 +2231,7 @@ function ListReorderHost({reorder}: {reorder: ListReorderContextValue}) { controller.configure({ options, announce, - messages: messagesFrom(t), + messages: reorderMessagesFrom(t), presentation: isTouch ? 'uikit' : 'theme', }); }); @@ -2553,144 +2267,25 @@ function ListReorderHost({reorder}: {reorder: ListReorderContextValue}) { ); } -const hintStyles = stylex.create({ - // A glyph or Done: the hint's text, with nothing of a button's own, the - // same size under every pointer. A finger's 44 px target is the shared - // touch hit layer, which stops short of a neighbouring target. - button: { - position: 'relative', - display: 'inline-flex', - alignItems: 'center', - justifyContent: 'center', - margin: 0, - padding: 0, - borderWidth: 0, - borderRadius: 4, - backgroundColor: 'transparent', - color: 'inherit', - fontFamily: 'inherit', - fontSize: 'inherit', - lineHeight: 'inherit', - cursor: { - default: 'pointer', - ':is(:disabled,[aria-disabled="true"])': 'default', - }, - }, - done: { - paddingInline: spacingVars['--spacing-1'], - }, -}); - -/** - * One of the hint's buttons: it never takes the focus from the handle (a - * press does not move it), and does what its key does. - */ -function HintButton({ - label, - onPress, - isText = false, - children, -}: { - label?: string; - onPress: () => void; - isText?: boolean; - children: ReactNode; -}) { - // A finger's target: the shared touch hit area grows the button's hit - // layer where the primary pointer is coarse. - const hitAreaRef = useTouchHitArea(true); - return ( - - ); -} - -/** - * Reorder mode's hint. It is anchored below the start of the handle whose - * row is in the mode, in Core's keyboard hint's layer and theme roles. It - * shows the moves for the list's axis and Done until the mode ends. Each - * move is a button that does what its key does, with the same announcement, - * and the focus stays on the handle. Done ends the mode as Escape does. So - * a pointer or a finger can reorder by tapping the handle, the moves, then - * Done. - */ +/** Reorder mode's hint for the list's rows, along the block axis. */ function ListReorderModeHint({ controller, }: { controller: ListReorderController; }): ReactNode { - const t = useComponentTranslator(); const target = useSyncExternalStore( controller.subscribeMode, () => controller.modeTarget, () => null, ); - const layer = useLayer({mode: 'context'}); - // The latest layer handle, for the effect below, which re-runs only when - // the mode's row changes. - const layerRef = useCommittedRef(layer); - const hintRef = useRef(null); - // External system: the hint's popover in the top layer (useLayer), - // anchored to the handle of the row in reorder mode. Shown while that row - // is in the mode; hidden and unanchored when the mode ends or moves on. - useIsomorphicLayoutEffect(() => { - if (target == null) { - return undefined; - } - const shown = layerRef.current; - shown.ref(target); - shown.show(); - return () => { - shown.hide(); - shown.ref(null); - }; - }, [target]); - // The shared dismissal stack. While the hint is up, an Escape that reaches - // the stack, with the focus in the hint, ends reorder mode. A layer below - // it, such as a Dialog, stays open. The handle claims its own Escape first. - useLayerDismissal({ - isActive: target != null, - onDismiss: () => controller.endMode(), - getContainer: () => hintRef.current, - }); - return renderAnchoredHint( - layer, - target == null ? null : ( - { - hintRef.current = element; - controller.setHintElement(element); - }} - {...stylex.props(anchoredHintStyles.keys)}> - controller.step(target, -1)}> - - - controller.step(target, 1)}> - - - controller.endMode()}> - {t('@astryx.list.reorderDone')} - - - ), - {isInteractive: true}, + return ( + controller.step(target, move === 'up' ? -1 : 1)} + onDone={() => controller.endMode()} + onHintElement={element => controller.setHintElement(element)} + /> ); } @@ -2698,6 +2293,8 @@ function ListReorderModeHint({ export const listReorderEngine: ListReorderEngine = { createSession: (getList, hintId, rows) => new ListReorderController(getList, hintId, rows), + mountStarter: (options, starter) => + mountSession(options.startedBy ?? options, starter), start: (options, key) => { const sessions = sessionsByOptions.get(options) ?? []; if (sessions.length > 1) { diff --git a/packages/core/src/List/reorderAutoscroll.ts b/packages/core/src/List/reorderAutoscroll.ts new file mode 100644 index 0000000000000..22b2daa1ca1ab --- /dev/null +++ b/packages/core/src/List/reorderAutoscroll.ts @@ -0,0 +1,41 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file reorderAutoscroll.ts + * @input How far to scroll on the next tick, and a way to scroll that far + * @output `reorderAutoscroll`: a reorder drag's edge autoscroll, on UIKit's + * reorder tick (motion/uikit/reorder.ts) and the shared edge timer + * (utils/edgeAutoscroll.ts) + * @position Read by List's reorder session (List/listReorderEngine.tsx), and + * by Lab collections through `@astryxdesign/core/internal/reorder-mode`, + * with + * `autoscrollStep` (List/reorderModel.ts) for each tick's distance + */ + +import {motionNow} from '../utils/rowMotion'; +import {reorder} from '../motion/uikit/reorder'; +import {edgeAutoscroll, type EdgeAutoscroll} from '../utils/edgeAutoscroll'; + +/** What `reorderAutoscroll` takes. */ +export interface ReorderAutoscrollOptions { + /** The signed distance to scroll on the next tick; 0 stops the timer. */ + readonly step: () => number; + /** Scrolls by `delta` and returns how far the content actually moved. */ + readonly apply: (delta: number) => number; +} + +/** A reorder drag's edge autoscroll; idle until `update` finds a step. */ +export function reorderAutoscroll({ + step, + apply, +}: ReorderAutoscrollOptions): EdgeAutoscroll { + return edgeAutoscroll({ + intervalMs: reorder.autoscroll.tickMs, + // UIKit's run-loop timer: a late fire catches up one tick, and a longer + // stall is skipped. Engines fire a 20 ms interval every 20 to 25 ms. + catchUp: true, + now: motionNow, + step, + apply, + }); +} diff --git a/packages/core/src/List/reorderMessages.ts b/packages/core/src/List/reorderMessages.ts new file mode 100644 index 0000000000000..73d6eca0e0455 --- /dev/null +++ b/packages/core/src/List/reorderMessages.ts @@ -0,0 +1,73 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file reorderMessages.ts + * @input A translator + * @output `reorderMessagesFrom`: the strings a reorder session announces, + * from the catalog's `@astryx.list.reorder*` messages + * @position Read by List's reorder session (List/listReorderEngine.tsx), and + * by Lab collections through `@astryxdesign/core/internal/reorder-mode`, so a + * collection that runs its own reorder mode announces as a List does + */ + +import english from '../i18n/generated-english/List/reorderMessages.generated'; +import {registerEnglishFallback} from '../i18n/useComponentTranslator'; +import type {TranslatorFn} from '../i18n/useTranslator'; + +registerEnglishFallback(english); + +/** The strings a reorder session announces, from the translator. */ +export interface ReorderMessages { + /** + * An item's place in reorder mode: its name, place and count. Also the + * names of the items before and after it, null at the top or the end. + */ + place: ( + label: string, + position: number, + total: number, + previous: string | null, + next: string | null, + ) => string; + /** A reorder mode move refused by the item that stays where it would go. */ + refused: (label: string) => string; + /** An item's name when it shows no text: its place. */ + itemAt: (position: number) => string; + /** Reorder mode ended: the item's name and its place. */ + modeDone: (label: string, position: number, total: number) => string; + pickedUp: (position: number, total: number) => string; + dropped: (position: number, total: number) => string; + cancelled: (position: number, total: number) => string; +} + +export function reorderMessagesFrom(t: TranslatorFn): ReorderMessages { + return { + place: (label, position, total, previous, next) => + previous == null + ? t('@astryx.list.reorderPlaceTop', {label, position, total, next}) + : next == null + ? t('@astryx.list.reorderPlaceEnd', { + label, + position, + total, + previous, + }) + : t('@astryx.list.reorderPlace', { + label, + position, + total, + previous, + next, + }), + refused: label => t('@astryx.list.reorderRefused', {label}), + itemAt: position => t('@astryx.list.reorderItemAt', {position}), + modeDone: (label, position, total) => + t('@astryx.list.reorderModeDone', {label, position, total}), + pickedUp: (position, total) => + t('@astryx.list.reorderPickedUp', {position, total}), + dropped: (position, total) => + t('@astryx.list.reorderDropped', {position, total}), + cancelled: (position, total) => + t('@astryx.list.reorderCancelled', {position, total}), + }; +} diff --git a/packages/core/src/List/reorderPointer.ts b/packages/core/src/List/reorderPointer.ts new file mode 100644 index 0000000000000..ad12849d21e5d --- /dev/null +++ b/packages/core/src/List/reorderPointer.ts @@ -0,0 +1,239 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file reorderPointer.ts + * @input A collection's container, how to find a handle from an event's + * target, and the touch layer's hold (List/ListReorderTouch.ts) + * @output `attachReorderMouse` and `attachReorderHold`: a reorder's pointer + * input. A mouse, or a pen where the primary pointer is fine, drags from a + * handle at once; a finger, and a pen where it is coarse, after a hold. + * Each reports a drag's began, changed, ended and cancelled positions + * @position Read by List's reorder session (List/listReorderEngine.tsx), and + * by Lab collections through `@astryxdesign/core/internal/reorder-mode` + */ + +import {VelocityTracker} from '../gestures/VelocityTracker'; +import {msSinceInput} from '../utils/inputAge'; +import {motionNow} from '../utils/rowMotion'; +import {attachTouchHold} from './ListReorderTouch'; + +/** How far, in px, a mouse moves from its press before it drags. */ +export const MOUSE_DRAG_SLOP = 4; + +/** A drag's position from a handle, in the viewport. */ +export interface ReorderPointerEvent { + readonly state: 'began' | 'changed' | 'ended' | 'cancelled'; + readonly x: number; + readonly y: number; + /** At a release, the pointer's velocity in px/s. */ + readonly velocity?: {readonly x: number; readonly y: number}; + /** At a release, its time on the motion clock. */ + readonly time?: number; +} + +/** What a reorder's pointer input reads from its collection. */ +export interface ReorderPointerOptions { + /** The reorder handle an event's target is in, or null. */ + readonly handleOf: (target: EventTarget | null) => HTMLElement | null; + /** A drag from `handle`: its began, changed, ended or cancelled position. */ + readonly onGesture: (handle: HTMLElement, event: ReorderPointerEvent) => void; +} + +/** A collection's mouse input, and the press it holds. */ +export interface ReorderMouse { + /** Ends the press in progress, if any, without a report. */ + endPress(): void; + detach(): void; +} + +/** + * Whether a pointer drags from a handle without a hold: a mouse, or a pen + * where the primary pointer is fine. A finger, and a pen where the primary + * pointer is coarse, keep the hold (`attachReorderHold`). + */ +function dragsAtOnce(pointerType: string, isCoarsePointer: boolean): boolean { + return pointerType === 'mouse' || (pointerType === 'pen' && !isCoarsePointer); +} + +/** + * Lets a mouse, or a pen where the primary pointer is fine, drag from a + * handle without a hold. `isCoarsePointer` is read at each press. There is + * one pointerdown listener on `container`. While a press is down, its move + * and lift listeners sit there too. The press is the handle's until it + * lifts, through pointer capture. It drags once it has moved + * MOUSE_DRAG_SLOP from where it pressed. `onPress` runs at each press on a + * handle, before it can drag. + */ +export function attachReorderMouse( + container: HTMLElement, + isCoarsePointer: () => boolean, + options: ReorderPointerOptions & {readonly onPress?: () => void}, +): ReorderMouse { + let endCurrent: (() => void) | null = null; + const onPointerDown = (event: PointerEvent) => { + if ( + !dragsAtOnce(event.pointerType, isCoarsePointer()) || + event.button !== 0 + ) { + return; + } + const handle = options.handleOf(event.target); + if (handle == null) { + return; + } + endCurrent?.(); + options.onPress?.(); + const {pointerId, clientX: x, clientY: y} = event; + let isDragging = false; + // The pointer's velocity, for the glide a release hands it to. + const velocity = new VelocityTracker(); + velocity.add(x, y, event.timeStamp); + const end = () => { + container.removeEventListener('pointermove', onMove); + container.removeEventListener('pointerup', onUp); + container.removeEventListener('pointercancel', onCancel); + container.removeEventListener('lostpointercapture', onCancel); + if (handle.hasPointerCapture?.(pointerId)) { + handle.releasePointerCapture(pointerId); + } + if (endCurrent === end) { + endCurrent = null; + } + }; + const onMove = (move: PointerEvent) => { + if (move.pointerId !== pointerId) { + return; + } + velocity.add(move.clientX, move.clientY, move.timeStamp); + if (!isDragging) { + if (Math.hypot(move.clientX - x, move.clientY - y) < MOUSE_DRAG_SLOP) { + return; + } + isDragging = true; + options.onGesture(handle, {state: 'began', x, y}); + } + options.onGesture(handle, { + state: 'changed', + x: move.clientX, + y: move.clientY, + }); + }; + const onUp = (up: PointerEvent) => { + if (up.pointerId !== pointerId) { + return; + } + end(); + if (isDragging) { + velocity.add(up.clientX, up.clientY, up.timeStamp); + options.onGesture(handle, { + state: 'ended', + x: up.clientX, + y: up.clientY, + velocity: velocity.velocity(up.timeStamp), + // The release on the motion clock, from the pointer's own stamp. + time: motionNow() - msSinceInput(up.timeStamp, up), + }); + } + }; + const onCancel = (cancel: PointerEvent) => { + if (cancel.pointerId !== pointerId) { + return; + } + end(); + if (isDragging) { + options.onGesture(handle, { + state: 'cancelled', + x: cancel.clientX, + y: cancel.clientY, + }); + } + }; + container.addEventListener('pointermove', onMove); + container.addEventListener('pointerup', onUp); + container.addEventListener('pointercancel', onCancel); + container.addEventListener('lostpointercapture', onCancel); + handle.setPointerCapture?.(pointerId); + endCurrent = end; + }; + container.addEventListener('pointerdown', onPointerDown); + return { + endPress: () => endCurrent?.(), + detach: () => { + endCurrent?.(); + container.removeEventListener('pointerdown', onPointerDown); + }, + }; +} + +/** A long press's state as a reorder gesture's; null while it waits. */ +function stateOf(state: string): ReorderPointerEvent['state'] | null { + switch (state) { + case 'began': + case 'changed': + case 'ended': + case 'cancelled': + return state; + case 'failed': + return 'cancelled'; + default: + return null; + } +} + +/** + * Lets a finger held still on a handle drag from it, under every primary + * pointer, and a pen where the primary pointer is coarse. One recognizer on + * `container` receives only the touches that begin on its handles. Returns + * the detach. + */ +export function attachReorderHold( + container: HTMLElement, + isCoarsePointer: boolean, + options: ReorderPointerOptions, +): () => void { + let held: HTMLElement | null = null; + // The finger's velocity, for the glide a release hands it to. + const velocity = new VelocityTracker(); + return attachTouchHold( + container, + isCoarsePointer ? ['touch', 'pen'] : ['touch'], + target => { + const handle = options.handleOf(target as EventTarget | null); + if (handle != null) { + held = handle; + } + return handle != null; + }, + recognizer => { + const state = stateOf(recognizer.state); + if (state === 'began') { + velocity.reset(); + } + // One sample per event, at the event's time. + const touch = recognizer.trackedTouches[0]; + if (touch != null && state != null && state !== 'cancelled') { + velocity.add(touch.x, touch.y, touch.time); + } + if (state == null || held == null) { + return; + } + const {x, y} = recognizer.location(); + options.onGesture(held, { + state, + x, + y, + velocity: + state === 'ended' && touch != null + ? velocity.velocity(touch.time) + : undefined, + // A tracked touch keeps the time of its last move, which can be long + // before the lift. The recognizer ends in the lift's own task, so + // now is the lift. + time: state === 'ended' ? motionNow() : undefined, + }); + }, + target => options.handleOf(target as EventTarget | null) != null, + ); +} diff --git a/packages/core/src/List/reorderScrollWatch.ts b/packages/core/src/List/reorderScrollWatch.ts new file mode 100644 index 0000000000000..b159f5fbe00f0 --- /dev/null +++ b/packages/core/src/List/reorderScrollWatch.ts @@ -0,0 +1,130 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file reorderScrollWatch.ts + * @input A reorder drag's scroller, and what the drag does when a scroll it + * did not cause needs folding in + * @output `watchReorderScroll`: a drag's watch of its scroller. It tells the + * drag's own scrolls from others, such as a wheel or a key. It folds each + * other scroll into the drag in a later frame, after the drag's writes + * render, so the drag's one read of the offset forces no layout + * @position Read by List's reorder session (List/listReorderEngine.tsx), and + * by Lab collections through `@astryxdesign/core/internal/reorder-mode` + */ + +import {subscribeInput} from '../utils/inputStream'; + +/** A drag's watch of its scroller. */ +export interface ReorderScrollWatch { + /** + * Notes a scroll the drag makes itself: its scroll event is skipped. A + * write that moves nothing sends no event, so the note lasts one frame. + */ + noteOwnScroll(): void; + /** Notes that the drag wrote the page, so a fold waits for a later frame. */ + noteWrite(): void; + /** + * Whether a scroll the drag did not cause moved the scroller since the + * last call. The drag then reads the offset once, before its writes. + */ + takeStale(): boolean; + /** Stops watching. */ + stop(): void; +} + +/** + * Watches `element`, the scroller of a drag, for a scroll the drag did not + * cause, also one around it, as when a wheel at the end of a box scrolls the + * page. `fold` runs in a later frame in which the drag has written nothing, + * unless the drag read the scroll in the meantime. + */ +export function watchReorderScroll( + element: Element, + fold: () => void, +): ReorderScrollWatch { + const doc = element.ownerDocument; + const view = doc.defaultView; + let isStale = false; + let isOwnScroll = false; + // The drag wrote since the last frame that renders its writes. + let hasWritten = true; + let isFoldArmed = false; + let isStopped = false; + const foldInFrame = () => { + isFoldArmed = false; + if (isStopped || !isStale) { + return; + } + if (hasWritten) { + // The drag wrote in this frame, so the read waits another frame. + hasWritten = false; + isFoldArmed = true; + requestAnimationFrame(foldInFrame); + return; + } + fold(); + }; + const armFold = () => { + if (isFoldArmed) { + return; + } + isFoldArmed = true; + requestAnimationFrame(() => { + // Everything written so far renders after this frame's callbacks. + hasWritten = false; + requestAnimationFrame(foldInFrame); + }); + }; + const page = doc.scrollingElement ?? doc.documentElement; + // The page's own scroll is reported on the document. + const own = element === page ? doc : element; + const isAround = (target: EventTarget) => + own !== doc && + (target === doc || + (target instanceof Element && + target !== element && + target.contains(element))); + const unsubscribe = + view == null + ? () => {} + : subscribeInput(view, 'scroll', event => { + const {target} = event; + if ( + target == null || + isStopped || + (target !== own && !isAround(target)) + ) { + return; + } + if (target === own && isOwnScroll) { + isOwnScroll = false; + return; + } + isStale = true; + armFold(); + }); + return { + noteOwnScroll: () => { + // Its scroll event comes in the next frame, before that frame's + // callbacks. + isOwnScroll = true; + requestAnimationFrame(() => { + isOwnScroll = false; + }); + }, + noteWrite: () => { + hasWritten = true; + }, + takeStale: () => { + const wasStale = isStale; + isStale = false; + return wasStale; + }, + stop: () => { + isStopped = true; + unsubscribe(); + }, + }; +} diff --git a/packages/core/src/internal/reorder-mode.ts b/packages/core/src/internal/reorder-mode.ts new file mode 100644 index 0000000000000..e6e2d3f45f539 --- /dev/null +++ b/packages/core/src/internal/reorder-mode.ts @@ -0,0 +1,45 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file reorder-mode.ts + * @input List's reorder parts: its mode hint, strings, pointer input, edge + * autoscroll, scroll watch, drop bounds, preview copy and the text it + * names items by + * @output `@astryxdesign/core/internal/reorder-mode`: those parts, for a Lab + * collection that runs its own reorder mode, such as one along the inline + * axis, so it hints, announces, drags, scrolls, bounds and previews as a + * List does + * @position An internal entry for Core and Lab, outside the public API, + * versioned in lockstep with Core. It loads the parts, not the reorder + * engine. A collection mounts its mode with `mountReorderStarter` from + * internal/reorder.ts. + * + * SYNC: When modified, update scripts/sync-exports.js. + */ + +export {ReorderModeHint} from '../List/ReorderModeHint'; +export type { + ReorderHintMove, + ReorderModeHintProps, +} from '../List/ReorderModeHint'; +export {reorderAutoscroll} from '../List/reorderAutoscroll'; +export type {ReorderAutoscrollOptions} from '../List/reorderAutoscroll'; +export {reorderMessagesFrom} from '../List/reorderMessages'; +export {attachReorderHold, attachReorderMouse} from '../List/reorderPointer'; +export type { + ReorderMouse, + ReorderPointerEvent, + ReorderPointerOptions, +} from '../List/reorderPointer'; +export type {ReorderMessages} from '../List/reorderMessages'; +export {autoscrollStep, movableRange} from '../List/reorderModel'; +export {watchReorderScroll} from '../List/reorderScrollWatch'; +export type {ReorderScrollWatch} from '../List/reorderScrollWatch'; +export type {ReorderRow} from '../List/reorderModel'; +export { + bareCopyOf, + paintedBackground, + previewCopyOf, +} from '../motion/inertClone'; +export {getNodeText} from '../utils/getNodeText'; +export type {EdgeAutoscroll} from '../utils/edgeAutoscroll'; diff --git a/packages/core/src/internal/reorder.ts b/packages/core/src/internal/reorder.ts index 4642ee6765b52..8f389bb0dbc6d 100644 --- a/packages/core/src/internal/reorder.ts +++ b/packages/core/src/internal/reorder.ts @@ -3,26 +3,23 @@ /** * @file reorder.ts * @input A reorderable object made by createReorderable - * @output `reorderableOptions`: the options a reorderable object was made - * with. `adaptReorderable`: an object that runs the owner's engine with - * other options. A Lab collection uses it to adapt the owner's moves, such - * as a staged selector that aims them at its draft. The owner's `start` - * still finds its list. Neither loads the reorder engine: it comes with the - * owner's object. - * It also gives List's reorder session for rows that are not ListItems, - * for Lab's ListInput: `useListReorderScope` and `ListReorderScope`. The - * handle each row ends with is the session's `Handle`: it comes with the - * owner's object, so this entry loads no reorder code. A Lab collection - * tells the handle from its own controls with `isReorderHandle` - * @position `@astryxdesign/core/internal/reorder`: an internal entry reserved - * for Core and Lab. It is undocumented, outside the public API and its - * compatibility promise, and versioned in lockstep with Core. + * @output `reorderableOptions` and `adaptReorderable`, which read or adapt a + * reorderable object's options. `useListReorderScope` and + * `ListReorderScope` run List's reorder session over a Lab collection's + * rows. `mountReorderStarter` lets the object's `start(key)` reach a Lab + * collection that runs its own reorder mode, with the parts in + * internal/reorder-mode.ts. `isReorderHandle` tells the handle from a + * collection's own controls + * @position `@astryxdesign/core/internal/reorder`: an internal entry for Core + * and Lab, outside the public API, versioned in lockstep with Core. It + * loads no reorder code: the engine comes with the owner's object */ import { REORDER_ENGINE, type ListReorderOptions, type ReorderableInternals, + type ReorderStarter, } from '../List/listReorderContext'; import type { Reorderable, @@ -61,9 +58,23 @@ export function adaptReorderable( return adapted as unknown as Reorderable; } +/** + * Lets the object's `start(key)` start reorder mode in a collection that + * runs its own, such as a Lab collection that reorders along the inline + * axis. Returns the removal. + */ +export function mountReorderStarter( + reorderable: Reorderable, + starter: ReorderStarter, +): () => void { + const internals = reorderable as unknown as ReorderableInternals; + return internals[REORDER_ENGINE].mountStarter(internals.options, starter); +} + export {ListReorderScope, useListReorderScope} from '../List/ListReorderScope'; export {isReorderHandle} from '../privateAttributes/listReorder.stylex'; export type { ListReorderContextValue, ListReorderHandleProps, + ReorderStarter, } from '../List/listReorderContext'; diff --git a/packages/core/src/internal/reorderShared.test.tsx b/packages/core/src/internal/reorderShared.test.tsx new file mode 100644 index 0000000000000..cbbc404374a02 --- /dev/null +++ b/packages/core/src/internal/reorderShared.test.tsx @@ -0,0 +1,253 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file reorderShared.test.tsx + * @input The parts of a List's reorder that Core's internal reorder entry + * shares with a collection that runs its own reorder mode + * @output Proof that the mode hint offers the moves of either axis and Done, + * that the strings read as a List's, that the edge autoscroll runs on a + * step and stops, that the scroll watch folds a scroll the drag did not + * cause, that a mouse drags from a handle past the slop, that a preview + * copy falls back to its bare box as a List row's does, and that the + * object's `start(key)` reaches a collection mounted with + * `mountReorderStarter` + * @position Testing for internal/reorder-mode.ts and internal/reorder.ts + */ + +import { + act, + fireEvent, + render, + renderHook, + screen, +} from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import {afterEach, describe, expect, it, vi} from 'vitest'; +import {createReorderable} from '../reorderable/createReorderable'; +import {useTranslator} from '../i18n/useTranslator'; +import {mountReorderStarter} from './reorder'; +import { + attachReorderMouse, + bareCopyOf, + getNodeText, + previewCopyOf, + ReorderModeHint, + reorderAutoscroll, + reorderMessagesFrom, + watchReorderScroll, +} from './reorder-mode'; + +describe("Core's internal reorder entry, for a collection's own reorder mode", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('hints the inline moves and Done, which do what their keys do', async () => { + const user = userEvent.setup(); + const onMove = vi.fn(); + const onDone = vi.fn(); + const target = document.createElement('button'); + document.body.append(target); + const {rerender} = render( + , + ); + // jsdom never opens a popover, so the hint stays hidden there. + await user.click( + screen.getByRole('button', {name: 'Move left', hidden: true}), + ); + await user.click( + screen.getByRole('button', {name: 'Move right', hidden: true}), + ); + await user.click(screen.getByRole('button', {name: 'Done', hidden: true})); + expect(onMove.mock.calls).toEqual([['left'], ['right']]); + expect(onDone).toHaveBeenCalledTimes(1); + rerender( + , + ); + await user.click( + screen.getByRole('button', {name: 'Move down', hidden: true}), + ); + expect(onMove).toHaveBeenLastCalledWith('down'); + rerender( + , + ); + expect( + screen.queryByRole('button', {name: 'Done', hidden: true}), + ).not.toBeInTheDocument(); + target.remove(); + }); + + it("announces with a List's strings, and names items by their text", () => { + const {result} = renderHook(() => reorderMessagesFrom(useTranslator())); + expect(result.current.place('Owner', 3, 5, 'Status', 'Due')).toBe( + 'Owner, position 3 of 5, after Status, before Due', + ); + expect(result.current.refused('Task')).toBe("Can't move past Task"); + expect(result.current.dropped(4, 5)).toBe('Dropped, position 4 of 5'); + // A handle's name reads a header's text as it renders. + expect( + getNodeText( + + Due
date
+
, + ), + ).toBe('Due date'); + }); + + it('scrolls one step a tick while the step is not 0, and stops', () => { + vi.useFakeTimers({toFake: ['setInterval', 'clearInterval', 'performance']}); + try { + let step = 12; + const apply = vi.fn((delta: number) => delta); + const autoscroll = reorderAutoscroll({step: () => step, apply}); + autoscroll.update(); + expect(autoscroll.isRunning).toBe(true); + act(() => { + vi.advanceTimersByTime(100); + }); + expect(apply).toHaveBeenCalledWith(12); + step = 0; + autoscroll.update(); + expect(autoscroll.isRunning).toBe(false); + } finally { + vi.useRealTimers(); + } + }); + + it('drags from a handle with a mouse once it moves past the slop, and reports each place', () => { + const container = document.createElement('div'); + const handle = document.createElement('button'); + const label = document.createElement('span'); + handle.append(label); + container.append(handle); + document.body.append(container); + const onGesture = vi.fn(); + let isCoarse = false; + const mouse = attachReorderMouse(container, () => isCoarse, { + handleOf: target => + target instanceof Node && handle.contains(target) ? handle : null, + onGesture, + }); + const press = {pointerType: 'mouse', pointerId: 1, button: 0}; + fireEvent.pointerDown(label, {...press, clientX: 10, clientY: 20}); + fireEvent.pointerMove(container, {...press, clientX: 12, clientY: 20}); + expect(onGesture).not.toHaveBeenCalled(); + fireEvent.pointerMove(container, {...press, clientX: 40, clientY: 20}); + fireEvent.pointerUp(container, {...press, clientX: 40, clientY: 20}); + expect( + onGesture.mock.calls.map(([, event]) => [event.state, event.x]), + ).toEqual([ + ['began', 10], + ['changed', 40], + ['ended', 40], + ]); + expect(onGesture.mock.calls[0][0]).toBe(handle); + // A finger keeps the hold, so it does not drag at once. + fireEvent.pointerDown(label, {...press, pointerType: 'touch'}); + fireEvent.pointerMove(container, { + ...press, + pointerType: 'touch', + clientX: 90, + }); + expect(onGesture).toHaveBeenCalledTimes(3); + // So does a pen where the primary pointer is coarse. + isCoarse = true; + fireEvent.pointerDown(label, {...press, pointerId: 2, pointerType: 'pen'}); + fireEvent.pointerMove(container, { + ...press, + pointerId: 2, + pointerType: 'pen', + clientX: 90, + }); + expect(onGesture).toHaveBeenCalledTimes(3); + mouse.detach(); + container.remove(); + }); + + it('folds a scroll the drag did not cause into it in a later frame, and skips its own', async () => { + const scroller = document.createElement('div'); + document.body.append(scroller); + const fold = vi.fn(); + const watch = watchReorderScroll(scroller, fold); + const nextFrames = async () => + new Promise(resolve => + requestAnimationFrame(() => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ), + ); + // The drag's own scroll: its event is skipped. + watch.noteOwnScroll(); + fireEvent.scroll(scroller); + await act(nextFrames); + expect(fold).not.toHaveBeenCalled(); + expect(watch.takeStale()).toBe(false); + // Another scroll, such as a wheel's, folds in a later frame. + fireEvent.scroll(scroller); + await act(nextFrames); + expect(fold).toHaveBeenCalledTimes(1); + expect(watch.takeStale()).toBe(true); + expect(watch.takeStale()).toBe(false); + watch.stop(); + fireEvent.scroll(scroller); + await act(nextFrames); + expect(fold).toHaveBeenCalledTimes(1); + scroller.remove(); + }); + + it("copies a preview as a List row's, and gives content whose canvas cannot be read its bare box", () => { + const cell = document.createElement('td'); + cell.id = 'notes'; + cell.className = 'cell'; + cell.innerHTML = 'Notes'; + // Readable pixels: the content is copied, without its id. + vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({ + drawImage: () => {}, + getImageData: () => ({data: new Uint8ClampedArray([0, 0, 0, 255])}), + } as unknown as CanvasRenderingContext2D); + const copy = previewCopyOf(cell); + expect(copy.textContent).toBe('Notes'); + expect(copy.id).toBe(''); + expect(copy.getAttribute('aria-hidden')).toBe('true'); + // A tainted canvas reads back nothing: the bare box, classes kept. + vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({ + drawImage: () => { + throw new Error('The canvas is tainted.'); + }, + } as unknown as CanvasRenderingContext2D); + const box = previewCopyOf(cell); + expect(box.childNodes).toHaveLength(0); + expect(box.className).toBe('cell'); + expect(box.id).toBe(''); + const shell = bareCopyOf(cell); + expect(shell.childNodes).toHaveLength(0); + expect(shell.id).toBe(''); + }); + + it("lets the object's start reach a collection mounted with it, until it leaves", () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const reorderable = createReorderable({onReorder: () => {}}); + const startByKey = vi.fn(() => true); + const unmount = mountReorderStarter(reorderable, {startByKey}); + reorderable.start('owner'); + expect(startByKey).toHaveBeenCalledWith('owner'); + expect(warn).not.toHaveBeenCalled(); + unmount(); + reorderable.start('owner'); + expect(startByKey).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/core/src/motion/animatedLayout.boundary.test.ts b/packages/core/src/motion/animatedLayout.boundary.test.ts index 4df883db29f5e..fc08cb672f0b2 100644 --- a/packages/core/src/motion/animatedLayout.boundary.test.ts +++ b/packages/core/src/motion/animatedLayout.boundary.test.ts @@ -158,6 +158,8 @@ describe('architecture:react-component-runtime INV12 source boundary', () => { .sort(); expect(users).toEqual([ 'List/listReorderEngine.tsx', + // Lab's column reorder builds its preview on it. + 'internal/reorder-mode.ts', 'motion/animatedLayout.ts', 'motion/transientCopy.ts', ]); diff --git a/packages/core/src/motion/inertClone.ts b/packages/core/src/motion/inertClone.ts index ddff717c189ce..30de06e6cf739 100644 --- a/packages/core/src/motion/inertClone.ts +++ b/packages/core/src/motion/inertClone.ts @@ -3,13 +3,18 @@ /** * @file inertClone.ts * @input The DOM - * @output Exports `inertClone`, a deep clone that takes no part in the page, - * and `paintedBackground`, the background an element shows + * @output Exports `inertClone`, a deep clone that takes no part in the page; + * `previewCopyOf`, a drag preview's copy, which falls back to the bare + * box `bareCopyOf` makes; and `paintedBackground`, the background an + * element shows * @position Motion foundation, internal to core. transientCopy.ts builds the * swap's and the layer exit's copies on the clone, and the List reorder * builds its drag preview on it */ +/** The attributes a copy drops, so it names, labels and focuses nothing. */ +const LIVE_ATTRIBUTES = ['id', 'data-testid', 'name', 'for', 'autofocus']; + /** The listed controls a form can own. */ const FORM_CONTROLS = 'button, fieldset, input, object, output, select, textarea'; @@ -70,7 +75,7 @@ export function inertClone(element: HTMLElement): HTMLElement | null { const sourceNodes = [element, ...element.querySelectorAll('*')]; const copyNodes = [copy, ...copy.querySelectorAll('*')]; for (const node of copyNodes) { - for (const name of ['id', 'data-testid', 'name', 'for', 'autofocus']) { + for (const name of LIVE_ATTRIBUTES) { node.removeAttribute(name); } } @@ -115,6 +120,28 @@ export function inertClone(element: HTMLElement): HTMLElement | null { return copy; } +/** + * A copy of `element` without its children, ids, test ids, names, label ties + * or autofocus: a drag preview's box for content it cannot copy, and the + * shell a preview lays copied content in. + */ +export function bareCopyOf(element: E): E { + const box = element.cloneNode(false) as E; + for (const name of LIVE_ATTRIBUTES) { + box.removeAttribute(name); + } + return box; +} + +/** + * A drag preview's copy of `element`, which takes no part in the page + * (`inertClone`). Content holding a canvas that reads back empty is not + * copied: its bare box is (`bareCopyOf`). + */ +export function previewCopyOf(element: HTMLElement): HTMLElement { + return inertClone(element) ?? bareCopyOf(element); +} + /** The background `element` shows: its own, or the nearest ancestor's. */ export function paintedBackground(element: Element): string { for (let node: Element | null = element; node; node = node.parentElement) { diff --git a/scripts/sync-exports.js b/scripts/sync-exports.js index 962654f4413d2..def1bc439275f 100644 --- a/scripts/sync-exports.js +++ b/scripts/sync-exports.js @@ -239,6 +239,7 @@ const FILE_MODULE_SUBPATH_EXPORTS = [ // (architecture:react-component-runtime INV13). 'internal/indicatorPress.stylex', 'internal/reorder', + 'internal/reorder-mode', 'internal/reorderHandle.stylex', 'internal/touchHitArea.stylex', 'internal/touch',