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 1/3] 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', From 42fbcb1f79cc25373ebcdd9cb7ed813e87721e48 Mon Sep 17 00:00:00 2001 From: Humberto Virtudes <22264642+humbertovirtudes@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:37:49 -0800 Subject: [PATCH 2/3] feat(lab): reorder Table columns by keyboard and by taps useTableDragAndDropColumns puts a reorder handle in the header cell of each column in columnKeys. The handle turns on reorder mode: Left and Right move the column one place at a time, mirrored in right-to-left, and List's mode hint offers the moves and Done as buttons. Each move reports once, and announces the column's place with List's reorder strings after it lands. The reorderable's handle option places the handle and reveals it, and its start(key) turns on the mode from the app's own action. --- .../TableDragAndDropColumns.stories.tsx | 277 ++++++++++ packages/cli/test/swizzle-proof/samples.mjs | 24 + ...leDragAndDropColumns.a11y.chromium.spec.ts | 218 ++++++++ .../lab/src/TableDragAndDrop/columnReorder.ts | 365 +++++++++++++ .../useTableDragAndDropColumns.doc.mjs | 31 ++ .../useTableDragAndDropColumns.test.tsx | 517 ++++++++++++++++++ .../useTableDragAndDropColumns.tsx | 435 +++++++++++++++ packages/lab/src/index.ts | 4 + 8 files changed, 1871 insertions(+) create mode 100644 apps/storybook/stories/TableDragAndDropColumns.stories.tsx create mode 100644 packages/lab/src/TableDragAndDrop/__tests__/TableDragAndDropColumns.a11y.chromium.spec.ts create mode 100644 packages/lab/src/TableDragAndDrop/columnReorder.ts create mode 100644 packages/lab/src/TableDragAndDrop/useTableDragAndDropColumns.doc.mjs create mode 100644 packages/lab/src/TableDragAndDrop/useTableDragAndDropColumns.test.tsx create mode 100644 packages/lab/src/TableDragAndDrop/useTableDragAndDropColumns.tsx diff --git a/apps/storybook/stories/TableDragAndDropColumns.stories.tsx b/apps/storybook/stories/TableDragAndDropColumns.stories.tsx new file mode 100644 index 0000000000000..55f01335038d5 --- /dev/null +++ b/apps/storybook/stories/TableDragAndDropColumns.stories.tsx @@ -0,0 +1,277 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +import {useMemo, useState, type Key} from 'react'; +import type {Meta, StoryObj} from '@storybook/react'; +import {createReorderable} from '@astryxdesign/core'; +import { + Table, + pixel, + useTableColumnSettings, + useTableColumnSettingsState, + useTableColumnsVirtualization, + useTableSelection, + useTableStickyColumns, + type TableColumn, +} from '@astryxdesign/core/Table'; +import {VStack} from '@astryxdesign/core/Layout'; +import {Text} from '@astryxdesign/core/Text'; +import {useTableDragAndDropColumns} from '@astryxdesign/lab'; + +interface Task extends Record { + id: string; + title: string; + owner: string; + status: string; + due: string; + points: number; +} + +const TASKS: Task[] = [ + { + id: 't1', + title: 'Draft the release notes', + owner: 'Ava Chen', + status: 'Open', + due: 'Mon', + points: 3, + }, + { + id: 't2', + title: 'Review the theme tokens', + owner: 'Liam Park', + status: 'Open', + due: 'Tue', + points: 5, + }, + { + id: 't3', + title: 'Check the empty states', + owner: 'Zoe Vega', + status: 'Done', + due: 'Wed', + points: 2, + }, + { + id: 't4', + title: 'Record the demo', + owner: 'Max Ross', + status: 'Open', + due: 'Thu', + points: 8, + }, +]; + +const COLUMNS: TableColumn[] = [ + {key: 'title', header: 'Task', width: pixel(240)}, + {key: 'owner', header: 'Owner', width: pixel(160)}, + {key: 'status', header: 'Status', width: pixel(120)}, + {key: 'due', header: 'Due', width: pixel(120)}, + {key: 'points', header: 'Points', width: pixel(120), align: 'end'}, +]; + +function moveKey(keys: ReadonlyArray, key: Key, to: number): string[] { + const rest = keys.filter(item => item !== key); + return [...rest.slice(0, to), String(key), ...rest.slice(to)]; +} + +function byKeys>( + columns: TableColumn[], + keys: ReadonlyArray, +): TableColumn[] { + return keys.flatMap(key => columns.filter(column => column.key === key)); +} + +const meta: Meta = { + title: 'Lab/TableDragAndDropColumns', + tags: ['autodocs'], +}; + +export default meta; + +function DefaultDemo() { + const [order, setOrder] = useState(() => COLUMNS.map(column => column.key)); + const reorderable = useMemo( + () => + createReorderable({ + onReorder: ({key, to}) => setOrder(keys => moveKey(keys, key, to)), + }), + [], + ); + const dragColumns = useTableDragAndDropColumns({ + reorderable, + columnKeys: order, + }); + return ( + + + + {order.join(' ')} + + + ); +} + +/** + * Focus the handle at the end of a column's header and press Space or Enter, + * then Left and Right, to move the column one place at a time. Or tap the + * handle, then the hint's moves. Escape or Done ends reorder mode. + */ +export const Default: StoryObj = { + render: () => , +}; + +function ColumnSettingsDemo() { + const [active, setActive] = useState>([ + 'title', + 'status', + 'due', + 'points', + ]); + const settings = useTableColumnSettingsState({ + columns: COLUMNS.map(column => ({ + key: column.key, + label: String(column.header), + isAlwaysVisible: column.key === 'title', + })), + activeColumnKeys: active, + onChangeActiveColumnKeys: setActive, + }); + const columnSettings = useTableColumnSettings( + settings.columnSettingsConfig, + ); + const [selected, setSelected] = useState>(new Set()); + const selection = useTableSelection({ + getIsItemSelected: task => selected.has(task.id), + onSelectItem: ({item, isSelected}) => + setSelected(current => { + const next = new Set(current); + if (isSelected) { + next.add(item.id); + } else { + next.delete(item.id); + } + return next; + }), + onSelectAll: ({isAllSelected}) => + setSelected( + isAllSelected ? new Set(TASKS.map(task => task.id)) : new Set(), + ), + getIsAllSelected: () => selected.size === TASKS.length, + getRowLabel: task => task.title, + }); + const reorderable = useMemo( + () => + createReorderable({ + onReorder: ({key, to}) => setActive(keys => moveKey(keys, key, to)), + // The task column starts every row and stays in place. + isReorderable: key => key !== 'title', + // Each handle starts its header cell, and shows while the cell is + // hovered or holds the focus where the pointer is fine. + handle: {placement: 'start', revealBehavior: 'adaptive'}, + }), + [], + ); + const dragColumns = useTableDragAndDropColumns({ + reorderable, + columnKeys: settings.activeColumnKeys, + }); + const sticky = useTableStickyColumns({startKeys: ['title']}); + return ( + +
+ + {settings.activeColumnKeys.join(' ')} + + + ); +} + +/** + * Column settings own the order: the moves count the active columns, and a + * hidden column keeps its place in the settings. The task column is pinned + * and stays first, and the selection column takes no part. Each handle + * starts its header cell and shows while the cell is hovered or focused. + */ +export const WithColumnSettingsSelectionAndPinnedColumn: StoryObj = { + render: () => , +}; + +interface Metrics extends Record { + id: string; + [metric: string]: string | number; +} + +const METRIC_COLUMNS: TableColumn[] = Array.from( + {length: 60}, + (_, index) => ({ + key: `m${index + 1}`, + header: `Metric ${index + 1}`, + width: pixel(120), + }), +); + +const METRIC_ROWS: Metrics[] = Array.from({length: 20}, (_, row) => ({ + id: `r${row + 1}`, + ...Object.fromEntries( + METRIC_COLUMNS.map((column, index) => [ + column.key, + (row + 1) * (index + 1), + ]), + ), +})); + +function WindowedDemo() { + const [order, setOrder] = useState(() => + METRIC_COLUMNS.map(column => column.key), + ); + const reorderable = useMemo( + () => + createReorderable({ + onReorder: ({key, to}) => setOrder(keys => moveKey(keys, key, to)), + }), + [], + ); + const dragColumns = useTableDragAndDropColumns({ + reorderable, + columnKeys: order, + }); + const virtualization = useTableColumnsVirtualization({ + initialViewportWidth: 800, + }); + return ( + +
+ + {order.slice(0, 12).join(' ')} + + + ); +} + +/** + * Sixty columns stay windowed. Each move reports its index among all the + * columns, and screen readers hear the column's place among all of them. + */ +export const WindowedColumns: StoryObj = { + render: () => , +}; diff --git a/packages/cli/test/swizzle-proof/samples.mjs b/packages/cli/test/swizzle-proof/samples.mjs index fb64c1918f6f2..7f2994dbd9f77 100644 --- a/packages/cli/test/swizzle-proof/samples.mjs +++ b/packages/cli/test/swizzle-proof/samples.mjs @@ -612,6 +612,30 @@ export const samples = { } return React.createElement(Sample); }, + // The hook takes a reorderable object and the keys of the columns it + // orders, as an app does. + lab__useTableDragAndDropColumns: ({React, mod, Core}) => { + function Sample() { + const [reorderable] = React.useState(() => + Core.createReorderable({onReorder: noop}), + ); + const dragColumns = mod.useTableDragAndDropColumns({ + reorderable, + columnKeys: ['name', 'owner'], + }); + return React.createElement(Core.Table, { + 'aria-label': 'Tasks', + data: [{id: 't1', name: 'Notes', owner: 'Ava'}], + columns: [ + {key: 'name', header: 'Name'}, + {key: 'owner', header: 'Owner'}, + ], + idKey: 'id', + plugins: {dragColumns}, + }); + } + return React.createElement(Sample); + }, // The hook throws by design without a positive count and whole-pixel // geometry, so the sample gives both, as an app does. lab__useTableInfinityVirtualization: ({React, mod, Core}) => { diff --git a/packages/lab/src/TableDragAndDrop/__tests__/TableDragAndDropColumns.a11y.chromium.spec.ts b/packages/lab/src/TableDragAndDrop/__tests__/TableDragAndDropColumns.a11y.chromium.spec.ts new file mode 100644 index 0000000000000..be45a80365366 --- /dev/null +++ b/packages/lab/src/TableDragAndDrop/__tests__/TableDragAndDropColumns.a11y.chromium.spec.ts @@ -0,0 +1,218 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file TableDragAndDropColumns.a11y.chromium.spec.ts + * @input The Lab/TableDragAndDropColumns stories in a built Storybook, driven + * by a real Chromium keyboard and mouse + * @output Browser evidence that reorder mode moves a column by keyboard and + * by the hint's buttons, mirrored in right-to-left. It keeps the focus on + * the handle and the column in view, marks the edge it came in through + * with a line, and announces each place. Kept, pinned, revealed and + * windowed columns compose with it + * @position Chromium proof for Lab's useTableDragAndDropColumns + */ + +import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright'; +import { + DEFAULT_STORYBOOK_DIR, + serveStorybook, + type StaticServer, +} from '@astryxdesign/a11y-spec/storybook'; + +let storybook: StaticServer; +test.beforeAll(async () => { + storybook = await serveStorybook( + process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR, + ); +}); +test.afterAll(async () => { + await storybook?.close(); +}); + +test.use({viewport: {width: 1000, height: 700}}); + +const ROOT = '#storybook-root'; + +async function openStory(page: Page, id: string, globals = '') { + await page.goto( + `${storybook.origin}/iframe.html?id=${id}&viewMode=story${globals}`, + ); + await expect( + page.locator(`${ROOT} button[aria-label^="Reorder "]`).first(), + ).toBeVisible(); +} + +const handleOf = (page: Page, name: string) => + page.locator(`${ROOT} button[aria-label="Reorder ${name}"]`); + +/** Everything the page's live regions say right now. */ +const announced = async (page: Page) => + page.evaluate(() => + Array.from(document.querySelectorAll('[aria-live], [role="status"]')) + .map(region => region.textContent ?? '') + .join(' | '), + ); + +/** The header cells' text and inline edges, in the DOM's order. */ +const headers = async (page: Page) => + page.evaluate( + root => + Array.from(document.querySelectorAll(`${root} thead th`)).map(cell => { + const box = cell.getBoundingClientRect(); + return { + text: cell.textContent?.trim() ?? '', + left: Math.round(box.left), + right: Math.round(box.right), + }; + }), + ROOT, + ); + +/** The insertion line's inline position, or null while it is hidden. */ +const lineAt = async (page: Page) => + page.evaluate(root => { + const line = document.querySelector(`${root} table`) + ?.previousElementSibling as HTMLElement | null; + if (line == null || line.hidden) { + return null; + } + const box = line.getBoundingClientRect(); + return {center: Math.round(box.left + box.width / 2), height: box.height}; + }, ROOT); + +const scrollAreaOf = (page: Page) => page.locator(`${ROOT} [role="group"]`); + +test('reorder mode moves a column by keyboard, keeps the focus on its handle, shows the hint and a line at the edge it came in through, and announces each place', async ({ + page, +}) => { + await openStory(page, 'lab-tabledraganddropcolumns--default'); + const handle = handleOf(page, 'Owner'); + await handle.focus(); + await page.keyboard.press('Space'); + await expect(handle).toHaveAttribute('aria-pressed', 'true'); + for (const name of ['Move left', 'Move right', 'Done']) { + await expect(page.getByRole('button', {name, exact: true})).toBeVisible(); + } + await page.keyboard.press('ArrowRight'); + await expect(page.getByTestId('order')).toHaveText( + 'title status owner due points', + ); + await expect(handle).toBeFocused(); + await expect + .poll(() => announced(page)) + .toContain('Owner, position 3 of 5, after Status, before Due'); + const owner = (await headers(page))[2]; + expect((await lineAt(page))?.center).toBeLessThanOrEqual(owner.left + 2); + // The hint's Move right does what the key does. + await page.getByRole('button', {name: 'Move right', exact: true}).click(); + await expect(page.getByTestId('order')).toHaveText( + 'title status due owner points', + ); + await expect(handle).toBeFocused(); + // A move toward the start moves the focused cell itself. + await page.keyboard.press('ArrowLeft'); + await expect(page.getByTestId('order')).toHaveText( + 'title status owner due points', + ); + await expect(handle).toBeFocused(); + await page.keyboard.press('ArrowRight'); + await page.keyboard.press('Escape'); + await expect(handle).toHaveAttribute('aria-pressed', 'false'); + expect(await lineAt(page)).toBeNull(); + await expect + .poll(() => announced(page)) + .toContain('Done, Owner at position 4 of 5'); +}); + +test('in right-to-left, Left moves a column toward the end', async ({page}) => { + await openStory( + page, + 'lab-tabledraganddropcolumns--default', + '&globals=direction:rtl', + ); + const handle = handleOf(page, 'Owner'); + await handle.focus(); + await page.keyboard.press('Enter'); + await page.keyboard.press('ArrowLeft'); + await expect(page.getByTestId('order')).toHaveText( + 'title status owner due points', + ); + // Owner sits to the left of Status, which is before it in the order. + const cells = await headers(page); + const status = cells.find(cell => cell.text === 'Status'); + const owner = cells.find(cell => cell.text === 'Owner'); + expect(owner?.right).toBeLessThanOrEqual((status?.left ?? 0) + 1); +}); + +test('with column settings, a pinned column the reorderable keeps bounds the moves and stays pinned, and the selection column takes no part', async ({ + page, +}) => { + await openStory( + page, + 'lab-tabledraganddropcolumns--with-column-settings-selection-and-pinned-column', + ); + await expect( + page.locator(`${ROOT} button[aria-label="Reorder Task"]`), + ).toHaveCount(0); + const handle = handleOf(page, 'Status'); + await handle.focus(); + await page.keyboard.press('Enter'); + await page.keyboard.press('ArrowLeft'); + await expect.poll(() => announced(page)).toContain("Can't move past Task"); + await page.keyboard.press('ArrowRight'); + await expect(page.getByTestId('order')).toHaveText('title due status points'); + await expect + .poll(() => announced(page)) + .toContain('Status, position 3 of 4, after Due, before Points'); + await page.keyboard.press('Escape'); + const task = page.locator(`${ROOT} thead th`, {hasText: 'Task'}); + const pinnedAt = (await task.boundingBox())?.x; + await scrollAreaOf(page).evaluate(area => { + area.scrollLeft = 200; + }); + await expect + .poll(() => scrollAreaOf(page).evaluate(area => area.scrollLeft)) + .toBeGreaterThan(0); + expect((await task.boundingBox())?.x).toBe(pinnedAt); +}); + +test('a handle the reorderable reveals shows while its header cell is hovered or holds the focus', async ({ + page, +}) => { + await openStory( + page, + 'lab-tabledraganddropcolumns--with-column-settings-selection-and-pinned-column', + ); + const handle = handleOf(page, 'Status'); + await page.mouse.move(0, 400); + await expect(handle).toHaveCSS('opacity', '0'); + await page.locator(`${ROOT} thead th`, {hasText: 'Status'}).hover(); + await expect(handle).toHaveCSS('opacity', '1'); + await page.mouse.move(0, 400); + await expect(handle).toHaveCSS('opacity', '0'); + await handle.focus(); + await expect(handle).toHaveCSS('opacity', '1'); +}); + +test('windowed columns stay windowed; reorder mode keeps a moving column in view and names unmounted neighbours', async ({ + page, +}) => { + await openStory(page, 'lab-tabledraganddropcolumns--windowed-columns'); + const mounted = () => page.locator(`${ROOT} thead th`).count(); + expect(await mounted()).toBeLessThan(20); + const handle = handleOf(page, 'Metric 2'); + await handle.focus(); + await page.keyboard.press('Enter'); + for (let move = 0; move < 9; move++) { + await page.keyboard.press('ArrowRight'); + } + await expect + .poll(() => announced(page)) + .toContain( + 'Metric 2, position 11 of 60, after Metric 11, before Metric 12', + ); + await expect(handle).toBeFocused(); + await expect(handle).toBeInViewport(); + await page.keyboard.press('Escape'); + expect(await mounted()).toBeLessThan(20); +}); diff --git a/packages/lab/src/TableDragAndDrop/columnReorder.ts b/packages/lab/src/TableDragAndDrop/columnReorder.ts new file mode 100644 index 0000000000000..bf2a7a90b0596 --- /dev/null +++ b/packages/lab/src/TableDragAndDrop/columnReorder.ts @@ -0,0 +1,365 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file columnReorder.ts + * @input Each ordered column's handle in its header cell, the latest + * render's options and strings, and the announcer inside the table + * @output `createColumnReorder`: the reorder of a Table's columns along the + * inline axis. Reorder mode moves a column one place per arrow key or hint + * button. An insertion line marks the edge the column came in through, and + * every move reports once and announces once, after it lands + * @position Internal to useTableDragAndDropColumns.tsx. It lives outside + * React, and a commit of the table lands its moves + */ + +import type {KeyboardEvent, RefObject} from 'react'; +import {isRtlElement as isRtl} from '@astryxdesign/core/internal/touch'; +import { + movableRange, + type ReorderMessages, +} from '@astryxdesign/core/internal/reorder-mode'; +import type {AnnounceFn} from '@astryxdesign/core/hooks'; + +/** The latest render's options and strings. */ +export interface ColumnReorderConfiguration { + readonly onReorder: (move: {key: string; to: number}) => void; + readonly isReorderable?: (key: string) => boolean; + readonly columnKeys: ReadonlyArray; + readonly messages: ReorderMessages; +} + +/** The reorder of a Table's columns, as the plugin and its parts use it. */ +export interface ColumnReorder { + readonly hintId: string; + subscribe(listener: () => void): () => void; + getModeKey(): string | null; + handleOf(key: string): HTMLElement | null; + /** + * Registers a column's handle, and the labels of all the table's columns. + * It returns the release. + */ + attachHandle( + key: string, + labels: ReadonlyMap, + element: HTMLElement | null, + ): (() => void) | undefined; + toggle(key: string): void; + /** Starts reorder mode for a column from the app's own UI. */ + startByKey(key: string): boolean; + endMode(): void; + keyDown(key: string, event: KeyboardEvent): void; + stepVisually(key: string, side: 'left' | 'right'): void; + setHintElement(element: HTMLElement | null): void; + /** + * The announcer of the table's host, inside the table, so a table in a + * modal announces in the modal. + */ + setAnnouncer(announcer: {readonly current: AnnounceFn} | null): void; + setScrollArea(area: RefObject): void; + setLine(line: HTMLDivElement | null): void; + /** Runs after each commit of the table: a reported move lands. */ + commit(): void; + dispose(): void; +} + +interface PendingMove { + readonly key: string; + readonly to: number; + readonly landed: () => string; + readonly kept: string; +} + +/** + * Whether the column at `to` bounds a move of the one at `from`: it is in a + * run of kept columns at an end of `order`. A kept column in the middle is + * passed. + */ +export function boundsMove( + order: ReadonlyArray, + isMovable: (key: string) => boolean, + from: number, + to: number, +): boolean { + const {start, end} = movableRange( + order.map(key => ({top: 0, height: 0, isFixed: !isMovable(key)})), + from, + ); + return to < start || to > end; +} + +export function createColumnReorder( + hintId: string, + configuration: {readonly current: ColumnReorderConfiguration}, +): ColumnReorder { + const handles = new Map(); + let labels: ReadonlyMap = new Map(); + const releases = new Map void>(); + const listeners = new Set<() => void>(); + let modeKey: string | null = null; + let hintElement: HTMLElement | null = null; + let scrollArea: RefObject | null = null; + let line: HTMLDivElement | null = null; + let pending: PendingMove | null = null; + let pendingTimer: ReturnType | null = null; + // Reorder mode's line marks the edge a moved column came in through. + let modeStep: -1 | 1 | null = null; + + const notify = () => { + for (const listener of [...listeners]) { + listener(); + } + }; + let announcer: {readonly current: AnnounceFn} | null = null; + const announce = (message: string) => announcer?.current(message); + const messages = () => configuration.current.messages; + const keys = () => configuration.current.columnKeys; + const isMovable = (key: string) => + configuration.current.isReorderable?.(key) !== false; + const nameAt = (order: ReadonlyArray, index: number) => + labels.get(order[index]) || messages().itemAt(index + 1); + const placeIn = (order: ReadonlyArray, at: number) => + messages().place( + nameAt(order, at), + at + 1, + order.length, + at > 0 ? nameAt(order, at - 1) : null, + at < order.length - 1 ? nameAt(order, at + 1) : null, + ); + + // Table names each header cell by its column's key. + const headerOf = (key: string) => + Array.from( + scrollArea?.current?.querySelectorAll('thead th') ?? [], + ).find(header => header.getAttribute('data-column-key') === key) ?? null; + + /** Shows the line at `x`, in viewport pixels, beside the table's cells. */ + const showLineAt = (x: number) => { + const area = scrollArea?.current; + const table = area?.querySelector('table'); + if (line == null || area == null || table == null) { + return; + } + const areaBox = area.getBoundingClientRect(); + const tableBox = table.getBoundingClientRect(); + const left = x - areaBox.left + area.scrollLeft - area.clientLeft; + const top = tableBox.top - areaBox.top + area.scrollTop - area.clientTop; + line.style.translate = `${left - 1}px ${top}px`; + line.style.blockSize = `${tableBox.height}px`; + line.hidden = false; + }; + const hideLine = () => { + if (line != null) { + line.hidden = true; + } + }; + + /** Reorder mode's line, at the edge the column in the mode came in through. */ + const placeModeLine = () => { + const header = modeKey == null ? null : headerOf(modeKey); + if (header == null || modeStep == null) { + hideLine(); + return; + } + const box = header.getBoundingClientRect(); + const isAtStart = modeStep === 1; + showLineAt(isAtStart !== isRtl(header) ? box.left : box.right); + }; + + const settle = (message: string) => { + if (pendingTimer != null) { + clearTimeout(pendingTimer); + pendingTimer = null; + } + pending = null; + announce(message); + }; + + /** Reports a move; it announces once the columns show it, or that it was kept. */ + const report = (move: PendingMove) => { + pending = move; + if (pendingTimer != null) { + clearTimeout(pendingTimer); + } + // A move the caller does not apply by the end of the task keeps its place. + pendingTimer = setTimeout(() => { + pendingTimer = null; + if (pending != null) { + settle(pending.kept); + reorder.commit(); + } + }, 0); + configuration.current.onReorder({key: move.key, to: move.to}); + }; + + const step = (key: string, delta: -1 | 1) => { + const order = keys(); + const from = order.indexOf(key); + const to = from + delta; + if (from < 0 || modeKey !== key || to < 0 || to >= order.length) { + return; + } + if (boundsMove(order, isMovable, from, to)) { + announce(messages().refused(nameAt(order, to))); + return; + } + modeStep = delta; + report({ + key, + to, + landed: () => placeIn(keys(), to), + kept: placeIn(order, from), + }); + }; + + const startMode = (key: string) => { + modeKey = key; + modeStep = null; + hideLine(); + notify(); + }; + + const reorder: ColumnReorder = { + hintId, + subscribe: listener => { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + getModeKey: () => modeKey, + handleOf: key => handles.get(key) ?? null, + attachHandle: (key, columnLabels, element) => { + if (element == null) { + return undefined; + } + releases.get(key)?.(); + handles.set(key, element); + labels = columnLabels; + const release = () => { + if (handles.get(key) === element) { + handles.delete(key); + releases.delete(key); + } + }; + releases.set(key, release); + return release; + }, + toggle: key => { + if (modeKey === key) { + reorder.endMode(); + } else if (isMovable(key)) { + startMode(key); + } + }, + startByKey: key => { + const handle = handles.get(key); + if (handle == null || !keys().includes(key) || !isMovable(key)) { + return false; + } + handle.focus(); + if (modeKey !== key) { + startMode(key); + } + return true; + }, + endMode: () => { + const key = modeKey; + if (key == null) { + return; + } + const handle = handles.get(key); + if ( + handle != null && + hintElement?.contains(handle.ownerDocument.activeElement) === true + ) { + handle.focus({preventScroll: true}); + } + modeKey = null; + modeStep = null; + hideLine(); + notify(); + const order = keys(); + const at = order.indexOf(key); + if (at >= 0) { + announce(messages().modeDone(nameAt(order, at), at + 1, order.length)); + } + }, + keyDown: (key, event) => { + if (modeKey !== key || event.altKey || event.ctrlKey || event.metaKey) { + return; + } + switch (event.key) { + case 'Escape': + event.preventDefault(); + event.stopPropagation(); + reorder.endMode(); + return; + case 'ArrowLeft': + case 'ArrowRight': + event.preventDefault(); + reorder.stepVisually( + key, + event.key === 'ArrowLeft' ? 'left' : 'right', + ); + return; + default: + return; + } + }, + stepVisually: (key, side) => { + const handle = handles.get(key); + const rtl = handle != null && isRtl(handle); + step(key, (side === 'right') !== rtl ? 1 : -1); + }, + setHintElement: element => { + hintElement = element; + }, + setAnnouncer: next => { + announcer = next; + }, + setScrollArea: area => { + scrollArea = area; + }, + setLine: element => { + line = element; + }, + commit: () => { + const order = keys(); + if (pending != null && order[pending.to] === pending.key) { + const moved = pending.key; + settle(pending.landed()); + const handle = handles.get(moved); + // A screen reader can put the focus on a hint button; the next key + // press belongs to the handle again. + if ( + modeKey === moved && + handle != null && + hintElement?.contains(handle.ownerDocument.activeElement) === true + ) { + handle.focus({preventScroll: true}); + } + // A column in reorder mode stays in view as it moves. + if (modeKey === moved) { + headerOf(moved)?.scrollIntoView?.({ + block: 'nearest', + inline: 'nearest', + }); + } + } + if (modeKey != null && !order.includes(modeKey)) { + modeKey = null; + notify(); + } + placeModeLine(); + }, + dispose: () => { + if (pendingTimer != null) { + clearTimeout(pendingTimer); + pendingTimer = null; + } + pending = null; + hideLine(); + }, + }; + return reorder; +} diff --git a/packages/lab/src/TableDragAndDrop/useTableDragAndDropColumns.doc.mjs b/packages/lab/src/TableDragAndDrop/useTableDragAndDropColumns.doc.mjs new file mode 100644 index 0000000000000..13f6b27aa6691 --- /dev/null +++ b/packages/lab/src/TableDragAndDrop/useTableDragAndDropColumns.doc.mjs @@ -0,0 +1,31 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** @type {import('@astryxdesign/cli/authoring').HookDoc} */ +export default { + type: 'function', + name: 'useTableDragAndDropColumns', + displayName: 'useTableDragAndDropColumns', + importPath: '@astryxdesign/lab', + relatedComponents: ['Table', 'createReorderable', 'useTableColumnSettings'], + keywords: ['table', 'columns', 'reorder', 'drag', 'drop', 'header', 'handle'], + params: [ + { + name: 'config', + type: '{reorderable: Reorderable; columnKeys: ReadonlyArray}', + description: + "reorderable comes from createReorderable. Its onReorder gets the moved column's key and its index after the move among columnKeys; apply the move to your column order. Its isReorderable keeps a column in place: the column shows no handle, and a column at either end bounds the moves. Its handle option places each handle at the end of its header cell (the default) or, with placement 'start', at its start; with revealBehavior 'adaptive', a handle shows while its header cell is hovered or holds the focus where the pointer is fine. columnKeys lists the columns people can reorder, in their order, such as useTableColumnSettingsState's activeColumnKeys. A column outside it, such as the selection column, gets no handle.", + }, + ], + returns: [ + { + name: 'plugin', + type: 'TablePlugin', + description: + "Pass it in Table's plugins under any name, with the columns in the order columnKeys gives. It puts a reorder handle in each ordered column's header cell, named Reorder and the header's text; the header keeps its own name.", + }, + ], + usage: { + description: + "Reorders a Table's columns by keyboard and by taps. The handle turns on reorder mode: Left and Right move the column one place at a time, mirrored in right-to-left, and Escape or the handle again ends the mode. A hint below the handle offers the moves and Done as buttons, so a pointer or a finger can also reorder by taps. The reorderable's start(key) turns on reorder mode for a column from the app's own action, such as a Move column menu item. Screen readers hear each move with the column's place and its neighbours. With column windowing, the columns stay windowed, and each move and place counts every column in columnKeys. A pinned column keeps its pin as it moves; keep it in place with isReorderable when it must stay first.", + }, +}; diff --git a/packages/lab/src/TableDragAndDrop/useTableDragAndDropColumns.test.tsx b/packages/lab/src/TableDragAndDrop/useTableDragAndDropColumns.test.tsx new file mode 100644 index 0000000000000..36c8ed402717f --- /dev/null +++ b/packages/lab/src/TableDragAndDrop/useTableDragAndDropColumns.test.tsx @@ -0,0 +1,517 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file useTableDragAndDropColumns.test.tsx + * @input A Table whose columns reorder through `useTableDragAndDropColumns`, + * alone, in right-to-left, beside selection, and with column settings + * @output Proof that each ordered column's header gets one reorder handle + * that leaves the header's own name alone. Reorder mode moves a column by + * key along the inline axis, mirrored in right-to-left, with one report per + * move, the focus kept on the handle, and each place announced among the + * ordered columns. A column the reorderable rejects bounds the moves, and + * the hint's buttons do what the keys do + * @position Testing for useTableDragAndDropColumns.tsx + */ + +import {useMemo, useState, type Key, type ReactNode} from 'react'; +import { + act, + cleanup, + render, + renderHook, + screen, + waitFor, +} from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import {afterEach, describe, expect, it, vi} from 'vitest'; +import {createReorderable, type ReorderableOptions} from '@astryxdesign/core'; +import {Dialog} from '@astryxdesign/core/Dialog'; +import {useAnnounce} from '@astryxdesign/core/hooks'; +import { + Table, + useTableColumnSettings, + useTableColumnSettingsState, + useTableSelection, + type TableColumn, +} from '@astryxdesign/core/Table'; +import {useTableDragAndDropColumns} from './useTableDragAndDropColumns'; + +interface Task extends Record { + id: string; + name: string; + owner: string; + status: string; + due: string; +} + +const TASKS: Task[] = [ + {id: 't1', name: 'Notes', owner: 'Ava', status: 'Open', due: 'Mon'}, + {id: 't2', name: 'Demo', owner: 'Liam', status: 'Done', due: 'Tue'}, +]; + +const COLUMNS: TableColumn[] = [ + {key: 'name', header: 'Name'}, + {key: 'owner', header: 'Owner'}, + {key: 'status', header: 'Status'}, + {key: 'due', header: 'Due'}, +]; + +function moveKey(keys: ReadonlyArray, key: Key, to: number): string[] { + const rest = keys.filter(item => item !== key); + return [...rest.slice(0, to), String(key), ...rest.slice(to)]; +} + +function Tasks({ + onReorder, + isReorderable, + hasSelection = false, + handle, +}: { + onReorder: (move: {key: Key; to: number}) => void; + isReorderable?: (key: Key) => boolean; + hasSelection?: boolean; + handle?: ReorderableOptions['handle']; +}): ReactNode { + const [order, setOrder] = useState(() => COLUMNS.map(column => column.key)); + const reorderable = useMemo( + () => + createReorderable({ + onReorder: move => { + onReorder(move); + setOrder(current => moveKey(current, move.key, move.to)); + }, + isReorderable, + handle, + }), + [onReorder, isReorderable, handle], + ); + const dragColumns = useTableDragAndDropColumns({ + reorderable, + columnKeys: order, + }); + const selection = useTableSelection({ + getIsItemSelected: () => false, + onSelectItem: () => {}, + onSelectAll: () => {}, + getIsAllSelected: () => false, + getRowLabel: task => task.name, + }); + const columns = order.map( + key => COLUMNS.find(column => column.key === key) as TableColumn, + ); + return ( +
+ ); +} + +function SettingsTasks({ + onReorder, +}: { + onReorder: (move: {key: Key; to: number}) => void; +}): ReactNode { + const [active, setActive] = useState>([ + 'name', + 'status', + 'due', + ]); + const settings = useTableColumnSettingsState({ + columns: COLUMNS.map(column => ({ + key: column.key, + label: String(column.header), + })), + activeColumnKeys: active, + onChangeActiveColumnKeys: setActive, + }); + const columnSettings = useTableColumnSettings( + settings.columnSettingsConfig, + ); + const reorderable = useMemo( + () => + createReorderable({ + onReorder: move => { + onReorder(move); + setActive(current => moveKey(current, move.key, move.to)); + }, + }), + [onReorder], + ); + const dragColumns = useTableDragAndDropColumns({ + reorderable, + columnKeys: settings.activeColumnKeys, + }); + return ( +
+ ); +} + +const handleOf = (name: string) => + screen.getByRole('button', {name: `Reorder ${name}`}); + +const headers = () => + screen.getAllByRole('columnheader').map(header => header.textContent); + +describe('useTableDragAndDropColumns', () => { + // The live region outlives each test: clear it, so one test's message is + // never read by the next. + afterEach(() => { + const {result, unmount} = renderHook(() => useAnnounce()); + act(() => result.current('')); + unmount(); + vi.restoreAllMocks(); + }); + + it("puts one reorder handle in each ordered column's header, and keeps the header's own name", () => { + render(); + for (const name of ['Name', 'Owner', 'Status', 'Due']) { + const handle = handleOf(name); + expect(handle).toHaveAttribute('aria-pressed', 'false'); + expect(screen.getByRole('columnheader', {name})).toContainElement(handle); + } + // The selection column is not one of the ordered columns. + expect(screen.getAllByRole('button', {name: /^Reorder /})).toHaveLength(4); + }); + + it("names a handle by its header's text as it reads, block by block", () => { + function TwoLineHeader(): ReactNode { + const reorderable = useMemo( + () => createReorderable({onReorder: () => {}}), + [], + ); + const dragColumns = useTableDragAndDropColumns({ + reorderable, + columnKeys: ['name', 'due'], + }); + return ( +
+ Due
date
+ + ), + }, + ]} + idKey="id" + plugins={{dragColumns}} + /> + ); + } + render(); + expect( + screen.getByRole('button', {name: 'Reorder Due date'}), + ).toBeInTheDocument(); + }); + + it("reveals each handle with its header cell for the reorderable's adaptive reveal, and keeps it named and in the tab order", async () => { + const user = userEvent.setup(); + render( + , + ); + const handle = handleOf('Name'); + const header = screen.getByRole('columnheader', {name: 'Name'}); + expect(header).toContainElement(handle); + const revealed = {handle: handle.className, header: header.className}; + await user.tab(); + expect(handle).toHaveFocus(); + cleanup(); + // The reveal hides only the paint, where the pointer is fine: a handle + // that always shows takes neither reveal style. + render(); + expect(handleOf('Name').className).not.toBe(revealed.handle); + expect(screen.getByRole('columnheader', {name: 'Name'}).className).not.toBe( + revealed.header, + ); + }); + + it('moves a column in reorder mode, one report per move, keeps the focus on its handle and announces its place and neighbours', async () => { + const onReorder = vi.fn(); + const user = userEvent.setup(); + render(); + handleOf('Owner').focus(); + await user.keyboard('{Enter}'); + expect(handleOf('Owner')).toHaveAttribute('aria-pressed', 'true'); + await user.keyboard('{ArrowRight}'); + expect(onReorder).toHaveBeenCalledTimes(1); + expect(onReorder).toHaveBeenLastCalledWith({key: 'owner', to: 2}); + expect(headers()).toEqual(['Name', 'Status', 'Owner', 'Due']); + expect(handleOf('Owner')).toHaveFocus(); + await waitFor(() => + expect(document.body).toHaveTextContent( + 'Owner, position 3 of 4, after Status, before Due', + ), + ); + await user.keyboard('{ArrowRight}'); + await waitFor(() => + expect(document.body).toHaveTextContent( + 'Owner, position 4 of 4, after Due, at the end', + ), + ); + // Past the end, nothing moves. + await user.keyboard('{ArrowRight}'); + expect(onReorder).toHaveBeenCalledTimes(2); + await user.keyboard('{Escape}'); + expect(handleOf('Owner')).toHaveAttribute('aria-pressed', 'false'); + await waitFor(() => + expect(document.body).toHaveTextContent('Done, Owner at position 4 of 4'), + ); + }); + + it('returns the focus to the handle after a move from a hint button that holds it', async () => { + const user = userEvent.setup(); + render(); + handleOf('Owner').focus(); + await user.keyboard('{Enter}'); + // A screen reader's cursor can focus the hint's buttons. + const right = screen.getByRole('button', { + name: 'Move right', + hidden: true, + }); + right.focus(); + await user.click(right); + expect(headers()).toEqual(['Name', 'Status', 'Owner', 'Due']); + await waitFor(() => expect(handleOf('Owner')).toHaveFocus()); + }); + + it('announces each move inside the modal its Table sits in', async () => { + const user = userEvent.setup(); + // jsdom has no modal dialogs: stand in for one opened modally. + const dialogs = HTMLDialogElement.prototype; + const ownShowModal = Object.getOwnPropertyDescriptor(dialogs, 'showModal'); + const ownClose = Object.getOwnPropertyDescriptor(dialogs, 'close'); + dialogs.showModal = vi.fn(function (this: HTMLDialogElement) { + this.setAttribute('open', ''); + this.dataset.modal = 'true'; + }); + dialogs.close = vi.fn(function (this: HTMLDialogElement) { + this.removeAttribute('open'); + delete this.dataset.modal; + }); + const matches = Element.prototype.matches; + const isModal = vi + .spyOn(Element.prototype, 'matches') + .mockImplementation(function (this: Element, selector: string) { + return selector === ':modal' + ? this instanceof HTMLDialogElement && + this.open && + this.dataset.modal === 'true' + : matches.call(this, selector); + }); + try { + function InDialog(): ReactNode { + const [order, setOrder] = useState(() => + COLUMNS.map(column => column.key), + ); + const reorderable = useMemo( + () => + createReorderable({ + onReorder: ({key, to}) => + setOrder(current => moveKey(current, key, to)), + }), + [], + ); + // The plugin's owner renders the dialog, so it sits outside it. + const dragColumns = useTableDragAndDropColumns({ + reorderable, + columnKeys: order, + }); + return ( + {}} aria-label="Columns"> +
+ COLUMNS.find( + column => column.key === key, + ) as TableColumn, + )} + idKey="id" + plugins={{dragColumns}} + /> + + ); + } + render(); + const dialog = screen.getByRole('dialog', {name: 'Columns'}); + handleOf('Owner').focus(); + await user.keyboard('{Enter}{ArrowRight}'); + await waitFor(() => + expect( + dialog.querySelector( + ':scope > [data-astryx-modal-live-region="polite"]', + ), + ).toHaveTextContent('Owner, position 3 of 4, after Status, before Due'), + ); + } finally { + cleanup(); + isModal.mockRestore(); + for (const [name, own] of [ + ['showModal', ownShowModal], + ['close', ownClose], + ] as const) { + if (own == null) { + Reflect.deleteProperty(dialogs, name); + } else { + Object.defineProperty(dialogs, name, own); + } + } + } + }); + + it('mirrors the arrow keys in right-to-left', async () => { + // jsdom computes no direction from `dir`: an element inside a + // right-to-left subtree reads as one. + const computed = window.getComputedStyle.bind(window); + vi.spyOn(window, 'getComputedStyle').mockImplementation( + (element, pseudo) => { + const style = computed(element, pseudo); + if (element.closest('[dir="rtl"]') == null) { + return style; + } + return new Proxy(style, { + get: (target, property) => { + if (property === 'direction') { + return 'rtl'; + } + const value = Reflect.get(target, property, target); + return typeof value === 'function' ? value.bind(target) : value; + }, + }); + }, + ); + const onReorder = vi.fn(); + const user = userEvent.setup(); + render( +
+ +
, + ); + handleOf('Owner').focus(); + await user.keyboard('{Enter}{ArrowLeft}'); + expect(onReorder).toHaveBeenLastCalledWith({key: 'owner', to: 2}); + await user.keyboard('{ArrowRight}{ArrowRight}'); + expect(onReorder).toHaveBeenLastCalledWith({key: 'owner', to: 0}); + await waitFor(() => + expect(document.body).toHaveTextContent( + 'Owner, position 1 of 4, at the top, before Name', + ), + ); + }); + + it('keeps a column the reorderable rejects in place, and refuses a move past it by name', async () => { + const onReorder = vi.fn(); + const user = userEvent.setup(); + render( + key !== 'name'} />, + ); + expect( + screen.queryByRole('button', {name: 'Reorder Name'}), + ).not.toBeInTheDocument(); + // The kept column keeps its header as it is: no room for a handle. + const name = screen.getByRole('columnheader', {name: 'Name'}); + const owner = screen.getByRole('columnheader', {name: /Owner/}); + expect(name.className).not.toBe(owner.className); + handleOf('Owner').focus(); + await user.keyboard('{Enter}{ArrowLeft}'); + expect(onReorder).not.toHaveBeenCalled(); + await waitFor(() => + expect(document.body).toHaveTextContent("Can't move past Name"), + ); + }); + + it("moves with the hint's buttons as with the keys", async () => { + const onReorder = vi.fn(); + const user = userEvent.setup(); + render(); + await user.click(handleOf('Status')); + expect(handleOf('Status')).toHaveAttribute('aria-pressed', 'true'); + // jsdom never opens a popover, so the hint stays hidden there. + await user.click( + screen.getByRole('button', {name: 'Move left', hidden: true}), + ); + expect(onReorder).toHaveBeenLastCalledWith({key: 'status', to: 1}); + expect(handleOf('Status')).toHaveFocus(); + await user.click(screen.getByRole('button', {name: 'Done', hidden: true})); + expect(handleOf('Status')).toHaveAttribute('aria-pressed', 'false'); + }); + + it("starts reorder mode from the app's own action through the reorderable's start", async () => { + const user = userEvent.setup(); + function WithAction(): ReactNode { + const [order, setOrder] = useState(() => + COLUMNS.map(column => column.key), + ); + const reorderable = useMemo( + () => + createReorderable({ + onReorder: ({key, to}) => + setOrder(current => moveKey(current, key, to)), + }), + [], + ); + const dragColumns = useTableDragAndDropColumns({ + reorderable, + columnKeys: order, + }); + return ( + <> + +
+ COLUMNS.find(column => column.key === key) as TableColumn, + )} + idKey="id" + plugins={{dragColumns}} + /> + + ); + } + render(); + await user.click(screen.getByRole('button', {name: 'Move Owner'})); + expect(handleOf('Owner')).toHaveFocus(); + expect(handleOf('Owner')).toHaveAttribute('aria-pressed', 'true'); + await user.keyboard('{ArrowRight}'); + expect(headers()).toEqual(['Name', 'Status', 'Owner', 'Due']); + }); + + it('counts the active columns of column settings, which own the order', async () => { + const onReorder = vi.fn(); + const user = userEvent.setup(); + render(); + expect(headers()).toEqual(['Name', 'Status', 'Due']); + handleOf('Due').focus(); + await user.keyboard('{Enter}{ArrowLeft}'); + expect(onReorder).toHaveBeenLastCalledWith({key: 'due', to: 1}); + expect(headers()).toEqual(['Name', 'Due', 'Status']); + await waitFor(() => + expect(document.body).toHaveTextContent( + 'Due, position 2 of 3, after Name, before Status', + ), + ); + }); +}); diff --git a/packages/lab/src/TableDragAndDrop/useTableDragAndDropColumns.tsx b/packages/lab/src/TableDragAndDrop/useTableDragAndDropColumns.tsx new file mode 100644 index 0000000000000..87c5b613be196 --- /dev/null +++ b/packages/lab/src/TableDragAndDrop/useTableDragAndDropColumns.tsx @@ -0,0 +1,435 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file useTableDragAndDropColumns.tsx + * @input A reorderable object made by createReorderable, the keys of the + * columns it orders, and a Table's header cells + * @output `useTableDragAndDropColumns`, a Table plugin that puts a reorder + * handle in the header cell of each of those columns. A column moves by + * keyboard or by the hint's buttons in reorder mode, and each move reports + * its key and its index after the move among the keys + * @position Lab Table plugin. Core's reorder session moves rows along the + * block axis only, so this plugin runs the same reorder mode, strings and + * hint along the inline axis + */ + +import { + useCallback, + useId, + useLayoutEffect, + useMemo, + useState, + useSyncExternalStore, + type CSSProperties, + type KeyboardEvent, + type ReactNode, +} from 'react'; +import * as stylex from '@stylexjs/stylex'; +import type {Reorderable} from '@astryxdesign/core'; +import { + useAnnounce, + useContainerReveal, + useMergedRefs, + type AnnounceFn, +} from '@astryxdesign/core/hooks'; +import {useCommittedRef} from '@astryxdesign/core/internal/committed-ref'; +import {useTranslator} from '@astryxdesign/core/i18n'; +import {Icon} from '@astryxdesign/core/Icon'; +import { + mountReorderStarter, + reorderableOptions, +} from '@astryxdesign/core/internal/reorder'; +import { + getNodeText, + ReorderModeHint, + reorderMessagesFrom, +} from '@astryxdesign/core/internal/reorder-mode'; +import {reorderHandle} from '@astryxdesign/core/internal/reorderHandle.stylex'; +import { + touchHitAreaStyles, + useTouchHitArea, +} from '@astryxdesign/core/internal/touch'; +import type {TableColumn, TablePlugin} from '@astryxdesign/core/Table'; +import {colorVars, spacingVars} from '@astryxdesign/core/theme/tokens.stylex'; +import {focusOutlineStyles, mergeProps} from '@astryxdesign/core/utils'; +import { + createColumnReorder, + type ColumnReorder, + type ColumnReorderConfiguration, +} from './columnReorder'; + +/** What `useTableDragAndDropColumns` takes. */ +export interface UseTableDragAndDropColumnsConfig { + /** + * The columns' reorder behavior, made by `createReorderable`. Its + * `onReorder` gets the moved column's key and its index after the move + * among `columnKeys`. Apply the move to the column order. Its + * `isReorderable` keeps a column in place. Its `handle.placement` puts + * each handle at the end of its header cell (the default) or at its + * start. Its `handle.revealBehavior` is `'always'` (the default) or + * `'adaptive'`: where the pointer is fine, a handle then shows while its + * header cell is hovered or holds the focus. + */ + reorderable: Reorderable; + /** + * The keys of the columns people can reorder, in their order: the order + * `onReorder` counts in, such as `useTableColumnSettingsState`'s + * `activeColumnKeys`. A column outside it, such as the selection column, + * gets no handle and keeps its place. + */ + columnKeys: ReadonlyArray; +} + +// A List row's reorder handle: its grip, and the target round it. +const HANDLE_SIZE = `calc(${reorderHandle.grip} + 2 * ${reorderHandle.targetReach})`; + +const styles = stylex.create({ + // The handle sits at an inline edge of the header cell, as an overlay, so + // its name stays out of the header's name. A pinned cell's inline + // `position: sticky` wins over this containing block. + headerWithStartHandle: { + position: 'relative', + paddingInlineStart: `calc(${spacingVars['--spacing-1']} + ${HANDLE_SIZE} + ${spacingVars['--spacing-1']})`, + }, + // At the end, the handle stays clear of a resize boundary on the edge. + headerWithEndHandle: { + position: 'relative', + paddingInlineEnd: `calc(${spacingVars['--spacing-2']} + ${HANDLE_SIZE} + ${spacingVars['--spacing-1']})`, + }, + handleAtStart: { + insetInlineStart: spacingVars['--spacing-1'], + }, + handleAtEnd: { + insetInlineEnd: spacingVars['--spacing-2'], + }, + handle: { + position: 'absolute', + insetBlockStart: '50%', + translate: '0 -50%', + display: 'inline-flex', + alignItems: 'center', + justifyContent: 'center', + inlineSize: HANDLE_SIZE, + blockSize: HANDLE_SIZE, + padding: 0, + borderWidth: 0, + borderStyle: 'none', + // As a List row's reorder handle: a quiet grip, filled only in reorder + // mode, as a pressed toggle button. + borderRadius: 4, + backgroundColor: 'transparent', + color: colorVars['--color-icon-secondary'], + cursor: { + default: 'grab', + ':is(:disabled,[aria-disabled="true"])': 'default', + }, + userSelect: 'none', + }, + pressed: { + backgroundColor: { + default: colorVars['--color-overlay-pressed'], + '@media (forced-colors: active)': 'Highlight', + }, + color: { + default: colorVars['--color-icon-secondary'], + '@media (forced-colors: active)': 'HighlightText', + }, + forcedColorAdjust: 'none', + }, + grip: { + pointerEvents: 'none', + }, + scrollArea: { + position: 'relative', + }, + // The insertion line: it stands between two header cells, the full height + // of the table, while reorder mode marks a column's new place. + line: { + position: 'absolute', + insetBlockStart: 0, + left: 0, + inlineSize: 2, + borderRadius: 1, + backgroundColor: { + default: colorVars['--color-accent'], + '@media (forced-colors: active)': 'Highlight', + }, + forcedColorAdjust: 'none', + pointerEvents: 'none', + zIndex: 3, + }, +}); + +/** A column header's reorder handle: a toggle for reorder mode. */ +function ColumnHandle({ + reorder, + columnKey, + labels, + isAtStart, + reveal, +}: { + reorder: ColumnReorder; + columnKey: string; + labels: ReadonlyMap; + isAtStart: boolean; + reveal: RevealProps; +}): ReactNode { + const t = useTranslator(); + const modeKey = useSyncExternalStore( + reorder.subscribe, + reorder.getModeKey, + () => null, + ); + const hitAreaRef = useTouchHitArea(true); + const attach = useCallback( + (element: HTMLElement | null) => + reorder.attachHandle(columnKey, labels, element), + [reorder, columnKey, labels], + ); + const ref = useMergedRefs(hitAreaRef, attach); + const label = labels.get(columnKey) ?? columnKey; + const isInMode = modeKey === columnKey; + return ( + + ); +} + +type RevealProps = {className?: string; style?: CSSProperties}; + +/** + * Reorder mode's hint, anchored below the handle of the column in the mode: + * Move left, Move right and Done, which do what the keys do. A pointer or a + * finger reorders by tapping the handle, the moves, then Done. + */ +function ColumnReorderHint({reorder}: {reorder: ColumnReorder}): ReactNode { + const modeKey = useSyncExternalStore( + reorder.subscribe, + reorder.getModeKey, + () => null, + ); + return ( + { + if (modeKey != null) { + reorder.stepVisually(modeKey, move === 'left' ? 'left' : 'right'); + } + }} + onDone={() => reorder.endMode()} + onHintElement={element => reorder.setHintElement(element)} + /> + ); +} + +/** + * Renders the handles' instructions and the hint beside the table, and lets + * the reorder read each commit of the table: a move announces once it lands, + * and a column in reorder mode stays in view. + */ +function ColumnReorderHost({reorder}: {reorder: ColumnReorder}): ReactNode { + const t = useTranslator(); + // Inside the table, so a table in a modal announces in the modal. + const announce: AnnounceFn = useAnnounce(); + const announcer = useCommittedRef(announce); + // Syncs the reorder, which lives outside React, with the host's announcer. + useLayoutEffect(() => { + reorder.setAnnouncer(announcer); + return () => reorder.setAnnouncer(null); + }, [reorder, announcer]); + // Syncs the reorder, which lives outside React, with this commit's columns. + useLayoutEffect(() => { + reorder.commit(); + }); + return ( + <> + + + + ); +} + +/** + * Makes a Table's columns reorderable by keyboard and by taps. Each + * column in `columnKeys` gets a reorder handle at the end of its header + * cell, or at its start, as the reorderable's `handle.placement` says. + * Activating the handle turns on reorder mode: Left and + * Right move the column one place at a time, mirrored in right-to-left, and + * Escape ends the mode. Screen readers hear each move with the column's place + * and neighbours. + * + * @example + * ``` + * const reorderable = useMemo( + * () => + * createReorderable({ + * onReorder: ({key, to}) => setOrder(keys => moveKey(keys, key, to)), + * }), + * [], + * ); + * const dragColumns = useTableDragAndDropColumns({reorderable, columnKeys: order}); + *
+ * ``` + */ +export function useTableDragAndDropColumns>({ + reorderable, + columnKeys, +}: UseTableDragAndDropColumnsConfig): TablePlugin { + const t = useTranslator(); + const hintId = useId(); + const options = reorderableOptions(reorderable); + // The latest options and strings, which the reorder reads at + // each event and commit. + const configuration = useCommittedRef({ + onReorder: move => options.onReorder(move), + isReorderable: options.isReorderable, + columnKeys, + messages: reorderMessagesFrom(t), + }); + const [reorder] = useState(() => createColumnReorder(hintId, configuration)); + // Ends reorder mode in progress as the plugin goes. + useLayoutEffect(() => () => reorder.dispose(), [reorder]); + // Syncs with the reorderable object: its `start(key)` reaches this table. + useLayoutEffect( + () => + mountReorderStarter(reorderable, { + startByKey: key => reorder.startByKey(String(key)), + }), + [reorderable, reorder], + ); + + const {handle} = reorderableOptions(reorderable); + const isAtStart = handle?.placement === 'start'; + // A Table's handles always show unless the reorderable asks to reveal + // them, as a List's do. + const isRevealed = handle?.revealBehavior === 'adaptive'; + const {getContainerProps, getContentRevealProps} = useContainerReveal({ + isEnabled: isRevealed, + }); + + return useMemo((): TablePlugin => { + const ordered = new Set(columnKeys); + const {isReorderable} = reorderableOptions(reorderable); + const headerReveal = getContainerProps(); + const handleReveal = getContentRevealProps({isLayoutPreserved: true}); + // The announcements name neighbours that column windowing does not mount. + const labelsByColumns = new WeakMap< + ReadonlyArray>, + ReadonlyMap + >(); + const labelsOf = (columns: ReadonlyArray>) => { + let labels = labelsByColumns.get(columns); + if (labels == null) { + labels = new Map( + columns.map(column => [ + column.key, + getNodeText(column.header) || column.key, + ]), + ); + labelsByColumns.set(columns, labels); + } + return labels; + }; + return { + transformHeaderCell(props, column, _columnIndex, columns) { + // A kept column shows no handle, so it keeps its header as it is. + if (!ordered.has(column.key) || isReorderable?.(column.key) === false) { + return props; + } + const control = ( + + ); + return { + ...props, + htmlProps: { + ...props.htmlProps, + ...mergeProps( + { + className: props.htmlProps.className, + style: props.htmlProps.style, + }, + headerReveal, + ), + }, + xstyle: [ + ...props.xstyle, + isAtStart + ? styles.headerWithStartHandle + : styles.headerWithEndHandle, + ], + overlay: ( + <> + {control} + {props.overlay} + + ), + }; + }, + transformScrollWrapper(props, context) { + if (context != null) { + reorder.setScrollArea(context.viewport); + } + return { + ...props, + xstyle: [...props.xstyle, styles.scrollArea], + beforeTable: ( + <> +
' + + '
'; + document.body.append(area); + let offset = 0; + Object.defineProperties(area, { + scrollLeft: { + configurable: true, + get: () => offset, + set: (value: number) => { + offset = value; + }, + }, + scrollWidth: {configurable: true, value: 2000}, + clientWidth: {configurable: true, value: 300}, + }); + area.getBoundingClientRect = () => box(0, 300); + const table = area.querySelector('table') as HTMLTableElement; + table.getBoundingClientRect = () => box(0, 2000); + const [first, second] = Array.from(area.querySelectorAll('th')); + first.getBoundingClientRect = () => box(0 - offset, 100 - offset); + second.getBoundingClientRect = () => box(100 - offset, 200 - offset); + const handle = first.querySelector('button') as HTMLButtonElement; + const drag = createColumnDrag({ + keys: () => ['a', 'b'], + headerOf: key => (key === 'a' ? first : second), + handleAt: target => + target instanceof Node && handle.contains(target) + ? {key: 'a', handle} + : null, + scrollArea: () => area, + rangeFrom: () => ({start: 0, end: 1}), + showLine: () => {}, + hideLine: () => {}, + endMode: () => {}, + announce: () => {}, + messages: () => ({ + place: () => '', + refused: () => '', + itemAt: () => '', + modeDone: () => '', + pickedUp: () => '', + dropped: () => '', + cancelled: () => '', + }), + report: () => {}, + }); + const detach = drag.attach(false); + const mouse = {pointerType: 'mouse', pointerId: 1, button: 0, clientY: 20}; + fireEvent.pointerDown(handle, {...mouse, clientX: 90}); + fireEvent.pointerMove(area, {...mouse, clientX: 95}); + // The column's end edge 5 px past the area's: the area autoscrolls. + fireEvent.pointerMove(area, {...mouse, clientX: 295}); + vi.advanceTimersByTime(20); + const step = offset; + expect(step).toBeGreaterThan(0); + // The drag's own scroll event. + fireEvent.scroll(area); + // A scroll the drag did not cause, such as a wheel's, before the next + // tick. + offset = 600; + fireEvent.scroll(area); + vi.advanceTimersByTime(20); + expect(offset).toBeGreaterThan(600); + fireEvent.pointerUp(area, {...mouse, clientX: 295}); + detach(); + }); + it('drops under the pointer after a scroll it did not cause just before the release', () => { + vi.useFakeTimers({ + toFake: [ + 'setInterval', + 'clearInterval', + 'setTimeout', + 'clearTimeout', + 'requestAnimationFrame', + 'cancelAnimationFrame', + 'performance', + ], + }); + const area = document.createElement('div'); + area.innerHTML = + '' + + '
'; + document.body.append(area); + let offset = 0; + Object.defineProperties(area, { + scrollLeft: { + configurable: true, + get: () => offset, + set: (value: number) => { + offset = value; + }, + }, + scrollWidth: {configurable: true, value: 2000}, + clientWidth: {configurable: true, value: 300}, + }); + area.getBoundingClientRect = () => box(0, 300); + const table = area.querySelector('table') as HTMLTableElement; + table.getBoundingClientRect = () => box(0, 2000); + const [first, second] = Array.from(area.querySelectorAll('th')); + first.getBoundingClientRect = () => box(0 - offset, 100 - offset); + second.getBoundingClientRect = () => box(100 - offset, 200 - offset); + const handle = first.querySelector('button') as HTMLButtonElement; + const report = vi.fn(); + const drag = createColumnDrag({ + keys: () => ['a', 'b'], + headerOf: key => (key === 'a' ? first : second), + handleAt: target => + target instanceof Node && handle.contains(target) + ? {key: 'a', handle} + : null, + scrollArea: () => area, + rangeFrom: () => ({start: 0, end: 1}), + showLine: () => {}, + hideLine: () => {}, + endMode: () => {}, + announce: () => {}, + messages: () => ({ + place: () => '', + refused: () => '', + itemAt: () => '', + modeDone: () => '', + pickedUp: () => '', + dropped: () => '', + cancelled: () => '', + }), + report, + }); + const detach = drag.attach(false); + const mouse = {pointerType: 'mouse', pointerId: 1, button: 0, clientY: 20}; + fireEvent.pointerDown(handle, {...mouse, clientX: 50}); + fireEvent.pointerMove(area, {...mouse, clientX: 60}); + // A scroll the drag did not cause brings b under the column, and the + // release comes before the watch folds it in. + offset = 100; + fireEvent.scroll(area); + fireEvent.pointerUp(area, {...mouse, clientX: 60}); + expect(report).toHaveBeenCalledWith( + expect.objectContaining({key: 'a', to: 1}), + ); + detach(); + }); + it('cancels a drag its pointer input leaves when it detaches', () => { + vi.useFakeTimers({ + toFake: [ + 'setInterval', + 'clearInterval', + 'setTimeout', + 'clearTimeout', + 'requestAnimationFrame', + 'cancelAnimationFrame', + 'performance', + ], + }); + const area = document.createElement('div'); + area.innerHTML = + '' + + '
'; + document.body.append(area); + let offset = 0; + Object.defineProperties(area, { + scrollLeft: { + configurable: true, + get: () => offset, + set: (value: number) => { + offset = value; + }, + }, + scrollWidth: {configurable: true, value: 2000}, + clientWidth: {configurable: true, value: 300}, + }); + area.getBoundingClientRect = () => box(0, 300); + const table = area.querySelector('table') as HTMLTableElement; + table.getBoundingClientRect = () => box(0, 2000); + const [first, second] = Array.from(area.querySelectorAll('th')); + first.getBoundingClientRect = () => box(0 - offset, 100 - offset); + second.getBoundingClientRect = () => box(100 - offset, 200 - offset); + const handle = first.querySelector('button') as HTMLButtonElement; + const report = vi.fn(); + const drag = createColumnDrag({ + keys: () => ['a', 'b'], + headerOf: key => (key === 'a' ? first : second), + handleAt: target => + target instanceof Node && handle.contains(target) + ? {key: 'a', handle} + : null, + scrollArea: () => area, + rangeFrom: () => ({start: 0, end: 1}), + showLine: () => {}, + hideLine: () => {}, + endMode: () => {}, + announce: () => {}, + messages: () => ({ + place: () => '', + refused: () => '', + itemAt: () => '', + modeDone: () => '', + pickedUp: () => '', + dropped: () => '', + cancelled: () => '', + }), + report, + }); + const detach = drag.attach(false); + const mouse = {pointerType: 'mouse', pointerId: 1, button: 0, clientY: 20}; + fireEvent.pointerDown(handle, {...mouse, clientX: 50}); + fireEvent.pointerMove(area, {...mouse, clientX: 60}); + expect(drag.isActive()).toBe(true); + detach(); + expect(drag.isActive()).toBe(false); + expect(report).not.toHaveBeenCalled(); + }); + it('cancels a drag whose handle leaves the page', () => { + vi.useFakeTimers({ + toFake: [ + 'setInterval', + 'clearInterval', + 'setTimeout', + 'clearTimeout', + 'requestAnimationFrame', + 'cancelAnimationFrame', + 'performance', + ], + }); + const area = document.createElement('div'); + area.innerHTML = + '' + + '
'; + document.body.append(area); + let offset = 0; + Object.defineProperties(area, { + scrollLeft: { + configurable: true, + get: () => offset, + set: (value: number) => { + offset = value; + }, + }, + scrollWidth: {configurable: true, value: 2000}, + clientWidth: {configurable: true, value: 300}, + }); + area.getBoundingClientRect = () => box(0, 300); + const table = area.querySelector('table') as HTMLTableElement; + table.getBoundingClientRect = () => box(0, 2000); + const [first, second] = Array.from(area.querySelectorAll('th')); + first.getBoundingClientRect = () => box(0 - offset, 100 - offset); + second.getBoundingClientRect = () => box(100 - offset, 200 - offset); + const handle = first.querySelector('button') as HTMLButtonElement; + const report = vi.fn(); + const drag = createColumnDrag({ + keys: () => ['a', 'b'], + headerOf: key => (key === 'a' ? first : second), + handleAt: target => + target instanceof Node && handle.contains(target) + ? {key: 'a', handle} + : null, + scrollArea: () => area, + rangeFrom: () => ({start: 0, end: 1}), + showLine: () => {}, + hideLine: () => {}, + endMode: () => {}, + announce: () => {}, + messages: () => ({ + place: () => '', + refused: () => '', + itemAt: () => '', + modeDone: () => '', + pickedUp: () => '', + dropped: () => '', + cancelled: () => '', + }), + report, + }); + const detach = drag.attach(false); + const mouse = {pointerType: 'mouse', pointerId: 1, button: 0, clientY: 20}; + fireEvent.pointerDown(handle, {...mouse, clientX: 50}); + fireEvent.pointerMove(area, {...mouse, clientX: 60}); + expect(drag.isActive()).toBe(true); + handle.remove(); + drag.release(handle); + expect(drag.isActive()).toBe(false); + detach(); + expect(drag.isActive()).toBe(false); + expect(report).not.toHaveBeenCalled(); + }); + + it('keeps the drag mark for the click a release raises, and drops it a task later or at a key when none comes', () => { + vi.useFakeTimers({ + toFake: [ + 'setInterval', + 'clearInterval', + 'setTimeout', + 'clearTimeout', + 'requestAnimationFrame', + 'cancelAnimationFrame', + 'performance', + ], + }); + const area = document.createElement('div'); + area.innerHTML = + '' + + '
'; + document.body.append(area); + let offset = 0; + Object.defineProperties(area, { + scrollLeft: { + configurable: true, + get: () => offset, + set: (value: number) => { + offset = value; + }, + }, + scrollWidth: {configurable: true, value: 2000}, + clientWidth: {configurable: true, value: 300}, + }); + area.getBoundingClientRect = () => box(0, 300); + const table = area.querySelector('table') as HTMLTableElement; + table.getBoundingClientRect = () => box(0, 2000); + const [first, second] = Array.from(area.querySelectorAll('th')); + first.getBoundingClientRect = () => box(0 - offset, 100 - offset); + second.getBoundingClientRect = () => box(100 - offset, 200 - offset); + const handle = first.querySelector('button') as HTMLButtonElement; + const report = vi.fn(); + const drag = createColumnDrag({ + keys: () => ['a', 'b'], + headerOf: key => (key === 'a' ? first : second), + handleAt: target => + target instanceof Node && handle.contains(target) + ? {key: 'a', handle} + : null, + scrollArea: () => area, + rangeFrom: () => ({start: 0, end: 1}), + showLine: () => {}, + hideLine: () => {}, + endMode: () => {}, + announce: () => {}, + messages: () => ({ + place: () => '', + refused: () => '', + itemAt: () => '', + modeDone: () => '', + pickedUp: () => '', + dropped: () => '', + cancelled: () => '', + }), + report, + }); + const detach = drag.attach(false); + const mouse = {pointerType: 'mouse', pointerId: 1, button: 0, clientY: 20}; + fireEvent.pointerDown(handle, {...mouse, clientX: 50}); + fireEvent.pointerMove(area, {...mouse, clientX: 60}); + fireEvent.pointerMove(area, {...mouse, clientX: 160}); + // Released over column b, away from the handle: no click follows. + fireEvent.pointerUp(area, {...mouse, clientX: 160}); + expect(drag.isActive()).toBe(false); + vi.runAllTimers(); + // The next Enter, Space or tap on the handle is no drag's click. + expect(drag.takeDrag(handle)).toBe(false); + // A release whose click comes in its own task still keeps the mark. + fireEvent.pointerDown(handle, {...mouse, clientX: 50}); + fireEvent.pointerMove(area, {...mouse, clientX: 60}); + fireEvent.pointerUp(handle, {...mouse, clientX: 60}); + expect(drag.takeDrag(handle)).toBe(true); + // A key drops the mark at once, ahead of any task: Enter after a drag + // whose release raised no click is no drag's click. + fireEvent.pointerDown(handle, {...mouse, clientX: 50}); + fireEvent.pointerMove(area, {...mouse, clientX: 60}); + fireEvent.pointerUp(area, {...mouse, clientX: 160}); + fireEvent.keyDown(handle, {key: 'Enter'}); + expect(drag.takeDrag(handle)).toBe(false); + detach(); + expect(report).toHaveBeenCalledTimes(1); + }); + + it("measures from the scroll area's content, inside a scrollbar on its left", () => { + const area = document.createElement('div'); + area.innerHTML = + '' + + '
'; + document.body.append(area); + // A 15 px scrollbar on the area's left, as in right-to-left. + Object.defineProperties(area, { + scrollLeft: {configurable: true, value: 0, writable: true}, + scrollWidth: {configurable: true, value: 300}, + clientWidth: {configurable: true, value: 300}, + clientLeft: {configurable: true, value: 15}, + }); + area.getBoundingClientRect = () => box(0, 315); + const table = area.querySelector('table') as HTMLTableElement; + table.getBoundingClientRect = () => box(15, 215); + const [first, second] = Array.from(area.querySelectorAll('th')); + first.getBoundingClientRect = () => box(15, 115); + second.getBoundingClientRect = () => box(115, 215); + const handle = first.querySelector('button') as HTMLButtonElement; + const lines: number[] = []; + const drag = createColumnDrag({ + keys: () => ['a', 'b'], + headerOf: key => (key === 'a' ? first : second), + handleAt: target => + target instanceof Node && handle.contains(target) + ? {key: 'a', handle} + : null, + scrollArea: () => area, + rangeFrom: () => ({start: 0, end: 1}), + showLine: x => lines.push(x), + hideLine: () => {}, + endMode: () => {}, + announce: () => {}, + messages: () => ({ + place: () => '', + refused: () => '', + itemAt: () => '', + modeDone: () => '', + pickedUp: () => '', + dropped: () => '', + cancelled: () => '', + }), + report: () => {}, + }); + const detach = drag.attach(false); + const mouse = {pointerType: 'mouse', pointerId: 1, button: 0, clientY: 20}; + fireEvent.pointerDown(handle, {...mouse, clientX: 60}); + fireEvent.pointerMove(area, {...mouse, clientX: 65}); + // Column a's centre over b's: the line after b, at b's end edge, 200 px + // into the content. + fireEvent.pointerMove(area, {...mouse, clientX: 165}); + expect(lines.at(-1)).toBe(200); + fireEvent.pointerCancel(area, {...mouse, clientX: 165}); + detach(); + }); +}); diff --git a/packages/lab/src/TableDragAndDrop/columnDrag.ts b/packages/lab/src/TableDragAndDrop/columnDrag.ts new file mode 100644 index 0000000000000..29214f7c4eaf6 --- /dev/null +++ b/packages/lab/src/TableDragAndDrop/columnDrag.ts @@ -0,0 +1,535 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file columnDrag.ts + * @input The column handles in a Table's scroll area, List's pointer input + * and edge autoscroll (`@astryxdesign/core/internal/reorder-mode`), and the + * column reorder it moves the columns through (columnReorder.ts) + * @output `createColumnDrag`: a column's drag along the inline axis. A mouse + * drags at once and a finger after a hold. A line marks the drop place + * nearest the dragged column, the scroll area scrolls near its inline + * edges, and the drop reports the move once, at the release + * @position Internal to columnReorder.ts. It reads the header cells' boxes + * and the scroll offset as a drag begins, the boxes again only once column + * windowing mounts other cells, and the offset again only after a scroll + * it did not cause, through List's scroll watch; a move reads no layout + */ + +import { + attachReorderHold, + attachReorderMouse, + autoscrollStep, + reorderAutoscroll, + type EdgeAutoscroll, + type ReorderMessages, + type ReorderPointerEvent, + type ReorderScrollWatch, + watchReorderScroll, +} from '@astryxdesign/core/internal/reorder-mode'; +import {isRtlElement as isRtl} from '@astryxdesign/core/internal/touch'; + +/** What a column drag reads from, and reports through, its reorder. */ +export interface ColumnDragHost { + keys(): ReadonlyArray; + headerOf(key: string): HTMLElement | null; + /** The column whose handle holds `target`, or null. */ + handleAt( + target: EventTarget | null, + ): {key: string; handle: HTMLElement} | null; + scrollArea(): HTMLElement | null; + /** The places, in the order, that the column at `from` can drop at. */ + rangeFrom(from: number): {start: number; end: number}; + /** Shows the insertion line at `x`, from `top` for `height`, in content px. */ + showLine(x: number, top: number, height: number): void; + hideLine(): void; + /** Ends reorder mode, if a column is in it. */ + endMode(): void; + announce(message: string): void; + messages(): ReorderMessages; + /** Reports a move, which announces `landed` once it lands, else `kept`. */ + report(move: { + readonly key: string; + readonly to: number; + readonly landed: () => string; + readonly kept: string; + }): void; +} + +/** The drags of a Table's column handles. */ +export interface ColumnDrag { + /** Attaches the pointer input to the scroll area. Returns the detach. */ + attach(isCoarsePointer: boolean): () => void; + isActive(): boolean; + /** Whether `handle`'s last press dragged, so its click is not a toggle. */ + takeDrag(handle: HTMLElement): boolean; + /** `handle` left the page: a drag from it can no longer end, so it ends. */ + release(handle: HTMLElement): void; + dispose(): void; +} + +/** A column's place for a drag: its box in the scroll area's content. */ +interface Slot { + readonly key: string; + readonly left: number; + readonly right: number; + /** + * A pinned header cell sticks where it shows, so its box is kept from the + * scroll area's visible start, not from the content's. + */ + readonly isPinned: boolean; +} + +/** + * A pinned header cell: its box from the scroll area's visible start, and + * whether it sticks at the left, so that its inner edge is its right one. + */ +interface PinnedCell { + readonly left: number; + readonly right: number; + readonly isAtLeft: boolean; +} + +interface Drag { + readonly key: string; + readonly area: HTMLElement; + /** The drop places: the header cells mounted when they were read. */ + slots: ReadonlyArray; + /** + * Every pinned header cell, such as the selection column's, from the + * scroll area's visible start: they cover the edges that scroll under + * them. + */ + pinned: ReadonlyArray; + /** The keys of those cells, in order, to tell when others mount. */ + mounted: string; + /** The dragged column's box, in the scroll area's content. */ + readonly source: {readonly left: number; readonly right: number}; + /** The column's box and the scroll area's, in the viewport, at pickup. */ + readonly sourceBox: {readonly left: number; readonly right: number}; + readonly areaBox: {readonly left: number; readonly right: number}; + readonly line: {readonly top: number; readonly height: number}; + readonly isRtl: boolean; + readonly scrollAtBegin: number; + /** The scroll offset the drag knows of, and the range it can take. */ + scroll: number; + readonly scrollRange: {readonly min: number; readonly max: number}; + /** The watch of the area for a scroll the drag did not cause. */ + readonly watch: ReorderScrollWatch; + readonly pointerAtBegin: number; + pointer: number; + /** The key of the column whose place the drop takes. */ + target: string; + readonly autoscroll: EdgeAutoscroll; +} + +export function createColumnDrag(host: ColumnDragHost): ColumnDrag { + let drag: Drag | null = null; + // The handle whose press became a drag, until its click, its next press, + // or a task after a release that raises no click. + let draggedHandle: HTMLElement | null = null; + /** Drops a mouse drag's mark a task after its release. */ + let markTimer: ReturnType | undefined; + + /** The keys of the mounted header cells: a DOM read, with no layout. */ + const mountedIn = (area: HTMLElement) => + Array.from(area.querySelectorAll('thead th'), header => + header.getAttribute('data-column-key'), + ).join('\n'); + + /** + * Where the scroll area's content starts in the viewport: inside its + * border, and inside a scrollbar on its left, as in right-to-left. + */ + const contentStart = (area: HTMLElement) => + area.getBoundingClientRect().left + area.clientLeft; + + /** Reads the mounted header cells' boxes, in the scroll area's content. */ + const measure = (area: HTMLElement, scroll: number): Slot[] => { + const start = contentStart(area); + const view = area.ownerDocument.defaultView; + return host.keys().flatMap(key => { + const header = host.headerOf(key); + if (header == null) { + return []; + } + const box = header.getBoundingClientRect(); + const isPinned = view?.getComputedStyle(header).position === 'sticky'; + const offset = (isPinned ? 0 : scroll) - start; + return [ + {key, left: box.left + offset, right: box.right + offset, isPinned}, + ]; + }); + }; + + /** + * Every pinned header cell, from the scroll area's visible start. Its + * side is its sticky inset's: a cell stuck at the left has a left inset. + */ + const measurePinned = (area: HTMLElement): PinnedCell[] => { + const start = contentStart(area); + const view = area.ownerDocument.defaultView; + const table = area.querySelector('table'); + return Array.from(table?.tHead?.rows ?? []).flatMap(row => + Array.from(row.cells).flatMap(cell => { + const style = view?.getComputedStyle(cell); + if (style?.position !== 'sticky') { + return []; + } + const box = cell.getBoundingClientRect(); + return [ + { + left: box.left - start, + right: box.right - start, + isAtLeft: style.left !== 'auto', + }, + ]; + }), + ); + }; + + /** A drop place's box in the content, at the scroll offset `scroll`. */ + const boxAt = (slot: Slot, scroll: number) => + slot.isPinned + ? {left: slot.left + scroll, right: slot.right + scroll} + : slot; + + /** The distance the dragged column has travelled in the content. */ + const travelOf = (current: Drag, scroll: number) => + current.pointer - current.pointerAtBegin + scroll - current.scrollAtBegin; + + /** + * Places the line at the drop place nearest the dragged column's centre, + * among the places it can drop at. + */ + const place = (current: Drag) => { + // A scroll the drag did not cause: its one read of the offset, before + // the drag writes. + if (current.watch.takeStale()) { + current.scroll = current.area.scrollLeft; + } + current.watch.noteWrite(); + const mounted = mountedIn(current.area); + if (mounted !== current.mounted) { + current.mounted = mounted; + current.slots = measure(current.area, current.scroll); + current.pinned = measurePinned(current.area); + } + const order = host.keys(); + const {start, end} = host.rangeFrom(order.indexOf(current.key)); + const {scroll} = current; + const center = (current.source.left + current.source.right) / 2; + const at = center + travelOf(current, scroll); + const places = current.slots.filter(slot => { + const index = order.indexOf(slot.key); + return index >= start && index <= end; + }); + // A pinned header cell covers the columns that scroll under it, so it + // takes the drop wherever the dragged column's centre is over it. + let target = places.find(slot => { + const box = boxAt(slot, scroll); + return slot.isPinned && at >= box.left && at <= box.right; + }); + let distance = Infinity; + for (const slot of target == null ? places : []) { + const box = boxAt(slot, scroll); + const gap = Math.abs((box.left + box.right) / 2 - at); + if (gap < distance) { + target = slot; + distance = gap; + } + } + current.target = target?.key ?? current.key; + if (target == null || target.key === current.key) { + host.hideLine(); + return; + } + // Before the target toward the order's start, after it toward its end. + const isTowardStart = + order.indexOf(target.key) < order.indexOf(current.key); + const box = boxAt(target, scroll); + const x = isTowardStart !== current.isRtl ? box.left : box.right; + host.showLine( + clearOfPinned(current, x, scroll), + current.line.top, + current.line.height, + ); + }; + + /** + * Where the line at `x` shows: pinned header cells cover the edges that + * scroll under them, so the line stands at the inner edge of the pinned + * run it falls in, where the dropped column comes into view. + */ + const clearOfPinned = (current: Drag, x: number, scroll: number) => { + let shown = x; + // Each step leaves one pinned cell, so a run of them takes one step each. + // A line at a pinned cell's own edge marks the place beside it and + // stays, unless an earlier step moved it there. + for (let step = 0; step <= current.pinned.length; step++) { + const isMoved = shown !== x; + const cover = current.pinned.find(pinned => { + const left = pinned.left + scroll; + const right = pinned.right + scroll; + return pinned.isAtLeft + ? shown > left - (isMoved ? 1 : 0) && shown < right + : shown > left && shown < right + (isMoved ? 1 : 0); + }); + if (cover == null) { + break; + } + shown = scroll + (cover.isAtLeft ? cover.right : cover.left); + } + return shown; + }; + + /** + * The signed distance the next autoscroll tick scrolls: toward the inline + * edge the dragged column passes, as a List row's drag scrolls toward a + * block edge. + */ + const stepOf = (current: Drag) => { + const moved = current.pointer - current.pointerAtBegin; + const forward = autoscrollStep( + current.sourceBox.right + moved - current.areaBox.right, + ); + return forward !== 0 + ? forward + : -autoscrollStep( + current.areaBox.left - (current.sourceBox.left + moved), + ); + }; + + const begin = (key: string, handle: HTMLElement, pointer: number) => { + // One drag at a time: the handles take no press while it runs, as a + // List's do. + if (drag != null) { + return; + } + // A drag ends reorder mode, keeping its moves, and says so. + host.endMode(); + const area = host.scrollArea(); + const header = host.headerOf(key); + const table = area?.querySelector('table'); + if (area == null || header == null || table == null) { + return; + } + const areaBox = area.getBoundingClientRect(); + const sourceBox = header.getBoundingClientRect(); + const tableBox = table.getBoundingClientRect(); + const scroll = area.scrollLeft; + const scrollMax = area.scrollWidth - area.clientWidth; + const isRtlHeader = isRtl(header); + const offset = scroll - areaBox.left - area.clientLeft; + const current: Drag = { + key, + area, + slots: measure(area, scroll), + pinned: measurePinned(area), + mounted: mountedIn(area), + source: { + left: sourceBox.left + offset, + right: sourceBox.right + offset, + }, + sourceBox: {left: sourceBox.left, right: sourceBox.right}, + areaBox: {left: areaBox.left, right: areaBox.right}, + line: { + top: tableBox.top - areaBox.top + area.scrollTop - area.clientTop, + height: tableBox.height, + }, + isRtl: isRtlHeader, + scrollAtBegin: scroll, + scroll, + // A right-to-left scroll offset runs from 0 down to minus its range. + scrollRange: isRtlHeader + ? {min: -scrollMax, max: 0} + : {min: 0, max: scrollMax}, + watch: watchReorderScroll(area, () => { + if (drag === current) { + place(current); + } + }), + pointerAtBegin: pointer, + pointer, + target: key, + autoscroll: reorderAutoscroll({ + step: () => (drag === current ? stepOf(current) : 0), + apply: delta => { + // A scroll the drag did not cause, read before the drag writes, + // so that the tick goes on from it rather than undoing it. + const isStale = current.watch.takeStale(); + if (isStale) { + current.scroll = area.scrollLeft; + } + const before = current.scroll; + const {min, max} = current.scrollRange; + const next = Math.min(max, Math.max(min, before + delta)); + if (next === before) { + // At the scroll end, a scroll read here still moves the line. + if (isStale) { + place(current); + } + return 0; + } + current.watch.noteOwnScroll(); + current.scroll = next; + area.scrollLeft = next; + place(current); + return next - before; + }, + }), + }; + drag = current; + draggedHandle = handle; + // Column windowing keeps a focused column mounted while a drag scrolls + // it away. A press does not focus a button in every browser. + handle.focus({preventScroll: true}); + const order = host.keys(); + host.announce( + host.messages().pickedUp(order.indexOf(key) + 1, order.length), + ); + }; + + const end = (isCancelled: boolean) => { + const current = drag; + if (current == null) { + return; + } + // A scroll the drag did not cause just before the release, which the + // watch has not folded in yet, still moves the drop, as a List's does. + if (!isCancelled && current.watch.takeStale()) { + current.scroll = current.area.scrollLeft; + place(current); + } + drag = null; + current.autoscroll.stop(); + current.watch.stop(); + host.hideLine(); + const order = host.keys(); + const from = order.indexOf(current.key); + const messages = host.messages(); + if (isCancelled) { + host.announce(messages.cancelled(from + 1, order.length)); + return; + } + const to = order.indexOf(current.target); + if (current.target === current.key || to < 0) { + host.announce(messages.dropped(from + 1, order.length)); + return; + } + host.report({ + key: current.key, + to, + landed: () => messages.dropped(to + 1, order.length), + kept: messages.cancelled(from + 1, order.length), + }); + }; + + const onGesture = (handle: HTMLElement, event: ReorderPointerEvent) => { + const column = host.handleAt(handle); + if (column == null) { + return; + } + switch (event.state) { + case 'began': + begin(column.key, handle, event.x); + return; + case 'changed': + if (drag?.key === column.key) { + drag.pointer = event.x; + place(drag); + drag.autoscroll.update(); + } + return; + case 'ended': + case 'cancelled': + if (drag?.key === column.key) { + end(event.state === 'cancelled'); + } + return; + } + }; + + // While a drag runs, no handle takes a press: a second pointer's press + // would end the drag's own press without an end. + const handleOf = (target: EventTarget | null) => + drag == null ? (host.handleAt(target)?.handle ?? null) : null; + + return { + attach: isCoarsePointer => { + const area = host.scrollArea(); + if (area == null) { + return () => {}; + } + const mouse = attachReorderMouse(area, () => isCoarsePointer, { + handleOf, + onPress: () => { + draggedHandle = null; + }, + onGesture: (handle, event) => { + onGesture(handle, event); + // The click a release on the handle raises comes in this task and + // takes the mark. A release away from the handle raises none: the + // mark goes a task later, so the next tap or click on the handle + // starts reorder mode. + if (event.state === 'ended' || event.state === 'cancelled') { + clearTimeout(markTimer); + markTimer = setTimeout(() => { + if (drag == null && draggedHandle === handle) { + draggedHandle = null; + } + }, 0); + } + }, + }); + const head = area.querySelector('thead') ?? area; + const detachHold = attachReorderHold(head, isCoarsePointer, { + handleOf, + onGesture: (handle, event) => { + onGesture(handle, event); + // A hold's lift raises no click to take the mark, so the next tap + // or key on the handle starts reorder mode. + if ( + (event.state === 'ended' || event.state === 'cancelled') && + draggedHandle === handle + ) { + draggedHandle = null; + } + }, + }); + // No key is part of a release, and the input may run a key's click + // ahead of the task that drops the mark: a key on a handle drops it + // first, so Enter or Space after a drag starts reorder mode. + const dropMarkOnKey = () => { + if (drag == null) { + draggedHandle = null; + } + }; + area.addEventListener('keydown', dropMarkOnKey, true); + return () => { + area.removeEventListener('keydown', dropMarkOnKey, true); + mouse.detach(); + detachHold(); + // A drag the detached input was running can no longer end: it is + // cancelled, so the handles take presses and toggles again. + end(true); + }; + }, + isActive: () => drag != null, + takeDrag: handle => { + const dragged = draggedHandle === handle; + draggedHandle = null; + return dragged; + }, + release: handle => { + if (drag != null && draggedHandle === handle) { + end(true); + } + }, + dispose: () => { + clearTimeout(markTimer); + drag?.autoscroll.stop(); + drag?.watch.stop(); + drag = null; + }, + }; +} diff --git a/packages/lab/src/TableDragAndDrop/columnReorder.ts b/packages/lab/src/TableDragAndDrop/columnReorder.ts index bf2a7a90b0596..5c30dcb109ce5 100644 --- a/packages/lab/src/TableDragAndDrop/columnReorder.ts +++ b/packages/lab/src/TableDragAndDrop/columnReorder.ts @@ -6,8 +6,9 @@ * render's options and strings, and the announcer inside the table * @output `createColumnReorder`: the reorder of a Table's columns along the * inline axis. Reorder mode moves a column one place per arrow key or hint - * button. An insertion line marks the edge the column came in through, and - * every move reports once and announces once, after it lands + * button, and a drag of its handle (columnDrag.ts) drops it once, at the + * release. An insertion line marks the new place, and every move reports + * once and announces once, after it lands * @position Internal to useTableDragAndDropColumns.tsx. It lives outside * React, and a commit of the table lands its moves */ @@ -19,6 +20,7 @@ import { type ReorderMessages, } from '@astryxdesign/core/internal/reorder-mode'; import type {AnnounceFn} from '@astryxdesign/core/hooks'; +import {createColumnDrag} from './columnDrag'; /** The latest render's options and strings. */ export interface ColumnReorderConfiguration { @@ -57,6 +59,8 @@ export interface ColumnReorder { setAnnouncer(announcer: {readonly current: AnnounceFn} | null): void; setScrollArea(area: RefObject): void; setLine(line: HTMLDivElement | null): void; + /** Attaches the drags to the scroll area. Returns the detach. */ + attachDrags(isCoarsePointer: boolean): () => void; /** Runs after each commit of the table: a reported move lands. */ commit(): void; dispose(): void; @@ -69,24 +73,6 @@ interface PendingMove { readonly kept: string; } -/** - * Whether the column at `to` bounds a move of the one at `from`: it is in a - * run of kept columns at an end of `order`. A kept column in the middle is - * passed. - */ -export function boundsMove( - order: ReadonlyArray, - isMovable: (key: string) => boolean, - from: number, - to: number, -): boolean { - const {start, end} = movableRange( - order.map(key => ({top: 0, height: 0, isFixed: !isMovable(key)})), - from, - ); - return to < start || to > end; -} - export function createColumnReorder( hintId: string, configuration: {readonly current: ColumnReorderConfiguration}, @@ -198,7 +184,8 @@ export function createColumnReorder( if (from < 0 || modeKey !== key || to < 0 || to >= order.length) { return; } - if (boundsMove(order, isMovable, from, to)) { + const {start, end} = rangeFrom(from); + if (to < start || to > end) { announce(messages().refused(nameAt(order, to))); return; } @@ -218,6 +205,39 @@ export function createColumnReorder( notify(); }; + const rangeFrom = (from: number) => + movableRange( + keys().map(key => ({top: 0, height: 0, isFixed: !isMovable(key)})), + from, + ); + + const drag = createColumnDrag({ + keys, + headerOf, + handleAt: target => { + for (const [key, handle] of handles) { + if (target instanceof Node && handle.contains(target)) { + return {key, handle}; + } + } + return null; + }, + scrollArea: () => scrollArea?.current ?? null, + rangeFrom, + showLine: (x, top, height) => { + if (line != null) { + line.style.translate = `${x - 1}px ${top}px`; + line.style.blockSize = `${height}px`; + line.hidden = false; + } + }, + hideLine, + endMode: () => reorder.endMode(), + announce, + messages, + report: move => report(move), + }); + const reorder: ColumnReorder = { hintId, subscribe: listener => { @@ -240,11 +260,24 @@ export function createColumnReorder( handles.delete(key); releases.delete(key); } + // A handle that leaves the page mid-drag cancels the drag, as a + // List's does. One React only re-attaches stays on the page. + queueMicrotask(() => { + if (!element.isConnected) { + drag.release(element); + } + }); }; releases.set(key, release); return release; }, toggle: key => { + const handle = handles.get(key); + // The click that ends a drag from the handle is not a toggle, and no + // handle toggles while a drag runs. + if (drag.isActive() || (handle != null && drag.takeDrag(handle))) { + return; + } if (modeKey === key) { reorder.endMode(); } else if (isMovable(key)) { @@ -323,6 +356,7 @@ export function createColumnReorder( setLine: element => { line = element; }, + attachDrags: isCoarsePointer => drag.attach(isCoarsePointer), commit: () => { const order = keys(); if (pending != null && order[pending.to] === pending.key) { @@ -350,9 +384,12 @@ export function createColumnReorder( modeKey = null; notify(); } - placeModeLine(); + if (!drag.isActive()) { + placeModeLine(); + } }, dispose: () => { + drag.dispose(); if (pendingTimer != null) { clearTimeout(pendingTimer); pendingTimer = null; diff --git a/packages/lab/src/TableDragAndDrop/useTableDragAndDropColumns.doc.mjs b/packages/lab/src/TableDragAndDrop/useTableDragAndDropColumns.doc.mjs index 13f6b27aa6691..efa81ed04d7dd 100644 --- a/packages/lab/src/TableDragAndDrop/useTableDragAndDropColumns.doc.mjs +++ b/packages/lab/src/TableDragAndDrop/useTableDragAndDropColumns.doc.mjs @@ -26,6 +26,6 @@ export default { ], usage: { description: - "Reorders a Table's columns by keyboard and by taps. The handle turns on reorder mode: Left and Right move the column one place at a time, mirrored in right-to-left, and Escape or the handle again ends the mode. A hint below the handle offers the moves and Done as buttons, so a pointer or a finger can also reorder by taps. The reorderable's start(key) turns on reorder mode for a column from the app's own action, such as a Move column menu item. Screen readers hear each move with the column's place and its neighbours. With column windowing, the columns stay windowed, and each move and place counts every column in columnKeys. A pinned column keeps its pin as it moves; keep it in place with isReorderable when it must stay first.", + "Reorders a Table's columns by dragging and by keyboard. A mouse, or a pen where the primary pointer is fine, drags a column sideways by its handle at once; a finger, or a pen where the primary pointer is coarse, after a hold: a line marks where it will land, the table scrolls when the column nears its edge, and the columns move once, at the drop. Without a drag, the handle turns on reorder mode: Left and Right move the column one place at a time, mirrored in right-to-left, and Escape or the handle again ends the mode. A hint below the handle offers the moves and Done as buttons, so a pointer or a finger can also reorder by taps. The reorderable's start(key) turns on reorder mode for a column from the app's own action, such as a Move column menu item. Screen readers hear each move with the column's place and its neighbours. With column windowing, the columns stay windowed, and each move and place counts every column in columnKeys. A pinned column keeps its pin as it moves; keep it in place with isReorderable when it must stay first.", }, }; diff --git a/packages/lab/src/TableDragAndDrop/useTableDragAndDropColumns.tsx b/packages/lab/src/TableDragAndDrop/useTableDragAndDropColumns.tsx index 87c5b613be196..d7943e86fde5a 100644 --- a/packages/lab/src/TableDragAndDrop/useTableDragAndDropColumns.tsx +++ b/packages/lab/src/TableDragAndDrop/useTableDragAndDropColumns.tsx @@ -7,12 +7,12 @@ * @input A reorderable object made by createReorderable, the keys of the * columns it orders, and a Table's header cells * @output `useTableDragAndDropColumns`, a Table plugin that puts a reorder - * handle in the header cell of each of those columns. A column moves by - * keyboard or by the hint's buttons in reorder mode, and each move reports + * handle in the header cell of each of those columns. A column drags by + * its handle, or moves by keyboard in reorder mode, and each move reports * its key and its index after the move among the keys * @position Lab Table plugin. Core's reorder session moves rows along the - * block axis only, so this plugin runs the same reorder mode, strings and - * hint along the inline axis + * block axis only, so this plugin runs the same reorder mode, strings, + * hint and pointer input along the inline axis */ import { @@ -50,6 +50,7 @@ import {reorderHandle} from '@astryxdesign/core/internal/reorderHandle.stylex'; import { touchHitAreaStyles, useTouchHitArea, + useTouchPresentation, } from '@astryxdesign/core/internal/touch'; import type {TableColumn, TablePlugin} from '@astryxdesign/core/Table'; import {colorVars, spacingVars} from '@astryxdesign/core/theme/tokens.stylex'; @@ -126,6 +127,13 @@ const styles = stylex.create({ ':is(:disabled,[aria-disabled="true"])': 'default', }, userSelect: 'none', + // Until a finger's hold claims the drag, a flick on the handle scrolls + // the table, as a List row's handle does. + touchAction: { + default: null, + '@media (pointer: coarse)': 'manipulation', + }, + WebkitTapHighlightColor: 'transparent', }, pressed: { backgroundColor: { @@ -145,7 +153,7 @@ const styles = stylex.create({ position: 'relative', }, // The insertion line: it stands between two header cells, the full height - // of the table, while reorder mode marks a column's new place. + // of the table, while a drag or reorder mode marks a column's new place. line: { position: 'absolute', insetBlockStart: 0, @@ -260,10 +268,15 @@ function ColumnReorderHost({reorder}: {reorder: ColumnReorder}): ReactNode { reorder.setAnnouncer(announcer); return () => reorder.setAnnouncer(null); }, [reorder, announcer]); + // A finger drags after a hold under every primary pointer; a pen does + // where the primary pointer is coarse. + const {isTouch} = useTouchPresentation(); // Syncs the reorder, which lives outside React, with this commit's columns. useLayoutEffect(() => { reorder.commit(); }); + // External system: the pointer input on the table's scroll area. + useLayoutEffect(() => reorder.attachDrags(isTouch), [reorder, isTouch]); return ( <>