An open source design system that's fully customizable and agent ready
TypeScript
feat(core): createReorderable makes List rows reorderable (#8139)
Christopher Chedeaua28d586eb28e
diff --git a/.changeset/cli-hook-docs-create.md b/.changeset/cli-hook-docs-create.mdnew file mode 100644index 0000000000..bfce77fd95--- /dev/null+++ b/.changeset/cli-hook-docs-create.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[feat] `astryx` lists a `create…` factory documented as a hook, such as `createReorderable`, with the hooks.++@vjeuxdiff --git a/.changeset/list-reorder-mode-hint.md b/.changeset/list-reorder-mode-hint.mdnew file mode 100644index 0000000000..a5dad52a05--- /dev/null+++ b/.changeset/list-reorder-mode-hint.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] While a reorderable `List` row is in reorder mode, a hint anchored to its handle, in the keyboard hint's layer and theme roles, shows the moves and Done. Each is a button that does what its key does and leaves the focus on the handle, so a row can be reordered by taps alone: the handle, the moves, then Done.++@vjeuxdiff --git a/.changeset/list-reorderable.md b/.changeset/list-reorderable.mdnew file mode 100644index 0000000000..47f7a9140a--- /dev/null+++ b/.changeset/list-reorderable.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] `createReorderable({onReorder, isReorderable})` makes a collection's reorder behavior, and `List` takes it as `reorderable`: each `ListItem` with an `itemKey` gets a reorder handle at its end, and each committed move calls `onReorder({key, to})` once, with the row's key and its index after the move. On a touch screen a finger held still on a handle picks up its row the way an iOS table's reorder control does (a flick on it still scrolls): the row stays in its place, dimmed, while a copy of it follows the finger and an accent line marks where it would land; the other rows stay still, the page scrolls near the edges, and on release the rows rearrange, gliding to their new places. A pen held on a handle picks up its row the same way where the primary pointer is coarse. A mouse, or a pen where the primary pointer is fine, drags a handle at once with the same copy and line, and rows take their places without motion; a cancelled drag puts everything back at once. Without a drag, a click, Space or Enter on a handle turns on reorder mode for its row: the insertion line marks the row's place, each arrow key moves it a place at once, announced with its place and neighbours, and Escape or another activation ends the mode, keeping the moves. The object's `start(key)` enters the same mode from the app's own UI, such as a row's context menu. A List without `reorderable` loads none of the reorder code.++@vjeuxdiff --git a/apps/storybook/stories/List.stories.tsx b/apps/storybook/stories/List.stories.tsxindex 34a26bdbff..2c73025f79 100644--- a/apps/storybook/stories/List.stories.tsx+++ b/apps/storybook/stories/List.stories.tsx@@ -7,10 +7,11 @@* @position Storybook demonstrations for List consumers*/-import {useEffect, useRef, useState} from 'react';+import {useEffect, useMemo, useRef, useState} from 'react';import * as stylex from '@stylexjs/stylex';import type {Meta, StoryObj} from '@storybook/react';import {List, ListItem} from '@astryxdesign/core/List';+import {createReorderable} from '@astryxdesign/core';import {Avatar} from '@astryxdesign/core/Avatar';import {Badge} from '@astryxdesign/core/Badge';import {Button} from '@astryxdesign/core/Button';@@ -21,6 +22,7 @@ import {Heading, Text} from '@astryxdesign/core/Text';import {VStack} from '@astryxdesign/core/Layout';import {useAnimatedLayout} from '@astryxdesign/core/hooks';import {rtlStyles} from '@astryxdesign/core/utils';+import {ContextMenu} from '@astryxdesign/core/ContextMenu';import {Cog6ToothIcon,BellIcon,@@ -914,3 +916,178 @@ export const AnimatedChangesSwipe: Story = {},},};++function moveKey(+ rows: ReadonlyArray<string>,+ key: unknown,+ to: number,+): string[] {+ const next = rows.filter(row => row !== key);+ next.splice(to, 0, key as string);+ return next;+}++function ReorderDemo({+ initial,+ pinned = [],+ edge,+}: {+ initial: ReadonlyArray<string>;+ pinned?: ReadonlyArray<string>;+ edge?: 'padded' | 'flush';+}) {+ const [rows, setRows] = useState(initial);+ return (+ <List+ hasDividers+ edge={edge}+ reorderable={createReorderable({+ onReorder: ({key, to}) => setRows(current => moveKey(current, key, to)),+ isReorderable: key => !pinned.includes(key as string),+ })}>+ {rows.map(label => (+ <ListItem key={label} itemKey={label} label={label} />+ ))}+ </List>+ );+}++export const Reorderable: Story = {+ render: () => (+ <ReorderDemo+ initial={['Inbox', 'Sent', 'Drafts', 'Archive', 'Spam', 'Trash']}+ />+ ),+ parameters: {+ docs: {+ description: {+ story:+ 'With `reorderable` (from `createReorderable`), each row with an ' ++ '`itemKey` gets a reorder handle. On a touch screen, hold a handle ' ++ 'for a moment, then drag: the row dims in place, a copy follows ' ++ 'your finger and a line marks where it will land, and the rows ' ++ 'rearrange on release. A mouse drags a handle at once, the same ' ++ 'way. Or activate a handle (click it, or press Space ' ++ 'or Enter) to turn on reorder mode for its row: each arrow key, or ' ++ 'each move in the hint below the handle, moves it a place, and ' ++ 'Escape or Done ends the mode.',+ },+ },+ },+};++export const ReorderFlush: Story = {+ render: () => (+ <ReorderDemo+ initial={['Inbox', 'Sent', 'Drafts', 'Archive']}+ edge="flush"+ />+ ),+ parameters: {+ docs: {+ description: {+ story:+ 'With `edge="flush"` the rows have no side padding, so each ' ++ "reorder handle ends at the row's edge, inside the list.",+ },+ },+ },+};++export const ReorderWithPinnedRows: Story = {+ render: () => (+ <ReorderDemo+ initial={['Favorites', 'Inbox', 'Sent', 'All mail', 'Drafts', 'Spam']}+ pinned={['Favorites', 'All mail']}+ />+ ),+ parameters: {+ docs: {+ description: {+ story:+ 'A row the object’s `isReorderable` rejects has no handle. At an ' ++ 'end of the list it also bounds the others (nothing drops above ' ++ 'Favorites); in the middle, other rows move past it.',+ },+ },+ },+};++function ReorderFromYourUIDemo() {+ const [rows, setRows] = useState([+ 'Inbox',+ 'Sent',+ 'Drafts',+ 'Archive',+ 'Spam',+ 'Trash',+ ]);+ const [selected, setSelected] = useState('Sent');+ const reorderable = useMemo(+ () =>+ createReorderable({+ onReorder: ({key, to}) => setRows(current => moveKey(current, key, to)),+ }),+ [],+ );+ return (+ <VStack gap={2}>+ <Button+ label={`Move ${selected}`}+ onClick={() => reorderable.start(selected)}+ />+ <ContextMenu+ label="Row actions"+ items={[+ {+ label: `Move ${selected}`,+ onClick: () => reorderable.start(selected),+ },+ ]}>+ <List hasDividers reorderable={reorderable}>+ {rows.map(label => (+ <ListItem+ key={label}+ itemKey={label}+ label={label}+ isSelected={label === selected}+ onClick={() => setSelected(label)}+ />+ ))}+ </List>+ </ContextMenu>+ </VStack>+ );+}++export const ReorderFromYourUI: Story = {+ render: () => <ReorderFromYourUIDemo />,+ parameters: {+ docs: {+ description: {+ story:+ 'The object’s `start(key)` turns on reorder mode for a row from ' ++ 'your own UI, here a button and the list’s context menu: the ' ++ 'focus moves to the row’s handle, and its arrow keys, hint and ' ++ 'Done work as they do from the handle.',+ },+ },+ },+};++export const ReorderLongList: Story = {+ render: () => (+ <ReorderDemo+ initial={Array.from({length: 30}, (_, index) => `Item ${index + 1}`)}+ />+ ),+ parameters: {+ docs: {+ description: {+ story:+ 'Dragging a row near the top or bottom of the screen scrolls the ' ++ 'page, faster the further past the edge the row goes.',+ },+ },+ },+};diff --git a/docs/architecture/react-component-runtime.md b/docs/architecture/react-component-runtime.mdindex 7744827d0d..50fa9a1cc9 100644--- a/docs/architecture/react-component-runtime.md+++ b/docs/architecture/react-component-runtime.md@@ -374,9 +374,12 @@ those contracts.measuring in JS, as `architecture:component-style-authoring` INV2 prefers. Aper-frame, scroll or resize path reads no layout, except a read a currentclause requires there: `architecture:layer-runtime`'s placement re-reads,- INV11's keyboard read, and INV12's and `component:Resizable` FR8's- before-and-after measurement. Each such read happens in one batched- measurement pass per change, never interleaved with writes. A read is one+ INV11's keyboard read, INV12's and `component:Resizable` FR8's+ before-and-after measurement, and the reorder drag's scroll read: during a+ reorder drag, the engine reads its scroller's scroll offset once per frame+ after a scroll it didn't cause, before its writes. Each such read happens+ in one batched measurement pass per change, never interleaved with writes.+ A read is onemeasurement pass: a remaining read names its reason in a comment and happensonce per change, not per frame, or as the before-and-after pair a currentclause requires. INV11's keyboard hook, which makes at most one layout read@@ -541,3 +544,4 @@ component suite is not blanket conformance with every invariant.| INV16 | Review of each Core component that handles a concern Core owns in a shared hook or utility | A Core component that keeps its own effect, listener, or tracker for that concern fails, whether or not it also calls the hook or utility || INV16 (slot presence) | `no-nullish-jsx-guard` strict lint over Core and RichText, with no baseline, and `no-truthy-jsx-guard` strict lint over Core, with no baseline; both catch inline guards only, so review also checks for a presence test hoisted into a variable, converted (`!!value`, `Boolean(value)`), made by an early return or a `??` default, or passed through a prop spread, which the lints pass; empty-slot tests that pass `''`, `false`, `true`, and `null` and compare with an omitted slot, plus `0` as content, in Item, MetadataList, ChatSystemMessage, TreeList, TopNavMegaMenu, RichTextEditor, and RichTextEditorToolbar | A slot given `''`, `true`, or `false` draws a wrapper, lane, border, or separator that an omitted slot does not, an element loses the name it has without the slot, `0` does not render, or a new bare nullish or truthiness presence test, inline or hoisted, a truthiness guard past the baseline, a baseline entry added, or a hand-written copy of the check lands || INV18 | Review of every added read that forces layout: `getBoundingClientRect`, `getClientRects`, `offset*`, `client*`, `scroll*` (`scrollTop`, `scrollHeight`, and the rest), `inner*` and `outer*`, `visualViewport` geometry, and `getComputedStyle` (evidence gap: no automated finding yet) | A layout read in a per-frame, scroll or resize path that no current clause requires there, a read interleaved with writes, a read without a comment that names its reason, more than one measurement pass per change beyond the before-and-after pair a current clause requires, or JavaScript measurement where CSS placement serves |+| INV18 reorder | Browser tests of a mouse drag in a reorderable List while a wheel scrolls its scroller: one checks the preview, the drop line and the drop, and one traces layout and counts the offset reads | A wheel scroll mid-drag that leaves the drop line or the preview off the pointer, a drop away from the pointer, a layout the read forces, or more than one read in a scrolled frame |diff --git a/docs/families/overlay-dismissal.md b/docs/families/overlay-dismissal.mdindex bf3c1efa64..acc9c375f3 100644--- a/docs/families/overlay-dismissal.md+++ b/docs/families/overlay-dismissal.md@@ -26,6 +26,7 @@ verified_by:packages/core/src/Dialog/__tests__/DialogSecondDocument.a11y.browser.spec.ts,packages/core/src/BottomSheet/__tests__/BottomSheetCloseScroll.a11y.browser.spec.ts,packages/core/src/Dialog/__tests__/DialogCloseScroll.a11y.browser.spec.ts,+ packages/core/src/List/__tests__/ListReorder.test.tsx,]members:[@@ -66,6 +67,7 @@ members:component:TourStep,component:ChatEmojiPicker,component:Table,+ component:List,]architecture: [architecture:public-component-api]contributing: []@@ -133,7 +135,7 @@ this record's current membership snapshot must be updated with it.for supporting or disabled text does not make the input itself a member.- **Other component-owned popups:** BreadcrumbItem, SideNavHeading,SideNavItem, TabMenu, TopNavHeading, TopNavMenu, TopNavMegaMenu, Table filtering,- Lab TourStep, and Lab ChatEmojiPicker.+ List's reorder-mode hint, Lab TourStep, and Lab ChatEmojiPicker.- **Collaborators:** `useLayerDismissal`, `layerStack`, `LayerDepthProvider`,and `useFocusTrap` own or adapt the shared protocol.- **Nonparticipating layers:** A layer that has no dismissal behavior is not a@@ -288,6 +290,7 @@ this record's current membership snapshot must be updated with it.| Focus traps with `onEscape` | shared owner through `useFocusTrap` | They provide DOM containment, not descendant depth || BreadcrumbItem, ChatComposerInput, ComplexSelector, DateInput, DateRangeInput, DateTimeInput, Selector, MultiSelector, PowerSearch, BaseTypeahead, Typeahead, Tokenizer, SideNavHeading, SideNavItem, TabMenu, TopNavHeading, TopNavMenu, TopNavMegaMenu, Table, Lab TourStep, Lab ChatEmojiPicker | shared owner through `usePopover` or a composed Popover owner | Table filtering owns controlled Popover state and discards its draft on close; TourStep routes Popover close to the Tour; ChatEmojiPicker owns controlled Popover state || DropdownMenu root, MoreMenu, ContextMenu, Selector, MultiSelector, TopNavHeading, TopNavMenu, TopNavMegaMenu, SideNavHeading, SideNavItem, BottomSheet, BottomSheetSwitcher, Lightbox | shared owner | Implementation gap: in another document (for BottomSheet, BottomSheetSwitcher and Lightbox, a Picture-in-Picture window), each decides focus return from the page's document and last input, so focus returns to the frame element or the page, or without the ring the last input in its document calls for (FR9) |+| List's reorder-mode hint | shared owner, registered while reorder mode is on | none || DropdownMenuSubMenu, PowerSearchEditPopover | local only | Must migrate from component-specific listeners or registries to the shared owner |The rows marked partial or local are current adoption gaps against FR1, and the@@ -305,6 +308,7 @@ modality, positioning, outside-dismissal, and open-state contracts.| FR2, FR3, FR4, FR6 | `layerDismissalInvariants.test.tsx` | nested same-DOM Dialogs, Lightbox over Dialog, Dialog in BottomSheet, platform cancel, IME | One request closes two surfaces, closes a host before its child, or dismisses during composition || FR1, FR2, FR3, FR7 | `layerDismissalFamilies.test.tsx` | Dialog, Lightbox, MobileNav, BottomSheet, Tooltip, HoverCard; controlled and blocking states | A family bypasses the stack, a lower member handles a request, or controlled ownership is ignored || FR1 | `useFocusTrap.test.tsx` | active, nested, and deactivated traps with `onEscape` | A dismissible trap stays off the shared stack or nested traps respond together |+| FR1, FR2 | `ListReorder.test.tsx` | List's reorder-mode hint holding the focus, above an open layer | Escape reaches the layer below, or reorder mode outlives the Escape || FR8 | `useLayerDismissal.test.tsx`; `Popover.test.tsx` | members in the page and a same-origin iframe; a Popover alone and inside a Dialog, in an iframe | A press in one document dismisses a member of another, or a host closes over its nested layer || FR8 | `PopoverSecondDocument.a11y.chromium.spec.ts` | a Popover in an iframe and in a Picture-in-Picture window, alone and with one open in the page | A press in the second document misses its own layer or dismisses the page's || FR9 | `DialogSecondDocument.a11y.browser.spec.ts` | a Dialog in an iframe and in a Picture-in-Picture window, closed by Escape or a control inside it, and a Dialog in an iframe opened from the page | Focus lands outside the opener's document, or its ring does not follow the closing input |diff --git a/docs/specs/AST-103-reorderable/spec.md b/docs/specs/AST-103-reorderable/spec.mdindex 52ccadc076..1ef0f3dcf8 100644--- a/docs/specs/AST-103-reorderable/spec.md+++ b/docs/specs/AST-103-reorderable/spec.md@@ -119,6 +119,8 @@ const {detach} = reorderable.attach(listElement, {nearest the dragged item's center, and a dropped item settles on that slot's center.An array whose length differs from the item count is ignored, as is`positions` in a tree; drop positions then come from the measured layout.+ Implementation gap: not built; `positions` does not exist yet, so drop+ positions always come from the measured layout.Without `positions`, drop positions come from the measured layout;in the callback, `key` names the moved item by its key and `to` is the index the item has after the move, counted in thecollection's full item order (every item it was given, mounted or not). In a@@ -182,6 +184,8 @@ const {detach} = reorderable.attach(listElement, {fine, a drag from the handle starts without a hold; a finger, or a penwhere the primary pointer is coarse, keeps the hold, which picks the rowup at `spec:AST-094`'s values, and a flick still scrolls;+ - a held drag near the scroll container's edge scrolls it toward that edge,+ faster the nearer it is, and stops at the end;- a drag commits once, at the drop (DR4), and `onReorder` is called oncefor it; a cancelled drag calls nothing;- under Reduce Motion the moving preview still follows the finger or pointer,@@ -244,7 +248,8 @@ const {detach} = reorderable.attach(listElement, {public; `start` and the handle enter the same mode.- **FR4b — Plain elements attach without React.** The object exposes`attach(container, {items})`, where `items()` returns one- `{key, element, handle}` per item in order, and it returns `{detach}`. An+ `{key, element, handle}` per item in order, and it returns `{detach}`.+ Implementation gap: not built; the object has no `attach` yet. Anattached container gets FR3's drag, FR4's reorder mode on each handle, andtheir announcements, with no collection component; `positions` and`isReorderable` apply as they do for a collection. `attach` gives each `handle` FR4's@@ -304,6 +309,7 @@ const {detach} = reorderable.attach(listElement, {| FR1, FR6–FR8 | Public-API review, type tests, and descriptor checks | the factory's options, `ReorderableLabels`' keys included; a collection's `reorderable` type; the factory's and List's descriptors | an extra gesture, timing, or animation option, an experimental name or subpath, a missing descriptor, a second public reorder API, a string the object announces or shows that no `labels` key replaces, or a translator option, fails || FR2 | Bundle and runtime check of a collection with and without the prop | without the prop; with the prop | reorder code in the bundle, a handle, or a reorder listener without the prop fails; the measured cost is recorded in the pull request || FR3 | Browser tests with real touch input and a mouse (`spec:AST-013` FR10) | a hold and drag; a flick; a drop; a cancelled drag; Reduce Motion; a fanned hand with custom `positions`; a list without them; a `positions` array of the wrong length; a tree with `positions`; custom `positions` beside a rejected end row; a pen drag on a fine and on a coarse primary pointer | a drag that starts off the handle, a commit before the drop, two callbacks for one drag, a callback on cancel, travel under Reduce Motion, a drop that ignores `positions` of the right length, a wrong-length array or a tree whose drops do not come from the measured layout, a drop outside the drop range, a mouse drag, or a pen drag on a fine primary pointer that waits for a hold, or a pen drag on a coarse primary pointer that starts without one, or a call without `positions` whose behavior changes fails |+| FR3 autoscroll | Browser tests with a mouse of a drag held near a scroll edge, and unit tests of the autoscroll step and its timer | a row held near the page's bottom edge, and held there until the list's end is in view; a row held near the bottom of a box the list scrolls in; the step at each depth past the edge; the timer at an edge | a held drag near an edge that scrolls nothing, scrolls the page while a box holds the list, scrolls away from the edge, keeps one speed nearer the edge, or scrolls past the end fails || FR4 | Keyboard, mouse, and announcement-routing tests of reorder mode (`spec:AST-009` FR17) | entering by click, Enter, and Space; arrows in vertical, horizontal, and grid collections; Up, Down, Left, and Right in a tree; each move's announcement at the top, middle, and end; a move past a rejected row; Escape and a second activation; focus and scroll after each move | a move that does not commit at once, an announcement missing, repeated, or before render, a move past a rejected row at either end, or a mid-list rejected row that blocks a move, focus leaving the handle, or moves undone on exit fails || FR4 hint | Browser tests with a mouse, a finger, and a keyboard | the hint's axis in vertical, horizontal, and grid collections; each move button and Done; a tap-only reorder; the hint's theme roles | a hint off the keyboard hint's layer, anchoring, or theme roles, buttons that ignore taps or are hidden from assistive technology, a button whose move or announcement differs from its key, focus leaving the handle, or a hint that outlives the mode fails || FR4 two-dimensional | Keyboard and announcement-routing tests on a wrapping card grid, left-to-right and right-to-left | Left and Right across a row end; Up and Down between full rows and into a short last row; announcements with row and column; the hint's four buttons; a resize that changes the column count | a move off reading order, a mirrored direction wrong in right-to-left, a short-row move that is not clamped to its last position, a missing row or column, or a column count read from anything but layout fails |diff --git a/docs/specs/components/List/List.spec.md b/docs/specs/components/List/List.spec.mdindex 51d0d6f2f8..e499eead78 100644--- a/docs/specs/components/List/List.spec.md+++ b/docs/specs/components/List/List.spec.md@@ -19,6 +19,12 @@ verified_by:packages/core/src/List/__tests__/ListDividers.interaction.browser.spec.ts,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/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,+ packages/core/src/List/__tests__/ListReorderMode.interaction.browser.spec.ts,+ packages/core/src/List/__tests__/reorderModel.test.ts,packages/core/src/theme/derivedVarRegistry.test.ts,packages/core/src/theme/generateThemeRules.test.ts,apps/storybook/stories/List.stories.tsx,@@ -54,7 +60,7 @@ system_specs:| Behavior | One edge treatment applies to every ListItem row and decides where row content and row paint sit relative to the list's edges and the host's padding. With `reorderable`, rows reorder by dragging a handle or through reorder mode (`spec:AST-103` FR3, FR4). Under a coarse pointer a row's press follows the cell profile (`spec:AST-094` FR11); with `animatedLayout`, row updates animate (`spec:AST-105`). A row menu opens from the row's own `<li>` on the context request (FR13). || End-user impact | Row text can share the line of the list header and a heading above, with row paint stopping at the text, reaching into the host padding, or reaching the host edges. Touch users get a 44 px row target (FR10) and the cell press (FR11), and every pointer keeps a highlighted row's dividers visible (FR11); with `animatedLayout`, row updates animate for every pointer (FR12). A row with a menu opens it by a long press, a right click, or Shift+F10, or through its More actions button (FR13). || Builder impact | One `edge` choice per list. `flush` works anywhere; `outset` and `bleed` act only inside a host that publishes container padding. Passing an `animatedLayout` handle is one new choice, and a row menu is the other: the caller passes a ListItem's ref to `useContextMenu` (FR13), and who draws a plain row's More actions button is open (OQ2); and rows animate only with an `itemKey`; the touch target and press need none. |-| Compatibility/readiness | Additive; omission keeps current geometry; `edgeCompensation` keeps working with a codemod to `edge`. `reorderable` is additive and stable, specified and not implemented yet. `itemKey` and `animatedLayout`'s row updates (FR12) are implemented; its start and end content motion is not. The touch target (FR10) and the press's compositor release (FR11) are implemented under coarse primary pointers. Neither changes anything under a fine pointer. Row menus (FR13) are additive and specified, not implemented yet. |+| Compatibility/readiness | Additive; omission keeps current geometry; `edgeCompensation` keeps working with a codemod to `edge`. `reorderable` is stable and built, but for its `labels` and `positions`. `itemKey` and `animatedLayout`'s row updates (FR12) are implemented; its start and end content motion is not. The touch target (FR10) and the press's compositor release (FR11) are implemented under coarse primary pointers. Neither changes anything under a fine pointer. Row menus (FR13) are additive and specified, not implemented yet. || Review checks | Reject header movement, row paint past the host's padding edge, duplicated padding values, physical-edge logic, automatic opt-in, a ListItem-level edge prop, or a second prop that can contradict `edge`. || Governing rules | `architecture:container-padding/INV3`, `INV9–INV11`; `spec:AST-002/DEC-1–DEC-2`; `spec:AST-017/FR4`; `spec:AST-057/FR9`. `spec:AST-103`. `spec:AST-094` FR4, FR5, FR11, FR13; `spec:AST-105` FR1–FR5, FR8. `spec:AST-107` FR8 (row menus). |@@ -189,7 +195,11 @@ Consumer migration instructions belong in consumer docs and release notes.listener, state, Effect, or render pass. Deprecation warnings are dev-only.- **PR2 — Motion only where it applies.** FR11 adds no listener, observer,measurement, or animation under a fine pointer, and FR12 measures rows only- with a handle. Every motion runs on transform and opacity.+ with a handle. Every motion runs on transform and opacity. Implementation+ gap: where the primary pointer is coarse, a reorder mode move forces one+ style pass for each row that glides for the first time. The shared animator+ then reads the row's `will-change` (`architecture:react-component-runtime`+ INV18).## Accessibility contractdiff --git a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.jsonindex 80662ad048..14096788fd 100644--- a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json+++ b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json@@ -591,9 +591,7 @@"spec:AST-085","spec:AST-085"],- "packages/core/src/List/List.tsx": ["FR29", "spec:AST-017"],"packages/core/src/List/ListContext.tsx": ["DEC-6", "spec:AST-061"],- "packages/core/src/List/ListItem.tsx": ["FR11", "spec:AST-061"],"packages/core/src/Markdown/Markdown.fr23.bench.ts": ["AST-036","FR23",diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.jsonindex 88f697c342..5361edffcc 100644--- a/internal/shadcn-registry/routes.lock.json+++ b/internal/shadcn-registry/routes.lock.json@@ -4036,6 +4036,11 @@"path": "hooks/create-pan-gesture","aliases": []},+ {+ "name": "hook-create-reorderable",+ "path": "hooks/create-reorderable",+ "aliases": []+ },{"name": "hook-use-animated-layout","path": "hooks/use-animated-layout",diff --git a/packages/cli/foundation/discovery/hook-discovery.mjs b/packages/cli/foundation/discovery/hook-discovery.mjsindex 93d8e29a26..4c4a478868 100644--- a/packages/cli/foundation/discovery/hook-discovery.mjs+++ b/packages/cli/foundation/discovery/hook-discovery.mjs@@ -12,6 +12,13 @@ import {levenshteinDistance} from '../text/string-utils.mjs';const SKIP_DIRS = new Set(['utils', '__tests__', 'node_modules']);+// A hook's doc outside src/hooks/: a `use…` hook, or a `create…` factory+// documented as one (its doc typed `HookDoc`, such as createReorderable).+const HOOK_DOC_FILE_RE = /^(?:use|create)[A-Z]\w*\.doc\.mjs$/;++// Matches the top-level `relatedHooks: [...]` field in a hook .doc.mjs file.+const RELATED_HOOKS_RE = /(?:^|\n) {0,4}relatedHooks:\s*\[([^\]]*)\]/;+// Matches the top-level `category: 'categoryName'` field in a hook .doc.mjs file.const CATEGORY_RE = /(?:^|\n) {0,4}category:\s*['"]([^'"]+)['"]/;@@ -32,6 +39,25 @@ function readHookMeta(docPath) {}}+/**+ * Whether a `create…` factory's doc names its own `use…` hook in+ * `relatedHooks`, as createAnimator's names useAnimator. Such a factory is+ * listed beside that hook, not on its own.+ * @param {string} docPath+ * @param {string} hookName+ * @returns {boolean}+ */+function isBesideOwnHook(docPath, hookName) {+ if (!hookName.startsWith('create')) return false;+ const ownHook = `use${hookName.slice('create'.length)}`;+ try {+ const related = RELATED_HOOKS_RE.exec(fs.readFileSync(docPath, 'utf-8'));+ return related != null && related[1].includes(`'${ownHook}'`);+ } catch {+ return false;+ }+}+/*** Extract the hook name from a doc filename.* e.g. 'useFocusTrap.doc.mjs' → 'useFocusTrap'@@ -70,7 +96,8 @@ export function discoverHooks(coreDir) {}}- // 2. Scan ALL component directories for files matching use*.doc.mjs+ // 2. Scan ALL component directories for hook docs: use*.doc.mjs, and+ // create*.doc.mjs for a factory documented as a hook (createReorderable)if (pathExists(srcDir)) {const topEntries = listDirEntries(srcDir);for (const entry of topEntries) {@@ -120,14 +147,10 @@ function scanDirForHookDocs(dirPath, hookCategories) {for (const entry of entries) {if (entry.isDirectory() && !SKIP_DIRS.has(entry.name)) {scanDirForHookDocs(path.join(dirPath, entry.name), hookCategories);- } else if (- entry.isFile() &&- entry.name.startsWith('use') &&- entry.name.endsWith('.doc.mjs')- ) {+ } else if (entry.isFile() && HOOK_DOC_FILE_RE.test(entry.name)) {const hookName = hookNameFromFile(entry.name);- if (!hookCategories.has(hookName)) {- const docPath = path.join(dirPath, entry.name);+ const docPath = path.join(dirPath, entry.name);+ if (!hookCategories.has(hookName) && !isBesideOwnHook(docPath, hookName)) {const {category} = readHookMeta(docPath);hookCategories.set(hookName, category || 'Other');}diff --git a/packages/cli/foundation/discovery/hook-discovery.test.mjs b/packages/cli/foundation/discovery/hook-discovery.test.mjsindex 711224ae1c..7e4a09a8fa 100644--- a/packages/cli/foundation/discovery/hook-discovery.test.mjs+++ b/packages/cli/foundation/discovery/hook-discovery.test.mjs@@ -88,6 +88,51 @@ describe('discoverHooks (real core)', () => {expect(discoverHooks(core)).toEqual({Interaction: ['useResizable']});});+ it('discovers a create*.doc.mjs factory documented as a hook, but no other file', () => {+ const core = mkTmp('as-hd-factory-');+ const dir = path.join(core, 'src', 'reorderable');+ fs.mkdirSync(dir, {recursive: true});+ fs.writeFileSync(+ path.join(dir, 'createReorderable.doc.mjs'),+ "export default {\n category: 'interaction',\n};\n",+ );+ // Neither a component doc nor a lowercase `create` prefix is a hook.+ fs.writeFileSync(path.join(dir, 'Creator.doc.mjs'), 'export default {};\n');+ fs.writeFileSync(+ path.join(dir, 'createdHelpers.doc.mjs'),+ 'export default {};\n',+ );+ expect(discoverHooks(core)).toEqual({Interaction: ['createReorderable']});+ expect(findHookDoc(core, 'createReorderable')).toBe(+ path.join(dir, 'createReorderable.doc.mjs'),+ );+ });++ it('lists a create*.doc.mjs factory beside its own hook, not on its own, when its relatedHooks names that hook', () => {+ const core = mkTmp('as-hd-beside-');+ const dir = path.join(core, 'src', 'thing');+ fs.mkdirSync(dir, {recursive: true});+ fs.writeFileSync(+ path.join(dir, 'useThing.doc.mjs'),+ "export default {\n category: 'interaction',\n};\n",+ );+ fs.writeFileSync(+ path.join(dir, 'createThing.doc.mjs'),+ "export default {\n relatedHooks: ['useThing'],\n category: 'interaction',\n};\n",+ );+ // A factory that names another hook still lists on its own.+ fs.writeFileSync(+ path.join(dir, 'createOther.doc.mjs'),+ "export default {\n relatedHooks: ['useThing'],\n category: 'interaction',\n};\n",+ );+ expect(discoverHooks(core)).toEqual({+ Interaction: ['createOther', 'useThing'],+ });+ expect(findHookDoc(core, 'createThing')).toBe(+ path.join(dir, 'createThing.doc.mjs'),+ );+ });+it('returns {} when src/ is missing (guarded with existsSync)', () => {const core = mkTmp('as-hd-nosrc-');expect(discoverHooks(core)).toEqual({});diff --git a/packages/core/api-report.md b/packages/core/api-report.mdindex b313df2702..283319c53e 100644--- a/packages/core/api-report.md+++ b/packages/core/api-report.md@@ -1521,6 +1521,7 @@ component List(props: ListProps)prop header?: ReactNodeprop listStyle?: ListMarkerStyle = 'none'prop ref?: React.Ref<HTMLUListElement | HTMLOListElement>+ prop reorderable?: Reorderableprop start?: number = 1prop xstyle?: StyleXStylesinherits AriaAttributes, DOMAttributes, HTMLAttributes@@ -3013,6 +3014,7 @@ function createISOTimeString: (value: string) => ISOTimeString | nullfunction createIncrementalState: <MathEnabled extends boolean = false>() => IncrementalState<MathEnabled>function createPanGesture: (element: Element, options: PanGestureOptions) => PanGesturefunction createPowerSearchConfig: <const D extends ReadonlyArray<FieldDefinition>>(definitions: D, configName?: string) => { config: PowerSearchConfig; applyFilters: <T extends InferData<D>>(filters: ReadonlyArray<PowerSearchFilter>, data: ReadonlyArray<T>) => T[] }+function createReorderable: <TKey extends string | number = string | number, TTo = number>(options: ReorderableOptions<TKey, TTo>) => Reorderable<TKey, TTo>function createStaticSource: <T extends SearchableItem>(items: T[], options?: CreateStaticSourceOptions<T>) => SearchSource<T>function dateToISO: (pd: PlainDate) => ISODateStringfunction decodeMarkdownCharacterReferences: (text: string) => string@@ -5088,6 +5090,15 @@ type RadiusVarName = keyof typeof radiusDefaultsinterface RelativeDateFilterPresetlabel: stringvalue: string+interface ReorderMove<TKey extends string | number = string | number, TTo = number>+ key: TKey+ to: TTo+interface Reorderable<TKey extends string | number = string | number, TTo = number>+ [reorderableBrand]: { readonly key: TKey; readonly to: TTo }+ start: (key: TKey) => void+interface ReorderableOptions<TKey extends string | number = string | number, TTo = number>+ isReorderable?: (key: TKey) => boolean+ onReorder: (move: ReorderMove<TKey, TTo>) => voidinterface ResizableConfigautoSaveId?: stringdefaultIsCollapsed?: booleandiff --git a/packages/core/locales/en.json b/packages/core/locales/en.jsonindex cf0a69cd9f..ed8ad5ebd4 100644--- a/packages/core/locales/en.json+++ b/packages/core/locales/en.json@@ -607,6 +607,70 @@"defaultMessage": "{count, number} {count, plural, one {other} other {others}}","description": "Overflow element for the chat typing status when three or more people type: the first name is shown and the rest collapse into this phrase, which is then joined to the name by Intl.ListFormat. Renders as the last list item, e.g. \"Ana and 2 others\"."},+ "@astryx.list.reorderHandle": {+ "defaultMessage": "Reorder {label}",+ "description": "Accessible label on the handle at the end of a List row that drags the row to a new place or moves it with the arrow keys. `{label}` is the row's text (e.g. \"Reorder Inbox\")."+ },+ "@astryx.list.reorderHandleVerb": {+ "defaultMessage": "Reorder",+ "description": "The handle's own accessible label at the end of a List row named through the row's label element: read first, then the row's label (e.g. \"Reorder\" then \"Inbox\"), so a label of any shape completes it. The verb alone, without the row's label."+ },+ "@astryx.list.reorderHandleAt": {+ "defaultMessage": "Reorder item {position, number}",+ "description": "Accessible label on a List row's reorder handle when the row has no text label to name it after. `{position}` is the row's 1-based place in the list (e.g. \"Reorder item 3\")."+ },+ "@astryx.list.reorderHint": {+ "defaultMessage": "Drag to move this item, or press Space or Enter, then the arrow keys to move it one place at a time. Press Escape when you are done.",+ "description": "Description read after the label of every reorder handle in a List: how to move a row by dragging, or in reorder mode, which the handle's Space or Enter turns on and Escape ends."+ },+ "@astryx.list.reorderPlace": {+ "defaultMessage": "{label}, position {position, number} of {total, number}, after {previous}, before {next}",+ "description": "Screen-reader announcement after each move of a List row in reorder mode. `{label}` is the row's text, `{position}` its new 1-based place, `{total}` the number of rows, and `{previous}` and `{next}` the texts of the rows now before and after it (e.g. \"Milk, position 3 of 5, after Eggs, before Bread\")."+ },+ "@astryx.list.reorderPlaceTop": {+ "defaultMessage": "{label}, position {position, number} of {total, number}, at the top, before {next}",+ "description": "Screen-reader announcement after a List row in reorder mode moves to the first place. `{label}` is the row's text, `{position}` its 1-based place, `{total}` the number of rows, and `{next}` the text of the row now after it (e.g. \"Milk, position 1 of 5, at the top, before Eggs\")."+ },+ "@astryx.list.reorderPlaceEnd": {+ "defaultMessage": "{label}, position {position, number} of {total, number}, after {previous}, at the end",+ "description": "Screen-reader announcement after a List row in reorder mode moves to the last place. `{label}` is the row's text, `{position}` its 1-based place, `{total}` the number of rows, and `{previous}` the text of the row now before it (e.g. \"Milk, position 5 of 5, after Bread, at the end\")."+ },+ "@astryx.list.reorderRefused": {+ "defaultMessage": "Can't move past {label}",+ "description": "Screen-reader announcement when an arrow key in reorder mode would move a List row past a row that keeps its place. `{label}` is that row's text (e.g. \"Can't move past Pinned\")."+ },+ "@astryx.list.reorderItemAt": {+ "defaultMessage": "Item {position, number}",+ "description": "What reorder announcements call a List row that shows no text, such as an icon-only row. `{position}` is its 1-based place (e.g. \"after Item 2\")."+ },+ "@astryx.list.reorderMoveUp": {+ "defaultMessage": "Move up",+ "description": "Accessible label of the up-arrow button in the hint a List row's reorder mode shows: it moves the row one place up, as the Up arrow key does."+ },+ "@astryx.list.reorderMoveDown": {+ "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.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."+ },+ "@astryx.list.reorderModeDone": {+ "defaultMessage": "Done, {label} at position {position, number} of {total, number}",+ "description": "Screen-reader announcement when a List row's reorder mode ends (Escape, the handle again, or Done), keeping its moves. `{label}` is the row's text, `{position}` its 1-based place, `{total}` the number of rows (e.g. \"Done, Milk at position 3 of 5\")."+ },+ "@astryx.list.reorderPickedUp": {+ "defaultMessage": "Picked up, position {position, number} of {total, number}.",+ "description": "Screen-reader announcement when a row of a List is picked up to be reordered, from its handle's keys or by a drag. `{position}` is the row's 1-based place, `{total}` the number of rows."+ },+ "@astryx.list.reorderDropped": {+ "defaultMessage": "Dropped, position {position, number} of {total, number}",+ "description": "Screen-reader announcement when a row being reordered in a List is dropped. `{position}` is its new 1-based place, `{total}` the number of rows."+ },+ "@astryx.list.reorderCancelled": {+ "defaultMessage": "Reorder cancelled, back to position {position, number} of {total, number}",+ "description": "Screen-reader announcement when a reorder in a List is cancelled and the row returns to where it was. `{position}` is that 1-based place, `{total}` the number of rows."+ },"@astryx.listInput.emptyTitle": {"defaultMessage": "No {itemName}s yet","description": "EmptyState title shown inside a lab ListInput when its collection has no records. `{itemName}` is the consumer's singular noun for one record (e.g. \"guest\"); the source appends a literal \"s\" to pluralize it, which only works for regular English plurals. If your language cannot pluralize an interpolated noun this way, rephrase around `{itemName}` instead (e.g. \"No {itemName} added yet\")."diff --git a/packages/core/src/Item/Item.tsx b/packages/core/src/Item/Item.tsxindex 7867977d2c..248505f631 100644--- a/packages/core/src/Item/Item.tsx+++ b/packages/core/src/Item/Item.tsx@@ -5,7 +5,8 @@/*** @file Item.tsx* @input Uses React, ReactNode, StyleXStyles, theme tokens, useClickableContainer,- * the shared press overlays and the compositor press layer+ * the shared press overlays and the compositor press layer, and a row's+ * trailing control (ItemTrailingContext)* @output Exports Item component, ItemProps type; publishes the shared inline inset.* Only numbered composing rows keep their start/label/end slots in one flex* group, through Item's private exact-marker scope; other marked rows keep@@ -54,8 +55,10 @@ import {mergeProps} from '../utils/mergeProps';import {chainEventHandlers} from '../utils/chainEventHandlers';import {useFocusAcrossSwap} from '../utils/useFocusAcrossSwap';import {ItemDescriptionContext} from './ItemDescriptionContext';+import {ItemLabelContext, ItemLabelNeededContext} from './ItemLabelContext';import {ItemListRowContext} from './ItemListRowContext';import {ItemMarkerColumnsContext} from './ItemMarkerColumnsContext';+import {ItemTrailingContext} from './ItemTrailingContext';import {useMergedRefs} from '../hooks/useMergedRefs';import {computeTargetAndRel} from '../Link/computeTargetAndRel';import {useLinkComponent} from '../Link/useLinkComponent';@@ -762,6 +765,13 @@ export function Item({// only once React runs it, such as an empty fragment, still publishes an id.const descriptionID = useId();const hasRenderableDescription = isRenderable(description);+ // The label element's id, published through ItemLabelContext for a control+ // Item renders in a slot that is named after the row (`aria-labelledby`).+ // Only a row with such a control gives its label an id.+ const labelID = useId();+ const isLabelNeeded = use(ItemLabelNeededContext);+ const publishedLabelID =+ isLabelNeeded && isRenderable(label) ? labelID : null;const isStringLabel = typeof label === 'string';const isStringDescription = typeof description === 'string';@@ -791,6 +801,7 @@ export function Item({const labelAndDescription = (<><span+ id={publishedLabelID ?? undefined}{...stylex.props(styles.label,isInline && styles.inlineLabel,@@ -850,6 +861,10 @@ export function Item({onClick?.(e);};+ // A control a row adds after the slots, unwrapped (ItemTrailingContext):+ // a List row's reorder handle when the row has no end content.+ const trailing = use(ItemTrailingContext);+const content = (<>{isRenderable(startContent) && (@@ -921,6 +936,7 @@ export function Item({{endContent}</span>)}+ {trailing}</>);@@ -1049,23 +1065,29 @@ export function Item({)}role={role}onClick={rootOnClick}>- <ItemDescriptionContext- value={hasRenderableDescription ? descriptionID : null}>- <ItemListRowContext value={false}>- {isRenderable(marker) && marker}- {isRenderable(marker) && columnMarker === marker ? (- <span- {...stylex.props(- styles.markerContent,- align === 'first-line' && styles.markerContentFirstLine,- )}>- {content}- </span>- ) : (- content- )}- </ItemListRowContext>- </ItemDescriptionContext>+ <ItemTrailingContext value={null}>+ <ItemDescriptionContext+ value={hasRenderableDescription ? descriptionID : null}>+ <ItemLabelContext value={publishedLabelID}>+ <ItemLabelNeededContext value={false}>+ <ItemListRowContext value={false}>+ {isRenderable(marker) && marker}+ {isRenderable(marker) && columnMarker === marker ? (+ <span+ {...stylex.props(+ styles.markerContent,+ align === 'first-line' && styles.markerContentFirstLine,+ )}>+ {content}+ </span>+ ) : (+ content+ )}+ </ItemListRowContext>+ </ItemLabelNeededContext>+ </ItemLabelContext>+ </ItemDescriptionContext>+ </ItemTrailingContext>{hasSwipe && (// The panels: out-of-flow children of this root, so the DOM is the one// the row had before the split. Suspense and lazy add no element, anddiff --git a/packages/core/src/Item/ItemLabelContext.tsx b/packages/core/src/Item/ItemLabelContext.tsxnew file mode 100644index 0000000000..3858b0b39f--- /dev/null+++ b/packages/core/src/Item/ItemLabelContext.tsx@@ -0,0 +1,39 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file ItemLabelContext.tsx+ * @input Uses createSharedContext+ * @output Exports ItemLabelContext and ItemLabelNeededContext+ * @position Internal seam between Item and a control it renders in a slot+ *+ * Item renders the row's label and owns the element that holds it. A control+ * in a slot points at that element with `aria-labelledby`, so a label of any+ * shape names it. A List row's reorder handle is one: "Reorder" followed by+ * the row's label. Only Item knows the element's id. Publishing it here keeps+ * that wiring internal, as ItemDescriptionContext does for the description.+ *+ * `null` when the row renders no label, or when no control asks for it+ * (ItemLabelNeededContext): a row gives its label an id only when needed.+ */++import {createSharedContext} from '../utils/sharedContext';++export const ItemLabelContext = createSharedContext<string | null>(+ 'ItemLabelContext',+ 1,+ null,+);+ItemLabelContext.displayName = 'ItemLabelContext';++/**+ * Whether a control in the row is named after the row's label. Item gives its+ * label element an id, and publishes it, only then.+ */+export const ItemLabelNeededContext = createSharedContext(+ 'ItemLabelNeededContext',+ 1,+ false,+);+ItemLabelNeededContext.displayName = 'ItemLabelNeededContext';diff --git a/packages/core/src/Item/ItemTrailingContext.tsx b/packages/core/src/Item/ItemTrailingContext.tsxnew file mode 100644index 0000000000..e4da0e1e04--- /dev/null+++ b/packages/core/src/Item/ItemTrailingContext.tsx@@ -0,0 +1,31 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file ItemTrailingContext.tsx+ * @input Uses createSharedContext+ * @output Exports ItemTrailingContext+ * @position Internal seam between Item and a row component that adds one+ * control after Item's slots+ *+ * A List row's reorder handle is the one element reordering adds to a row.+ * With end content, the handle joins Item's end slot.+ * Without it, putting the handle in `endContent` would wrap it in an end-slot+ * element of its own, a second element. Such a row passes the handle here+ * instead, and Item renders it after its slots, unwrapped. Item resets the+ * context for what it renders, so a nested Item never renders its parent's+ * control.+ *+ * `null` when the row adds nothing.+ */++import type {ReactNode} from 'react';+import {createSharedContext} from '../utils/sharedContext';++export const ItemTrailingContext = createSharedContext<ReactNode>(+ 'ItemTrailingContext',+ 1,+ null,+);+ItemTrailingContext.displayName = 'ItemTrailingContext';diff --git a/packages/core/src/List/List.doc.mjs b/packages/core/src/List/List.doc.mjsindex 66e53237bd..0801de3fe9 100644--- a/packages/core/src/List/List.doc.mjs+++ b/packages/core/src/List/List.doc.mjs@@ -66,6 +66,12 @@ export const docs = {description:'The handle from useAnimatedLayout({containerRef}). With it, when rows are inserted, removed or reordered, an inserted row enters, a removed row collapses in place, a row that crosses rows moving the other way rides above them with the surface color behind it, and the rows after a change and the content after the list, up to that container, glide to their new places, all on one shared motion, under every pointer. Under Reduce Motion nothing travels. A row is identified by its itemKey: a row without one changes at once. Without a handle the list changes at once.',},+ {+ name: 'reorderable',+ type: 'Reorderable',+ description:+ "Makes the rows reorderable, with the object createReorderable({onReorder, isReorderable}) makes: each ListItem with an itemKey gets a reorder handle at its end, and each committed move calls onReorder once with the row's key and its index after the move ({key, to}); render the rows in the new order to apply it. A row the object's isReorderable rejects has no handle and keeps its place; one at either end of the list also bounds the others. The object may be made on every render. On a touch screen, a finger held still on a handle for a moment picks up its row (a flick on it still scrolls): the row stays in its place, dimmed, while a copy of it follows the finger and an accent line marks where it would land; the other rows stay still, the page scrolls near the edges, and on release the rows rearrange, gliding to their new places. A mouse drags a handle at once with the same copy and line, and the rows take their places without motion; a drag reports once, at the drop, and a cancelled drag puts everything back at once. In reorder mode the line marks the row's new place after each move. Without a drag, the handle is a toggle: a click, Space or Enter turns on reorder mode for its row (aria-pressed), in which each Up or Down arrow moves the row a place at once and reports it, and Escape or another activation ends the mode, keeping the moves. Each move is announced once it renders, with the row's place and its neighbours ('Milk, position 3 of 5, after Eggs, before Bread'), and a move into a row that keeps its place is refused and announced. While the mode is on, a hint anchored to the handle shows the moves and Done as buttons that do what the keys do, so a row can also be reordered by taps alone. The object's start(key) enters the same mode from your own UI, such as a row's context menu. A disabled row's handle stays focusable but moves nothing.",+ },{name: 'edge',type: "'padded' | 'flush' | 'outset' | 'bleed'",@@ -177,6 +183,18 @@ export const docs = {required: false,description: 'Additional detail for an individual list item.',},+ {+ name: 'Reorder handle',+ required: false,+ description:+ 'With reorderable: the button at the end of each row that can move. It drags the row, and toggles its reorder mode.',+ },+ {+ name: 'Reorder hint',+ required: false,+ description:+ "While a row is in reorder mode: the hint below its handle, like Core's keyboard hint, whose moves and Done are buttons.",+ },],},};@@ -243,6 +261,18 @@ export const docsZh = {required: false,description: 'Additional detail for an individual list item.',},+ {+ name: 'Reorder handle',+ required: false,+ description:+ 'With reorderable: the button at the end of each row that can move. It drags the row, and toggles its reorder mode.',+ },+ {+ name: 'Reorder hint',+ required: false,+ description:+ "While a row is in reorder mode: the hint below its handle, like Core's keyboard hint, whose moves and Done are buttons.",+ },],},};@@ -312,6 +342,18 @@ export const docsDense = {required: false,description: 'Additional detail for an individual list item.',},+ {+ name: 'Reorder handle',+ required: false,+ description:+ 'With reorderable: the button at the end of each row that can move. It drags the row, and toggles its reorder mode.',+ },+ {+ name: 'Reorder hint',+ required: false,+ description:+ "While a row is in reorder mode: the hint below its handle, like Core's keyboard hint, whose moves and Done are buttons.",+ },],},};diff --git a/packages/core/src/List/List.tsx b/packages/core/src/List/List.tsxindex 7c1e6739b6..7c6e79368c 100644--- a/packages/core/src/List/List.tsx+++ b/packages/core/src/List/List.tsx@@ -9,7 +9,14 @@* intrinsic marker column, including when a counter changes digit count.* @output Exports List component, ListProps, ListDensity, ListEdge, ListStyle* types- * @position Core implementation; consumed by index.ts, tested by List.test.tsx+ * @position Core implementation. Consumed by index.ts, tested by List.test.tsx+ *+ * `animatedLayout` runs the layout updates (List/listLayoutUpdates.ts);+ * `reorderable` runs the reorder session after them. List imports only the+ * reorderable object's type and its key (List/listReorderContext.ts). It+ * hands the reorder to its rows through ListContext. The session, its handle+ * and its listeners come with the object (reorderable/createReorderable.ts).+ * So a List without it loads no reorder code.** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/List/List.doc.mjs@@ -19,7 +26,8 @@* - /packages/cli/assets/templates/blocks/components/List/ (showcase blocks)*/-import {useId, useMemo, useRef, type ReactNode} from 'react';+import {useCallback, useId, useMemo, useRef, type ReactNode} from 'react';+import type {Reorderable} from '../reorderable/createReorderable';import * as stylex from '@stylexjs/stylex';import {spacingVars} from '../theme/tokens.stylex';import type {BaseProps} from '../BaseProps';@@ -36,6 +44,12 @@ import {LayoutChangeSnapshot} from '../motion/LayoutChangeSnapshot';import type {AnimatedLayout} from '../motion/animatedLayout';import {themeProps} from '../utils/themeProps';import {useDevWarning} from '../hooks/useDevWarning';+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';+import {+ REORDER_ENGINE,+ type ListReorderOptions,+ type ReorderableInternals,+} from './listReorderContext';export {type ListDensity,@@ -73,6 +87,31 @@ export interface ListProps extends BaseProps<*/animatedLayout?: AnimatedLayout;+ /**+ * Makes the rows reorderable, with the object `createReorderable` makes.+ * Each ListItem with an `itemKey` gets a reorder handle at its end. One the+ * object's `isReorderable` rejects keeps its place. Each committed move+ * calls its `onReorder` once with the row's key and its index after the+ * move. Apply it by rendering the rows in their new order. A drop on the+ * starting place, a cancel, or a move the order does not take changes+ * nothing.+ *+ * On a touch screen, a finger held still on a handle for a moment picks up+ * its row. A flick on it still scrolls. The row stays in its place, dimmed,+ * while a copy of it follows the finger. An accent line marks where it+ * would land. The other rows stay still, the list scrolls near the edges,+ * and on release the rows rearrange. A mouse drags a handle at once, the+ * same way.+ *+ * Without a drag, activating a handle (a click, Space or Enter) turns on+ * reorder mode for its row. Each arrow key moves it a place at once,+ * reported and announced with its place and neighbours. Escape or another+ * activation ends the mode, keeping the moves.+ * While it is on, a hint anchored to the handle shows the moves and Done as+ * buttons, so taps alone can reorder.+ */+ reorderable?: Reorderable;+/*** Whether to show dividers between list items.* @default false@@ -290,6 +329,7 @@ const dynamicStyles = stylex.create({export function List({children,animatedLayout,+ reorderable,density = 'balanced',hasDividers = false,edge: edgeProp,@@ -306,7 +346,30 @@ export function List({}: ListProps) {const headerId = useId();const listRef = useRef<HTMLUListElement & HTMLOListElement>(null);+ // The reorder's machinery comes with the object. The+ // object may be made on every render: the session lasts as long as its+ // machinery, and reads the object's latest callbacks.+ const reorder = reorderable as ReorderableInternals | undefined;+ const reorderEngine = reorder?.[REORDER_ENGINE];+ const reorderOptions = reorder?.options;+ // The handles' instructions take the header's id with a suffix.+ const reorderSession = useMemo(+ () => reorderEngine?.createSession(() => listRef.current, `${headerId}h`),+ [reorderEngine, headerId],+ );const measureRows = useListLayoutUpdates(listRef, animatedLayout);+ // A drag's or a reorder-mode move's commits are the reorder's to move, so+ // the layout updates measure nothing for them.+ const measureUnlessReordering = useCallback(() => {+ if (reorderSession?.ownsCommit() !== true) {+ measureRows();+ }+ }, [measureRows, reorderSession]);+ // Syncs the reorder session, which lives outside React, after each commit.+ // It runs after the layout updates, so a drop's commit is the reorder's.+ useIsomorphicLayoutEffect(() => {+ reorderSession?.commit();+ });const mergedRef = useMergedRefs(listRef,ref as React.Ref<HTMLUListElement & HTMLOListElement>,@@ -314,7 +377,7 @@ export function List({const isOrdered = listStyle === 'decimal';const Tag = isOrdered ? 'ol' : 'ul';// Plain use of the deprecated prop is reported by its @deprecated type;- // development warns only when the two names conflict (spec:AST-017 FR29).+ // development warns only when the two names conflict.useDevWarning('List','`edge` and the deprecated `edgeCompensation` are both set; `edge` wins. ' +@@ -332,8 +395,21 @@ export function List({edge,listStyle,animatedLayout,+ // With a session there is an object, so its options too.+ reorder: reorderSession && {+ session: reorderSession,+ options: reorderOptions as ListReorderOptions,+ },}),- [density, hasDividers, edge, listStyle, animatedLayout],+ [+ density,+ hasDividers,+ edge,+ listStyle,+ animatedLayout,+ reorderSession,+ reorderOptions,+ ],);const listElement = (@@ -372,6 +448,7 @@ export function List({(start != null && start !== 1? dynamicStyles.counterStart(start - 1): styles.withCounter),+ reorderSession?.listStyle,xstyle,),className,@@ -385,14 +462,24 @@ export function List({// calls this in the commit, before the DOM changes.const snapshot =animatedLayout != null ? (- <LayoutChangeSnapshot value={children} onBeforeChange={measureRows} />+ <LayoutChangeSnapshot+ value={children}+ onBeforeChange={measureUnlessReordering}+ />) : null;+ // The session's options and listeners, and the handles' instructions.+ const {reorder: reorderValue} = contextValue;+ const reorderHost = reorderValue && (+ <reorderValue.session.Host reorder={reorderValue} />+ );+if (header == null) {return (<ListContext value={contextValue}>{snapshot}{listElement}+ {reorderHost}</ListContext>);}@@ -410,6 +497,7 @@ export function List({{header}</div>{listElement}+ {reorderHost}</div></ListContext>);diff --git a/packages/core/src/List/ListContext.tsx b/packages/core/src/List/ListContext.tsxindex 99df9cacad..63dd629994 100644--- a/packages/core/src/List/ListContext.tsx+++ b/packages/core/src/List/ListContext.tsx@@ -5,17 +5,18 @@/*** @file ListContext.tsx* @input Layer-scoped React context- * @output Exports ListContext for sharing density, dividers, the row edge- * treatment, and marker style between List and ListItem, and- * ListMarkerScope, which sets the marker for the items inside it, or a- * task item's checkbox in its place, and whether their List has a marker- * gutter whose outside counters keep the ordinary themed text inset- * @position Internal context; consumed by List.tsx and ListItem.tsx+ * @output Exports ListContext, which shares density, dividers, the row edge+ * treatment, marker style and a reorderable List's reorder with ListItem.+ * Also exports ListMarkerScope, which sets the marker for the items inside+ * it, or a task item's checkbox in its place. It also says whether their+ * List has a marker gutter whose outside counters keep the themed inset+ * @position Internal context. Consumed by List.tsx and ListItem.tsx*/import {use, useMemo, type ReactNode} from 'react';import {createLayerScopedContext} from '../Layer/layerScopedContext';import type {AnimatedLayout} from '../hooks/useAnimatedLayout';+import type {ListReorderContextValue} from './listReorderContext';export type ListDensity = 'compact' | 'balanced' | 'spacious';export type ListMarkerStyle = 'none' | 'disc' | 'decimal' | 'circle';@@ -76,6 +77,11 @@ export interface ListContextValue {* The list's `animatedLayout` handle, for its rows.*/animatedLayout?: AnimatedLayout;+ /**+ * A reorderable List's reorder (`List reorderable`); internal. Its rows end+ * with the handle it carries (List/listReorderContext.ts).+ */+ reorder?: ListReorderContextValue | null;}export const ListContext = createLayerScopedContext<ListContextValue | null>(diff --git a/packages/core/src/List/ListItem.doc.mjs b/packages/core/src/List/ListItem.doc.mjsindex 52a2267180..8fa7974cae 100644--- a/packages/core/src/List/ListItem.doc.mjs+++ b/packages/core/src/List/ListItem.doc.mjs@@ -110,7 +110,7 @@ export const docs = {{name: 'itemKey',type: 'string | number',- description: "The row's item key, a string or a number from the data (the shape Table's idKey returns). It is the row's identity for the list's animated layout (List animatedLayout): with a handle, the list matches rows by it to animate inserts, removals and moves, and a row without one changes at once. Separate from React's key.",+ description: "The row's item key, a string or a number from the data (the shape Table's idKey returns). It is the row's identity for the list's animated layout (List animatedLayout): with a handle, the list matches rows by it to animate inserts, removals and moves, and a row without one changes at once. In a reorderable List (List reorderable), it is the key the reorderable object's onReorder reports and isReorderable is asked about, and a row without one has no reorder handle and keeps its place. Separate from React's key.",},{name: 'swipeActions',@@ -207,7 +207,7 @@ export const docsZh = {{name: 'itemKey',type: 'string | number',- description: '行的项目键,取自数据的字符串或数字(与 Table 的 idKey 返回的形状相同)。它是列表动画布局(List animatedLayout)中该行的身份:传入句柄时,列表按它匹配各行,为插入、删除和移动添加动画;没有项目键的行会立即变化。与 React 的 key 相互独立。',+ description: '行的项目键,取自数据的字符串或数字(与 Table 的 idKey 返回的形状相同)。它是列表动画布局(List animatedLayout)中该行的身份:传入句柄时,列表按它匹配各行,为插入、删除和移动添加动画;没有项目键的行会立即变化。在可重新排序的 List(List reorderable)中,它是可重新排序对象的 onReorder 报告的键,也是 isReorderable 判断的键;没有项目键的行没有重新排序手柄,保持原位。与 React 的 key 相互独立。',},{name: 'swipeActions',@@ -247,6 +247,6 @@ export const docsDense = {rel: 'Link relationship tokens. noopener noreferrer are merged for target="_blank".',isDisabled: 'Disabled state; sets aria-disabled.',isSelected: 'Selected state; sets aria-current="true".',- itemKey: "The row's identity for List animatedLayout; a row without one changes at once.",+ itemKey: "The row's identity for List animatedLayout and the key a reorderable List's onReorder reports; a row without one changes at once and has no reorder handle.",},};diff --git a/packages/core/src/List/ListItem.tsx b/packages/core/src/List/ListItem.tsxindex 74d15c2677..f96be4ae78 100644--- a/packages/core/src/List/ListItem.tsx+++ b/packages/core/src/List/ListItem.tsx@@ -12,13 +12,18 @@* items of mixed lists. It also reads Item's private exact-marker formatting* scope for numbered* rows. Number markers stay on one line in the List's shared column,- * keeping every sibling's text and nested list on the same start line;- * they end on one line too, right-aligned with tabular figures, and hang+ * keeping every sibling's text and nested list on the same start line.+ * They end on one line too, right-aligned with tabular figures, and hang* into the row's inline inset before they widen that column. Markdown's* outside counters keep the themed column and may paint beyond it, matching* RichText's native outside markers without a finite width threshold.* @output Exports ListItem component, ListItemProps type- * @position Core implementation; consumed by List, index.ts, tested by List.test.tsx+ * @position Core implementation. Consumed by List, index.ts, tested by List.test.tsx+ *+ * In a reorderable List (`List reorderable`), each row with an `itemKey`+ * that the reorderable object lets move ends with its handle. The handle+ * comes through ListContext's `reorder` with the rest of the reorder+ * machinery (List/listReorderContext.ts). A row without one keeps its place.** Composes Item for the shared start content + label + description + end content layout* and the invisible button/anchor interactive pattern.@@ -31,7 +36,7 @@* - /packages/cli/assets/templates/blocks/components/List/ (showcase blocks)*/-import {use, useMemo, type ReactNode} from 'react';+import {use, useMemo, useRef, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import type {StyleXStyles} from '@stylexjs/stylex';import {@@ -48,6 +53,8 @@ import {rowPressLayerStyles} from '../privateAttributes/press.stylex';import {Item, servesSwipeActions} from '../Item/Item';import {ItemListRowContext} from '../Item/ItemListRowContext';import {ItemMarkerColumnsContext} from '../Item/ItemMarkerColumnsContext';+import {ItemLabelNeededContext} from '../Item/ItemLabelContext';+import {ItemTrailingContext} from '../Item/ItemTrailingContext';import type {ItemAlign, ItemSwipeActions, ItemSwipeBehavior} from '../Item';import {themeProps} from '../utils/themeProps';import {useMergedRefs} from '../hooks/useMergedRefs';@@ -149,7 +156,9 @@ export interface ListItemProps extends BaseProps<HTMLLIElement> {/*** The row's item key, a string or a number from the data, in the shape* Table's `idKey` returns. It is the row's identity for the list's- * `animatedLayout`. A row without one changes at once. It is separate from+ * `animatedLayout`. In a reorderable List (`List reorderable`), it is the+ * key `onReorder` reports and `isReorderable` is asked about. A row without+ * one changes at once and has no reorder handle. It is separate from* React's `key`, which stays React's own.*/itemKey?: string | number;@@ -358,7 +367,7 @@ const markerStyles = stylex.create({},// Markdown's non-swipe lists allow outside marker paint. Keep their marker// column at the ordinary themed width, as RichText's native outside markers- // do (spec:AST-061 FR11). The counter itself stays intrinsic and unbroken;+ // do. The counter itself stays intrinsic and unbroken;// flex-end aligns its end even when it overflows toward inline-start. A// larger finite negative margin would only move the parity failure threshold.gutterHang: {@@ -455,15 +464,60 @@ export function ListItem({...restProps}: ListItemProps) {const ctx = use(ListContext);+ // The row's element, which a row without a handle names for the reorder.+ const rowRef = useRef<HTMLLIElement | null>(null);// A List isolates its rows, so what a row raises stays below a page-level// sticky header. Outside a List nothing bounds a raise, so a row raises// nothing there.const isInList = ctx != null;+ // In a reorderable List: a trailing handle, or a row that stays put.+ const reorder = ctx?.reorder;+ const hasHandle =+ reorder != null &&+ itemKey != null &&+ (reorder.options.isReorderable?.(itemKey) ?? true);+ // The handle is the one element reordering adds to a row. With end content+ // it joins the end slot. Without, it is the row's own child+ // (ItemTrailingContext), since an end slot of its own would be a second+ // element.+ const isHandleInRow = hasHandle && endContent == null;+ const rowLabel = restProps['aria-label'];+ const rowLabelledBy = restProps['aria-labelledby'];+ const rowAlign = isHandleInRow ? (align ?? 'center') : undefined;+ const Handle = reorder?.session.Handle;+ const reorderHandle = useMemo(+ () =>+ hasHandle && Handle != null && itemKey != null ? (+ <Handle+ label={label}+ itemKey={itemKey}+ isDisabled={isDisabled}+ rowLabel={rowLabel}+ rowLabelledBy={rowLabelledBy}+ rowAlign={rowAlign}+ />+ ) : null,+ [+ Handle,+ hasHandle,+ isDisabled,+ itemKey,+ label,+ rowAlign,+ rowLabel,+ rowLabelledBy,+ ],+ );// Under a finger, the row's hit target grows where its neighbors leave room.const isTouchTarget =(onClick != null || href != null || interactiveRef != null) && !isDisabled;const hitAreaRef = useTouchHitArea(isTouchTarget);- const mergedRef = useMergedRefs(ref, hitAreaRef, keepPresentationOnDetach);+ const mergedRef = useMergedRefs(+ ref,+ rowRef,+ hitAreaRef,+ keepPresentationOnDetach,+ );// A row that Item serves swipe actions on is a stacking context at rest. So// its band's own z-index orders only inside it, and under a finger the row// raises itself. Its root is its `<li>`, never a link.@@ -530,6 +584,14 @@ export function ListItem({[task, markerKind, hasMarkerGutter],);+ // A row without a handle in a reorderable List still has a name for the+ // announcements of the moves beside it. It follows the row, so the row's+ // element is set when it records it.+ const reorderName =+ reorder && !reorderHandle ? (+ <reorder.session.RowName row={rowRef} label={label} />+ ) : null;+const item = (<Itemas="li"@@ -538,7 +600,16 @@ export function ListItem({startContent={startContent}label={label}description={description}- endContent={endContent}+ endContent={+ reorderHandle != null && !isHandleInRow ? (+ <>+ {endContent}+ {reorderHandle}+ </>+ ) : (+ endContent+ )+ }onClick={onClick}interactiveRef={interactiveRef}href={href}@@ -565,6 +636,9 @@ export function ListItem({edge === 'flush' && styles.edgeFlush,edge === 'outset' && styles.edgeOutset,edge === 'bleed' && styles.edgeBleed,+ // A focused handle rings itself; the row's focus-within ring stays+ // off for it (two rings, and the list clips the row's sides).+ reorderHandle && reorder?.session.rowStyle,xstyle,] as StyleXStyles}@@ -576,11 +650,24 @@ export function ListItem({const row = <ItemListRowContext value>{item}</ItemListRowContext>;// Only numbered rows contribute two cells to List's shared counter grid.// Passing the marker identity keeps this request off unrelated Items in slots.- return usesNumberColumns ? (+ const marked = usesNumberColumns ? (<ItemMarkerColumnsContext value={marker}>{row}</ItemMarkerColumnsContext>) : (row);+ return (+ <>+ {/* One shape whether or not the handle is the row's own child, so the+ row keeps its element when that changes. */}+ <ItemTrailingContext value={isHandleInRow ? reorderHandle : null}>+ {/* The handle is named after the row's label. */}+ <ItemLabelNeededContext value={reorderHandle != null}>+ {marked}+ </ItemLabelNeededContext>+ </ItemTrailingContext>+ {reorderName}+ </>+ );}ListItem.displayName = 'ListItem';diff --git a/packages/core/src/List/ListReorderHandle.tsx b/packages/core/src/List/ListReorderHandle.tsxnew file mode 100644index 0000000000..5acb9a0fb1--- /dev/null+++ b/packages/core/src/List/ListReorderHandle.tsx@@ -0,0 +1,443 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file ListReorderHandle.tsx+ * @input The List's reorder session (List/listReorderEngine.tsx, through+ * ListContext's `reorder`), the translator and theme tokens+ * @output `ListReorderHandle`, `ListReorderRowName` and `reorderRowStyle`.+ * The handle ends a reorderable List row. A finger held still on it drags+ * it, and so does a pen where the primary pointer is coarse. A mouse, or a+ * pen where it is fine, drags it at once. It is also a toggle+ * (`aria-pressed`): a click, Space or Enter turns its row's reorder mode on+ * and off. The row name serves a row without one, and the style a row that+ * has one+ * @position Part of the reorder machinery that createReorderable carries.+ * ListItem renders it, from the List's context, at the end of each row+ * that can move+ *+ * UIKit's reorder control (iOS 26.2, measured) is three gray lines at the+ * trailing edge of a row in edit mode. A finger held still on it for the+ * scroll view's content-touch delay (150 ms) claims the drag. A flick that+ * starts on it scrolls the table instead. So until the claim, the handle+ * leaves the browser everything but double-tap zoom (`manipulation`). That+ * `touch-action` applies only where the primary pointer is coarse. Elsewhere+ * a finger gets the browser's defaults until the hold claims it. The handle is the one element the reorder+ * adds to a row. Its lines are a pseudo-element, and it listens to nothing+ * itself. The session's listeners take its drags. Its keys go through+ * React's.+ *+ * SYNC: When modified, update List/listReorderEngine.tsx and+ * List/ListItem.tsx.+ */++import {+ use,+ useEffect,+ useRef,+ useState,+ useSyncExternalStore,+ useId,+ type KeyboardEvent,+} from 'react';+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';+import {useMergedRefs} from '../hooks/useMergedRefs';+import * as stylex from '@stylexjs/stylex';+import {colorVars, focusVars, typeScaleVars} from '../theme/tokens.stylex';+import {focusOutlineProps} from '../utils/focusOutline.stylex';+import {+ ownRingContainerStyles,+ ownRingProps,+} from '../privateAttributes/ownRing.stylex';+import {listReorderHandleProps} from '../privateAttributes/listReorder.stylex';+import {reorderingHandleStyles} from '../privateAttributes/reordering.stylex';+import {reorderLineStyles} from '../privateAttributes/reorderLine.stylex';+import {useTouchHitArea} from '../utils/touchHitArea';+import {touchHitAreaStyles} from '../internal/touchHitArea.stylex';+import {+ registerEnglishFallback,+ useComponentTranslator,+} from '../i18n/useComponentTranslator';+import english from '../i18n/generated-english/List/ListReorderHandle.generated';+import {createDevWarnings} from '../utils/devWarning';+import {getNodeText} from '../utils/getNodeText';+import {ItemLabelContext} from '../Item/ItemLabelContext';+import {ListContext} from './ListContext';+import type {+ ListReorderHandleProps,+ ListReorderRowNameProps,+} from './listReorderContext';+import type {ListReorderController} from './listReorderEngine';++registerEnglishFallback(english);++/**+ * The handle's side, for every pointer: a small control's size. A finger's+ * 44 px target is an invisible coarse-only hit layer, clamped so it never+ * takes from a neighbour (utils/hitArea.ts), not a bigger handle.+ */+const HANDLE_SIZE = 28;+/** The three lines' height: the handle's share of its row's height. */+const LINES_HEIGHT = 14;+/** The lines' length and thickness, and the distance between them. */+const LINE_WIDTH = 20;+const LINE_THICKNESS = 2;+const LINE_GAP = (LINES_HEIGHT - LINE_THICKNESS) / 2;++const styles = stylex.create({+ handle: {+ // Centred on its row, with the lines in its middle. It takes only the+ // lines' height in the row's layout (the negative block margins). So a+ // compact row stays compact. The handle and its focus ring reach past+ // that into the row's padding, never past it. They go no further than the+ // row's own inline inset, so a flush row's handle stays inside the clip.+ position: 'relative',+ alignSelf: 'center',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ flexShrink: 0,+ width: HANDLE_SIZE,+ height: HANDLE_SIZE,+ marginBlock: (LINES_HEIGHT - HANDLE_SIZE) / 2,+ marginInlineEnd: 'calc(-1 * min(8px, var(--_item-inset-inline, 8px)))',+ padding: 0,+ borderWidth: 0,+ borderRadius: 4,+ // The ring sits inside the handle: the handle reaches the row's inline+ // end, and the list clips what passes it.+ outlineOffset: {+ default: '0',+ ':focus-visible': `calc(-1 * ${focusVars['--focus-outline-width']})`,+ },+ // Pressed while its row is in reorder mode, as a pressed toggle button+ // is; in forced colors, the system's highlight.+ backgroundColor: {+ default: 'transparent',+ ':is([aria-pressed="true"])': {+ default: colorVars['--color-overlay-pressed'],+ '@media (forced-colors: active)': 'Highlight',+ },+ },+ forcedColorAdjust: {+ default: null,+ ':is([aria-pressed="true"])': 'none',+ },+ color: {+ default: colorVars['--color-icon-secondary'],+ ':is([aria-disabled="true"])': colorVars['--color-icon-disabled'],+ ':is([aria-pressed="true"])': {+ default: colorVars['--color-icon-secondary'],+ '@media (forced-colors: active)': 'HighlightText',+ },+ },+ // Where the primary pointer is coarse, the page keeps its scrolling and+ // its pinch-zoom until the hold claims the drag. A flick on the handle+ // scrolls, as on iOS. That is `manipulation`, what a long press leaves the+ // browser. The hold's selection lock stops text selection while the+ // finger is down, so a mouse keeps the page's selection. Where the+ // pointer is fine, a finger gets the browser's defaults.+ touchAction: {+ default: null,+ '@media (pointer: coarse)': 'manipulation',+ },+ WebkitTapHighlightColor: {+ default: null,+ '@media (pointer: coarse)': 'transparent',+ },+ // The three lines: one bar and its two shadows, in the handle's color.+ // Forced colors keep them (shadows and backgrounds go there otherwise),+ // drawn in the system's button text.+ '::before': {+ content: '""',+ display: 'block',+ width: LINE_WIDTH,+ height: LINE_THICKNESS,+ borderRadius: LINE_THICKNESS / 2,+ backgroundColor: 'currentColor',+ boxShadow: `0 -${LINE_GAP}px currentColor, 0 ${LINE_GAP}px currentColor`,+ forcedColorAdjust: 'none',+ pointerEvents: 'none',+ },+ },+ // The row's own child, in a row without end content. It ends the row, as+ // the end slot would. It aligns as the row's `align` would align that slot.+ inRow: {+ marginInlineStart: 'auto',+ },+ // `start`: at the top of the row's content.+ inRowStart: {+ alignSelf: 'flex-start',+ },+ // `first-line`: centred on the label's first line, a line of body text at+ // the top of the row's content. Item's first-line slots centre on it too.+ // Its layout height stays the lines' height (the end margin).+ inRowFirstLine: {+ alignSelf: 'flex-start',+ marginBlockStart: `calc((${typeScaleVars['--text-body-leading']} - ${HANDLE_SIZE}px) / 2)`,+ },+});++/**+ * The style of a row that ends with a handle, which ListItem applies. Its+ * ring on focus within stays off for the handle, which rings itself.+ */+export const reorderRowStyle = ownRingContainerStyles.focusWithin;++/** The insertion line's thickness, px (the engine centres it on a gap). */+export const INSERTION_LINE_THICKNESS = 2;++const listStyles = stylex.create({+ // The insertion line is the list's own pseudo-element. It is decoration+ // with no semantic role, so no element joins the list. The engine shows it+ // with `showReorderLine` and places it with the list's custom properties.+ // They set its top (`--astryx-reorder-line-y`, a compositor translate) and+ // its inline start and size, which are the dragged row's.+ list: {+ '::after': {+ content: '""',+ position: 'absolute',+ top: 0,+ insetInlineStart: 'var(--astryx-reorder-line-start, 0px)',+ inlineSize: 'var(--astryx-reorder-line-size, 0px)',+ blockSize: INSERTION_LINE_THICKNESS,+ borderRadius: INSERTION_LINE_THICKNESS / 2,+ backgroundColor: {+ default: colorVars['--color-accent'],+ '@media (forced-colors: active)': 'Highlight',+ },+ forcedColorAdjust: 'none',+ translate: '0 var(--astryx-reorder-line-y, 0px)',+ pointerEvents: 'none',+ zIndex: 2,+ },+ },+});++/** The style of a reorderable list (List applies it): its insertion line. */+export const reorderListStyle = [listStyles.list, reorderLineStyles.list];++/** The text the row's label element shows, collapsed; empty without one. */+function labelTextOf(handle: HTMLElement | null, labelID: string | null) {+ const element =+ labelID == null+ ? null+ : (handle?.ownerDocument.getElementById(labelID) ?? null);+ return (element?.textContent ?? '').replace(/\s+/g, ' ').trim();+}++/**+ * Whether the row's label element names it: it shows text, or holds an icon+ * or image with an accessible name of its own.+ */+function namesRow(element: HTMLElement | null): boolean {+ if (element == null) {+ return false;+ }+ return (+ (element.textContent ?? '').trim() !== '' ||+ element.querySelector(+ '[aria-label]:not([aria-label=""]), [aria-labelledby], img[alt]:not([alt=""])',+ ) != null+ );+}++/**+ * The reorder handle of a List row. Renders nothing outside a reorderable+ * List.+ */+export function ListReorderHandle({+ label,+ itemKey,+ isDisabled = false,+ rowLabel,+ rowLabelledBy,+ rowAlign,+}: ListReorderHandleProps) {+ const ref = useRef<HTMLButtonElement>(null);+ const t = useComponentTranslator();+ const controller = use(ListContext)?.reorder?.session as+ ListReorderController | undefined;+ // The row's label element, when the handle sits in an Item's slot.+ const labelID = use(ItemLabelContext);+ const verbID = useId();+ const text = getNodeText(label).replace(/\s+/g, ' ').trim();+ // Named "Reorder" followed by the row's name: the name+ // its caller gave the row. Else the elements that name the row (its+ // caller's `aria-labelledby`, or the label element Item renders), so a+ // label of any shape names it. Outside an Item, the label's text. A row+ // that shows no name is named after its place.+ const callerLabel = rowLabel?.trim() || null;+ const labelledBy =+ callerLabel != null ? undefined : (rowLabelledBy ?? labelID ?? undefined);+ const named = callerLabel != null || labelledBy != null || text !== '';+ const verb = t('@astryx.list.reorderHandleVerb');+ const [warn] = useState(createDevWarnings);+ // Syncs the handle into the reorder session, which lives outside React. The+ // session moves the row only with its handle recorded, and reports its+ // moves with the row's key.+ useIsomorphicLayoutEffect(+ () => controller?.registerHandle(ref.current, itemKey),+ [controller, itemKey],+ );+ // Syncs the row's name into the session, which announces the moves with+ // it. A new name keeps the handle recorded, so its row stays in reorder+ // mode. A component label's text is read from its element, rendered by now.+ useIsomorphicLayoutEffect(() => {+ const spoken =+ callerLabel ??+ (text !== '' ? text : labelTextOf(ref.current, labelID ?? null));+ return controller?.registerName(ref.current, spoken);+ }, [controller, callerLabel, text, labelID]);+ const isPressed = useSyncExternalStore(+ controller?.subscribeMode ?? subscribeNothing,+ () => controller?.isInMode(ref.current) ?? false,+ () => false,+ );+ const isEnabled = controller != null && !isDisabled;+ // A finger's target: the shared touch hit area grows the handle's hit+ // layer where the primary pointer is coarse.+ const hitAreaRef = useTouchHitArea(true);+ const handleRef = useMergedRefs(ref, hitAreaRef);+ // A handle that stops taking gestures mid-drag sends a drag of its row+ // home, whichever pointer or key drives it. Its row may be disabled or no+ // longer reorderable, or the handle may be gone.+ useIsomorphicLayoutEffect(() => {+ const handle = ref.current;+ if (!isEnabled || controller == null) {+ return undefined;+ }+ return () => controller.release(handle);+ }, [controller, isEnabled]);+ // That place is read from the DOM after each commit (the row does not+ // know its index). A passive effect: the list's own ref is attached after+ // its rows' layout effects run.+ useEffect(() => {+ const handle = ref.current;+ if (handle == null) {+ return;+ }+ // Named by Item's label element only while it shows a name: a label of+ // an unnamed icon alone falls back to the place.+ if (labelID != null && labelledBy === labelID) {+ if (namesRow(handle.ownerDocument.getElementById(labelID))) {+ handle.setAttribute('aria-labelledby', `${verbID} ${labelID}`);+ handle.setAttribute('aria-label', verb);+ return;+ }+ handle.removeAttribute('aria-labelledby');+ } else if (named) {+ return;+ }+ const position = controller?.positionOf(handle) ?? null;+ if (position == null) {+ return;+ }+ // Named after its place only: a person hears "Reorder item 3" with+ // nothing to tell the rows apart. Development says so, once a handle.+ warn(+ 'ListItem',+ 'A reorderable row has no accessible name, so its reorder handle is ' ++ 'named after its place ("Reorder item N"). Give the row a text ' ++ 'label or an aria-label.',+ );+ handle.setAttribute(+ 'aria-label',+ t('@astryx.list.reorderHandleAt', {position}),+ );+ });+ if (controller == null) {+ return null;+ }+ // Named through the label element. The handle's own `aria-label` is the+ // verb. It lists itself first in its `aria-labelledby`, which reads its+ // `aria-label` there: "Reorder", then the row's label.+ const name =+ callerLabel != null+ ? t('@astryx.list.reorderHandle', {label: callerLabel})+ : labelledBy != null+ ? verb+ : text !== ''+ ? t('@astryx.list.reorderHandle', {label: text})+ : undefined;+ return (+ <button+ ref={handleRef}+ id={labelledBy == null ? undefined : verbID}+ type="button"+ {...listReorderHandleProps}+ // The handle takes its own press, so the row does not highlight under+ // it (it paints nothing itself).+ data-astryx-pressable=""+ // It rings itself: the row's focus-within ring stays off for it.+ {...ownRingProps}+ aria-label={name}+ aria-labelledby={+ labelledBy == null ? undefined : `${verbID} ${labelledBy}`+ }+ aria-describedby={controller.hintId}+ aria-disabled={isDisabled || undefined}+ aria-pressed={isPressed}+ // A click, Space or Enter: reorder mode, unless the press dragged.+ onClick={() => {+ if (!controller.takeDrag(ref.current) && !isDisabled) {+ controller.toggleMode(ref.current);+ }+ }}+ onKeyDown={(event: KeyboardEvent<HTMLButtonElement>) => {+ if (!isDisabled) {+ controller.keyDown(ref.current, event);+ }+ }}+ onBlur={event => controller.blur(ref.current, event.relatedTarget)}+ // The row's own pointer handling (its swipe) never sees the handle's+ // presses: the list's listeners have them, before this.+ onPointerDown={event => event.stopPropagation()}+ // A hold on the handle picks the row up. Only a hold elsewhere on the+ // row opens the row's menu. A menu around the row never starts its long+ // press from the handle, and a finger's long press there sends it no+ // context request. A mouse's right click on the handle still reaches it.+ onTouchStart={event => event.stopPropagation()}+ onContextMenu={event => {+ if (+ (event.nativeEvent as Partial<PointerEvent>).pointerType === 'touch'+ ) {+ event.preventDefault();+ event.stopPropagation();+ }+ }}+ {...focusOutlineProps.focusVisible(+ styles.handle,+ reorderingHandleStyles.cursor,+ touchHitAreaStyles.layer,+ rowAlign != null && styles.inRow,+ rowAlign === 'start' && styles.inRowStart,+ rowAlign === 'first-line' && styles.inRowFirstLine,+ )}+ />+ );+}++ListReorderHandle.displayName = 'ListReorderHandle';++const subscribeNothing = () => () => {};++/**+ * Names a reorderable List's row that has no handle, for the announcements+ * of the moves beside it. That is a row that stays, or one without an item+ * key. Renders nothing.+ */+export function ListReorderRowName({row, label}: ListReorderRowNameProps) {+ const controller = use(ListContext)?.reorder?.session as+ ListReorderController | undefined;+ const text = getNodeText(label).replace(/\s+/g, ' ').trim();+ // Syncs the row's name into the reorder session, which lives outside React.+ useIsomorphicLayoutEffect(+ () => controller?.registerName(row.current, text),+ [controller, row, text],+ );+ return null;+}++ListReorderRowName.displayName = 'ListReorderRowName';diff --git a/packages/core/src/List/ListReorderTouch.ts b/packages/core/src/List/ListReorderTouch.tsnew file mode 100644index 0000000000..f1e409f01b--- /dev/null+++ b/packages/core/src/List/ListReorderTouch.ts@@ -0,0 +1,219 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file ListReorderTouch.ts+ * @input The gesture system's long press and host, the reorder claim values+ * (motion/uikit/reorder.ts), the row motion (utils/rowMotion.ts) and the+ * selection lock (utils/selectionLock.ts)+ * @output The List reorder's touch layer. `attachTouchHold` is the list's one+ * hold, which picks up a row from its handle under a finger. `touchMotion`+ * moves the rows under a finger. It plays the shared settle role, the+ * drop's glide at the release's velocity, the way home, and the+ * continuation across the commit+ * @position Imported by List/listReorderEngine.tsx alone: what the reorder+ * runs only under a finger sits behind this one import+ *+ * UIKit's reorder control (iOS 26.2, measured): a finger held still on it for+ * the scroll view's content-touch delay (150 ms) claims the drag. A flick that+ * starts on it scrolls the table instead. So the handle lets the browser pan+ * vertically and pinch-zoom until the claim, through its own `touch-action`.+ * The long press then holds the touch, through the gesture system's blocking+ * listener for a mid-gesture claim. A second finger before the claim makes+ * it the browser's pinch (WCAG 1.4.4). After the claim, extra fingers change+ * nothing. The gesture host owns the touch listeners and counts the fingers+ * on the screen. The hold keeps its own styles, so the list locks text+ * selection under a held finger itself. One hold serves the whole list. It+ * receives only the touches that begin on the list's handles, so the list's+ * blocking listener is its only one.+ *+ * SYNC: When modified, update List/listReorderEngine.tsx.+ */++import {getGestureHost} from '../gestures/GestureHost';+import {LongPressGestureRecognizer} from '../gestures/LongPressGestureRecognizer';+import type {PointerKind} from '../gestures/types';+import {resolveMotion} from '../motion/resolveMotion';+import {+ durationBounceOf,+ toSpring,+ type DurationBounce,+ type SpringDescription,+} from '../motion/spring';+import {reorder} from '../motion/uikit/reorder';+import {registerSpringsTable, springs} from '../motion/uikit/springs';+import {subscribeInput} from '../utils/inputStream';+import {+ animateRow,+ animatorFor,+ motionOf,+ releaseMotion,+} from '../utils/rowMotion';+import {lockSelection, locksSelectionFor} from '../utils/selectionLock';++/**+ * The list's hold: a finger held still for the content-touch delay on one of+ * its handles (a touch `receives` takes) picks up that handle's row.+ * `pointerTypes` are the pointers that hold: a finger always, and a pen where+ * the primary pointer is coarse. `isOnHandle` tells the touches that start on+ * a handle, which lock text selection until they lift. Returns the detach.+ */+export function attachTouchHold(+ list: HTMLElement,+ pointerTypes: ReadonlyArray<PointerKind>,+ receives: (target: unknown) => boolean,+ onGesture: (recognizer: LongPressGestureRecognizer) => void,+ isOnHandle: (target: unknown) => boolean,+): () => void {+ const host = getGestureHost(list.ownerDocument);+ const recognizer = new LongPressGestureRecognizer({+ name: 'List.reorder',+ minimumPressDuration: reorder.claim.delayMs,+ allowableMovement: reorder.claim.allowableMovement,+ allowedPointerTypes: pointerTypes,+ // Only the touches that begin on a handle: the rest of the list's+ // touches never reach the hold.+ shouldReceiveTouch: (_recognizer, touch) => receives(touch.target),+ // Only a lone finger: two are the browser's pinch, wherever the second+ // one landed (the gesture host counts every finger on the screen).+ shouldBegin: () => host.fingersDown() <= 1,+ // The hold keeps its own styles, so the list itself locks text+ // selection under a held finger.+ });+ const unlisten = recognizer.addListener(onGesture);+ // The handles set their own `touch-action`.+ const detach = host.attach(list, recognizer, {manageStyle: false});+ const unlock = lockSelectionWhileHeld(list, pointerTypes, isOnHandle);+ return () => {+ detach();+ unlisten();+ unlock();+ };+}++/**+ * The hold's selection lock. The host leaves it to the list, since the list+ * keeps its own styles. From a finger's or a pen's touch-down on a handle+ * until it lifts, no text on the list starts a selection or the callout.+ * iOS starts its own selection under a still finger before the hold claims+ * the drag, so the lock starts at the touch-down. Returns the detach.+ */+function lockSelectionWhileHeld(+ list: HTMLElement,+ pointerTypes: ReadonlyArray<PointerKind>,+ isOnHandle: (target: unknown) => boolean,+): () => void {+ const view = list.ownerDocument.defaultView;+ if (view == null) {+ return () => {};+ }+ const held = new Map<number, () => void>();+ const release = (event: PointerEvent) => {+ held.get(event.pointerId)?.();+ held.delete(event.pointerId);+ };+ const unsubscribe = [+ subscribeInput(view, 'pointerdown', event => {+ if (+ locksSelectionFor(event.pointerType) &&+ pointerTypes.some(type => type === event.pointerType) &&+ isOnHandle(event.target)+ ) {+ release(event);+ held.set(event.pointerId, lockSelection([list], event.target));+ }+ }),+ subscribeInput(view, 'pointerup', release),+ subscribeInput(view, 'pointercancel', release),+ ];+ return () => {+ for (const stop of unsubscribe) {+ stop();+ }+ for (const unlockHeld of held.values()) {+ unlockHeld();+ }+ held.clear();+ };+}++/** Releases a row's offset once its motion arrives. */+function releaseOnArrival(element: HTMLElement, arrived: Promise<boolean>) {+ void arrived.then(done => {+ if (done) {+ releaseMotion(element, 'translate');+ }+ });+}++/** UIKit's motion for the rows of a reorder under a finger. */+export const touchMotion = {+ /**+ * The rows' glide to their new places once a move commits: a drop or a+ * reorder mode move. It is coordinated layout movement, so it plays the+ * shared settle role, `springs.settle`, as useAnimatedLayout does. The role+ * is read once when the glide starts. Registers the springs table first.+ */+ glideBase(list: HTMLElement): DurationBounce {+ registerSpringsTable();+ return durationBounceOf(toSpring(resolveMotion(list, springs.settle)));+ },++ /**+ * The dropped row glides from where its preview was, `shift` from its new+ * place, to that place on `spring`. It starts at the release's y+ * `velocity` in px/s. Its offset goes once it arrives.+ */+ glide(+ element: HTMLElement,+ shift: number,+ spring: SpringDescription,+ at: number,+ velocity: number,+ ): void {+ animatorFor(element).rebase({y: shift}, {at});+ releaseOnArrival(+ element,+ animateRow(element, {y: 0}, spring, {at, velocity: {y: velocity}})+ .finished,+ );+ },+ /**+ * A row goes back to its place on `spring` (the dragged row from rest),+ * and its offset goes once it arrives.+ */+ home(+ element: HTMLElement,+ spring: SpringDescription,+ at: number,+ fromRest: boolean,+ ): void {+ releaseOnArrival(+ element,+ animateRow(element, {y: 0}, spring, {+ at,+ velocity: fromRest ? {y: 0} : undefined,+ }).finished,+ );+ },+ /**+ * The layout moved a row by `shift`: a commit put it in its new place. Its+ * running spring, or `spring` from rest, goes on to the new place from+ * where it is shown. The spring and velocity stay, and the target moves+ * with the layout. So the curve on screen continues: springs are memoryless.+ */+ follow(+ element: HTMLElement,+ shift: number,+ spring: SpringDescription,+ at: number,+ ): void {+ const running = motionOf(element, 'y')?.spring ?? spring;+ animatorFor(element).rebase({y: shift}, {at});+ releaseOnArrival(+ element,+ animateRow(element, {y: 0}, running, {at}).finished,+ );+ },+};diff --git a/packages/core/src/List/__tests__/ListReorder.test.tsx b/packages/core/src/List/__tests__/ListReorder.test.tsxnew file mode 100644index 0000000000..bc7b700cb9--- /dev/null+++ b/packages/core/src/List/__tests__/ListReorder.test.tsx@@ -0,0 +1,1790 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ListReorder.test.tsx+ * @input List with `reorderable` (createReorderable), ListItem `itemKey`,+ * Testing Library+ * @output jsdom proofs of a reorderable List. Each row with an item key gets+ * a named reorder handle that the list's instructions describe. A row+ * without a key, or one `isReorderable` rejects, gets none. Only such rows+ * at either end bound the others. The handle's click, Space or Enter+ * toggles reorder mode (`aria-pressed`). There, each arrow moves the row at+ * once and reports its key and its index after the move. Each move is+ * announced with its place and neighbours once it lands, by the names the+ * rows have then. A move that renames the row keeps the mode. A move into a+ * row that stays at either end is refused and announced. Escape or another+ * activation ends the mode and keeps the moves; a lost focus keeps it.+ * While the mode is on, a hint shows the moves and Done as buttons. They+ * do what the keys do and leave the focus on the handle. The+ * object's start(key) enters the same mode from the app's own UI. It keeps+ * the mode when that UI hands its focus back. It only warns for a key that+ * cannot move or is not mounted. It uses the list mounted last for an+ * object on two. A mouse drags past the slop, and a drag's click leaves the+ * mode alone. A new object keeps the mode, and the next move calls the+ * latest callback. One object serves two lists apart. The reorder adds one+ * element to a row and no listener to a row or handle. A List without it+ * loads no reorder module+ * @position Tests for List/listReorderEngine.tsx, List/ListReorderHandle.tsx+ * and reorderable/createReorderable.ts+ */++import {readFileSync} from 'node:fs';+import {useState, type Key, type ReactNode} from 'react';+import {afterEach, describe, expect, it, vi} from 'vitest';+import {+ act,+ fireEvent,+ render,+ renderHook,+ screen,+ waitFor,+} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import {ContextMenu} from '../../ContextMenu';+import {List} from '../List';+import {ListItem} from '../ListItem';+import {INSERTION_LINE_THICKNESS} from '../ListReorderHandle';+import {MOUSE_DRAG_SLOP} from '../listReorderEngine';+import {+ createReorderable,+ type Reorderable,+ type ReorderMove,+} from '../../reorderable/createReorderable';+import {DRAG_SLOP} from '../../DateInput/usePointerDragScroll';+import {useAnnounce} from '../../hooks/useAnnounce';+import {LayerDepthProvider} from '../../Layer/LayerDepthContext';+import {useLayerDismissal} from '../../Layer/useLayerDismissal';+import {animatorFor} from '../../motion/animator';+import {motionRole} from '../../motion/roles';+import {getGestureHost} from '../../gestures/GestureHost';+import {pointerQuery} from '../../gestures/__tests__/pointerQuery';+import {touchMotion} from '../ListReorderTouch';++function moveKey<T extends Key>(+ items: ReadonlyArray<T>,+ key: Key,+ to: number,+): T[] {+ const next = items.filter(item => item !== key);+ next.splice(to, 0, key as T);+ return next;+}++const NONE: ReadonlyArray<string> = [];++function ReorderableRows({+ initial,+ fixed = NONE,+ onReorder,+ isDisabled = NONE,+}: {+ initial: ReadonlyArray<string>;+ fixed?: ReadonlyArray<string>;+ onReorder?: (move: ReorderMove) => void;+ isDisabled?: ReadonlyArray<string>;+}) {+ const [items, setItems] = useState(initial);+ // A new object on every render, as a caller may make it.+ const reorderable = createReorderable({+ onReorder: move => {+ onReorder?.(move);+ setItems(previous => moveKey(previous, move.key, move.to));+ },+ isReorderable: key => !fixed.includes(key as string),+ });+ return (+ <List reorderable={reorderable}>+ {items.map(item => (+ <ListItem+ key={item}+ itemKey={item}+ label={item}+ isDisabled={isDisabled.includes(item)}+ />+ ))}+ </List>+ );+}++/** The primary pointer: coarse (a touch screen) or fine (a mouse). */+let restorePointer: (() => void) | null = null;++/** The primary pointer a test needs (jsdom's is fine), until it ends. */+function stubPrimaryPointer(coarse: boolean) {+ restorePointer?.();+ restorePointer = pointerQuery(coarse).restore;+}++/**+ * jsdom lays nothing out: 44 px rows from 300 px down the viewport. Each read+ * of a row's layout top calls `onRead`.+ */+function layOut(list: HTMLElement, onRead?: () => void) {+ const place = (row: Element) => Array.from(list.children).indexOf(row);+ for (const row of Array.from(list.children)) {+ Object.defineProperty(row, 'offsetParent', {+ configurable: true,+ get: () => list,+ });+ Object.defineProperty(row, 'offsetTop', {+ configurable: true,+ get: () => {+ onRead?.();+ return place(row) * 44;+ },+ });+ Object.defineProperty(row, 'offsetHeight', {configurable: true, value: 44});+ row.getBoundingClientRect = () =>+ DOMRect.fromRect({+ x: 0,+ y: 300 + place(row) * 44,+ width: 300,+ height: 44,+ });+ }+}++const MOUSE = {pointerType: 'mouse', pointerId: 1, button: 0, clientX: 280};++/** A mouse presses `handle` at `from`, moves past the slop, then to `to`. */+function mouseDrag(handle: Element, from: number, to: number) {+ fireEvent.pointerDown(handle, {...MOUSE, clientY: from});+ fireEvent.pointerMove(handle, {...MOUSE, clientY: from + MOUSE_DRAG_SLOP});+ fireEvent.pointerMove(handle, {...MOUSE, clientY: to});+}++/** The rows' labels, without what the reorder draws over them. */+const labels = () =>+ Array.from(document.querySelectorAll('li:not([data-astryx-leaving])')).map(+ row => row.textContent,+ );++const handleOf = (label: string) =>+ screen.getByRole('button', {name: `Reorder ${label}`});++/**+ * A button of reorder mode's hint. jsdom never opens a popover, so the hint+ * layer stays `display: none` there: the query includes hidden elements.+ */+const hintButton = (name: string) =>+ screen.queryByRole('button', {name, hidden: true});++describe('List reorderable', () => {+ // 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();+ restorePointer?.();+ restorePointer = null;+ });++ it('adds no handle and no listener without reorderable', () => {+ render(+ <List>+ <ListItem itemKey="inbox" label="Inbox" />+ <ListItem itemKey="sent" label="Sent" />+ </List>,+ );+ expect(screen.queryAllByRole('button')).toHaveLength(0);+ expect(document.querySelector('[data-astryx-list-reorder]')).toBeNull();+ });++ it('loads no reorder module from List or ListItem: they import its type and context only', () => {+ // spec:AST-103 FR2: the machinery ships with createReorderable.+ for (const file of ['../List.tsx', '../ListItem.tsx']) {+ const source = readFileSync(new URL(file, import.meta.url), 'utf8');+ const imports = Array.from(+ source.matchAll(/^import\s+(type\s+)?[^;]*?from\s+'([^']+)';/gms),+ match => ({isType: match[1] != null, from: match[2]}),+ );+ for (const {isType, from} of imports) {+ if (/reorder/i.test(from)) {+ expect(+ isType || from === './listReorderContext',+ `${file} imports ${from}`,+ ).toBe(true);+ }+ }+ }+ });++ it('gives each row with an item key a handle named after it and described by the instructions', () => {+ render(<ReorderableRows initial={['Inbox', 'Sent', 'Drafts']} />);+ const handle = handleOf('Inbox');+ expect(handle).toHaveAttribute('type', 'button');+ expect(handle).toHaveAttribute('aria-pressed', 'false');+ expect(handle).toHaveAccessibleDescription(+ 'Drag to move this item, or press Space or Enter, then the arrow keys to move it one place at a time. Press Escape when you are done.',+ );+ expect(screen.getAllByRole('button', {name: /^Reorder /})).toHaveLength(3);+ // The instructions are not shown, and sit outside the list.+ const hint = document.getElementById(+ handle.getAttribute('aria-describedby') ?? '',+ );+ expect(hint).not.toBeNull();+ expect(hint).toHaveAttribute('hidden');+ expect(hint?.closest('ul')).toBeNull();+ expect(screen.getByRole('list').children).toHaveLength(3);+ });++ it('names the handle of a row with a rich label after its text, and of one that shows no text after its place', async () => {+ render(+ <List reorderable={createReorderable({onReorder: () => {}})}>+ <ListItem itemKey="inbox" label="Inbox" />+ <ListItem+ itemKey="sent"+ label={+ <span>+ <strong>Sent</strong> {'mail'}+ </span>+ }+ />+ <ListItem itemKey="star" label={<svg aria-label="Starred" />} />+ </List>,+ );+ expect(handleOf('Sent mail')).toBeInTheDocument();+ // An icon with its own name names the row through the label element.+ expect(+ await screen.findByRole('button', {name: 'Reorder Starred'}),+ ).toBeInTheDocument();+ });++ it('names the handle "Reorder" then the row label element, for a component label too (spec:AST-103 FR4)', async () => {+ function FieldName({name}: {name: string}) {+ return <span>{name}</span>;+ }+ render(+ <List reorderable={createReorderable({onReorder: () => {}})}>+ <ListItem itemKey="inbox" label="Inbox" />+ <ListItem itemKey="custom" label={<FieldName name="Custom Name" />} />+ </List>,+ );+ expect(handleOf('Inbox')).toBeInTheDocument();+ const custom = await screen.findByRole('button', {+ name: 'Reorder Custom Name',+ });+ // Named by the label element ListItem renders, not by a copied string.+ expect(custom.getAttribute('aria-labelledby')?.split(' ')).toHaveLength(2);+ });++ it("names the handle after the row's own aria-label or aria-labelledby when its caller gave one", async () => {+ render(+ <>+ <span id="row-name">Billing address</span>+ <List reorderable={createReorderable({onReorder: () => {}})}>+ <ListItem itemKey="a" label={<span>A</span>} aria-label="Account" />+ <ListItem+ itemKey="b"+ label={<span>B</span>}+ aria-labelledby="row-name"+ />+ </List>+ </>,+ );+ expect(handleOf('Account')).toBeInTheDocument();+ expect(+ await screen.findByRole('button', {name: 'Reorder Billing address'}),+ ).toBeInTheDocument();+ });++ it('names the handle of a row that shows no text and has no name after its place, and warns in development', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const rows = () => (+ <List reorderable={createReorderable({onReorder: () => {}})}>+ <ListItem itemKey="inbox" label="Inbox" />+ <ListItem itemKey="dot" label={<svg aria-hidden="true" />} />+ <ListItem itemKey="star" label={<svg aria-label="Starred" />} />+ </List>+ );+ const {rerender} = render(rows());+ expect(+ await screen.findByRole('button', {name: 'Reorder item 2'}),+ ).toBeInTheDocument();+ // Only the nameless row warns, once, however often it renders.+ rerender(rows());+ const nameless = warn.mock.calls.filter(([message]) =>+ String(message).includes('A reorderable row has no accessible name'),+ );+ expect(nameless).toHaveLength(1);+ warn.mockRestore();+ });++ it('does not warn about a nameless reorderable row in production', async () => {+ vi.resetModules();+ vi.stubEnv('NODE_ENV', 'production');+ try {+ const {List: ProdList} = await import('../List');+ const {ListItem: ProdListItem} = await import('../ListItem');+ const {createReorderable: prodCreate} =+ await import('../../reorderable/createReorderable');+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ render(+ <ProdList reorderable={prodCreate({onReorder: () => {}})}>+ <ProdListItem itemKey="dot" label={<svg aria-hidden="true" />} />+ </ProdList>,+ );+ expect(+ await screen.findByRole('button', {name: 'Reorder item 1'}),+ ).toBeInTheDocument();+ expect(+ warn.mock.calls.some(([message]) =>+ String(message).includes('A reorderable row has no accessible name'),+ ),+ ).toBe(false);+ warn.mockRestore();+ } finally {+ vi.unstubAllEnvs();+ }+ });++ it("gives a finger's target as an invisible hit layer, not a bigger handle: the hit area writes its insets where the primary pointer is coarse", async () => {+ stubPrimaryPointer(true);+ render(<ReorderableRows initial={['A', 'B']} />);+ const handle = handleOf('A');+ await waitFor(() =>+ expect(handle.style.getPropertyValue('--astryx-hit-inset-top')).toMatch(+ /px$/,+ ),+ );+ for (const side of ['right', 'bottom', 'left']) {+ expect(+ handle.style.getPropertyValue(`--astryx-hit-inset-${side}`),+ side,+ ).toMatch(/px$/);+ }+ });++ it("starts the hit area's observers only where the primary pointer is coarse (spec:AST-094 FR24)", () => {+ const observed: Element[] = [];+ class Recording {+ observe(target: Element) {+ observed.push(target);+ }+ unobserve() {}+ disconnect() {}+ takeRecords() {+ return [];+ }+ }+ vi.stubGlobal('IntersectionObserver', Recording);+ vi.stubGlobal('ResizeObserver', Recording);+ const resizes = vi.spyOn(window, 'addEventListener');+ try {+ stubPrimaryPointer(false);+ const fine = render(<ReorderableRows initial={['A', 'B']} />);+ expect(observed).not.toContain(handleOf('A'));+ expect(resizes.mock.calls.filter(([type]) => type === 'resize')).toEqual(+ [],+ );+ fine.unmount();+ // The positive control: under a finger it watches the handle.+ stubPrimaryPointer(true);+ render(<ReorderableRows initial={['A', 'B']} />);+ expect(observed).toContain(handleOf('A'));+ } finally {+ resizes.mockRestore();+ vi.unstubAllGlobals();+ }+ });++ it('adds only the handle to a row without end content: no end-slot wrapper (spec:AST-103 FR5)', () => {+ const rows = (reorderable?: Reorderable) => (+ <List reorderable={reorderable}>+ <ListItem itemKey="inbox" label="Inbox" />+ <ListItem itemKey="sent" label="Sent" align="first-line" />+ </List>+ );+ const {rerender} = render(rows());+ const inbox = screen.getByText('Inbox').closest('li') as HTMLElement;+ const sent = screen.getByText('Sent').closest('li') as HTMLElement;+ const before = [inbox, sent].map(row => row.querySelectorAll('*').length);+ rerender(rows(createReorderable({onReorder: () => {}})));+ expect(inbox.querySelectorAll('*').length).toBe(before[0] + 1);+ expect(sent.querySelectorAll('*').length).toBe(before[1] + 1);+ // The handle is the row's own child, after the label.+ expect(handleOf('Inbox').parentElement).toBe(inbox);+ expect(handleOf('Sent').parentElement).toBe(sent);+ });++ it('adds one element to a row, the handle, whose lines are a pseudo-element', () => {+ const rows = (reorderable?: Reorderable) => (+ <List reorderable={reorderable}>+ <ListItem itemKey="inbox" label="Inbox" endContent={<span>3</span>} />+ </List>+ );+ const {rerender} = render(rows());+ const row = screen.getByText('Inbox').closest('li') as HTMLElement;+ const before = row.querySelectorAll('*').length;+ rerender(rows(createReorderable({onReorder: () => {}})));+ expect(row.querySelectorAll('*').length).toBe(before + 1);+ const handle = handleOf('Inbox');+ expect(handle.children).toHaveLength(0);+ expect(handle.textContent).toBe('');+ });++ it('keeps a row the object rejects in place: no handle, and nothing added to it', () => {+ const rows = (reorderable?: Reorderable) => (+ <List reorderable={reorderable}>+ <ListItem itemKey="inbox" label="Inbox" />+ <ListItem itemKey="trash" label="Trash" endContent={<span>9</span>} />+ </List>+ );+ const {rerender} = render(rows());+ const trash = screen.getByText('Trash').closest('li') as HTMLElement;+ const before = trash.outerHTML;+ rerender(+ rows(+ createReorderable({+ onReorder: () => {},+ isReorderable: key => key !== 'trash',+ }),+ ),+ );+ expect(screen.queryByRole('button', {name: 'Reorder Trash'})).toBeNull();+ expect(handleOf('Inbox')).toBeInTheDocument();+ expect(trash.outerHTML).toBe(before);+ });++ it('keeps a row without an item key in place, and warns in development when no row has one', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const warnings = () =>+ warn.mock.calls.filter(([message]) =>+ String(message).includes('`itemKey`'),+ );+ const {unmount} = render(+ <List reorderable={createReorderable({onReorder: () => {}})}>+ <ListItem itemKey="inbox" label="Inbox" />+ <ListItem label="Sent" />+ </List>,+ );+ expect(screen.queryByRole('button', {name: 'Reorder Sent'})).toBeNull();+ expect(handleOf('Inbox')).toBeInTheDocument();+ expect(warnings()).toHaveLength(0);+ unmount();+ const unkeyed = () => (+ <List reorderable={createReorderable({onReorder: () => {}})}>+ <ListItem label="Sent" />+ <ListItem label="Drafts" />+ </List>+ );+ const {rerender} = render(unkeyed());+ expect(warnings()).toHaveLength(1);+ // Once a list, however often it renders.+ rerender(unkeyed());+ expect(warnings()).toHaveLength(1);+ warn.mockRestore();+ });++ it('keeps reorder mode through a move that renames its row, and announces the rows by their new names', async () => {+ const user = userEvent.setup();+ function RowsNamedByPlace() {+ const [items, setItems] = useState(['a', 'b', 'c']);+ const reorderable = createReorderable({+ onReorder: move =>+ setItems(previous => moveKey(previous, move.key, move.to)),+ });+ // Each row is named after its place, so a move renames it.+ return (+ <List reorderable={reorderable}>+ {items.map((item, index) => (+ <ListItem key={item} itemKey={item} label={`Row ${index + 1}`} />+ ))}+ </List>+ );+ }+ render(<RowsNamedByPlace />);+ const handle = handleOf('Row 1');+ handle.focus();+ await user.keyboard('{Enter}');+ expect(handle).toHaveAttribute('aria-pressed', 'true');+ await user.keyboard('{ArrowDown}');+ expect(handle).toHaveAccessibleName('Reorder Row 2');+ expect(handle).toHaveAttribute('aria-pressed', 'true');+ await waitFor(() =>+ expect(document.body).toHaveTextContent(+ 'Row 2, position 2 of 3, after Row 1, before Row 3',+ ),+ );+ await user.keyboard('{ArrowDown}');+ expect(handle).toHaveAccessibleName('Reorder Row 3');+ expect(handle).toHaveAttribute('aria-pressed', 'true');+ await waitFor(() =>+ expect(document.body).toHaveTextContent(+ 'Row 3, position 3 of 3, after Row 2, at the end',+ ),+ );+ });++ it.each([+ ['Space', ' '],+ ['Enter', '{Enter}'],+ ])(+ 'turns reorder mode on with %s: each arrow moves the row at once, reported and announced with its place and neighbours',+ async (_, press) => {+ const user = userEvent.setup();+ const onReorder = vi.fn();+ render(+ <ReorderableRows+ initial={['Inbox', 'Sent', 'Drafts']}+ onReorder={onReorder}+ />,+ );+ const handle = handleOf('Inbox');+ expect(handle).toHaveAttribute('aria-pressed', 'false');+ handle.focus();+ await user.keyboard(press);+ expect(handle).toHaveAttribute('aria-pressed', 'true');+ await user.keyboard('{ArrowDown}');+ expect(onReorder).toHaveBeenCalledTimes(1);+ expect(onReorder).toHaveBeenLastCalledWith({key: 'Inbox', to: 1});+ expect(labels()).toEqual(['Sent', 'Inbox', 'Drafts']);+ expect(handle).toHaveFocus();+ expect(handle).toHaveAttribute('aria-pressed', 'true');+ await waitFor(() =>+ expect(document.body).toHaveTextContent(+ 'Inbox, position 2 of 3, after Sent, before Drafts',+ ),+ );+ await user.keyboard('{ArrowDown}');+ expect(onReorder).toHaveBeenLastCalledWith({key: 'Inbox', to: 2});+ await waitFor(() =>+ expect(document.body).toHaveTextContent(+ 'Inbox, position 3 of 3, after Drafts, at the end',+ ),+ );+ // Past the end: nothing moves.+ await user.keyboard('{ArrowDown}');+ expect(onReorder).toHaveBeenCalledTimes(2);+ await user.keyboard('{ArrowUp}{ArrowUp}');+ expect(onReorder).toHaveBeenCalledTimes(4);+ expect(onReorder).toHaveBeenLastCalledWith({key: 'Inbox', to: 0});+ expect(labels()).toEqual(['Inbox', 'Sent', 'Drafts']);+ await waitFor(() =>+ expect(document.body).toHaveTextContent(+ 'Inbox, position 1 of 3, at the top, before Sent',+ ),+ );+ expect(handle).toHaveFocus();+ },+ );++ it('turns reorder mode on with a click, and the arrows move the row', async () => {+ const user = userEvent.setup();+ const onReorder = vi.fn();+ render(+ <ReorderableRows+ initial={['Inbox', 'Sent', 'Drafts']}+ onReorder={onReorder}+ />,+ );+ const handle = handleOf('Sent');+ await user.click(handle);+ expect(handle).toHaveAttribute('aria-pressed', 'true');+ expect(handle).toHaveFocus();+ await user.keyboard('{ArrowUp}');+ expect(onReorder).toHaveBeenCalledWith({key: 'Sent', to: 0});+ expect(labels()).toEqual(['Sent', 'Inbox', 'Drafts']);+ });++ it.each([+ ['Escape', '{Escape}'],+ ['a second activation', ' '],+ ])('leaves reorder mode with %s, keeping its moves', async (_, leave) => {+ const user = userEvent.setup();+ const onReorder = vi.fn();+ render(+ <ReorderableRows+ initial={['Inbox', 'Sent', 'Drafts']}+ onReorder={onReorder}+ />,+ );+ const handle = handleOf('Inbox');+ handle.focus();+ await user.keyboard(' {ArrowDown}{ArrowDown}');+ await user.keyboard(leave);+ expect(handle).toHaveAttribute('aria-pressed', 'false');+ expect(handle).toHaveFocus();+ // Kept: two moves, nothing undone, and where the row is announced.+ expect(onReorder).toHaveBeenCalledTimes(2);+ expect(labels()).toEqual(['Sent', 'Drafts', 'Inbox']);+ await waitFor(() =>+ expect(document.body).toHaveTextContent('Done, Inbox at position 3 of 3'),+ );+ // Out of the mode, the arrows move nothing.+ await user.keyboard('{ArrowUp}');+ expect(onReorder).toHaveBeenCalledTimes(2);+ });++ it("marks the row's place with the insertion line for the whole mode, and each key move's new place (design:ordered-collection-reordering)", async () => {+ const user = userEvent.setup();+ render(<ReorderableRows initial={['Inbox', 'Sent', 'Drafts']} />);+ const list = screen.getByRole('list');+ layOut(list);+ const handle = handleOf('Inbox');+ handle.focus();+ await user.keyboard(' ');+ // From the start of the mode, before a move: the line sits on the row's+ // top edge, the first row's at the list's top.+ expect(list).toHaveAttribute('data-astryx-reorder-line');+ expect(list.style.getPropertyValue('--astryx-reorder-line-y')).toBe(+ `${-INSERTION_LINE_THICKNESS / 2}px`,+ );+ await user.keyboard('{ArrowDown}');+ layOut(list);+ await user.keyboard('{ArrowDown}');+ expect(labels()).toEqual(['Sent', 'Drafts', 'Inbox']);+ // The line is the list's own pseudo-element, placed by its custom+ // properties: no element joins the list (component-style-authoring INV7).+ expect(list).toHaveAttribute('data-astryx-reorder-line');+ expect(list.style.getPropertyValue('--astryx-reorder-line-y')).toMatch(+ /px$/,+ );+ expect(list.children).toHaveLength(3);+ await user.keyboard('{Escape}');+ expect(list).not.toHaveAttribute('data-astryx-reorder-line');+ expect(list.style.getPropertyValue('--astryx-reorder-line-y')).toBe('');+ });++ it('moves nothing with the arrows outside reorder mode', async () => {+ const user = userEvent.setup();+ const onReorder = vi.fn();+ render(+ <ReorderableRows+ initial={['Inbox', 'Sent', 'Drafts']}+ onReorder={onReorder}+ />,+ );+ handleOf('Inbox').focus();+ await user.keyboard('{ArrowDown}{ArrowUp}');+ expect(onReorder).not.toHaveBeenCalled();+ expect(labels()).toEqual(['Inbox', 'Sent', 'Drafts']);+ });++ it('refuses a move into a row the object rejects at either end, announcing it, and passes one in the middle', async () => {+ const user = userEvent.setup();+ const onReorder = vi.fn();+ render(+ <ReorderableRows+ initial={['Pinned', 'Inbox', 'Sent', 'Locked', 'Drafts', 'Trash']}+ fixed={['Pinned', 'Locked', 'Trash']}+ onReorder={onReorder}+ />,+ );+ handleOf('Inbox').focus();+ await user.keyboard(' {ArrowUp}');+ expect(onReorder).not.toHaveBeenCalled();+ await waitFor(() =>+ expect(document.body).toHaveTextContent("Can't move past Pinned"),+ );+ // Down past Sent, past Locked (in the middle), past Drafts.+ await user.keyboard('{ArrowDown}{ArrowDown}');+ expect(onReorder).toHaveBeenLastCalledWith({key: 'Inbox', to: 3});+ await waitFor(() =>+ expect(document.body).toHaveTextContent(+ 'Inbox, position 4 of 6, after Locked, before Drafts',+ ),+ );+ await user.keyboard('{ArrowDown}{ArrowDown}');+ expect(onReorder).toHaveBeenCalledTimes(3);+ expect(onReorder).toHaveBeenLastCalledWith({key: 'Inbox', to: 4});+ expect(labels()).toEqual([+ 'Pinned',+ 'Sent',+ 'Locked',+ 'Drafts',+ 'Inbox',+ 'Trash',+ ]);+ await waitFor(() =>+ expect(document.body).toHaveTextContent("Can't move past Trash"),+ );+ });++ it('leaves out the ghost of a removed row still collapsing: places and names count only the rows', async () => {+ const user = userEvent.setup();+ const onReorder = vi.fn();+ render(+ <ReorderableRows+ initial={['Inbox', 'Sent', 'Drafts']}+ onReorder={onReorder}+ />,+ );+ // The update motion keeps a removed row in the list while it collapses.+ const list = screen.getByRole('list');+ const ghost = document.createElement('li');+ ghost.setAttribute('data-astryx-leaving', '');+ ghost.setAttribute('aria-hidden', 'true');+ ghost.textContent = 'Spam';+ list.insertBefore(ghost, list.children[1]);+ handleOf('Drafts').focus();+ await user.keyboard(' {ArrowUp}');+ expect(onReorder).toHaveBeenCalledWith({key: 'Drafts', to: 1});+ await waitFor(() =>+ expect(document.body).toHaveTextContent(+ 'Drafts, position 2 of 3, after Inbox, before Sent',+ ),+ );+ // Up again: Inbox, not the ghost, is passed.+ await user.keyboard('{ArrowUp}');+ expect(onReorder).toHaveBeenLastCalledWith({key: 'Drafts', to: 0});+ ghost.remove();+ });++ it('names a row that shows no text after its place', async () => {+ const user = userEvent.setup();+ render(+ <List+ reorderable={createReorderable({+ onReorder: () => {},+ isReorderable: key => key !== 'star',+ })}>+ <ListItem itemKey="star" label={<svg aria-label="Starred" />} />+ <ListItem itemKey="inbox" label="Inbox" />+ </List>,+ );+ handleOf('Inbox').focus();+ await user.keyboard(' {ArrowUp}');+ await waitFor(() =>+ expect(document.body).toHaveTextContent("Can't move past Item 1"),+ );+ });++ it('keeps reorder mode when its handle loses focus: only Escape, Done, the handle or the row going ends it (spec:AST-103 FR4a)', async () => {+ const user = userEvent.setup();+ const onReorder = vi.fn();+ render(+ <ReorderableRows+ initial={['Inbox', 'Sent', 'Drafts']}+ onReorder={onReorder}+ />,+ );+ const handle = handleOf('Inbox');+ handle.focus();+ await user.keyboard(' {ArrowDown}');+ await user.tab();+ expect(handle).not.toHaveFocus();+ expect(handle).toHaveAttribute('aria-pressed', 'true');+ expect(onReorder).toHaveBeenCalledTimes(1);+ expect(labels()).toEqual(['Sent', 'Inbox', 'Drafts']);+ // Back on the handle, its arrows move the row again; Escape ends it.+ handle.focus();+ await user.keyboard('{ArrowDown}');+ expect(onReorder).toHaveBeenCalledTimes(2);+ expect(labels()).toEqual(['Sent', 'Drafts', 'Inbox']);+ await user.keyboard('{Escape}');+ expect(handle).toHaveAttribute('aria-pressed', 'false');+ });++ it('ignores arrows with a modifier: they are shortcuts', async () => {+ const onReorder = vi.fn();+ const user = userEvent.setup();+ render(+ <ReorderableRows+ initial={['Inbox', 'Sent', 'Drafts']}+ onReorder={onReorder}+ />,+ );+ handleOf('Inbox').focus();+ await user.keyboard(' {Meta>}{ArrowDown}{/Meta}{Alt>}{ArrowDown}{/Alt}');+ expect(onReorder).not.toHaveBeenCalled();+ });++ it("keeps a disabled row's handle focusable but moves nothing from it", async () => {+ const onReorder = vi.fn();+ const user = userEvent.setup();+ render(+ <ReorderableRows+ initial={['Inbox', 'Sent']}+ isDisabled={['Inbox']}+ onReorder={onReorder}+ />,+ );+ const handle = handleOf('Inbox');+ expect(handle).toHaveAttribute('aria-disabled', 'true');+ expect(handle).not.toHaveAttribute('disabled');+ handle.focus();+ expect(handle).toHaveFocus();+ await user.keyboard(' {ArrowDown}');+ expect(handle).toHaveAttribute('aria-pressed', 'false');+ expect(onReorder).not.toHaveBeenCalled();+ expect(handleOf('Sent')).not.toHaveAttribute('aria-disabled');+ });++ it('announces a move only once it lands, and a declined one with the place the row kept', async () => {+ const user = userEvent.setup();+ const onReorder = vi.fn();+ // A caller that keeps its order: the row never moves.+ render(+ <List reorderable={createReorderable({onReorder})}>+ {['Inbox', 'Sent', 'Drafts'].map(item => (+ <ListItem key={item} itemKey={item} label={item} />+ ))}+ </List>,+ );+ const handle = handleOf('Drafts');+ handle.focus();+ await user.keyboard(' {ArrowUp}');+ expect(onReorder).toHaveBeenCalledWith({key: 'Drafts', to: 1});+ await waitFor(() =>+ expect(document.body).toHaveTextContent(+ 'Drafts, position 3 of 3, after Sent, at the end',+ ),+ );+ expect(document.body).not.toHaveTextContent('position 2 of 3');+ expect(labels()).toEqual(['Inbox', 'Sent', 'Drafts']);+ expect(handle).toHaveAttribute('aria-pressed', 'true');+ expect(handle).toHaveFocus();+ });++ it('reports the item key as given, a string or a number (spec:AST-103 FR1)', async () => {+ const user = userEvent.setup();+ const onReorder = vi.fn();+ const {rerender} = render(+ <List reorderable={createReorderable<number>({onReorder})}>+ <ListItem itemKey={7} label="Seven" />+ <ListItem itemKey={8} label="Eight" />+ </List>,+ );+ handleOf('Seven').focus();+ await user.keyboard(' {ArrowDown}');+ expect(onReorder).toHaveBeenLastCalledWith({key: 7, to: 1});+ await user.keyboard('{Escape}');+ rerender(+ <List reorderable={createReorderable<string>({onReorder})}>+ <ListItem itemKey="a" label="Alpha" />+ <ListItem itemKey="b" label="Beta" />+ </List>,+ );+ handleOf('Alpha').focus();+ await user.keyboard(' {ArrowDown}');+ expect(onReorder).toHaveBeenLastCalledWith({key: 'a', to: 1});+ // The key has Table's idKey shape: a string or a number, nothing else.+ // @ts-expect-error: a bigint is no item key.+ void (<ListItem itemKey={7n} label="Seven" />);+ // Nor is it a reorderable object's key: no item could report one+ // (spec:AST-103 FR1).+ // @ts-expect-error: a bigint is no reorder key.+ void createReorderable<bigint>({onReorder: () => {}});+ });++ it('keeps reorder mode when the object is made anew, and calls the latest onReorder', async () => {+ const user = userEvent.setup();+ const first = vi.fn();+ const second = vi.fn();+ const rows = (onReorder: (move: ReorderMove) => void) => (+ <List reorderable={createReorderable({onReorder})}>+ {['Inbox', 'Sent', 'Drafts'].map(item => (+ <ListItem key={item} itemKey={item} label={item} />+ ))}+ </List>+ );+ const {rerender} = render(rows(first));+ const handle = handleOf('Inbox');+ handle.focus();+ await user.keyboard(' ');+ rerender(rows(second));+ expect(handle).toHaveAttribute('aria-pressed', 'true');+ await user.keyboard('{ArrowDown}');+ expect(first).not.toHaveBeenCalled();+ expect(second).toHaveBeenCalledTimes(1);+ expect(second).toHaveBeenCalledWith({key: 'Inbox', to: 1});+ });++ it('reorders two lists that share one object each on its own', async () => {+ const user = userEvent.setup();+ const onReorder = vi.fn();+ const reorderable = createReorderable({onReorder});+ render(+ <>+ <List reorderable={reorderable} aria-label="Today">+ <ListItem itemKey="a1" label="A1" />+ <ListItem itemKey="a2" label="A2" />+ </List>+ <List reorderable={reorderable} aria-label="Later">+ <ListItem itemKey="b1" label="B1" />+ <ListItem itemKey="b2" label="B2" />+ </List>+ </>,+ );+ handleOf('B1').focus();+ await user.keyboard(' ');+ expect(handleOf('B1')).toHaveAttribute('aria-pressed', 'true');+ expect(handleOf('A1')).toHaveAttribute('aria-pressed', 'false');+ await user.keyboard('{ArrowDown}');+ expect(onReorder).toHaveBeenLastCalledWith({key: 'b1', to: 1});+ act(() => handleOf('A2').focus());+ // Focus leaving B1's handle does not end its list's mode (FR4a).+ expect(handleOf('B1')).toHaveAttribute('aria-pressed', 'true');+ await user.keyboard(' {ArrowUp}');+ expect(onReorder).toHaveBeenLastCalledWith({key: 'a2', to: 0});+ });++ /** Rows whose object a button outside the list starts reorder mode with. */+ function StartableRows({+ initial,+ fixed = NONE,+ onReorder,+ start,+ isMenu = false,+ }: {+ initial: ReadonlyArray<string>;+ fixed?: ReadonlyArray<string>;+ onReorder?: (move: ReorderMove) => void;+ start: string;+ isMenu?: boolean;+ }) {+ const [items, setItems] = useState(initial);+ // A new object on every render: `start` on the latest one works.+ const reorderable = createReorderable({+ onReorder: move => {+ onReorder?.(move);+ setItems(previous => moveKey(previous, move.key, move.to));+ },+ isReorderable: key => !fixed.includes(key as string),+ });+ return (+ <>+ <button+ type="button"+ onClick={event => {+ reorderable.start(start);+ // A closing menu hands the focus back to what had it.+ if (isMenu) {+ event.currentTarget.focus();+ }+ }}>+ Move {start}+ </button>+ <List reorderable={reorderable}>+ {items.map(item => (+ <ListItem key={item} itemKey={item} label={item} />+ ))}+ </List>+ </>+ );+ }++ it("starts reorder mode from the app's own UI with start(key): the focus moves to the handle, and the arrows move the row", async () => {+ const user = userEvent.setup();+ const onReorder = vi.fn();+ render(+ <StartableRows+ initial={['Inbox', 'Sent', 'Drafts']}+ onReorder={onReorder}+ start="Sent"+ />,+ );+ await user.click(screen.getByRole('button', {name: 'Move Sent'}));+ const handle = handleOf('Sent');+ expect(handle).toHaveAttribute('aria-pressed', 'true');+ expect(handle).toHaveFocus();+ await user.keyboard('{ArrowDown}');+ expect(onReorder).toHaveBeenCalledWith({key: 'Sent', to: 2});+ await waitFor(() =>+ expect(document.body).toHaveTextContent(+ 'Sent, position 3 of 3, after Drafts, at the end',+ ),+ );+ await user.keyboard('{Escape}');+ expect(handle).toHaveAttribute('aria-pressed', 'false');+ expect(labels()).toEqual(['Inbox', 'Drafts', 'Sent']);+ });++ it('keeps the mode start(key) entered when the UI that started it hands its focus back, as a closing menu does', async () => {+ const user = userEvent.setup();+ render(+ <StartableRows+ initial={['Inbox', 'Sent', 'Drafts']}+ start="Sent"+ isMenu+ />,+ );+ await user.click(screen.getByRole('button', {name: 'Move Sent'}));+ const handle = handleOf('Sent');+ await waitFor(() => expect(handle).toHaveFocus());+ expect(handle).toHaveAttribute('aria-pressed', 'true');+ });++ it.each([+ ['cannot move', 'Pinned'],+ ['is not mounted', 'Spam'],+ ])(+ 'does nothing with start(key) for a key that %s, and warns in development',+ async (_, key) => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const user = userEvent.setup();+ const onReorder = vi.fn();+ render(+ <StartableRows+ initial={['Pinned', 'Inbox', 'Sent']}+ fixed={['Pinned']}+ onReorder={onReorder}+ start={key}+ />,+ );+ await user.click(screen.getByRole('button', {name: `Move ${key}`}));+ for (const label of ['Inbox', 'Sent']) {+ expect(handleOf(label)).toHaveAttribute('aria-pressed', 'false');+ }+ await user.keyboard('{ArrowDown}');+ expect(onReorder).not.toHaveBeenCalled();+ expect(+ warn.mock.calls.some(([message]) =>+ String(message).includes(`start(${key})`),+ ),+ ).toBe(true);+ warn.mockRestore();+ },+ );++ it('starts reorder mode in the list mounted last when one object serves two, and warns in development', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const reorderable = createReorderable({onReorder: () => {}});+ render(+ <>+ <List reorderable={reorderable} aria-label="Today">+ <ListItem itemKey="same" label="Today's" />+ </List>+ <List reorderable={reorderable} aria-label="Later">+ <ListItem itemKey="same" label="Later's" />+ </List>+ </>,+ );+ act(() => reorderable.start('same'));+ expect(handleOf("Later's")).toHaveAttribute('aria-pressed', 'true');+ expect(handleOf("Today's")).toHaveAttribute('aria-pressed', 'false');+ expect(+ warn.mock.calls.some(([message]) =>+ String(message).includes('more than one collection'),+ ),+ ).toBe(true);+ warn.mockRestore();+ });++ it('shows a hint with the moves and Done while a row is in reorder mode', async () => {+ const user = userEvent.setup();+ render(<ReorderableRows initial={['Inbox', 'Sent', 'Drafts']} />);+ expect(hintButton('Move down')).toBeNull();+ handleOf('Sent').focus();+ await user.keyboard(' ');+ const down = hintButton('Move down') as HTMLElement;+ expect(hintButton('Move up')).toBeInTheDocument();+ expect(hintButton('Done')).toBeInTheDocument();+ // In the anchored hint layer, outside the list; never a tab stop.+ expect(down.closest('[popover]')).not.toBeNull();+ expect(down.closest('ul')).toBeNull();+ expect(down).toHaveAttribute('tabindex', '-1');+ await user.keyboard('{Escape}');+ expect(hintButton('Move down')).toBeNull();+ });++ it("gives the hint's buttons a finger's target as an invisible hit layer: the hit area writes their insets where the primary pointer is coarse", async () => {+ stubPrimaryPointer(true);+ const user = userEvent.setup();+ render(<ReorderableRows initial={['Inbox', 'Sent', 'Drafts']} />);+ handleOf('Sent').focus();+ await user.keyboard(' ');+ for (const name of ['Move up', 'Move down', 'Done']) {+ const button = hintButton(name) as HTMLElement;+ await waitFor(() =>+ expect(+ button.style.getPropertyValue('--astryx-hit-inset-top'),+ name,+ ).toMatch(/px$/),+ );+ }+ });++ it("starts the hint buttons' hit area only where the primary pointer is coarse (spec:AST-094 FR24)", async () => {+ const observed: Element[] = [];+ class Recording {+ observe(target: Element) {+ observed.push(target);+ }+ unobserve() {}+ disconnect() {}+ takeRecords() {+ return [];+ }+ }+ vi.stubGlobal('IntersectionObserver', Recording);+ vi.stubGlobal('ResizeObserver', Recording);+ try {+ const user = userEvent.setup();+ const hintButtons = () =>+ ['Move up', 'Move down', 'Done'].map(+ name => hintButton(name) as HTMLElement,+ );+ stubPrimaryPointer(false);+ const fine = render(+ <ReorderableRows initial={['Inbox', 'Sent', 'Drafts']} />,+ );+ handleOf('Sent').focus();+ await user.keyboard(' ');+ for (const button of hintButtons()) {+ expect(observed).not.toContain(button);+ }+ fine.unmount();+ // The positive control: under a finger it watches them.+ stubPrimaryPointer(true);+ render(<ReorderableRows initial={['Inbox', 'Sent', 'Drafts']} />);+ handleOf('Sent').focus();+ await user.keyboard(' ');+ for (const button of hintButtons()) {+ await waitFor(() => expect(observed).toContain(button));+ }+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it('takes an Escape that reaches the dismissal stack with the focus in the hint: the mode ends, and a layer below stays open', async () => {+ const user = userEvent.setup();+ const outer = vi.fn();+ // A layer the list sits in, such as a Dialog.+ function OuterLayer({children}: {children: ReactNode}) {+ useLayerDismissal({isActive: true, onDismiss: outer});+ return <LayerDepthProvider>{children}</LayerDepthProvider>;+ }+ render(+ <OuterLayer>+ <ReorderableRows initial={['Inbox', 'Sent', 'Drafts']} />+ </OuterLayer>,+ );+ handleOf('Sent').focus();+ await user.keyboard(' ');+ expect(handleOf('Sent')).toHaveAttribute('aria-pressed', 'true');+ // A screen reader moved into the hint: its Escape goes past the handle,+ // to the stack, whose top-most layer is the hint.+ fireEvent.keyDown(hintButton('Move up') as HTMLElement, {key: 'Escape'});+ expect(handleOf('Sent')).toHaveAttribute('aria-pressed', 'false');+ expect(hintButton('Move up')).toBeNull();+ expect(outer).not.toHaveBeenCalled();+ // The next Escape is the layer below's.+ fireEvent.keyDown(document, {key: 'Escape'});+ expect(outer).toHaveBeenCalledTimes(1);+ });++ it("reorders by taps alone: the handle, the hint's moves, then Done, the focus staying on the handle", async () => {+ const user = userEvent.setup();+ const onReorder = vi.fn();+ render(+ <ReorderableRows+ initial={['Inbox', 'Sent', 'Drafts']}+ onReorder={onReorder}+ />,+ );+ const handle = handleOf('Inbox');+ await user.click(handle);+ await user.click(hintButton('Move down') as HTMLElement);+ expect(onReorder).toHaveBeenCalledTimes(1);+ expect(onReorder).toHaveBeenLastCalledWith({key: 'Inbox', to: 1});+ expect(labels()).toEqual(['Sent', 'Inbox', 'Drafts']);+ expect(handle).toHaveFocus();+ await waitFor(() =>+ expect(document.body).toHaveTextContent(+ 'Inbox, position 2 of 3, after Sent, before Drafts',+ ),+ );+ await user.click(hintButton('Move down') as HTMLElement);+ expect(onReorder).toHaveBeenLastCalledWith({key: 'Inbox', to: 2});+ await user.click(hintButton('Move up') as HTMLElement);+ expect(onReorder).toHaveBeenCalledTimes(3);+ expect(onReorder).toHaveBeenLastCalledWith({key: 'Inbox', to: 1});+ expect(handle).toHaveFocus();+ expect(handle).toHaveAttribute('aria-pressed', 'true');+ await user.click(hintButton('Done') as HTMLElement);+ expect(handle).toHaveAttribute('aria-pressed', 'false');+ expect(hintButton('Done')).toBeNull();+ expect(handle).toHaveFocus();+ // Done ends the mode as Escape does, announcing where the row is.+ await waitFor(() =>+ expect(document.body).toHaveTextContent('Done, Inbox at position 2 of 3'),+ );+ // Kept: nothing undone.+ expect(onReorder).toHaveBeenCalledTimes(3);+ expect(labels()).toEqual(['Sent', 'Inbox', 'Drafts']);+ });++ it("refuses the hint's move into a row that keeps its place, as the key does", async () => {+ const user = userEvent.setup();+ const onReorder = vi.fn();+ render(+ <ReorderableRows+ initial={['Pinned', 'Inbox', 'Sent']}+ fixed={['Pinned']}+ onReorder={onReorder}+ />,+ );+ await user.click(handleOf('Inbox'));+ await user.click(hintButton('Move up') as HTMLElement);+ expect(onReorder).not.toHaveBeenCalled();+ await waitFor(() =>+ expect(document.body).toHaveTextContent("Can't move past Pinned"),+ );+ });++ it('shows the same hint when start(key) enters reorder mode', async () => {+ const user = userEvent.setup();+ render(+ <StartableRows initial={['Inbox', 'Sent', 'Drafts']} start="Drafts" />,+ );+ await user.click(screen.getByRole('button', {name: 'Move Drafts'}));+ await user.click(hintButton('Move up') as HTMLElement);+ expect(labels()).toEqual(['Inbox', 'Drafts', 'Sent']);+ expect(handleOf('Drafts')).toHaveFocus();+ expect(handleOf('Drafts')).toHaveAttribute('aria-pressed', 'true');+ });++ it("keeps the mouse drag slop equal to the date wheel's", () => {+ expect(MOUSE_DRAG_SLOP).toBe(DRAG_SLOP);+ });++ it('drags with a mouse once it moves the slop, from where it pressed; a smaller move stays a click', async () => {+ stubPrimaryPointer(false);+ const onReorder = vi.fn();+ render(<ReorderableRows initial={['A', 'B', 'C']} onReorder={onReorder} />);+ const list = screen.getByRole('list');+ layOut(list);+ const handle = handleOf('A');+ // Under the slop: a click, so nothing is picked up and nothing announced.+ fireEvent.pointerDown(handle, {...MOUSE, clientY: 322});+ fireEvent.pointerMove(handle, {+ ...MOUSE,+ clientY: 322 + MOUSE_DRAG_SLOP - 1,+ });+ expect(list).not.toHaveAttribute('data-astryx-reordering');+ fireEvent.pointerUp(handle, {...MOUSE, clientY: 322 + MOUSE_DRAG_SLOP - 1});+ expect(document.body).not.toHaveTextContent('Picked up');+ // That click turns reorder mode on, and another turns it off.+ fireEvent.click(handle);+ expect(handle).toHaveAttribute('aria-pressed', 'true');+ fireEvent.click(handle);+ expect(handle).toHaveAttribute('aria-pressed', 'false');+ // Past it the row follows from the press point: past both boundaries.+ mouseDrag(handle, 322, 322 + 70);+ expect(list).toHaveAttribute('data-astryx-reordering');+ await waitFor(() =>+ expect(document.body).toHaveTextContent('Picked up, position 1 of 3'),+ );+ act(() => {+ fireEvent.pointerUp(handle, {...MOUSE, clientY: 322 + 70});+ });+ expect(onReorder).toHaveBeenCalledTimes(1);+ expect(onReorder).toHaveBeenCalledWith({key: 'A', to: 2});+ expect(labels()).toEqual(['B', 'C', 'A']);+ // The drag's own click leaves reorder mode off.+ fireEvent.click(handle);+ expect(handle).toHaveAttribute('aria-pressed', 'false');+ await waitFor(() =>+ expect(document.body).toHaveTextContent('Dropped, position 3 of 3'),+ );+ });++ it('keeps the other rows still during a drag: the source dims in place, a preview follows the pointer, and an insertion line marks the drop position (design:ordered-collection-reordering)', async () => {+ stubPrimaryPointer(false);+ const onReorder = vi.fn();+ render(<ReorderableRows initial={['A', 'B', 'C']} onReorder={onReorder} />);+ const list = screen.getByRole('list');+ layOut(list);+ const [a, b, c] = Array.from(list.querySelectorAll('li'));+ const restCount = a.querySelectorAll('*').length;+ mouseDrag(handleOf('A'), 322, 322 + 70);+ // The rows the drag passes stay where they are.+ for (const row of [a, b, c]) {+ expect(['', '0px 0px', 'none']).toContain(row.style.translate);+ }+ // The source stays in its place, dimmed.+ expect(a).toHaveAttribute('data-astryx-reorder-source');+ // A preview of it follows the pointer, hidden from assistive technology.+ const preview = list.querySelector<HTMLElement>(+ '[data-astryx-reorder-preview]',+ );+ expect(preview).not.toBeNull();+ expect(preview).toHaveAttribute('aria-hidden', 'true');+ expect(preview!.textContent).toBe(a.textContent);+ // The same item, moving: the row's reduced emphasis, not raised (DR2).+ expect(preview!.style.opacity).toBe(a.style.opacity);+ expect(preview!.style.boxShadow).toBe('none');+ expect(preview!.style.translate).toBe('0px 70px');+ // The preview, the one transient copy, sits right before its source. Its+ // counter reads the source's number in a numbered list. The source counts+ // nothing while it is picked up, and the last row keeps :last-child.+ expect(preview!.nextElementSibling).toBe(a);+ expect(a.style.counterIncrement).toBe('none');+ // The line sits after C, where A would land (position 2 of 0-2). It is+ // the list's own pseudo-element, so the list holds only the rows and the+ // preview. The picked-up row holds what it held at rest.+ expect(list).toHaveAttribute('data-astryx-reorder-line');+ expect(list.style.getPropertyValue('--astryx-reorder-line-y')).toBe(+ '131px',+ );+ expect(list.children).toHaveLength(4);+ expect(a.querySelectorAll('*')).toHaveLength(restCount);+ // The drop rearranges the rows and takes the preview and line away.+ act(() => {+ fireEvent.pointerUp(handleOf('A'), {...MOUSE, clientY: 322 + 70});+ });+ expect(onReorder).toHaveBeenCalledWith({key: 'A', to: 2});+ expect(labels()).toEqual(['B', 'C', 'A']);+ expect(list.querySelector('[data-astryx-reorder-preview]')).toBeNull();+ expect(list).not.toHaveAttribute('data-astryx-reorder-line');+ expect(list.children).toHaveLength(3);+ expect(a.querySelectorAll('*')).toHaveLength(restCount);+ expect(a).not.toHaveAttribute('data-astryx-reorder-source');+ expect(a.style.counterIncrement).toBe('');+ });++ it('announces Done when a drag ends reorder mode, keeping its moves', async () => {+ stubPrimaryPointer(false);+ render(<ReorderableRows initial={['A', 'B', 'C']} />);+ const list = screen.getByRole('list');+ layOut(list);+ const handle = handleOf('A');+ fireEvent.click(handle);+ expect(handle).toHaveAttribute('aria-pressed', 'true');+ mouseDrag(handle, 322, 322 + 70);+ expect(handle).toHaveAttribute('aria-pressed', 'false');+ await waitFor(() =>+ expect(document.body).toHaveTextContent('Done, A at position 1 of 3'),+ );+ act(() => {+ fireEvent.pointerUp(handle, {...MOUSE, clientY: 322 + 70});+ });+ });++ it('restores a cancelled drag at once: no preview, no line, the source undimmed, nothing moved', async () => {+ stubPrimaryPointer(false);+ const onReorder = vi.fn();+ render(<ReorderableRows initial={['A', 'B', 'C']} onReorder={onReorder} />);+ const list = screen.getByRole('list');+ layOut(list);+ const a = list.querySelector('li')!;+ mouseDrag(handleOf('A'), 322, 322 + 70);+ expect(list.querySelector('[data-astryx-reorder-preview]')).not.toBeNull();+ act(() => {+ fireEvent.pointerCancel(handleOf('A'), {...MOUSE, clientY: 322 + 70});+ });+ expect(list.querySelector('[data-astryx-reorder-preview]')).toBeNull();+ expect(list).not.toHaveAttribute('data-astryx-reorder-line');+ expect(a).not.toHaveAttribute('data-astryx-reorder-source');+ expect(a.style.counterIncrement).toBe('');+ expect(onReorder).not.toHaveBeenCalled();+ expect(labels()).toEqual(['A', 'B', 'C']);+ });++ it.each([+ ['its row is disabled', {isDisabled: ['A']}],+ ['its row stops being reorderable', {fixed: ['A']}],+ ['the list stops being reorderable', {isReorderable: false}],+ ])(+ 'sends a mouse drag home when %s mid-drag',+ async (+ _,+ change: {+ isDisabled?: ReadonlyArray<string>;+ fixed?: ReadonlyArray<string>;+ isReorderable?: boolean;+ },+ ) => {+ stubPrimaryPointer(false);+ const onReorder = vi.fn();+ const rows = ({+ isDisabled = NONE,+ fixed = NONE,+ isReorderable = true,+ }: typeof change) => (+ <List+ reorderable={+ isReorderable+ ? createReorderable({+ onReorder,+ isReorderable: key => !fixed.includes(key as string),+ })+ : undefined+ }>+ {['A', 'B', 'C'].map(item => (+ <ListItem+ key={item}+ itemKey={item}+ label={item}+ isDisabled={isDisabled.includes(item)}+ />+ ))}+ </List>+ );+ const {rerender} = render(rows({}));+ const list = screen.getByRole('list');+ layOut(list);+ mouseDrag(handleOf('A'), 322, 322 + 70);+ expect(list).toHaveAttribute('data-astryx-reordering');+ rerender(rows(change));+ // No pointer reports this end: the session sends the row home.+ await waitFor(() =>+ expect(document.body).toHaveTextContent(+ 'Reorder cancelled, back to position 1 of 3',+ ),+ );+ expect(list).not.toHaveAttribute('data-astryx-reordering');+ fireEvent.pointerUp(list, {...MOUSE, clientY: 322 + 70});+ expect(onReorder).not.toHaveBeenCalled();+ expect(labels()).toEqual(['A', 'B', 'C']);+ },+ );++ it('writes no offset to a row a drop leaves at rest at 0, and leaves it no inline offset', () => {+ stubPrimaryPointer(false);+ render(<ReorderableRows initial={['A', 'B', 'C', 'D']} />);+ const list = screen.getByRole('list');+ layOut(list);+ const d = list.querySelectorAll('li')[3];+ // A glide that ended leaves this identity offset until its release runs.+ d.style.setProperty('translate', 'none');+ const set = vi.spyOn(animatorFor(d), 'set');+ try {+ const handle = handleOf('A');+ mouseDrag(handle, 322, 322 + 70);+ act(() => {+ fireEvent.pointerUp(handle, {...MOUSE, clientY: 322 + 70});+ });+ expect(labels()).toEqual(['B', 'C', 'A', 'D']);+ expect(set).not.toHaveBeenCalled();+ expect(d.style.getPropertyValue('translate')).toBe('');+ } finally {+ set.mockRestore();+ }+ });++ it("reads every row's layout before a drop's first glide, and the glide's spring once", () => {+ stubPrimaryPointer(true);+ const events: string[] = [];+ const glide = vi+ .spyOn(touchMotion, 'glide')+ .mockImplementation(() => events.push('write'));+ const follow = vi+ .spyOn(touchMotion, 'follow')+ .mockImplementation(() => events.push('write'));+ const spring = vi.spyOn(touchMotion, 'glideBase');+ try {+ render(<ReorderableRows initial={['A', 'B', 'C', 'D']} />);+ const list = screen.getByRole('list');+ layOut(list, () => events.push('read'));+ const handle = handleOf('A');+ mouseDrag(handle, 322, 322 + 70);+ events.length = 0;+ act(() => {+ fireEvent.pointerUp(handle, {...MOUSE, clientY: 322 + 70});+ });+ expect(labels()).toEqual(['B', 'C', 'A', 'D']);+ expect(glide).toHaveBeenCalledTimes(1);+ expect(follow).toHaveBeenCalledTimes(2);+ expect(events.slice(events.indexOf('write'))).not.toContain('read');+ expect(spring).toHaveBeenCalledTimes(1);+ } finally {+ glide.mockRestore();+ follow.mockRestore();+ spring.mockRestore();+ }+ });++ it("reads a key move's glide spring once, however many rows slide", async () => {+ stubPrimaryPointer(true);+ const follow = vi.spyOn(touchMotion, 'follow');+ const spring = vi.spyOn(touchMotion, 'glideBase');+ try {+ const user = userEvent.setup();+ render(<ReorderableRows initial={['A', 'B', 'C', 'D']} />);+ const list = screen.getByRole('list');+ layOut(list);+ handleOf('A').focus();+ await user.keyboard(' {ArrowDown}');+ await waitFor(() => expect(labels()).toEqual(['B', 'A', 'C', 'D']));+ expect(follow).toHaveBeenCalledTimes(2);+ expect(spring).toHaveBeenCalledTimes(1);+ } finally {+ follow.mockRestore();+ spring.mockRestore();+ }+ });++ it("plays a committed move's glide on the shared settle role, springs.settle (spec:AST-105 FR4)", async () => {+ stubPrimaryPointer(true);+ const glide = vi.spyOn(touchMotion, 'glideBase');+ const user = userEvent.setup();+ render(<ReorderableRows initial={['A', 'B', 'C']} />);+ const list = screen.getByRole('list');+ layOut(list);+ const handle = handleOf('A');+ handle.focus();+ await user.keyboard(' {ArrowDown}');+ await waitFor(() => expect(glide).toHaveBeenCalled());+ expect(glide.mock.results[0]?.value).toEqual({duration: 0.5, bounce: 0});+ expect(motionRole('springs.settle')).toBeDefined();+ glide.mockRestore();+ });++ it('sends a still-gliding row home on the shared settle role, keeping its velocity (spec:AST-094 FR4, FR6)', async () => {+ stubPrimaryPointer(true);+ const home = vi.spyOn(touchMotion, 'home');+ const spring = vi.spyOn(touchMotion, 'glideBase');+ const user = userEvent.setup();+ render(<ReorderableRows initial={['A', 'B', 'C']} />);+ const list = screen.getByRole('list');+ layOut(list);+ // A key move commits, and its rows glide on springs.settle.+ handleOf('A').focus();+ await user.keyboard(' {ArrowDown}{Escape}');+ await waitFor(() => expect(labels()).toEqual(['B', 'A', 'C']));+ layOut(list);+ // Picked up again while it still glides, then cancelled. It goes home on+ // the same role from where it is shown, at the speed it has.+ const handle = handleOf('A');+ mouseDrag(handle, 344, 344 + 30);+ spring.mockClear();+ fireEvent.pointerCancel(handle, {...MOUSE, clientY: 344 + 30});+ // Both rows of the move still glide, and the spring is read once.+ expect(home).toHaveBeenCalledTimes(2);+ expect(spring).toHaveBeenCalledTimes(1);+ const draggedRow = handle.closest('li');+ const calls = home.mock.calls.filter(([element]) => element === draggedRow);+ expect(calls.length).toBeGreaterThan(0);+ for (const [, spring, , fromRest] of calls) {+ expect(spring).toEqual({duration: 0.5, bounce: 0});+ expect(fromRest).toBe(false);+ }+ home.mockRestore();+ spring.mockRestore();+ });++ it('puts its listeners on the list: none on a row or a handle', () => {+ stubPrimaryPointer(true);+ const add = vi.spyOn(EventTarget.prototype, 'addEventListener');+ render(<ReorderableRows initial={['Inbox', 'Sent', 'Drafts']} />);+ const list = screen.getByRole('list');+ const targets = add.mock.contexts;+ const rows = Array.from(list.children);+ const handles = Array.from(+ list.querySelectorAll('[data-astryx-list-reorder]'),+ );+ expect(handles).toHaveLength(3);+ expect(+ targets.filter(target => handles.includes(target as Element)),+ ).toEqual([]);+ expect(targets.filter(target => rows.includes(target as Element))).toEqual(+ [],+ );+ expect(+ add.mock.calls.filter(+ (_, index) => targets[index] === list && _[0] === 'pointerdown',+ ),+ ).toHaveLength(1);+ add.mockRestore();+ });++ it('attaches one hold to the list under every primary pointer: it takes a finger everywhere, and a pen only where the primary pointer is coarse', () => {+ const attached = (coarse: boolean) => {+ stubPrimaryPointer(coarse);+ const host = getGestureHost(document);+ const attach = vi.spyOn(host, 'attach');+ const {unmount} = render(+ <ReorderableRows initial={['Inbox', 'Sent', 'Drafts']} />,+ );+ const elements = attach.mock.calls.map(([element]) => element);+ const pointerTypes = attach.mock.calls.map(([, recognizer]) =>+ [...(recognizer.allowedPointerTypes ?? [])].sort(),+ );+ const list = screen.getByRole('list');+ unmount();+ attach.mockRestore();+ return {elements, pointerTypes, list};+ };+ const coarse = attached(true);+ expect(coarse.elements).toEqual([coarse.list]);+ expect(coarse.pointerTypes).toEqual([['pen', 'touch']]);+ const fine = attached(false);+ expect(fine.elements).toEqual([fine.list]);+ expect(fine.pointerTypes).toEqual([['touch']]);+ });++ it('drags with a pen at once where the primary pointer is fine, as a mouse does', async () => {+ stubPrimaryPointer(false);+ const onReorder = vi.fn();+ render(<ReorderableRows initial={['A', 'B', 'C']} onReorder={onReorder} />);+ const list = screen.getByRole('list');+ layOut(list);+ const handle = handleOf('A');+ const PEN = {...MOUSE, pointerType: 'pen', pointerId: 2};+ fireEvent.pointerDown(handle, {...PEN, clientY: 322});+ fireEvent.pointerMove(handle, {...PEN, clientY: 322 + MOUSE_DRAG_SLOP});+ fireEvent.pointerMove(handle, {...PEN, clientY: 322 + 70});+ expect(list).toHaveAttribute('data-astryx-reordering');+ act(() => {+ fireEvent.pointerUp(handle, {...PEN, clientY: 322 + 70});+ });+ expect(onReorder).toHaveBeenCalledTimes(1);+ expect(onReorder).toHaveBeenCalledWith({key: 'A', to: 2});+ expect(labels()).toEqual(['B', 'C', 'A']);+ });++ it('starts no drag at once for a pen where the primary pointer is coarse: the pen keeps the hold, as a finger does', () => {+ stubPrimaryPointer(true);+ const onReorder = vi.fn();+ render(<ReorderableRows initial={['A', 'B', 'C']} onReorder={onReorder} />);+ const list = screen.getByRole('list');+ layOut(list);+ const handle = handleOf('A');+ const PEN = {...MOUSE, pointerType: 'pen', pointerId: 2};+ fireEvent.pointerDown(handle, {...PEN, clientY: 322});+ fireEvent.pointerMove(handle, {...PEN, clientY: 322 + MOUSE_DRAG_SLOP});+ fireEvent.pointerMove(handle, {...PEN, clientY: 322 + 70});+ expect(list).not.toHaveAttribute('data-astryx-reordering');+ fireEvent.pointerUp(handle, {...PEN, clientY: 322 + 70});+ expect(onReorder).not.toHaveBeenCalled();+ expect(labels()).toEqual(['A', 'B', 'C']);+ });++ it('listens for touches on its window only while the list is mounted', () => {+ // A touch screen, so the hold takes the window's touches.+ stubPrimaryPointer(true);+ // A window of its own, so no earlier test has touched it, whose primary+ // pointer is the page's. The gesture host listens in the window's capture+ // phase.+ const frame = document.createElement('iframe');+ document.body.append(frame);+ const doc = frame.contentDocument as Document;+ Object.defineProperty(frame.contentWindow, 'matchMedia', {+ configurable: true,+ value: (query: string) => window.matchMedia(query),+ });+ const view = frame.contentWindow as Window;+ const touches = new Set([+ 'touchstart',+ 'touchmove',+ 'touchcancel',+ 'pointerdown',+ 'pointermove',+ 'pointerup',+ 'pointercancel',+ ]);+ const added = vi.spyOn(view, 'addEventListener');+ const removed = vi.spyOn(view, 'removeEventListener');+ const mount = () => {+ const container = doc.createElement('div');+ doc.body.append(container);+ return render(<ReorderableRows initial={['Inbox', 'Sent']} />, {+ container,+ baseElement: doc.body,+ });+ };+ const first = mount();+ const second = mount();+ const listeners = added.mock.calls.filter(([type]) => touches.has(type));+ expect(listeners.length).toBeGreaterThan(0);+ first.unmount();+ second.unmount();+ // Every touch listener the lists put on the window went with them.+ for (const [type, listener, options] of listeners) {+ expect(+ removed.mock.calls.some(+ ([removedType, removedListener]) =>+ removedType === type && removedListener === listener,+ ),+ `${type} ${JSON.stringify(options)}`,+ ).toBe(true);+ }+ added.mockRestore();+ removed.mockRestore();+ frame.remove();+ });++ it('a hold on the handle opens no row menu, and a hold elsewhere on the row opens it (spec:AST-103)', () => {+ vi.useFakeTimers();+ const show = vi.spyOn(HTMLElement.prototype, 'showPopover');+ try {+ render(+ <ContextMenu label="Row actions" items={[{label: 'Move Inbox'}]}>+ <List reorderable={createReorderable({onReorder: () => {}})}>+ <ListItem itemKey="inbox" label="Inbox" />+ <ListItem itemKey="sent" label="Sent" />+ </List>+ </ContextMenu>,+ );+ const handle = handleOf('Inbox');+ show.mockClear();+ // Held past the menu's long press: the handle's hold is the row's, not+ // the menu's.+ fireEvent.touchStart(handle, {touches: [{clientX: 300, clientY: 20}]});+ act(() => {+ vi.advanceTimersByTime(800);+ });+ fireEvent.touchEnd(handle, {touches: []});+ expect(show).not.toHaveBeenCalled();+ // A finger's long press on the handle sends the menu no context+ // request either.+ const request = new MouseEvent('contextmenu', {+ bubbles: true,+ cancelable: true,+ });+ Object.defineProperty(request, 'pointerType', {value: 'touch'});+ act(() => {+ handle.dispatchEvent(request);+ });+ expect(request.defaultPrevented).toBe(true);+ expect(show).not.toHaveBeenCalled();+ // A hold on the row's label opens the row's menu.+ const label = screen.getByText('Inbox');+ fireEvent.touchStart(label, {touches: [{clientX: 40, clientY: 20}]});+ act(() => {+ vi.advanceTimersByTime(500);+ });+ fireEvent.touchEnd(label, {touches: []});+ expect(show).toHaveBeenCalled();+ } finally {+ show.mockRestore();+ vi.useRealTimers();+ }+ });++ it("keeps the handle's touch from a row menu without hiding it from the gesture host or capture listeners", () => {+ // The handle stops its touchstart in React's bubble phase. The gesture+ // host and its recognizers listen in the capture phase. So they still see+ // every touch that starts on the handle, as does any capture listener.+ stubPrimaryPointer(true);+ render(+ <ContextMenu label="Row actions" items={[{label: 'Move Inbox'}]}>+ <List reorderable={createReorderable({onReorder: () => {}})}>+ <ListItem itemKey="inbox" label="Inbox" />+ <ListItem itemKey="sent" label="Sent" />+ </List>+ </ContextMenu>,+ );+ const handle = handleOf('Inbox');+ const captured = vi.fn();+ document.addEventListener('touchstart', captured, {capture: true});+ const host = getGestureHost(document);+ try {+ const touch = {identifier: 0, clientX: 300, clientY: 20, target: handle};+ fireEvent.touchStart(handle, {touches: [touch], changedTouches: [touch]});+ expect(captured).toHaveBeenCalledTimes(1);+ expect(host.fingersDown()).toBe(1);+ fireEvent.touchEnd(handle, {touches: [], changedTouches: [touch]});+ expect(host.fingersDown()).toBe(0);+ } finally {+ document.removeEventListener('touchstart', captured, {capture: true});+ }+ });++ it('does not activate an interactive row from its handle', async () => {+ const user = userEvent.setup();+ const onClick = vi.fn();+ render(+ <List reorderable={createReorderable({onReorder: () => {}})}>+ <ListItem itemKey="inbox" label="Inbox" onClick={onClick} />+ </List>,+ );+ await user.click(handleOf('Inbox'));+ expect(onClick).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/src/List/__tests__/ListReorderLayout.test.tsx b/packages/core/src/List/__tests__/ListReorderLayout.test.tsxnew file mode 100644index 0000000000..9fe3ecc33c--- /dev/null+++ b/packages/core/src/List/__tests__/ListReorderLayout.test.tsx@@ -0,0 +1,111 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ListReorderLayout.test.tsx+ * @input List with `reorderable` and an `animatedLayout` handle, Testing+ * Library+ * @output Proof that a drag's commits are the reorder's own. The layout+ * updates measure nothing for them, and they measure the list's other+ * changes+ * @position Tests for List/List.tsx and List/listReorderEngine.tsx+ */++import {useRef, useState, type Key} from 'react';+import {describe, expect, it, vi} from 'vitest';+import {act, fireEvent, render, screen} from '@testing-library/react';+import {useAnimatedLayout} from '../../hooks/useAnimatedLayout';+import {createReorderable} from '../../reorderable/createReorderable';+import {List} from '../List';+import {ListItem} from '../ListItem';+import type * as LayoutUpdates from '../listLayoutUpdates';+import {MOUSE_DRAG_SLOP} from '../listReorderEngine';++const measureRows = vi.fn();++// The layout updates' measure, observed: List calls it before a change of+// its rows lands.+vi.mock('../listLayoutUpdates', async importOriginal => ({+ ...(await importOriginal<typeof LayoutUpdates>()),+ useListLayoutUpdates: () => measureRows,+}));++function moveKey(items: ReadonlyArray<string>, key: Key, to: number) {+ const next = items.filter(item => item !== key);+ next.splice(to, 0, key as string);+ return next;+}++let addRow: (label: string) => void = () => {};++function AnimatedReorderableRows() {+ const containerRef = useRef<HTMLDivElement>(null);+ const animatedLayout = useAnimatedLayout({containerRef});+ const [items, setItems] = useState<ReadonlyArray<string>>(['A', 'B', 'C']);+ addRow = label => setItems(previous => [...previous, label]);+ return (+ <div ref={containerRef}>+ <List+ animatedLayout={animatedLayout}+ reorderable={createReorderable({+ onReorder: ({key, to}) =>+ setItems(previous => moveKey(previous, key, to)),+ })}>+ {items.map(item => (+ <ListItem key={item} itemKey={item} label={item} />+ ))}+ </List>+ </div>+ );+}++/** jsdom lays nothing out: 44 px rows from 300 px down the viewport. */+function layOut(list: HTMLElement) {+ const place = (row: Element) => Array.from(list.children).indexOf(row);+ for (const row of Array.from(list.children)) {+ Object.defineProperty(row, 'offsetParent', {+ configurable: true,+ get: () => list,+ });+ Object.defineProperty(row, 'offsetTop', {+ configurable: true,+ get: () => place(row) * 44,+ });+ Object.defineProperty(row, 'offsetHeight', {configurable: true, value: 44});+ row.getBoundingClientRect = () =>+ DOMRect.fromRect({+ x: 0,+ y: 300 + place(row) * 44,+ width: 300,+ height: 44,+ });+ }+}++const MOUSE = {pointerType: 'mouse', pointerId: 1, button: 0, clientX: 280};++describe('List reorderable with an animatedLayout handle', () => {+ it("leaves a drag's commit to the reorder, and measures the list's other changes", () => {+ render(<AnimatedReorderableRows />);+ const list = screen.getByRole('list');+ layOut(list);+ // A change that is no reorder's: the layout updates measure it.+ act(() => addRow('D'));+ expect(measureRows).toHaveBeenCalled();+ layOut(list);+ measureRows.mockClear();+ // A drag of A to C's place. Its drop commits the new order.+ const handle = screen.getByRole('button', {name: 'Reorder A'});+ fireEvent.pointerDown(handle, {...MOUSE, clientY: 322});+ fireEvent.pointerMove(handle, {...MOUSE, clientY: 322 + MOUSE_DRAG_SLOP});+ fireEvent.pointerMove(handle, {...MOUSE, clientY: 322 + 70});+ act(() => {+ fireEvent.pointerUp(handle, {...MOUSE, clientY: 322 + 70});+ });+ expect(+ Array.from(list.querySelectorAll('li:not([data-astryx-leaving])')).map(+ row => row.textContent,+ ),+ ).toEqual(['B', 'C', 'A', 'D']);+ expect(measureRows).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/src/List/__tests__/ListReorderMode.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListReorderMode.interaction.browser.spec.tsnew file mode 100644index 0000000000..5d44aa8680--- /dev/null+++ b/packages/core/src/List/__tests__/ListReorderMode.interaction.browser.spec.ts@@ -0,0 +1,743 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ListReorderMode.interaction.browser.spec.ts+ * @input The built List "Reorderable" and "Reorder From Your UI" stories,+ * with a mouse and in the touch phone context, and the interaction+ * harness's touch driver+ * @output Browser proofs of reorder mode and its hint, in each engine. A+ * mouse click on a handle turns the mode on and shows the hint's moves and+ * Done. The focus stays on the handle, and no drop is announced. Space or+ * Enter turns it on. Each arrow commits a move at once with the focus on+ * the handle. Escape ends it, keeps the moves and announces where the row+ * is. An Escape with the focus in the hint ends the mode too, and the focus+ * goes back to the handle. A start(key) call from a button or context menu+ * enters the same mode with the focus on the handle. Under a finger, taps+ * alone reorder: the handle, the moves, then Done. A drag leaves the mode+ * off. Each of the hint's buttons is a 44 px target centered on what it+ * shows, and none covers its neighbour. A key move measures the rows in+ * one pass, before their glides start+ * @position Interaction evidence for List/listReorderEngine.tsx (reorder+ * mode and its hint) and List/ListReorderHandle.tsx+ */++import {+ expect,+ test,+ type Locator,+ type Page,+} from '@astryxdesign/a11y-spec/playwright';+import {+ drag,+ openStory,+ tap,+ touchDriver,+ waitForRest,+ withStorybook,+ type Point,+} from '@astryxdesign/interaction-harness';+import {reorder} from '../../motion/uikit/reorder';+import {describePasses, forcedPassesDuring, passesUnder} from './forcedPasses';++const storybook = withStorybook(test);++const STORY = 'core-list--reorderable';+const START_STORY = 'core-list--reorder-from-your-ui';+const ROWS = ['Inbox', 'Sent', 'Drafts', 'Archive', 'Spam', 'Trash'];+const HOLD_MS = reorder.claim.delayMs + 80;++/**+ * The list's rows, without the reorder's insertion line and drag preview:+ * inert, aria-hidden ghosts of the list (`data-astryx-leaving`).+ */+const ROW = '#storybook-root li:not([data-astryx-leaving])';++const row = (page: Page, label: string) =>+ page.locator(ROW).filter({hasText: label}).first();++const handle = (page: Page, label: string) =>+ page.getByRole('button', {name: `Reorder ${label}`, exact: true});++const labels = async (page: Page) =>+ page+ .locator(ROW)+ .evaluateAll(rows => rows.map(element => element.textContent ?? ''));++const translateY = async (element: Locator) =>+ element.evaluate(el => {+ const value = getComputedStyle(el).translate;+ if (value === 'none' || value === '') {+ return 0;+ }+ const [, y = '0px'] = value.split(' ');+ return Number.parseFloat(y);+ });++/** 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(element => element.textContent ?? '')+ .join(' '),+ );++async function centerOf(element: Locator): Promise<Point> {+ const box = await element.boundingBox();+ if (box == null) {+ throw new Error('no box');+ }+ return {x: box.x + box.width / 2, y: box.y + box.height / 2};+}++test.describe('with a mouse', () => {+ test.use({+ hasTouch: false,+ isMobile: false,+ viewport: {width: 900, height: 700},+ });++ /** This context's primary pointer is fine: a case here is a mouse's. */+ const expectFinePointer = async (page: Page) =>+ expect(+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(false);++ /**+ * The open anchored hint. It reads its surface, the theme roles it wears,+ * and its anchoring, the layer's placement rules. It also reads where it+ * sits against its anchor, the element whose `anchor-name` its+ * `position-anchor` names. That is the gap below it, and which of its edges+ * the hint lines up with. It is `start`, or `end` where the start would+ * leave the viewport.+ */+ const openHint = async (page: Page) =>+ page.evaluate(() => {+ const hint = Array.from(+ document.querySelectorAll<HTMLElement>('[popover]'),+ ).find(element => element.matches(':popover-open'));+ if (hint == null) {+ return null;+ }+ const name = getComputedStyle(hint)+ .getPropertyValue('position-anchor')+ .trim();+ const anchor = Array.from(+ document.querySelectorAll<HTMLElement>('*'),+ ).find(element =>+ element.style+ .getPropertyValue('anchor-name')+ .split(',')+ .map(part => part.trim())+ .includes(name),+ );+ if (anchor == null) {+ return null;+ }+ const box = hint.getBoundingClientRect();+ const anchorBox = anchor.getBoundingClientRect();+ const style = getComputedStyle(hint);+ return {+ below: box.top - anchorBox.bottom,+ edge:+ Math.abs(box.left - anchorBox.left) < 0.5+ ? 'start'+ : Math.abs(box.right - anchorBox.right) < 0.5+ ? 'end'+ : 'none',+ inView: box.left >= 0 && box.right <= window.innerWidth,+ anchoring: {+ positionArea: style.getPropertyValue('position-area'),+ positionTryFallbacks: style.getPropertyValue(+ 'position-try-fallbacks',+ ),+ marginBlockStart: style.marginBlockStart,+ },+ surface: {+ backgroundColor: style.backgroundColor,+ borderRadius: style.borderRadius,+ boxShadow: style.boxShadow,+ color: style.color,+ fontSize: style.fontSize,+ fontWeight: style.fontWeight,+ lineHeight: style.lineHeight,+ padding: style.padding,+ position: style.position,+ },+ };+ });++ test("reorder mode's hint sits where Core's keyboard hint does and wears the same surface", async ({+ page,+ }) => {+ // Core's keyboard hint: a tab list reached with the keyboard.+ await openStory(page, storybook(), 'core-tablist--default');+ await expectFinePointer(page);+ await page.keyboard.press('Tab');+ await expect.poll(async () => openHint(page)).not.toBeNull();+ await page.waitForTimeout(300);+ const keyboard = await openHint(page);+ // Reorder mode's hint, below the handle whose row is in the mode. The+ // list is narrowed so its handles, at the rows' end, are as far from the+ // viewport's edge as the tab list is. So each hint has the room to line+ // up with its anchor's start, and the layer flips neither.+ await openStory(page, storybook(), STORY);+ await page.evaluate(() => {+ const root = document.getElementById('storybook-root');+ if (root != null) {+ root.style.width = '420px';+ }+ });+ await handle(page, 'Inbox').focus();+ await page.keyboard.press('Space');+ await expect(page.getByRole('button', {name: 'Done'})).toBeVisible();+ await page.waitForTimeout(300);+ const reorderHint = await openHint(page);+ // The same layer, anchoring and theme roles. That is the same surface,+ // the same placement rules, the same gap below the anchor, and the same+ // edge to line up with.+ expect(reorderHint?.surface).toEqual(keyboard?.surface);+ expect(reorderHint?.anchoring).toEqual(keyboard?.anchoring);+ expect(+ Math.abs((reorderHint?.below ?? Number.NaN) - (keyboard?.below ?? 0)),+ ).toBeLessThan(0.5);+ expect(keyboard?.edge).toBe('start');+ expect(reorderHint?.edge).toBe('start');+ expect(reorderHint?.inView).toBe(true);+ // Done wears the hint's own text role, as the keyboard hint's label does.+ const done = await page+ .getByRole('button', {name: 'Done'})+ .evaluate(element => {+ const style = getComputedStyle(element);+ return {color: style.color, fontWeight: style.fontWeight};+ });+ expect(done).toEqual({+ color: keyboard?.surface.color,+ fontWeight: keyboard?.surface.fontWeight,+ });+ await page.keyboard.press('Escape');+ });++ test("a mouse click on a handle turns on reorder mode and shows its hint's moves and Done, and announces no drop", async ({+ page,+ }) => {+ await openStory(page, storybook(), STORY);+ await expectFinePointer(page);+ await handle(page, 'Inbox').click();+ await expect(handle(page, 'Inbox')).toHaveAttribute('aria-pressed', 'true');+ for (const name of ['Move up', 'Move down', 'Done']) {+ await expect(page.getByRole('button', {name})).toBeVisible();+ }+ // A click's focus is the handle's, whatever the engine does with a+ // clicked button.+ await expect(handle(page, 'Inbox')).toBeFocused();+ // Nothing was picked up: the click announces no drop.+ expect(await announced(page)).not.toContain('Dropped');+ });++ for (const key of ['Space', 'Enter']) {+ test(`${key} turns on reorder mode, each arrow commits a move at once with the focus on the handle, and Escape ends the mode keeping the moves`, async ({+ page,+ }) => {+ // spec:AST-103 FR4, in this engine: the key's own activation of the+ // button (Space's comes with its keyup) toggles the mode once.+ await openStory(page, storybook(), STORY);+ await expectFinePointer(page);+ await page.keyboard.press('Shift');+ await handle(page, 'Inbox').focus();+ await page.keyboard.press(key);+ await expect(handle(page, 'Inbox')).toHaveAttribute(+ 'aria-pressed',+ 'true',+ );+ await expect(page.getByRole('button', {name: 'Done'})).toBeVisible();+ await page.keyboard.press('ArrowDown');+ await expect+ .poll(async () => labels(page))+ .toEqual(['Sent', 'Inbox', 'Drafts', 'Archive', 'Spam', 'Trash']);+ await expect(handle(page, 'Inbox')).toBeFocused();+ await page.keyboard.press('ArrowDown');+ await expect+ .poll(async () => labels(page))+ .toEqual(['Sent', 'Drafts', 'Inbox', 'Archive', 'Spam', 'Trash']);+ await expect(handle(page, 'Inbox')).toBeFocused();+ await page.keyboard.press('Escape');+ await expect(handle(page, 'Inbox')).toHaveAttribute(+ 'aria-pressed',+ 'false',+ );+ await expect(page.getByRole('button', {name: 'Done'})).toBeHidden();+ // Leaving announces where the row is.+ await expect+ .poll(async () => announced(page))+ .toContain('Done, Inbox at position 3 of 6');+ // Kept, and at rest: with a mouse nothing travels.+ expect(await labels(page)).toEqual([+ 'Sent',+ 'Drafts',+ 'Inbox',+ 'Archive',+ 'Spam',+ 'Trash',+ ]);+ await expect(handle(page, 'Inbox')).toBeFocused();+ for (const label of ROWS) {+ expect(await translateY(row(page, label))).toBe(0);+ }+ });+ }++ test('an Escape with the focus in the hint ends reorder mode, and the focus goes back to the handle', async ({+ page,+ }) => {+ // A screen reader can move the focus into the hint's buttons; their+ // Escape reaches the shared dismissal stack, not the handle.+ await openStory(page, storybook(), STORY);+ await expectFinePointer(page);+ await handle(page, 'Sent').click();+ await expect(handle(page, 'Sent')).toHaveAttribute('aria-pressed', 'true');+ const up = page.getByRole('button', {name: 'Move up'});+ await up.focus();+ await expect(up).toBeFocused();+ await page.keyboard.press('Escape');+ await expect(handle(page, 'Sent')).toHaveAttribute('aria-pressed', 'false');+ await expect(up).toBeHidden();+ await expect(handle(page, 'Sent')).toBeFocused();+ expect(await labels(page)).toEqual(ROWS);+ });++ for (const from of ['a button', 'the context menu']) {+ test(`start(key) from ${from} turns on reorder mode with the focus on the handle, and the arrows and the hint work`, async ({+ page,+ }) => {+ // spec:AST-103 FR4a: a closing menu restores its trigger's focus; the+ // handle takes it back.+ await openStory(page, storybook(), START_STORY);+ await expectFinePointer(page);+ if (from === 'a button') {+ await page.getByRole('button', {name: 'Move Sent'}).click();+ } else {+ await row(page, 'Drafts').click({button: 'right'});+ await page.getByRole('menuitem', {name: 'Move Sent'}).click();+ }+ await expect(handle(page, 'Sent')).toHaveAttribute(+ 'aria-pressed',+ 'true',+ );+ await expect(handle(page, 'Sent')).toBeFocused();+ await expect(page.getByRole('button', {name: 'Done'})).toBeVisible();+ await page.keyboard.press('ArrowDown');+ await expect+ .poll(async () => labels(page))+ .toEqual(['Inbox', 'Drafts', 'Sent', 'Archive', 'Spam', 'Trash']);+ await page.getByRole('button', {name: 'Move up'}).click();+ await expect.poll(async () => labels(page)).toEqual(ROWS);+ await expect(handle(page, 'Sent')).toBeFocused();+ await page.keyboard.press('Escape');+ await expect(handle(page, 'Sent')).toHaveAttribute(+ 'aria-pressed',+ 'false',+ );+ });+ }+});++test.describe('with a finger', () => {+ /**+ * Opens the story on a touch screen: Chromium's touch emulation is a+ * coarse pointer.+ */+ async function open(page: Page) {+ await openStory(page, storybook(), STORY);+ const touch = await page.evaluate(+ () => matchMedia('(pointer: coarse)').matches,+ );+ test.skip(!touch, 'the touch hint runs on a touch screen');+ await expect(handle(page, 'Inbox')).toBeVisible();+ }++ test('a key move measures the rows in one pass, before their glides start', async ({+ page,+ browser,+ browserName,+ }) => {+ test.skip(browserName !== 'chromium', 'the layout trace is Chromium CDP');+ await open(page);+ await expect(page.locator(ROW)).toHaveCount(ROWS.length);+ await handle(page, 'Inbox').focus();+ await page.keyboard.press('Space');+ await expect(handle(page, 'Inbox')).toHaveAttribute('aria-pressed', 'true');+ const move = async (key: string, order: ReadonlyArray<string>) =>+ forcedPassesDuring(browser, page, async () => {+ await page.keyboard.press(key);+ await expect.poll(async () => labels(page)).toEqual(order);+ // The commit's glides start before the next frame.+ await page.evaluate(+ async () =>+ new Promise(resolve => {+ requestAnimationFrame(() => requestAnimationFrame(resolve));+ }),+ );+ });+ // The first move: Inbox and Sent glide for the first time.+ const first = await move('ArrowDown', [+ 'Sent',+ 'Inbox',+ 'Drafts',+ 'Archive',+ 'Spam',+ 'Trash',+ ]);+ expect(first.events.has('keydown')).toBe(true);+ expect(first.rounds).toBeGreaterThan(0);+ // The reorder's own reads, in the key's move and in its commit, are one+ // measurement pass at most. The shared animator reads a row's will-change+ // on its first glide, a cost of its own. Two rows glide here for the first+ // time, so it adds two passes at most.+ const moves = passesUnder(first.passes, ['step', 'commit']);+ const animators = moves.filter(pass =>+ pass.sources[0]?.includes('animator'),+ );+ const firstReport = describePasses(first.passes);+ expect(moves.length - animators.length, firstReport).toBeLessThanOrEqual(1);+ expect(animators.length, firstReport).toBeLessThanOrEqual(2);+ // Once the glides end, a move back over the same rows counts every read.+ await waitForRest(row(page, 'Inbox'));+ await waitForRest(row(page, 'Sent'));+ // The animator lets each row's layer go once its glide has lingered, and+ // then reads the stylesheet's will-change in a zero-delay task. A move+ // before that read would make it itself, so the case waits for both.+ await expect+ .poll(+ async () =>+ page+ .locator(ROW)+ .evaluateAll(rows =>+ rows.every(+ element =>+ !(element as HTMLElement).style.willChange.includes(+ 'translate',+ ),+ ),+ ),+ {message: 'the animator lets the gliding rows go', timeout: 5000},+ )+ .toBe(true);+ await page.evaluate(+ async () =>+ new Promise(resolve => {+ setTimeout(resolve, 0);+ }),+ );+ const back = await move('ArrowUp', ROWS);+ expect(back.events.has('keydown')).toBe(true);+ expect(back.rounds).toBeGreaterThan(0);+ expect(+ passesUnder(back.passes, ['step', 'commit']).length,+ describePasses(back.passes),+ ).toBeLessThanOrEqual(1);+ });++ test("a key move at the screen's bottom edge brings the row's new place into view", async ({+ page,+ }) => {+ await openStory(page, storybook(), 'core-list--reorder-long-list');+ const touch = await page.evaluate(+ () => matchMedia('(pointer: coarse)').matches,+ );+ test.skip(!touch, 'the rows slide where the primary pointer is coarse');+ await expect(page.locator(ROW)).toHaveCount(30);+ const moved = handle(page, 'Item 20');+ const row = moved.locator('xpath=ancestor::li[1]');+ // The row's bottom sits on the screen's bottom edge, the page scrolled.+ await row.evaluate(element => {+ element.scrollIntoView({block: 'end'});+ });+ expect(await page.evaluate(() => window.scrollY)).toBeGreaterThan(0);+ await moved.focus();+ await page.keyboard.press('Space');+ await expect(moved).toHaveAttribute('aria-pressed', 'true');+ expect((await labels(page)).indexOf('Item 20')).toBe(19);+ await page.keyboard.press('ArrowDown');+ // The row moves one place down, glides there, then rests.+ await expect+ .poll(async () => (await labels(page)).indexOf('Item 20'), {+ message: 'Item 20 moves one place down',+ timeout: 5000,+ })+ .toBe(20);+ await waitForRest(row);+ const box = await row.boundingBox();+ const height = page.viewportSize()?.height ?? 0;+ expect(box).not.toBeNull();+ expect(Math.round((box?.y ?? 0) + (box?.height ?? 0))).toBeLessThanOrEqual(+ height,+ );+ });++ test("taps alone reorder: the handle turns on reorder mode, the hint's moves move the row, and Done ends the mode", async ({+ page,+ browserName,+ }) => {+ // Linux WebKit's injected touches dispatch pointer and touch events but+ // no click, so a tap cannot activate a button there (iOS Safari's tap+ // does).+ test.skip(browserName === 'webkit', 'injected touches synthesize no click');+ await open(page);+ const before = await labels(page);+ const driver = await touchDriver(page);+ await driver.play(tap(await centerOf(handle(page, 'Inbox'))));+ await expect(handle(page, 'Inbox')).toHaveAttribute('aria-pressed', 'true');+ const down = page.getByRole('button', {name: 'Move down'});+ await expect(down).toBeVisible();+ await driver.play(tap(await centerOf(down)));+ await expect+ .poll(async () => labels(page))+ .toEqual([before[1], before[0], ...before.slice(2)]);+ // The focus stayed on the handle through the taps.+ await expect(handle(page, 'Inbox')).toBeFocused();+ await driver.play(+ tap(await centerOf(page.getByRole('button', {name: 'Done'}))),+ );+ await expect(handle(page, 'Inbox')).toHaveAttribute(+ 'aria-pressed',+ 'false',+ );+ await expect(down).toBeHidden();+ expect(await labels(page)).toEqual([+ before[1],+ before[0],+ ...before.slice(2),+ ]);+ });++ test('a drag does not also turn on reorder mode', async ({page}) => {+ await open(page);+ const pitch = await row(page, 'Inbox').evaluate(element => {+ const next = element.nextElementSibling as HTMLElement | null;+ return next == null+ ? (element as HTMLElement).offsetHeight+ : next.offsetTop - (element as HTMLElement).offsetTop;+ });+ const from = await centerOf(handle(page, 'Inbox'));+ const driver = await touchDriver(page);+ await driver.play(+ drag(+ from,+ {x: from.x, y: from.y + 1.2 * pitch},+ {holdMs: HOLD_MS, durationMs: 300, restMs: 150},+ ),+ );+ await page.waitForTimeout(400);+ await expect(handle(page, 'Inbox')).toHaveAttribute(+ 'aria-pressed',+ 'false',+ );+ await expect(page.getByRole('button', {name: 'Done'})).toBeHidden();+ });++ test("each of the hint's buttons keeps its size, and its touch target grows toward 44 px without covering its neighbour", async ({+ page,+ browser,+ browserName,+ }) => {+ // No control grows for a finger. Where the primary pointer is coarse, a+ // target reaches toward 44 px through an invisible hit layer. Each side+ // stops at half the gap to a neighbouring target, so a tap always goes to+ // the nearer one.+ await open(page);+ await handle(page, 'Sent').focus();+ await page.keyboard.press('Enter');+ await expect(handle(page, 'Sent')).toHaveAttribute('aria-pressed', 'true');+ const names = ['Move up', 'Move down', 'Done'];+ for (const name of names) {+ await expect(page.getByRole('button', {name})).toBeVisible();+ }+ // The hit layer's insets are written a frame after the hint shows.+ await expect+ .poll(async () =>+ page+ .getByRole('button', {name: 'Move up'})+ .evaluate(element =>+ getComputedStyle(element)+ .getPropertyValue('--astryx-hit-inset-top')+ .trim(),+ ),+ )+ .not.toBe('');+ const targets = await page.evaluate(+ list =>+ list.map(name => {+ const element = Array.from(document.querySelectorAll('button')).find(+ button =>+ button.getAttribute('aria-label') === name ||+ button.textContent?.trim() === name,+ );+ if (element == null) {+ throw new Error(`no ${name}`);+ }+ const style = getComputedStyle(element);+ const inset = (side: string) =>+ parseFloat(style.getPropertyValue(`--astryx-hit-inset-${side}`)) ||+ 0;+ const box = element.getBoundingClientRect();+ const glyph = (+ element.firstElementChild ?? element+ ).getBoundingClientRect();+ // What the button adds around what it shows: its glyph's box, or+ // its text's.+ // A text's height is its line's, which the button's height holds.+ const range = document.createRange();+ range.selectNodeContents(element);+ const glyphBox = element.firstElementChild?.getBoundingClientRect();+ const lineHeight = parseFloat(getComputedStyle(element).lineHeight);+ const content = glyphBox ?? {+ width: range.getBoundingClientRect().width,+ height: Number.isFinite(lineHeight)+ ? lineHeight+ : range.getBoundingClientRect().height,+ };+ return {+ name,+ chrome: {+ x: box.width - content.width,+ y: box.height - content.height,+ },+ box: {+ left: box.left,+ right: box.right,+ top: box.top,+ bottom: box.bottom,+ },+ hit: {+ left: box.left - inset('left'),+ right: box.right + inset('right'),+ top: box.top - inset('top'),+ bottom: box.bottom + inset('bottom'),+ },+ glyph: {left: glyph.left, right: glyph.right},+ };+ }),+ names,+ );+ // The same hint where the primary pointer is fine. Each button adds the+ // same space around what it shows, since no control grows for a finger.+ // Only the invisible hit layer reaches further. The theme's type scale may+ // set larger text where the primary pointer is coarse, so the comparison+ // leaves the text's own size out.+ const fineContext = await browser.newContext({+ viewport: page.viewportSize() ?? {width: 390, height: 844},+ hasTouch: false,+ isMobile: false,+ });+ const fine = await fineContext.newPage();+ await openStory(fine, storybook(), STORY);+ expect(+ await fine.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(false);+ await handle(fine, 'Sent').focus();+ await fine.keyboard.press('Enter');+ await expect(handle(fine, 'Sent')).toHaveAttribute('aria-pressed', 'true');+ const fineSizes = await fine.evaluate(+ list =>+ list.map(name => {+ const element = Array.from(document.querySelectorAll('button')).find(+ button =>+ button.getAttribute('aria-label') === name ||+ button.textContent?.trim() === name,+ );+ if (element == null) {+ throw new Error(`no ${name}`);+ }+ const box = element.getBoundingClientRect();+ // A text's height is its line's, which the button's height holds.+ const range = document.createRange();+ range.selectNodeContents(element);+ const glyphBox = element.firstElementChild?.getBoundingClientRect();+ const lineHeight = parseFloat(getComputedStyle(element).lineHeight);+ const content = glyphBox ?? {+ width: range.getBoundingClientRect().width,+ height: Number.isFinite(lineHeight)+ ? lineHeight+ : range.getBoundingClientRect().height,+ };+ return {+ x: box.width - content.width,+ y: box.height - content.height,+ };+ }),+ names,+ );+ await fineContext.close();+ for (const [index, {name, box, hit, chrome}] of targets.entries()) {+ // Its own size around what it shows: the same as under a fine pointer.+ expect(+ Math.abs(chrome.x - fineSizes[index].x),+ `${name} adds no width for a finger`,+ ).toBeLessThanOrEqual(0.5);+ expect(+ Math.abs(chrome.y - fineSizes[index].y),+ `${name} adds no height for a finger`,+ ).toBeLessThanOrEqual(0.5);+ // The hit layer only grows, and never past 44 px unless the button+ // itself is larger.+ const width = box.right - box.left;+ const height = box.bottom - box.top;+ expect(+ hit.right - hit.left,+ `${name} target width`,+ ).toBeGreaterThanOrEqual(width);+ expect(hit.bottom - hit.top).toBeGreaterThanOrEqual(height);+ expect(hit.right - hit.left).toBeLessThanOrEqual(+ Math.max(44, width) + 0.5,+ );+ expect(hit.bottom - hit.top).toBeLessThanOrEqual(+ Math.max(44, height) + 0.5,+ );+ }+ // Neighbouring targets meet at most halfway: none covers the next.+ for (let index = 0; index + 1 < targets.length; index += 1) {+ expect(+ targets[index].hit.right,+ `${targets[index].name} stops short of ${targets[index + 1].name}`,+ ).toBeLessThanOrEqual(targets[index + 1].hit.left + 0.5);+ }+ // Every point of each glyph, and the edge of each target, hits its own+ // button.+ for (const {name, box, hit, glyph} of targets) {+ const y = (box.top + box.bottom) / 2;+ for (const x of [+ glyph.left + 1,+ glyph.right - 1,+ hit.left + 1,+ hit.right - 1,+ ]) {+ const label = await page.evaluate(+ ([px, py]) => {+ const button = document.elementFromPoint(px, py)?.closest('button');+ return (+ button?.getAttribute('aria-label') ??+ button?.textContent?.trim() ??+ null+ );+ },+ [x, y] as const,+ );+ expect(label, `${name} at x=${x.toFixed(1)}`).toBe(name);+ }+ }+ // A tap in Move up's target just past its visible edge, nearer it than+ // Move down, moves the row up. A tap activates a button in every engine,+ // except under Linux WebKit's injected touches.+ if (browserName === 'webkit') {+ return;+ }+ const [up] = targets;+ const driver = await touchDriver(page);+ await driver.play(+ tap({x: up.hit.right - 1, y: (up.box.top + up.box.bottom) / 2}),+ );+ await expect+ .poll(async () => labels(page))+ .toEqual(['Sent', 'Inbox', 'Drafts', 'Archive', 'Spam', 'Trash']);+ });+});diff --git a/packages/core/src/List/__tests__/ListReorderPointer.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListReorderPointer.interaction.browser.spec.tsnew file mode 100644index 0000000000..8e3d164eae--- /dev/null+++ b/packages/core/src/List/__tests__/ListReorderPointer.interaction.browser.spec.ts@@ -0,0 +1,740 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ListReorderPointer.interaction.browser.spec.ts+ * @input The built List "Reorderable" story in two contexts: one with no+ * touch screen, so the primary pointer is fine, and the touch phone. A real+ * mouse and the harness's real engine pen drive it (the pen in Chromium)+ * @output Browser proofs of who drags a row without a hold. A mouse drags a+ * row from its handle at once. So does a pen where the primary pointer is+ * fine. A pen where the primary pointer is coarse keeps the hold, as a+ * finger does. A quick stroke moves nothing, and a held one moves the row.+ * A row held near a scroll edge scrolls the page, or the box the list+ * scrolls in, and stops at the end. A wheel during a drag scrolls the+ * page, and the preview and the drop stay under the pointer. Each scrolled+ * frame reads the scroll offset once at most and forces no layout. A drop+ * measures the rows in one pass, before its writes, whatever their count. The+ * preview and the insertion line run along a row set in from the list's+ * start, in either direction. A checked radio in the dragged row stays+ * checked through the drag+ * @position Beside ListReorderTouch.interaction.browser.spec.ts, which proves+ * the hold under a finger+ */++import {+ expect,+ test,+ type Browser,+ type Page,+} from '@astryxdesign/a11y-spec/playwright';+import {+ openStory,+ PEN_SKIP,+ webInputDriver,+ withStorybook,+ type PenPoint,+} from '@astryxdesign/interaction-harness';+import {reorder} from '../../motion/uikit/reorder';+import {describePasses, forcedPassesDuring, passesUnder} from './forcedPasses';++const storybook = withStorybook(test);++const STORY = 'core-list--reorderable';++const LONG_STORY = 'core-list--reorder-long-list';++/** Past the claim delay: the hold claims the drag. */+const HOLD_MS = reorder.claim.delayMs + 150;++/** The story's row labels, in order. */+async function labels(page: Page): Promise<string[]> {+ return page+ .locator('#storybook-root li:not([data-astryx-leaving])')+ .evaluateAll(rows => rows.map(row => row.textContent?.trim() ?? ''));+}++/** The centre of `label`'s handle and the height of its row. */+async function handleOf(page: Page, label: string) {+ const handle = page.getByRole('button', {name: `Reorder ${label}`});+ await expect(handle).toBeVisible();+ const box = await handle.boundingBox();+ const row = await handle+ .locator('xpath=ancestor::li[1]')+ .evaluate(element => element.getBoundingClientRect().height);+ if (box == null) {+ throw new Error(`no handle for ${label}`);+ }+ return {+ at: {x: box.x + box.width / 2, y: box.y + box.height / 2},+ rowHeight: row,+ };+}++/** The first row moved two places down: the order a two-row drag commits. */+function movedTwoDown(order: ReadonlyArray<string>): string[] {+ return [order[1], order[2], order[0], ...order.slice(3)];+}++/**+ * The story in a context with no touch screen, so the primary pointer is+ * fine. Contexts made here inherit the project's phone options unless they+ * are named.+ */+async function openFinePointerStory(browser: Browser, story = STORY) {+ const context = await browser.newContext({+ viewport: {width: 800, height: 900},+ deviceScaleFactor: 1,+ isMobile: false,+ hasTouch: false,+ });+ const page = await context.newPage();+ await openStory(page, storybook(), story);+ expect(+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(false);+ return {page, close: async () => context.close()};+}++/** A stroke from `at` straight down `distance`, a point every 16 ms. */+function strokeDown(+ at: {x: number; y: number},+ distance: number,+ startMs = 0,+): PenPoint[] {+ const steps = 16;+ return Array.from({length: steps + 1}, (_, step) => ({+ x: at.x,+ y: at.y + (distance * step) / steps,+ t: startMs + step * 16,+ }));+}++test('a mouse drags a row from its handle at once, where the primary pointer is fine', async ({+ browser,+}) => {+ const story = await openFinePointerStory(browser);+ try {+ const {page} = story;+ const before = await labels(page);+ expect(before.length).toBeGreaterThanOrEqual(3);+ const {at, rowHeight} = await handleOf(page, before[0]);+ await page.mouse.move(at.x, at.y);+ await page.mouse.down();+ await page.mouse.move(at.x, at.y + rowHeight * 2.5, {steps: 12});+ await page.mouse.up();+ await expect.poll(async () => labels(page)).toEqual(movedTwoDown(before));+ } finally {+ await story.close();+ }+});++test('a row held near the bottom of the page scrolls the page', async ({+ browser,+}) => {+ const story = await openFinePointerStory(browser, LONG_STORY);+ try {+ const {page} = story;+ const order = await labels(page);+ // Item 4: an earlier one's name is a prefix of a later row's.+ const {at} = await handleOf(page, order[3]);+ const bottom = await page.evaluate(() => window.innerHeight);+ expect(await page.evaluate(() => window.scrollY)).toBe(0);+ await page.mouse.move(at.x, at.y);+ await page.mouse.down();+ await page.mouse.move(at.x, bottom - 4, {steps: 12});+ await expect+ .poll(async () => page.evaluate(() => window.scrollY), {timeout: 3000})+ .toBeGreaterThan(0);+ await page.keyboard.press('Escape');+ await page.mouse.up();+ } finally {+ await story.close();+ }+});++test('a row held at the bottom of the page stops at its end, under the pointer', async ({+ browser,+}) => {+ const story = await openFinePointerStory(browser, LONG_STORY);+ try {+ const {page} = story;+ const order = await labels(page);+ // Item 4: an earlier one's name is a prefix of a later row's.+ const {at} = await handleOf(page, order[3]);+ const viewport = page.viewportSize();+ await page.mouse.move(at.x, at.y);+ await page.mouse.down();+ await page.mouse.move(at.x, (viewport?.height ?? 0) - 4, {steps: 12});+ // The page scrolls until the list's end is in view, then stops.+ let last = Number.NaN;+ await expect+ .poll(+ async () => {+ const y = await page.evaluate(() => window.scrollY);+ const isStill = y > 0 && y === last;+ last = y;+ return isStill;+ },+ {intervals: [250], timeout: 8000},+ )+ .toBe(true);+ const listBottom = await page.evaluate(+ () =>+ document.querySelector('#storybook-root ul')?.getBoundingClientRect()+ .bottom ?? Number.NaN,+ );+ expect(listBottom).toBeLessThanOrEqual(viewport?.height ?? 0);+ const previewTop = async () =>+ page.evaluate(+ () =>+ document+ .querySelector('[data-astryx-reorder-preview]')+ ?.getBoundingClientRect().top ?? Number.NaN,+ );+ const atEnd = await previewTop();+ await page.waitForTimeout(300);+ // Held at the end, nothing moves: the page stays where it stopped, and+ // the preview stays where the pointer holds it.+ expect(await page.evaluate(() => window.scrollY)).toBe(last);+ expect(Math.abs((await previewTop()) - atEnd)).toBeLessThan(1);+ await page.keyboard.press('Escape');+ await page.mouse.up();+ } finally {+ await story.close();+ }+});++test('a wheel during a drag scrolls the page, and the preview and the drop stay under the pointer', async ({+ browser,+}) => {+ const story = await openFinePointerStory(browser, LONG_STORY);+ try {+ const {page} = story;+ const order = await labels(page);+ // Item 4: an earlier one's name is a prefix of a later row's.+ const {at, rowHeight} = await handleOf(page, order[3]);+ const pitch = await page.evaluate(() => {+ const rows = document.querySelectorAll('#storybook-root ul > li');+ return (+ rows[1].getBoundingClientRect().top -+ rows[0].getBoundingClientRect().top+ );+ });+ // The preview's top and the insertion line's y, in the viewport.+ const placed = async () =>+ page.evaluate(() => {+ const list = document.querySelector<HTMLElement>('#storybook-root ul');+ const preview = document.querySelector('[data-astryx-reorder-preview]');+ const line = parseFloat(+ list == null+ ? ''+ : getComputedStyle(list).getPropertyValue(+ '--astryx-reorder-line-y',+ ),+ );+ return {+ preview: preview?.getBoundingClientRect().top ?? Number.NaN,+ line: (list?.getBoundingClientRect().top ?? Number.NaN) + line,+ };+ });+ await page.mouse.move(at.x, at.y);+ await page.mouse.down();+ await page.mouse.move(at.x, at.y + rowHeight * 1.5, {steps: 8});+ await expect(page.locator('[data-astryx-reorder-preview]')).toHaveCount(1);+ const before = await placed();+ // Counts rendered frames from the last scroll to the first frame that+ // shows the preview and the line under the pointer again.+ await page.evaluate(target => {+ const state = {frame: 0, lastScroll: -1, settledAt: -1};+ Object.assign(window, {c06Frames: state});+ const check = () => {+ if (state.lastScroll < 0 || state.settledAt >= 0) {+ return;+ }+ const list = document.querySelector<HTMLElement>('#storybook-root ul');+ const preview = document.querySelector('[data-astryx-reorder-preview]');+ if (list == null || preview == null) {+ return;+ }+ const line =+ list.getBoundingClientRect().top ++ parseFloat(+ getComputedStyle(list).getPropertyValue('--astryx-reorder-line-y'),+ );+ const top = preview.getBoundingClientRect().top;+ if (+ Math.abs(top - target.preview) < 1 &&+ Math.abs(line - target.line) < 1+ ) {+ state.settledAt = state.frame;+ }+ };+ const tick = () => {+ state.frame += 1;+ // After the frame renders.+ setTimeout(check, 0);+ requestAnimationFrame(tick);+ };+ requestAnimationFrame(tick);+ document.addEventListener(+ 'scroll',+ () => {+ // The scroll steps come before the frame's callbacks.+ state.lastScroll = state.frame + 1;+ state.settledAt = -1;+ },+ {passive: true},+ );+ }, before);+ await page.mouse.wheel(0, pitch * 3);+ // The wheel's scroll animates: wait for it to rest.+ let last = Number.NaN;+ await expect+ .poll(+ async () => {+ const y = await page.evaluate(() => window.scrollY);+ const isStill = y > 0 && y === last;+ last = y;+ return isStill;+ },+ {intervals: [100], timeout: 5000},+ )+ .toBe(true);+ const frames = async () =>+ page.evaluate(+ () =>+ (+ window as unknown as {+ c06Frames: {lastScroll: number; settledAt: number};+ }+ ).c06Frames,+ );+ // The preview and the line come back under the pointer.+ await expect+ .poll(async () => (await frames()).settledAt >= 0, {timeout: 100})+ .toBe(true);+ const {lastScroll, settledAt} = await frames();+ // Within two frames of the scroll, as a native drag follows it.+ expect(settledAt - lastScroll).toBeLessThanOrEqual(2);+ await page.mouse.up();+ // The drop lands under the pointer, past the rows the wheel scrolled by.+ await expect+ .poll(async () => (await labels(page)).indexOf(order[3]), {+ timeout: 600,+ })+ .toBe(4 + Math.round(last / pitch));+ } finally {+ await story.close();+ }+});++test('a wheel during a drag forces no layout, and reads the scroll offset once a scrolled frame at most', async ({+ browser,+ browserName,+}) => {+ test.skip(browserName !== 'chromium', 'the layout trace is Chromium CDP');+ const story = await openFinePointerStory(browser, LONG_STORY);+ try {+ const {page} = story;+ const order = await labels(page);+ // Item 4: an earlier one's name is a prefix of a later row's.+ const {at, rowHeight} = await handleOf(page, order[3]);+ await page.mouse.move(at.x, at.y);+ await page.mouse.down();+ await page.mouse.move(at.x, at.y + rowHeight * 1.5, {steps: 8});+ await expect(page.locator('[data-astryx-reorder-preview]')).toHaveCount(1);+ // Counts reads of the page scroller's offset, and the frames a scroll+ // lands in.+ await page.evaluate(() => {+ const scroller = document.scrollingElement as Element;+ const own = Object.getOwnPropertyDescriptor(+ Element.prototype,+ 'scrollTop',+ );+ const counts = {reads: 0, frames: 0};+ Object.assign(window, {c06Counts: counts});+ Object.defineProperty(scroller, 'scrollTop', {+ configurable: true,+ get() {+ counts.reads += 1;+ return own?.get?.call(this) as number;+ },+ set(value: number) {+ own?.set?.call(this, value);+ },+ });+ let isCounted = false;+ document.addEventListener(+ 'scroll',+ () => {+ if (!isCounted) {+ isCounted = true;+ counts.frames += 1;+ requestAnimationFrame(() => {+ isCounted = false;+ });+ }+ },+ {passive: true},+ );+ });+ await browser.startTracing(page, {+ categories: [+ 'devtools.timeline',+ 'disabled-by-default-devtools.timeline',+ 'disabled-by-default-devtools.timeline.stack',+ ],+ });+ await page.mouse.wheel(0, rowHeight * 3);+ // The pointer moves too, so moves and scrolls share frames.+ for (let step = 1; step <= 16; step += 1) {+ await page.mouse.move(at.x, at.y + rowHeight * 1.5 + step);+ await page.waitForTimeout(16);+ }+ await page.waitForTimeout(400);+ const trace = JSON.parse((await browser.stopTracing()).toString()) as {+ traceEvents: {+ name: string;+ ph: string;+ pid: number;+ tid: number;+ args?: {+ name?: string;+ beginData?: {stackTrace?: {functionName?: string}[]};+ };+ }[];+ };+ const counts = await page.evaluate(+ () =>+ (window as unknown as {c06Counts: {reads: number; frames: number}})+ .c06Counts,+ );+ await page.mouse.up();+ const mainThreads = new Set(+ trace.traceEvents+ .filter(e => e.ph === 'M' && e.name === 'thread_name')+ .filter(e => e.args?.name === 'CrRendererMain')+ .map(e => `${e.pid}:${e.tid}`),+ );+ // A style or layout pass with a script stack ran inside script: a read+ // after a write forced it, instead of the frame's own pass.+ const forced = trace.traceEvents.filter(+ e =>+ (e.name === 'Layout' || e.name === 'UpdateLayoutTree') &&+ mainThreads.has(`${e.pid}:${e.tid}`) &&+ (e.args?.beginData?.stackTrace ?? []).length > 0,+ );+ expect(+ forced.map(+ e =>+ `${e.name} in ${e.args?.beginData?.stackTrace?.[0]?.functionName ?? '?'}`,+ ),+ ).toEqual([]);+ expect(counts.frames).toBeGreaterThan(0);+ expect(counts.reads).toBeGreaterThan(0);+ expect(counts.reads).toBeLessThanOrEqual(counts.frames);+ } finally {+ await story.close();+ }+});++test('a drop measures the rows in one pass, before its writes, whatever their count', async ({+ browser,+ browserName,+}) => {+ test.skip(browserName !== 'chromium', 'the layout trace is Chromium CDP');+ const story = await openFinePointerStory(browser, LONG_STORY);+ try {+ const {page} = story;+ const order = await labels(page);+ expect(order.length).toBeGreaterThanOrEqual(20);+ const {at, rowHeight} = await handleOf(page, order[3]);+ await page.mouse.move(at.x, at.y);+ await page.mouse.down();+ await page.mouse.move(at.x, at.y + rowHeight * 4.5, {steps: 12});+ await expect(page.locator('[data-astryx-reorder-preview]')).toHaveCount(1);+ const {passes, events, rounds} = await forcedPassesDuring(+ browser,+ page,+ async () => {+ await page.mouse.up();+ await expect.poll(async () => labels(page)).not.toEqual(order);+ // The commit's rebase runs before the next frame.+ await page.evaluate(+ async () =>+ new Promise(resolve => {+ requestAnimationFrame(() => requestAnimationFrame(resolve));+ }),+ );+ },+ );+ // The trace saw the drop: its release, and the page's rendering after it.+ expect(events.has('pointerup')).toBe(true);+ expect(rounds).toBeGreaterThan(0);+ // The reorder's own reads, in the drop and in its commit, are one+ // measurement pass at most. Moving the focused row makes React and the+ // browser force passes of their own, outside the reorder.+ const reorders = passesUnder(passes, ['drop', 'commit']);+ expect(reorders.length, describePasses(passes)).toBeLessThanOrEqual(1);+ } finally {+ await story.close();+ }+});++test('a row held near the bottom of a box the list scrolls in scrolls that box, not the page', async ({+ browser,+}) => {+ const story = await openFinePointerStory(browser, LONG_STORY);+ try {+ const {page} = story;+ // The list scrolls in a 400 px box instead of the page.+ const boxBottom = await page.evaluate(() => {+ const root = document.querySelector<HTMLElement>('#storybook-root');+ if (root == null) {+ return null;+ }+ root.style.blockSize = '400px';+ root.style.overflowY = 'auto';+ return (+ root.getBoundingClientRect().top + root.clientTop + root.clientHeight+ );+ });+ expect(boxBottom).not.toBeNull();+ const order = await labels(page);+ // Item 4: an earlier one's name is a prefix of a later row's.+ const {at} = await handleOf(page, order[3]);+ await page.mouse.move(at.x, at.y);+ await page.mouse.down();+ await page.mouse.move(at.x, (boxBottom ?? 0) - 4, {steps: 12});+ await expect+ .poll(+ async () =>+ page.evaluate(+ () => document.querySelector('#storybook-root')?.scrollTop ?? 0,+ ),+ {timeout: 3000},+ )+ .toBeGreaterThan(0);+ expect(await page.evaluate(() => window.scrollY)).toBe(0);+ await page.keyboard.press('Escape');+ await page.mouse.up();+ } finally {+ await story.close();+ }+});++test('a checked radio in the dragged row stays checked through the drag and a drop in place', async ({+ browser,+}) => {+ const story = await openFinePointerStory(browser);+ try {+ const {page} = story;+ // Each row holds a radio of one group, and the first row's is checked.+ await page.evaluate(() => {+ const rows = document.querySelectorAll('#storybook-root ul > li');+ rows.forEach((row, index) => {+ const radio = document.createElement('input');+ radio.type = 'radio';+ radio.name = 'pick';+ radio.value = String(index);+ radio.checked = index === 0;+ row.append(radio);+ });+ });+ const checked = async () =>+ page.evaluate(() =>+ Array.from(+ document.querySelectorAll<HTMLInputElement>(+ '#storybook-root ul > li:not([data-astryx-leaving]) input[type="radio"]',+ ),+ radio => radio.checked,+ ),+ );+ const order = await labels(page);+ const {at, rowHeight} = await handleOf(page, order[0]);+ await page.mouse.move(at.x, at.y);+ await page.mouse.down();+ await page.mouse.move(at.x, at.y + rowHeight * 0.4, {steps: 4});+ await expect(page.locator('[data-astryx-reorder-preview]')).toHaveCount(1);+ const during = await checked();+ // Back to its place, and dropped there.+ await page.mouse.move(at.x, at.y, {steps: 4});+ await page.mouse.up();+ await expect(page.locator('[data-astryx-reorder-preview]')).toHaveCount(0);+ const after = await checked();+ expect(await labels(page)).toEqual(order);+ expect(during[0], 'during the drag').toBe(true);+ expect(after[0], 'after the drop').toBe(true);+ expect(after.filter(Boolean)).toHaveLength(1);+ } finally {+ await story.close();+ }+});++for (const dir of ['ltr', 'rtl'] as const) {+ test(`${dir}: the preview and the insertion line run along a dragged row set in from the list's start`, async ({+ browser,+ }) => {+ const story = await openFinePointerStory(browser);+ try {+ const {page} = story;+ // Each row is set in 32 px from the list's inline start.+ await page.evaluate(direction => {+ const list = document.querySelector<HTMLElement>('#storybook-root ul');+ if (list == null) {+ return;+ }+ list.dir = direction;+ for (const row of Array.from(list.children)) {+ (row as HTMLElement).style.marginInlineStart = '32px';+ }+ }, dir);+ const before = await labels(page);+ const {at, rowHeight} = await handleOf(page, before[0]);+ await page.mouse.move(at.x, at.y);+ await page.mouse.down();+ await page.mouse.move(at.x, at.y + rowHeight * 1.5, {steps: 8});+ const edges = await page.evaluate(() => {+ const list = document.querySelector<HTMLElement>('#storybook-root ul');+ const row = document.querySelector<HTMLElement>(+ '#storybook-root [data-astryx-reorder-source]',+ );+ const preview = document.querySelector<HTMLElement>(+ '#storybook-root [data-astryx-reorder-preview]',+ );+ if (list == null || row == null || preview == null) {+ return null;+ }+ const after = getComputedStyle(list, '::after');+ const listBox = list.getBoundingClientRect();+ const start = parseFloat(after.insetInlineStart);+ const width = parseFloat(after.width);+ // The line's own edges in the viewport, from its inline start.+ const lineLeft =+ list.dir === 'rtl'+ ? listBox.right - list.clientLeft - start - width+ : listBox.left + list.clientLeft + start;+ const rowBox = row.getBoundingClientRect();+ const previewBox = preview.getBoundingClientRect();+ return {+ row: [rowBox.left, rowBox.right],+ preview: [previewBox.left, previewBox.right],+ line: [lineLeft, lineLeft + width],+ };+ });+ await page.keyboard.press('Escape');+ await page.mouse.up();+ expect(edges).not.toBeNull();+ for (const part of ['preview', 'line'] as const) {+ const [left, right] = edges?.[part] ?? [NaN, NaN];+ const [rowLeft, rowRight] = edges?.row ?? [NaN, NaN];+ expect(Math.abs(left - rowLeft), `${part} left`).toBeLessThan(1);+ expect(Math.abs(right - rowRight), `${part} right`).toBeLessThan(1);+ }+ } finally {+ await story.close();+ }+ });+}++for (const dir of ['ltr', 'rtl'] as const) {+ test(`${dir}: the insertion line runs along the dragged row in a list set in from its container`, async ({+ browser,+ }) => {+ const story = await openFinePointerStory(browser);+ try {+ const {page} = story;+ // The list sits 40 px in from its container, which stays its offset+ // parent until a drag positions the list.+ await page.evaluate(direction => {+ const list = document.querySelector<HTMLElement>('#storybook-root ul');+ if (list != null) {+ list.dir = direction;+ list.style.marginInlineStart = '40px';+ }+ }, dir);+ const before = await labels(page);+ const {at, rowHeight} = await handleOf(page, before[0]);+ await page.mouse.move(at.x, at.y);+ await page.mouse.down();+ await page.mouse.move(at.x, at.y + rowHeight * 1.5, {steps: 8});+ const line = await page.evaluate(() => {+ const list = document.querySelector<HTMLElement>('#storybook-root ul');+ const row = document.querySelector<HTMLElement>(+ '#storybook-root [data-astryx-reorder-source]',+ );+ if (list == null || row == null) {+ return null;+ }+ const after = getComputedStyle(list, '::after');+ const listBox = list.getBoundingClientRect();+ const rowBox = row.getBoundingClientRect();+ const start = parseFloat(after.insetInlineStart);+ const width = parseFloat(after.width);+ // The line's own edges in the viewport, from its inline start.+ const left =+ list.dir === 'rtl'+ ? listBox.right - list.clientLeft - start - width+ : listBox.left + list.clientLeft + start;+ return {+ left,+ right: left + width,+ rowLeft: rowBox.left,+ rowRight: rowBox.right,+ };+ });+ await page.keyboard.press('Escape');+ await page.mouse.up();+ expect(line).not.toBeNull();+ expect(+ Math.abs((line?.left ?? NaN) - (line?.rowLeft ?? NaN)),+ ).toBeLessThan(1);+ expect(+ Math.abs((line?.right ?? NaN) - (line?.rowRight ?? NaN)),+ ).toBeLessThan(1);+ } finally {+ await story.close();+ }+ });+}++test('a pen drags a row from its handle at once, as a mouse does, where the primary pointer is fine', async ({+ browser,+}) => {+ const story = await openFinePointerStory(browser);+ try {+ const {page} = story;+ const driver = await webInputDriver(page);+ test.skip(!driver.pens, PEN_SKIP);+ const before = await labels(page);+ expect(before.length).toBeGreaterThanOrEqual(3);+ const {at, rowHeight} = await handleOf(page, before[0]);+ await driver.pen(strokeDown(at, rowHeight * 2.5));+ await expect.poll(async () => labels(page)).toEqual(movedTwoDown(before));+ } finally {+ await story.close();+ }+});++test('a pen keeps the hold where the primary pointer is coarse: a quick stroke moves nothing, and a held one moves the row', async ({+ page,+}) => {+ await openStory(page, storybook(), STORY);+ expect(+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(true);+ const driver = await webInputDriver(page);+ test.skip(!driver.pens, PEN_SKIP);+ const before = await labels(page);+ expect(before.length).toBeGreaterThanOrEqual(3);+ const {at, rowHeight} = await handleOf(page, before[0]);+ await driver.pen(strokeDown(at, rowHeight * 2.5));+ await page.waitForTimeout(300);+ expect(await labels(page)).toEqual(before);+ // The same stroke, after the pen rests on the handle past the claim delay.+ await driver.pen([+ {x: at.x, y: at.y, t: 0},+ ...strokeDown(at, rowHeight * 2.5, HOLD_MS),+ ]);+ await expect.poll(async () => labels(page)).toEqual(movedTwoDown(before));+});diff --git a/packages/core/src/List/__tests__/ListReorderSelectionLock.test.tsx b/packages/core/src/List/__tests__/ListReorderSelectionLock.test.tsxnew file mode 100644index 0000000000..813b4b8449--- /dev/null+++ b/packages/core/src/List/__tests__/ListReorderSelectionLock.test.tsx@@ -0,0 +1,114 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ListReorderSelectionLock.test.tsx+ * @input A reorderable List (createReorderable), the iOS WebKit query+ * stubbed per test, Testing Library+ * @output jsdom proofs that a finger held on a reorder handle locks text+ * selection on the whole list from its touch-down until it lifts. On iOS+ * WebKit the lock writes the list's selection and callout styles;+ * elsewhere it refuses `selectstart`. A mouse press never locks+ * @position Tests for List/ListReorderTouch.ts's selection lock+ */++import {afterEach, describe, expect, it, vi} from 'vitest';+import {fireEvent, render, screen} from '@testing-library/react';+import {List} from '../List';+import {ListItem} from '../ListItem';+import {createReorderable} from '../../reorderable/createReorderable';+import type * as TouchQueries from '../../utils/touchQueries';++const ios = vi.hoisted(() => ({value: false}));++vi.mock('../../utils/touchQueries', async importOriginal => ({+ ...(await importOriginal<typeof TouchQueries>()),+ isIosWebKit: () => ios.value,+}));++const ITEMS = ['Inbox', 'Sent', 'Drafts'];++function Rows() {+ const reorderable = createReorderable({onReorder: () => {}});+ return (+ <List reorderable={reorderable}>+ {ITEMS.map(item => (+ <ListItem key={item} itemKey={item} label={item} />+ ))}+ </List>+ );+}++const FINGER = {+ pointerType: 'touch',+ pointerId: 7,+ button: 0,+ clientX: 280,+ clientY: 320,+};+const MOUSE = {...FINGER, pointerType: 'mouse', pointerId: 1};++const handleOf = (label: string) =>+ screen.getByRole('button', {name: `Reorder ${label}`});++/** Whether a selection that starts on the row's label is refused. */+function refusesSelection(label: string): boolean {+ const event = new Event('selectstart', {bubbles: true, cancelable: true});+ screen.getByText(label).dispatchEvent(event);+ return event.defaultPrevented;+}++afterEach(() => {+ ios.value = false;+});++describe('a reorderable List under a held finger', () => {+ it("writes the list's selection and callout styles on iOS WebKit from the touch-down on a handle until the lift", () => {+ ios.value = true;+ render(<Rows />);+ const list = screen.getByRole('list');+ const setProperty = vi.spyOn(list.style, 'setProperty');+ const removeProperty = vi.spyOn(list.style, 'removeProperty');+ fireEvent.pointerDown(handleOf('Sent'), FINGER);+ for (const name of [+ '-webkit-touch-callout',+ '-webkit-user-select',+ 'user-select',+ ]) {+ expect(setProperty).toHaveBeenCalledWith(name, 'none');+ }+ expect(removeProperty).not.toHaveBeenCalled();+ fireEvent.pointerUp(handleOf('Sent'), FINGER);+ for (const name of [+ '-webkit-touch-callout',+ '-webkit-user-select',+ 'user-select',+ ]) {+ expect(removeProperty).toHaveBeenCalledWith(name);+ }+ });++ it('refuses a selection on any row elsewhere from the touch-down on a handle until the lift, and a cancel ends it too', () => {+ render(<Rows />);+ expect(refusesSelection('Inbox')).toBe(false);+ fireEvent.pointerDown(handleOf('Sent'), FINGER);+ // The row beside the held handle too: the lock covers the whole list.+ expect(refusesSelection('Inbox')).toBe(true);+ expect(refusesSelection('Drafts')).toBe(true);+ fireEvent.pointerUp(handleOf('Sent'), FINGER);+ expect(refusesSelection('Inbox')).toBe(false);+ fireEvent.pointerDown(handleOf('Sent'), FINGER);+ expect(refusesSelection('Inbox')).toBe(true);+ fireEvent.pointerCancel(handleOf('Sent'), FINGER);+ expect(refusesSelection('Inbox')).toBe(false);+ });++ it('takes no lock for a mouse press on a handle, nor for a finger on a row away from its handle', () => {+ render(<Rows />);+ fireEvent.pointerDown(handleOf('Sent'), MOUSE);+ expect(refusesSelection('Inbox')).toBe(false);+ fireEvent.pointerUp(handleOf('Sent'), MOUSE);+ fireEvent.pointerDown(screen.getByText('Sent'), FINGER);+ expect(refusesSelection('Inbox')).toBe(false);+ fireEvent.pointerUp(screen.getByText('Sent'), FINGER);+ });+});diff --git a/packages/core/src/List/__tests__/ListReorderTouch.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListReorderTouch.interaction.browser.spec.tsnew file mode 100644index 0000000000..ccef259b76--- /dev/null+++ b/packages/core/src/List/__tests__/ListReorderTouch.interaction.browser.spec.ts@@ -0,0 +1,687 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ListReorderTouch.interaction.browser.spec.ts+ * @input The built List reorder stories and real touch input through the+ * interaction harness (Chromium CDP or WebKit's input command). Also the+ * claim delay from the UIKit constants table (motion/uikit/reorder.ts)+ * @output Interaction proofs for a reorderable List under a finger. A hold on+ * a handle then a drag moves the row, and the drop settles it into its new+ * place. While the finger holds the drag, the rows stay still, the source+ * dims, a preview follows and an insertion line marks the drop position. A+ * flick on a handle scrolls and moves nothing. A cancelled drag puts the+ * row back. With Reduce Motion the drop takes its place without travel. A+ * flush row's handle stays inside the list. A finger held on a handle+ * refuses text selection on the list until it lifts. A drag that crosses+ * rows forces no style or layout pass, and neither does the pick-up. A+ * drop measures the rows in one pass, before their glides start+ * @position Interaction evidence for List's reorder (List/listReorderEngine.tsx,+ * List/ListReorderTouch.ts, List/ListReorderHandle.tsx) in the touch phone+ * context+ */++import {+ expect,+ test,+ type CDPSession,+ type Page,+} from '@astryxdesign/a11y-spec/playwright';+import {+ flick,+ holdThenDrag,+ openStory,+ toTouchEvents,+ touchDriver,+ withStorybook,+} from '@astryxdesign/interaction-harness';+import {solveSpring, toSpring} from '../../motion/spring';+import {reorder} from '../../motion/uikit/reorder';+import {springs} from '../../motion/uikit/springs';+import {describePasses, forcedPassesDuring, passesUnder} from './forcedPasses';++const storybook = withStorybook(test);++/** Past the claim delay: the hold claims the drag. */+const HOLD_MS = reorder.claim.delayMs + 150;+/**+ * Long enough for a drop's glide to settle: it plays the shared settle role,+ * springs.settle (spec:AST-105 FR4).+ */+const SETTLE_MS =+ solveSpring(toSpring(springs.settle), {from: 0, to: 1}).settleTime(0.001) *+ 1000 ++ 300;++const isTouch = async (page: Page) =>+ page.evaluate(() => matchMedia('(pointer: coarse)').matches);++/** The story's row labels, in order. */+async function labels(page: Page): Promise<string[]> {+ return page+ .locator('#storybook-root li:not([data-astryx-leaving])')+ .evaluateAll(rows => rows.map(row => row.textContent?.trim() ?? ''));+}++/** The centre of `label`'s handle and the height of its row. */+async function handleOf(page: Page, label: string) {+ const handle = page.getByRole('button', {name: `Reorder ${label}`});+ await expect(handle).toBeVisible();+ const box = await handle.boundingBox();+ const row = await handle+ .locator('xpath=ancestor::li[1]')+ .evaluate(element => element.getBoundingClientRect().height);+ if (box == null) {+ throw new Error(`no handle for ${label}`);+ }+ return {+ at: {x: box.x + box.width / 2, y: box.y + box.height / 2},+ rowHeight: row,+ };+}++/**+ * A hold on `at` then a drag to `to`, all but the lift, sent through+ * Chromium's CDP on the script's own clock. The harness's player takes only+ * scripts that end with every finger lifted. Resolves when the lift would+ * have come, with the session that ends the touch.+ */+async function holdAndDragWithoutLift(+ page: Page,+ at: {x: number; y: number},+ to: {x: number; y: number},+): Promise<CDPSession> {+ const events = toTouchEvents(+ holdThenDrag(at, to, {holdMs: HOLD_MS, durationMs: 400, restMs: 120}),+ );+ const lift = events[events.length - 1];+ const cdp = await page.context().newCDPSession(page);+ let now = 0;+ for (const step of events.slice(0, -1)) {+ await page.waitForTimeout(step.t - now);+ now = step.t;+ await cdp.send('Input.dispatchTouchEvent', {+ type: step.type,+ touchPoints: step.fingers.map(f => ({+ x: f.x,+ y: f.y,+ id: f.id,+ radiusX: 1,+ radiusY: 1,+ force: 1,+ })),+ });+ }+ await page.waitForTimeout(lift.t - now);+ return cdp;+}++/** The layout top of each row, by label, once nothing animates. */+async function settledTops(page: Page): Promise<Record<string, number>> {+ return page+ .locator('#storybook-root li:not([data-astryx-leaving])')+ .evaluateAll(rows => {+ const tops: Record<string, number> = {};+ for (const row of rows) {+ tops[row.textContent?.trim() ?? ''] = Math.round(+ row.getBoundingClientRect().top,+ );+ }+ return tops;+ });+}++test.describe('under a finger', () => {+ test.beforeEach(async ({page}) => {+ await openStory(page, storybook(), 'core-list--reorderable');+ test.skip(+ !(await isTouch(page)),+ 'this engine reports a fine primary pointer; the touch hold applies under (pointer: coarse)',+ );+ });++ test('a hold on a handle then a drag moves the row, and the drop settles it into its new place', async ({+ page,+ }) => {+ const before = await settledTops(page);+ const {at, rowHeight} = await handleOf(page, 'Inbox');+ const driver = await touchDriver(page);+ await driver.play(+ holdThenDrag(+ at,+ {x: at.x, y: at.y + rowHeight * 2},+ {holdMs: HOLD_MS, durationMs: 400, restMs: 120},+ ),+ );+ await page.waitForTimeout(SETTLE_MS);+ expect(await labels(page)).toEqual([+ 'Sent',+ 'Drafts',+ 'Inbox',+ 'Archive',+ 'Spam',+ 'Trash',+ ]);+ // Settled: the dropped row sits in the third place, nothing moving.+ const after = await settledTops(page);+ expect(after.Inbox).toBe(before.Drafts);+ expect(+ await page+ .locator('#storybook-root li')+ .evaluateAll(rows =>+ rows.some(row =>+ row+ .getAnimations({subtree: true})+ .some(animation => animation.playState === 'running'),+ ),+ ),+ ).toBe(false);+ });++ test('while the finger holds a drag, the rows stay still: the source dims in place, a preview follows, and an insertion line marks the drop position', async ({+ page,+ browserName,+ }) => {+ test.skip(+ browserName !== 'chromium',+ 'the held finger lifts through Chromium CDP',+ );+ const before = await settledTops(page);+ const {at, rowHeight} = await handleOf(page, 'Inbox');+ const cdp = await holdAndDragWithoutLift(page, at, {+ x: at.x,+ y: at.y + rowHeight * 2,+ });+ expect(await settledTops(page)).toEqual(before);+ const state = await page.evaluate(() => {+ const source = document.querySelector<HTMLElement>(+ '[data-astryx-reorder-source]',+ );+ const preview = document.querySelector<HTMLElement>(+ '[data-astryx-reorder-preview]',+ );+ // The insertion line is the list's own ::after (no element joins the+ // list), placed by a translate from the list's padding box.+ const list = document.querySelector<HTMLElement>('#storybook-root ul');+ const line = list == null ? null : getComputedStyle(list, '::after');+ const lineY =+ line == null ? Number.NaN : parseFloat(line.translate.split(' ')[1]);+ return {+ sourceOpacity: source == null ? null : getComputedStyle(source).opacity,+ previewTop: preview?.getBoundingClientRect().top ?? null,+ lineShown: line != null && line.display !== 'none',+ lineTop:+ list == null+ ? null+ : list.getBoundingClientRect().top + list.clientTop + lineY,+ };+ });+ expect(Number(state.sourceOpacity)).toBeLessThan(1);+ expect(state.previewTop).toBeGreaterThan(before.Inbox + rowHeight);+ expect(state.lineShown).toBe(true);+ // In the gap after Drafts, where Inbox would land.+ expect(+ Math.abs((state.lineTop ?? Number.NaN) - (before.Drafts + rowHeight)),+ ).toBeLessThan(4);+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchEnd',+ touchPoints: [],+ });+ await page.waitForTimeout(SETTLE_MS);+ expect(await labels(page)).toEqual([+ 'Sent',+ 'Drafts',+ 'Inbox',+ 'Archive',+ 'Spam',+ 'Trash',+ ]);+ expect(+ await page.evaluate(+ () =>+ document.querySelector(+ '[data-astryx-reorder-preview], [data-astryx-reorder-line]',+ ) == null,+ ),+ ).toBe(true);+ });++ test('picking a row up forces no style or layout pass before its first frame', async ({+ page,+ browser,+ browserName,+ }) => {+ test.skip(+ browserName !== 'chromium',+ 'the layout trace and the held finger go through Chromium CDP',+ );+ const {at} = await handleOf(page, 'Inbox');+ const cdp = await page.context().newCDPSession(page);+ const touch = async (+ type: 'touchStart' | 'touchMove' | 'touchEnd',+ y?: number,+ ) =>+ cdp.send('Input.dispatchTouchEvent', {+ type,+ touchPoints:+ y == null+ ? []+ : [{x: at.x, y, id: 1, radiusX: 1, radiusY: 1, force: 1}],+ });+ await touch('touchStart', at.y);+ // The trace starts after the touch lands, and before the hold picks the+ // row up.+ await browser.startTracing(page, {+ categories: [+ 'devtools.timeline',+ 'disabled-by-default-devtools.timeline',+ 'disabled-by-default-devtools.timeline.stack',+ ],+ });+ await page.waitForTimeout(HOLD_MS);+ await touch('touchMove', at.y + 4);+ await expect(page.locator('[data-astryx-reorder-preview]')).toHaveCount(1);+ await page.waitForTimeout(100);+ const trace = JSON.parse((await browser.stopTracing()).toString()) as {+ traceEvents: {+ name: string;+ ph: string;+ pid: number;+ tid: number;+ args?: {+ name?: string;+ beginData?: {stackTrace?: {functionName?: string}[]};+ };+ }[];+ };+ await touch('touchEnd');+ await page.waitForTimeout(SETTLE_MS);+ const mainThreads = new Set(+ trace.traceEvents+ .filter(e => e.ph === 'M' && e.name === 'thread_name')+ .filter(e => e.args?.name === 'CrRendererMain')+ .map(e => `${e.pid}:${e.tid}`),+ );+ // A style or layout pass with a script stack ran inside script: a read+ // after a write forced it, instead of the frame's own pass.+ const forced = trace.traceEvents.filter(+ e =>+ (e.name === 'Layout' || e.name === 'UpdateLayoutTree') &&+ mainThreads.has(`${e.pid}:${e.tid}`) &&+ (e.args?.beginData?.stackTrace ?? []).length > 0,+ );+ expect(+ forced.map(+ e =>+ `${e.name} in ${e.args?.beginData?.stackTrace?.[0]?.functionName ?? '?'}`,+ ),+ ).toEqual([]);+ });++ test('a drag forces no style or layout pass as it crosses rows', async ({+ page,+ browser,+ browserName,+ }) => {+ test.skip(+ browserName !== 'chromium',+ 'the layout trace and the held finger go through Chromium CDP',+ );+ const {at, rowHeight} = await handleOf(page, 'Inbox');+ const cdp = await page.context().newCDPSession(page);+ const touch = async (+ type: 'touchStart' | 'touchMove' | 'touchEnd',+ y?: number,+ ) =>+ cdp.send('Input.dispatchTouchEvent', {+ type,+ touchPoints:+ y == null+ ? []+ : [{x: at.x, y, id: 1, radiusX: 1, radiusY: 1, force: 1}],+ });+ await touch('touchStart', at.y);+ await page.waitForTimeout(HOLD_MS);+ await touch('touchMove', at.y + 4);+ await expect(page.locator('[data-astryx-reorder-preview]')).toHaveCount(1);+ // Only the crossings are traced: the pick-up reads the rows once.+ await browser.startTracing(page, {+ categories: [+ 'devtools.timeline',+ 'disabled-by-default-devtools.timeline',+ 'disabled-by-default-devtools.timeline.stack',+ ],+ });+ for (let step = 1; step <= 24; step += 1) {+ await touch('touchMove', at.y + 4 + (rowHeight * 3 * step) / 24);+ await page.waitForTimeout(16);+ }+ await page.waitForTimeout(150);+ const trace = JSON.parse((await browser.stopTracing()).toString()) as {+ traceEvents: {+ name: string;+ ph: string;+ pid: number;+ tid: number;+ args?: {+ name?: string;+ beginData?: {stackTrace?: {functionName?: string}[]};+ };+ }[];+ };+ await touch('touchEnd');+ await page.waitForTimeout(SETTLE_MS);+ const mainThreads = new Set(+ trace.traceEvents+ .filter(e => e.ph === 'M' && e.name === 'thread_name')+ .filter(e => e.args?.name === 'CrRendererMain')+ .map(e => `${e.pid}:${e.tid}`),+ );+ // A style or layout pass with a script stack ran inside script: a read+ // after a write forced it, instead of the frame's own pass.+ const forced = trace.traceEvents.filter(+ e =>+ (e.name === 'Layout' || e.name === 'UpdateLayoutTree') &&+ mainThreads.has(`${e.pid}:${e.tid}`) &&+ (e.args?.beginData?.stackTrace ?? []).length > 0,+ );+ expect(+ forced.map(+ e =>+ `${e.name} in ${e.args?.beginData?.stackTrace?.[0]?.functionName ?? '?'}`,+ ),+ ).toEqual([]);+ // The drag did cross: Inbox lands three rows down.+ expect((await labels(page)).indexOf('Inbox')).toBe(3);+ });++ test('a drop measures the rows in one pass, before their glides start', async ({+ page,+ browser,+ browserName,+ }) => {+ test.skip(browserName !== 'chromium', 'the layout trace is Chromium CDP');+ const {at, rowHeight} = await handleOf(page, 'Inbox');+ const driver = await touchDriver(page);+ const {passes, events, rounds} = await forcedPassesDuring(+ browser,+ page,+ async () => {+ await driver.play(+ holdThenDrag(+ at,+ {x: at.x, y: at.y + rowHeight * 3},+ {holdMs: HOLD_MS, durationMs: 400, restMs: 120},+ ),+ );+ await expect.poll(async () => (await labels(page))[0]).toBe('Sent');+ // The commit's glides start before the next frame.+ await page.evaluate(+ async () =>+ new Promise(resolve => {+ requestAnimationFrame(() => requestAnimationFrame(resolve));+ }),+ );+ },+ );+ // The trace saw the drop: the finger's lift, and the rendering after it.+ expect(events.has('pointerup')).toBe(true);+ expect(rounds).toBeGreaterThan(0);+ // The drop's own reads, in the drop and in the commit that applies it,+ // are one measurement pass at most.+ expect(+ passesUnder(passes, ['drop', 'commit']).length,+ describePasses(passes),+ ).toBeLessThanOrEqual(1);+ });++ test('a cancelled drag puts the row back and moves nothing', async ({+ page,+ browserName,+ }) => {+ test.skip(+ browserName !== 'chromium',+ 'the cancel is a touchcancel through Chromium CDP',+ );+ const before = await settledTops(page);+ const {at, rowHeight} = await handleOf(page, 'Inbox');+ // The cancel comes when the lift would have.+ const cdp = await holdAndDragWithoutLift(page, at, {+ x: at.x,+ y: at.y + rowHeight * 2,+ });+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchCancel',+ touchPoints: [],+ });+ await page.waitForTimeout(SETTLE_MS);+ expect(await labels(page)).toEqual([+ 'Inbox',+ 'Sent',+ 'Drafts',+ 'Archive',+ 'Spam',+ 'Trash',+ ]);+ expect((await settledTops(page)).Inbox).toBe(before.Inbox);+ });++ test('with Reduce Motion the drop takes its place without travel', async ({+ page,+ }) => {+ await page.emulateMedia({reducedMotion: 'reduce'});+ const before = await settledTops(page);+ const {at, rowHeight} = await handleOf(page, 'Inbox');+ const driver = await touchDriver(page);+ await driver.play(+ holdThenDrag(+ at,+ {x: at.x, y: at.y + rowHeight * 2},+ {holdMs: HOLD_MS, durationMs: 400, restMs: 120},+ ),+ );+ // Two frames after the lift: already in place, nothing travelling.+ await page.evaluate(+ async () =>+ new Promise<void>(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ ),+ );+ expect(await labels(page)).toEqual([+ 'Sent',+ 'Drafts',+ 'Inbox',+ 'Archive',+ 'Spam',+ 'Trash',+ ]);+ expect((await settledTops(page)).Inbox).toBe(before.Drafts);+ // Nothing travels. A running animation may only fade: the rows the drop+ // passed take Reduce Motion's opacity dip in their new places+ // (design:reduced-motion), and none moves.+ expect(+ await page+ .locator('#storybook-root li')+ .evaluateAll(rows =>+ rows.some(row =>+ row+ .getAnimations({subtree: true})+ .some(+ animation =>+ animation.playState === 'running' &&+ animation.effect instanceof KeyframeEffect &&+ animation.effect+ .getKeyframes()+ .some(frame =>+ ['translate', 'transform', 'top', 'insetBlockStart'].some(+ property => frame[property] != null,+ ),+ ),+ ),+ ),+ ),+ ).toBe(false);+ });+});++test.describe('a row that reorders and has a menu', () => {+ test.beforeEach(async ({page, browserName}) => {+ await openStory(page, storybook(), 'core-list--reorder-from-your-ui');+ test.skip(+ !(await isTouch(page)),+ 'this engine reports a fine primary pointer; the touch hold applies under (pointer: coarse)',+ );+ test.skip(+ browserName !== 'chromium',+ 'the held finger lifts through Chromium CDP',+ );+ });++ /** A finger held still at `at` for `ms`, read while it is down, then lifted. */+ async function holdStill(+ page: Page,+ at: {x: number; y: number},+ ms: number,+ ): Promise<{picked: boolean; menu: boolean}> {+ const cdp = await page.context().newCDPSession(page);+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchStart',+ touchPoints: [+ {x: at.x, y: at.y, id: 0, radiusX: 1, radiusY: 1, force: 1},+ ],+ });+ await page.waitForTimeout(ms);+ const held = await page.evaluate(() => ({+ picked: document.querySelector('[data-astryx-reorder-preview]') != null,+ menu: Array.from(document.querySelectorAll('[role="menu"]')).some(+ element => element.getBoundingClientRect().height > 0,+ ),+ }));+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchEnd',+ touchPoints: [],+ });+ return held;+ }++ const menuShown = async (page: Page) =>+ page.evaluate(() =>+ Array.from(document.querySelectorAll('[role="menu"]')).some(+ element => element.getBoundingClientRect().height > 0,+ ),+ );++ test('a finger held on a handle refuses a text selection on the list from its touch-down until it lifts', async ({+ page,+ browserName,+ }) => {+ test.skip(+ browserName !== 'chromium',+ 'the held finger lifts through Chromium CDP',+ );+ const {at} = await handleOf(page, 'Inbox');+ // A selection that starts on another row: the lock covers the whole list.+ const refused = async () =>+ page.evaluate(() => {+ const row = Array.from(+ document.querySelectorAll('#storybook-root li'),+ ).find(element => element.textContent?.trim() === 'Sent');+ const event = new Event('selectstart', {+ bubbles: true,+ cancelable: true,+ });+ row?.dispatchEvent(event);+ return event.defaultPrevented;+ });+ expect(await refused()).toBe(false);+ const cdp = await page.context().newCDPSession(page);+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchStart',+ touchPoints: [+ {x: at.x, y: at.y, id: 0, radiusX: 1, radiusY: 1, force: 1},+ ],+ });+ // Before the hold claims the drag, as when iOS starts its own selection.+ expect(await refused()).toBe(true);+ await page.waitForTimeout(HOLD_MS);+ expect(await refused()).toBe(true);+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchEnd',+ touchPoints: [],+ });+ await page.waitForTimeout(SETTLE_MS);+ expect(await refused()).toBe(false);+ });++ test('a hold on the reorder handle picks the row up and opens no menu', async ({+ page,+ }) => {+ const order = await labels(page);+ const {at} = await handleOf(page, 'Inbox');+ // Held still past the row menu's long press (500 ms).+ const held = await holdStill(page, at, 800);+ expect(held.picked).toBe(true);+ expect(held.menu).toBe(false);+ await page.waitForTimeout(SETTLE_MS);+ expect(await menuShown(page)).toBe(false);+ expect(await labels(page)).toEqual(order);+ });++ test('a hold anywhere else on the row opens its menu and picks nothing up', async ({+ page,+ }) => {+ const row = page+ .locator('#storybook-root li:not([data-astryx-leaving])')+ .filter({hasText: 'Inbox'})+ .first();+ const box = await row.boundingBox();+ if (box == null) {+ throw new Error('no row');+ }+ const held = await holdStill(+ page,+ {x: box.x + 40, y: box.y + box.height / 2},+ 800,+ );+ expect(held.picked).toBe(false);+ expect(held.menu).toBe(true);+ await page.keyboard.press('Escape');+ });+});++test('a flick on a handle scrolls the page and moves nothing', async ({+ page,+}) => {+ await openStory(page, storybook(), 'core-list--reorder-long-list');+ test.skip(+ !(await isTouch(page)),+ 'this engine reports a fine primary pointer; the touch hold applies under (pointer: coarse)',+ );+ const order = await labels(page);+ const {at} = await handleOf(page, 'Item 8');+ const driver = await touchDriver(page);+ test.skip(+ !driver.drivesNativeGestures,+ "this engine's injected touches drive no native scroll (the harness's drivesNativeGestures)",+ );+ const scrolled = await page.evaluate(() => window.scrollY);+ await driver.play(flick(at, {velocity: {x: 0, y: -1500}}));+ await page.waitForTimeout(SETTLE_MS);+ expect(await page.evaluate(() => window.scrollY)).toBeGreaterThan(scrolled);+ expect(await labels(page)).toEqual(order);+});++test('a flush row keeps its handle inside the list', async ({page}) => {+ await openStory(page, storybook(), 'core-list--reorder-flush');+ const handle = page.getByRole('button', {name: 'Reorder Inbox'});+ await expect(handle).toBeVisible();+ const [handleBox, listBox] = await Promise.all([+ handle.boundingBox(),+ page.locator('#storybook-root ul').first().boundingBox(),+ ]);+ if (handleBox == null || listBox == null) {+ throw new Error('no handle or list');+ }+ expect(handleBox.x + handleBox.width).toBeLessThanOrEqual(+ listBox.x + listBox.width + 0.5,+ );+});diff --git a/packages/core/src/List/__tests__/forcedPasses.ts b/packages/core/src/List/__tests__/forcedPasses.tsnew file mode 100644index 0000000000..3d575f6b06--- /dev/null+++ b/packages/core/src/List/__tests__/forcedPasses.ts@@ -0,0 +1,174 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file forcedPasses.ts+ * @input A Chromium page, its browser, and an action to trace+ * @output `forcedPassesDuring`: the measurement passes that script forced+ * while the action ran, each with the functions and sources on its stack.+ * Also the DOM events dispatched and every style and layout round, so a+ * case can show the trace saw the action+ * @position A helper for the List reorder interaction specs, in Chromium,+ * the engine with a rendering trace+ */++import type {Browser, Page} from '@astryxdesign/a11y-spec/playwright';++interface StackFrame {+ functionName?: string;+ url?: string;+ lineNumber?: number;+ columnNumber?: number;+}++interface TraceEvent {+ name: string;+ ph: string;+ pid: number;+ tid: number;+ ts?: number;+ args?: {+ name?: string;+ beginData?: {stackTrace?: StackFrame[]};+ data?: {stackTrace?: StackFrame[]; type?: string};+ };+}++/**+ * The style and layout work one read forced. One read can run several+ * rounds of both, for example when anchored elements are laid out again.+ */+export interface ForcedPass {+ /** Each round, in order: `UpdateLayoutTree` or `Layout`. */+ readonly rounds: ReadonlyArray<string>;+ /** The functions on the reading script's stack, innermost first. */+ readonly frames: ReadonlyArray<string>;+ /** The script source of each of those functions. */+ readonly sources: ReadonlyArray<string>;+}++const FORCED = new Set(['Layout', 'UpdateLayoutTree']);+const INVALIDATIONS = new Set([+ 'ScheduleStyleRecalculation',+ 'InvalidateLayout',+]);++const keyOf = (stack: ReadonlyArray<StackFrame>) =>+ stack+ .map(+ frame =>+ `${frame.functionName}@${frame.url}:${frame.lineNumber}:${frame.columnNumber}`,+ )+ .join(' < ');++/** What the trace of an action saw on the page's main thread. */+export interface ActionTrace {+ /** The measurement passes that script forced. */+ readonly passes: ForcedPass[];+ /** The type of each DOM event dispatched, such as `pointerup`. */+ readonly events: ReadonlySet<string>;+ /** Every style and layout round, forced or not. */+ readonly rounds: number;+}++/**+ * Traces `action`, then returns each measurement pass that script forced on+ * the page's main thread. A round with the reading script's stack is forced.+ * A round joins the pass before it when the same read caused it: same+ * stack, and no write from another stack in between.+ */+export async function forcedPassesDuring(+ browser: Browser,+ page: Page,+ action: () => Promise<void>,+): Promise<ActionTrace> {+ await browser.startTracing(page, {+ categories: [+ 'devtools.timeline',+ 'disabled-by-default-devtools.timeline',+ 'disabled-by-default-devtools.timeline.stack',+ ],+ });+ let buffer: Buffer | undefined;+ try {+ await action();+ } finally {+ buffer = await browser.stopTracing();+ }+ const {traceEvents} = JSON.parse(String(buffer)) as {+ traceEvents: TraceEvent[];+ };+ const mainThreads = new Set(+ traceEvents+ .filter(e => e.ph === 'M' && e.name === 'thread_name')+ .filter(e => e.args?.name === 'CrRendererMain')+ .map(e => `${e.pid}:${e.tid}`),+ );+ const events = traceEvents+ .filter(e => mainThreads.has(`${e.pid}:${e.tid}`) && e.ts != null)+ .sort((a, b) => (a.ts ?? 0) - (b.ts ?? 0));+ const passes: (ForcedPass & {key: string; rounds: string[]})[] = [];+ const dispatched = new Set<string>();+ let rounds = 0;+ let wroteSince = false;+ for (const e of events) {+ if (e.name === 'EventDispatch' && e.args?.data?.type != null) {+ dispatched.add(e.args.data.type);+ }+ if (FORCED.has(e.name)) {+ rounds += 1;+ }+ if (INVALIDATIONS.has(e.name)) {+ const stack = e.args?.data?.stackTrace ?? [];+ if (stack.length > 0 && keyOf(stack) !== passes[passes.length - 1]?.key) {+ wroteSince = true;+ }+ continue;+ }+ const stack = e.args?.beginData?.stackTrace ?? [];+ if (!FORCED.has(e.name) || stack.length === 0) {+ continue;+ }+ const key = keyOf(stack);+ const last = passes[passes.length - 1];+ if (last != null && last.key === key && !wroteSince) {+ last.rounds.push(e.name);+ continue;+ }+ passes.push({+ key,+ rounds: [e.name],+ frames: stack.map(frame => frame.functionName ?? ''),+ sources: stack.map(frame => frame.url ?? ''),+ });+ wroteSince = false;+ }+ return {+ passes: passes.map(pass => ({+ rounds: pass.rounds,+ frames: pass.frames,+ sources: pass.sources,+ })),+ events: dispatched,+ rounds,+ };+}++/** The passes forced under one of `functions`. */+export function passesUnder(+ passes: ReadonlyArray<ForcedPass>,+ functions: ReadonlyArray<string>,+): ForcedPass[] {+ return passes.filter(pass =>+ pass.frames.some(frame => functions.includes(frame)),+ );+}++/** One line per pass, for an assertion's message. */+export function describePasses(passes: ReadonlyArray<ForcedPass>): string {+ return passes+ .map(+ pass =>+ `${pass.rounds.join('+')} in ${pass.frames.slice(0, 4).join(' < ')}`,+ )+ .join('; ');+}diff --git a/packages/core/src/List/__tests__/reorderModel.test.ts b/packages/core/src/List/__tests__/reorderModel.test.tsnew file mode 100644index 0000000000..67082c6149--- /dev/null+++ b/packages/core/src/List/__tests__/reorderModel.test.ts@@ -0,0 +1,224 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file reorderModel.test.ts+ * @input reorderModel.ts and the UIKit reorder values (motion/uikit/reorder.ts)+ * @output Unit proofs of the reorder model against the UIKit lab measurements+ * (iOS 26.2 simulator, 44 pt rows with rows 6 and 9 at 88 pt). They cover+ * the drop positions of a measured drag and the movable range that only the+ * fixed rows ending a list bound. They also cover the autoscroll steps and+ * the tracking clamp+ * @position Tests for List/reorderModel.ts+ */++import {describe, expect, it} from 'vitest';+import {reorder} from '../../motion/uikit/reorder';+import {+ autoscrollStep,+ clampTop,+ movableRange,+ dropPosition,+ type ReorderGeometry,+ type ReorderRow,+} from '../reorderModel';++function table(+ heights: ReadonlyArray<number>,+ {gap = 0, fixed = []}: {gap?: number; fixed?: ReadonlyArray<number>} = {},+): ReorderGeometry {+ let top = 0;+ const rows: ReorderRow[] = heights.map((height, index) => {+ const row = {top, height, isFixed: fixed.includes(index)};+ top += height + gap;+ return row;+ });+ return {rows, gap};+}++/** The measured table: 40 rows of 44 pt, rows 6 and 9 at 88 pt. */+const MEASURED = table(+ Array.from({length: 40}, (_, index) =>+ index === 6 || index === 9 ? 88 : 44,+ ),+);++describe('dropPosition', () => {+ it('reproduces the measured drag of row 3 down over the 88 pt row and back', () => {+ // Each proposal of the UIKit lab drag (table.proposed), with the dragged+ // row's centre (list coordinates) on the frame before it. Down, the position+ // moves once the centre is past the boundary; up, once it is back on it.+ const measured: ReadonlyArray<[center: number, position: number]> = [+ [178, 4],+ [221, 5],+ [309, 6],+ [354, 7],+ [398, 8],+ [396, 7],+ [352, 6],+ [306.8, 5],+ ];+ for (const [center, position] of measured) {+ expect(dropPosition(MEASURED, 3, center), `centre ${center}`).toBe(+ position,+ );+ }+ });++ it('swaps a 44 pt neighbour after half a row and the 88 pt row after its height', () => {+ // Row 3's centre starts at 3 × 44 + 22 = 154.+ expect(dropPosition(MEASURED, 3, 154)).toBe(3);+ expect(dropPosition(MEASURED, 3, 154 + 22)).toBe(3);+ expect(dropPosition(MEASURED, 3, 154 + 22.5)).toBe(4);+ expect(dropPosition(MEASURED, 3, 154 - 22)).toBe(2);+ // From position 5 (centre past 220) to position 6 takes the 88 pt row's height.+ expect(dropPosition(MEASURED, 3, 221)).toBe(5);+ expect(dropPosition(MEASURED, 3, 307)).toBe(5);+ expect(dropPosition(MEASURED, 3, 309)).toBe(6);+ });++ it("moves a tall row past a short neighbour once its centre passes that row's near edge", () => {+ // Row 1 (88 pt) rests with its centre at 88. The 44 pt row below starts at+ // 132, so the centre travels half the tall row before they change places.+ const geometry = table([44, 88, 44, 44]);+ expect(dropPosition(geometry, 1, 88)).toBe(1);+ expect(dropPosition(geometry, 1, 89)).toBe(1);+ expect(dropPosition(geometry, 1, 132)).toBe(1);+ expect(dropPosition(geometry, 1, 132.5)).toBe(2);+ // Up: past the 44 pt row above once the centre passes its bottom (44).+ expect(dropPosition(geometry, 1, 44.5)).toBe(1);+ expect(dropPosition(geometry, 1, 44)).toBe(0);+ });++ it('never proposes a new position at rest, whatever the heights', () => {+ // More than twice the row below: a 100 pt row over 44 pt rows.+ const tall = table([44, 100, 44, 44]);+ expect(dropPosition(tall, 1, 44 + 50)).toBe(1);+ expect(dropPosition(tall, 1, 144)).toBe(1);+ expect(dropPosition(tall, 1, 144.5)).toBe(2);+ for (const heights of [+ [44, 100, 44, 44],+ [30, 120, 30, 30, 30],+ [88, 44, 88, 44],+ [44, 44, 200, 44],+ ]) {+ const geometry = table(heights, {gap: 4});+ for (const [index, row] of geometry.rows.entries()) {+ expect(+ dropPosition(geometry, index, row.top + row.height / 2),+ `${heights.join(',')} row ${index}`,+ ).toBe(index);+ }+ }+ });++ it('moves a short row up past a tall row above as it moves down past one below', () => {+ // The mirror of the measured drag over the 88 pt row. Row 7 (44 pt) below+ // row 6 (88 pt, 264–352) changes places once its centre is above+ // 264 + 44 = 308. That is the tall row's height less half its own, from+ // rest at 374.+ expect(dropPosition(MEASURED, 7, 374)).toBe(7);+ expect(dropPosition(MEASURED, 7, 309)).toBe(7);+ expect(dropPosition(MEASURED, 7, 308)).toBe(6);+ });++ it('puts the boundary in the middle of the gap between rows', () => {+ const geometry = table([40, 40, 40], {gap: 4});+ // Without row 0, row 1 sits at 0..40; its boundary is at 42.+ expect(dropPosition(geometry, 0, 42)).toBe(0);+ expect(dropPosition(geometry, 0, 42.5)).toBe(1);+ });++ it('stops at a fixed row that ends the list and passes one in the middle', () => {+ // spec:AST-103 FR1, FR4: only a rejected row at either end bounds the+ // drop range. One in the middle is passed over, as reorder mode's keys+ // pass it.+ const ends = table([44, 44, 44, 44, 44], {fixed: [0, 4]});+ expect(dropPosition(ends, 2, 1000)).toBe(3);+ expect(dropPosition(ends, 2, -1000)).toBe(1);+ const middle = table([44, 44, 44, 44, 44], {fixed: [2]});+ expect(dropPosition(middle, 0, 1000)).toBe(4);+ expect(dropPosition(middle, 4, -1000)).toBe(0);+ });+});++describe('movableRange', () => {+ it('is bounded only by the fixed rows that end the list', () => {+ // Runs of fixed rows at either end bound the range.+ const {rows} = table([44, 44, 44, 44, 44, 44], {fixed: [0, 1, 5]});+ expect(movableRange(rows, 3)).toEqual({start: 2, end: 4});+ // A fixed row in the middle is passed over (spec:AST-103 FR1, FR4).+ const middle = table([44, 44, 44, 44, 44, 44], {fixed: [1, 4]}).rows;+ expect(movableRange(middle, 2)).toEqual({start: 0, end: 5});+ expect(movableRange(middle, 0)).toEqual({start: 0, end: 5});+ expect(movableRange(middle, 5)).toEqual({start: 0, end: 5});+ expect(movableRange(table([44, 44, 44]).rows, 1)).toEqual({+ start: 0,+ end: 2,+ });+ });+});++describe('autoscrollStep', () => {+ it('follows the measured steps by edge depth', () => {+ expect(autoscrollStep(-12)).toBe(0);+ expect(autoscrollStep(-reorder.autoscroll.startInset - 0.5)).toBe(0);+ expect(autoscrollStep(-reorder.autoscroll.startInset)).toBe(2);+ expect(autoscrollStep(-3)).toBe(2);+ expect(autoscrollStep(6)).toBe(2);+ expect(autoscrollStep(8)).toBe(3);+ expect(autoscrollStep(10)).toBe(3);+ expect(autoscrollStep(12)).toBe(4);+ expect(autoscrollStep(16)).toBe(6);+ expect(autoscrollStep(20)).toBe(8);+ expect(autoscrollStep(22)).toBe(10);+ expect(autoscrollStep(40)).toBe(10);+ });++ it('interpolates whole points between samples', () => {+ expect(autoscrollStep(14)).toBe(5);+ expect(autoscrollStep(21)).toBe(9);+ for (let depth = -8; depth <= 30; depth += 0.25) {+ expect(Number.isInteger(autoscrollStep(depth))).toBe(true);+ }+ });+});++describe('clampTop', () => {+ it("stops the centre on the scroller's visible edges", () => {+ // The measured top clamp: a 44 pt row on a table starting at 62 stops at+ // a top of 40 (its centre on the edge).+ const bounds = {+ scrollTop: 62,+ scrollBottom: 800,+ listTop: 0,+ listBottom: 2000,+ };+ expect(clampTop(0, 44, bounds)).toBe(40);+ expect(clampTop(100, 44, bounds)).toBe(100);+ expect(clampTop(900, 44, bounds)).toBe(778);+ });++ it('stops the edges on the ends of a list inside the visible area', () => {+ // A list from 300 to 564 in a scroller showing 0–800: the row stays in it.+ const bounds = {+ scrollTop: 0,+ scrollBottom: 800,+ listTop: 300,+ listBottom: 564,+ };+ expect(clampTop(100, 44, bounds)).toBe(300);+ expect(clampTop(400, 44, bounds)).toBe(400);+ expect(clampTop(700, 44, bounds)).toBe(520);+ });++ it('takes whichever edge comes first', () => {+ // The list runs past the visible bottom: the scroll edge stops the centre.+ const bounds = {+ scrollTop: 0,+ scrollBottom: 800,+ listTop: 300,+ listBottom: 2000,+ };+ expect(clampTop(900, 44, bounds)).toBe(778);+ });+});diff --git a/packages/core/src/List/listReorderContext.ts b/packages/core/src/List/listReorderContext.tsnew file mode 100644index 0000000000..5a971e2aa6--- /dev/null+++ b/packages/core/src/List/listReorderContext.ts@@ -0,0 +1,137 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file listReorderContext.ts+ * @input Nothing at run time but a symbol+ * @output `REORDER_ENGINE`, the key a reorderable object carries its+ * machinery under. Also the internal types between List, ListItem and that+ * machinery: what a List hands its rows through ListContext's `reorder`+ * @position Internal to List. List imports only this module and the+ * reorderable object's type, and ListItem only types. So a List without+ * `reorderable` loads no reorder code. The machinery+ * (List/listReorderEngine.tsx) ships with createReorderable, which puts it+ * on the object.+ *+ * SYNC: When modified, update List/List.tsx, List/ListItem.tsx,+ * List/ListContext.tsx, List/listReorderEngine.tsx and+ * reorderable/createReorderable.ts.+ */++import type {ItemAlign} from '../Item/Item';+import type {ComponentType, Key, ReactNode, RefObject} from 'react';+import type {StyleXStyles} from '@stylexjs/stylex';+import type {reorderListStyle} from './ListReorderHandle';++/**+ * The key a reorderable object carries its machinery under. No description:+ * it would ship in every List.+ */+export const REORDER_ENGINE: unique symbol = Symbol();++/** What a List's reorder reports and asks, as createReorderable took them. */+export interface ListReorderOptions {+ /** Called once per committed move: the item's key and its index after it. */+ readonly onReorder: (move: {key: Key; to: number}) => void;+ /** Whether the item with `key` moves; every item does without it. */+ readonly isReorderable?: (key: Key) => boolean;+}++/** The handle a reorderable row ends with (List/ListReorderHandle.tsx). */+export interface ListReorderHandleProps {+ /** The row's label: its text names the handle. */+ readonly label: ReactNode;+ /** The row's item key (ListItem `itemKey`), which its moves report. */+ readonly itemKey: Key;+ /**+ * The row's own accessible name, when its caller gave one (ListItem+ * `aria-label`): the handle is "Reorder" followed by it.+ */+ readonly rowLabel?: string;+ /**+ * The elements that name the row, when its caller gave them (ListItem+ * `aria-labelledby`): the handle is "Reorder" followed by them.+ */+ readonly rowLabelledBy?: string;+ /**+ * The row is disabled: the handle stays focusable with+ * `aria-disabled="true"`, and no gesture or key moves the row.+ */+ readonly isDisabled?: boolean;+ /**+ * The row's alignment (ListItem `align`) when the handle is the row's own+ * child, after its label. That is a row without end content, which has no+ * end slot to align it. Absent inside the end slot.+ */+ readonly rowAlign?: ItemAlign;+}++/**+ * A reorderable List's row without a handle: its label names it in the+ * announcements of the moves beside it (List/ListReorderHandle.tsx).+ */+export interface ListReorderRowNameProps {+ /** The row's element. */+ readonly row: RefObject<HTMLElement | null>;+ /** The row's label. */+ readonly label: ReactNode;+}++/** The parts of a List's reorder session that its List and rows use. */+export interface ListReorderSession {+ /**+ * Runs after every List commit, after the List's layout updates. When a+ * drop's new order is applied, each row's old place is put back. Its+ * running spring then continues to the new one.+ */+ commit(): void;+ /**+ * Whether a drag or a reorder-mode move owns the list's next commit. The+ * List's layout updates measure nothing for such a commit.+ */+ ownsCommit(): boolean;+ /**+ * Rendered by the List beside its rows while it reorders. It keeps the+ * session's callbacks, strings and listeners current. It renders the+ * handles' instructions and disposes of the session when it goes.+ */+ readonly Host: ComponentType<{reorder: ListReorderContextValue}>;+ /** The handle each reorderable row ends with. */+ readonly Handle: ComponentType<ListReorderHandleProps>;+ /** Names a row without a handle for the announcements; renders nothing. */+ readonly RowName: ComponentType<ListReorderRowNameProps>;+ /** A row with a handle: its focus ring stays off for the handle's own. */+ readonly rowStyle: StyleXStyles;+ /** The list itself: its insertion line, a pseudo-element. */+ readonly listStyle: typeof reorderListStyle;+}++/** The machinery a reorderable object carries. */+export interface ListReorderEngine {+ /** A List's reorder session over the rows of the element `getList` returns. */+ createSession(+ getList: () => HTMLElement | null,+ hintId: string,+ ): ListReorderSession;+ /**+ * Reorder mode for the item with `key`, started from the app's own UI. It+ * runs in the collection the object with `options` is mounted on, or the+ * one mounted last if several.+ */+ start(options: ListReorderOptions, key: Key): void;+}++/** What a reorderable object holds (reorderable/createReorderable.ts). */+export interface ReorderableInternals {+ readonly options: ListReorderOptions;+ readonly [REORDER_ENGINE]: ListReorderEngine;+ /** Reorder mode for the item with `key`, from the app's own UI. */+ start(key: Key): void;+}++/** What a reorderable List hands its rows. */+export interface ListReorderContextValue {+ readonly session: ListReorderSession;+ readonly options: ListReorderOptions;+}diff --git a/packages/core/src/List/listReorderEngine.tsx b/packages/core/src/List/listReorderEngine.tsxnew file mode 100644index 0000000000..50e675cb83--- /dev/null+++ b/packages/core/src/List/listReorderEngine.tsx@@ -0,0 +1,2334 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file listReorderEngine.tsx+ * @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)+ * @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+ * of it follows the pointer. An insertion line marks where it would land,+ * and the list autoscrolls near the scroll edges. The drop reports the move+ * once and the rows rearrange. The dragged row glides from where its+ * preview was. A cancelled drag restores everything at once. Activating a+ * handle without a drag turns on reorder mode for its row. Each arrow+ * moves it a place at once, with one report, and announces its place and+ * neighbours. Escape or another activation ends the mode, keeping the moves.+ * While the mode is on, a hint anchored to the handle shows the moves and+ * Done as buttons that do what the keys do+ * @position Internal to the reorder. Only createReorderable imports it, so a+ * List without `reorderable` loads none of it. ListReorderHandle drives it+ * from each row's handle+ *+ * The drag's look follows the reorder design. The surrounding rows stay+ * still until the drop, and the source is dimmed in place. A preview follows+ * the pointer one to one, its centre stopping at the scroll view's edges. An+ * accent insertion line, shared by pointer and keyboard, marks the candidate+ * position. UIKit's edit-mode reorder (iOS 26.2, measured) supplies the+ * clocks. They are the hold, the rows' glide to their new places after the+ * drop, and autoscroll. Autoscroll is a 20 ms timer whose step grows with how+ * far the preview's edge is past the scroll edge. With a mouse (the theme's+ * presentation) or Reduce Motion, the rows jump to their new places.+ *+ * HOW IT RUNS. Everything after the drag begins is imperative: no React+ * render and no layout read until the drop, but one. After a scroll the+ * engine did not cause, a later frame reads the scroller's offset once,+ * before it writes. The begin reads each row's+ * layout once. Each move writes one `translate` on the preview, through the+ * shared per-element animator's `set`. A position change writes one on the+ * insertion line. The list root carries `data-astryx-reordering` from the+ * begin until the commit that applies the drop. So the List's layout updates+ * (List/listLayoutUpdates.ts) leave that commit to the reorder. After it,+ * each row's old layout place is put back with an inverse offset that glides+ * to 0. For the dragged row, that is where its preview was dropped. The+ * commit reads every row before its first write, so it lays out once. If+ * `onReorder` does not commit a new order by the end of the task, nothing+ * moves. Reorder mode reports each key's move at once. Once it commits,+ * under a finger's presentation, the rows slide to their new places. The+ * listeners are the list's, not each row's. There is one pointerdown+ * listener for a mouse, and for a pen where the primary pointer is fine.+ * There is one hold recognizer for a finger, and for a pen where the primary+ * pointer is coarse. It receives only the touches that begin on this list's+ * handles. A row moves when it holds a handle registered here with+ * its item key. The others keep their places, and those at either end bound+ * the rest. What runs only on a touch screen is in ListReorderTouch.ts,+ * imported here alone.+ *+ * SYNC: When modified, update List/listReorderContext.ts, List/List.tsx,+ * List/ListReorderHandle.tsx and List/ListReorderTouch.ts.+ */++import {+ useRef,+ useSyncExternalStore,+ type Key,+ type KeyboardEvent,+ type ReactNode,+} from 'react';+import * as stylex from '@stylexjs/stylex';+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 {+ animatorFor,+ isMoving,+ motionNow,+ motionOf,+ releaseMotion,+} from '../utils/rowMotion';+import {edgeAutoscroll, type EdgeAutoscroll} from '../utils/edgeAutoscroll';+import {subscribeInput} from '../utils/inputStream';+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 {isLeaving, markLeaving} from '../privateAttributes/leaving.stylex';+import {+ closestReorderHandle,+ reorderHandlesIn,+} from '../privateAttributes/listReorder.stylex';+import {+ clearReorderSource,+ markReorderSource,+} from '../privateAttributes/reorderSource.stylex';+import {markReorderPreview} from '../privateAttributes/reorderPreview.stylex';+import {+ hideReorderLine,+ showReorderLine,+} from '../privateAttributes/reorderLine.stylex';+import {+ clearReordering,+ isReordering,+ markReordering,+} from '../privateAttributes/reordering.stylex';+import {+ INSERTION_LINE_THICKNESS,+ ListReorderHandle,+ ListReorderRowName,+ reorderListStyle,+ reorderRowStyle,+} from './ListReorderHandle';+import {attachTouchHold, touchMotion} from './ListReorderTouch';+import type {+ ListReorderContextValue,+ ListReorderEngine,+ ListReorderOptions,+ ListReorderSession,+} from './listReorderContext';+import {+ autoscrollStep,+ clampTop,+ dropPosition,+ type ReorderGeometry,+} from './reorderModel';++registerEnglishFallback(english);++/**+ * A mouse's travel, in px, before its press drags the row: below it the+ * press stays a click. A mouse shifts a pixel or two under the press of the+ * 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;++/** Moves under half a pixel are layout noise. */+const MIN_MOVE_PX = 0.5;++/**+ * How long after `start` the handle takes back the focus that the UI hands+ * back, in ms. A menu restores its trigger's focus as it closes, within a+ * task or two. No person moves the focus that fast.+ */+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[]+>();++/** Records `controller` as mounted with `options`; returns the removal. */+function mountSession(+ options: ListReorderOptions,+ controller: ListReorderController,+): () => void {+ const sessions = sessionsByOptions.get(options) ?? [];+ sessionsByOptions.set(options, [+ ...sessions.filter(session => session !== controller),+ controller,+ ]);+ return () => {+ const rest = (sessionsByOptions.get(options) ?? []).filter(+ session => session !== controller,+ );+ if (rest.length > 0) {+ sessionsByOptions.set(options, rest);+ } else {+ sessionsByOptions.delete(options);+ }+ };+}++/**+ * Where a row's `y` is on screen at `at`: its shared animator's value, which+ * the drag writes directly (`set`) as well as through springs.+ */+function shownY(element: HTMLElement, at: number): number {+ return animatorFor(element).get('y', at);+}++/**+ * Puts a row at rest at 0 at once. A row already at rest there takes no+ * write. The animator's `set` reads the row's style back after its write, so+ * one `set` per row forces a style pass per row.+ */+function settleAtRest(+ element: HTMLElement,+ value: number,+ moving: boolean,+): void {+ if (value !== 0 || moving) {+ animatorFor(element).set({y: 0});+ }+ releaseMotion(element, 'translate');+}++/**+ * The list's rows: its element children. A removed row put back for its exit+ * holds no place in the order, so it is left out (`markLeaving`).+ */+function rowsOf(list: HTMLElement): HTMLElement[] {+ return Array.from(list.children).filter(+ (child): child is HTMLElement =>+ child instanceof HTMLElement && !isLeaving(child),+ );+}++/**+ * Which rows bound the drop range: the rows that cannot move at either end+ * of the list, each run of them. One in the middle is passed like any other+ * row; it only has no handle.+ */+function boundsOf(movable: ReadonlyArray<boolean>): boolean[] {+ const bounds = movable.map(() => false);+ for (let index = 0; index < movable.length && !movable[index]; index += 1) {+ bounds[index] = true;+ }+ for (+ let index = movable.length - 1;+ index >= 0 && !movable[index];+ index -= 1+ ) {+ bounds[index] = true;+ }+ return bounds;+}++/**+ * The temporary reduced emphasis the dragged row and its preview share:+ * the same item, moving, and+ * not raised.+ */+const MOVING_OPACITY = '0.6';++/**+ * An element the drag draws over the list: no row to the list's order or+ * its layout updates (`markLeaving`), inert and hidden from assistive+ * technology.+ */+function overlay(element: HTMLElement): HTMLElement {+ markLeaving(element);+ element.setAttribute('aria-hidden', 'true');+ element.inert = true;+ Object.assign(element.style, {+ position: 'absolute',+ margin: '0',+ pointerEvents: 'none',+ zIndex: '2',+ translate: '0px 0px',+ });+ 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.+ */+function previewOf(+ preview: HTMLElement,+ top: number,+ span: LineSpan,+ background: string | null,+) {+ markReorderPreview(preview);+ overlay(preview);+ Object.assign(preview.style, {+ top: `${top}px`,+ insetInlineStart: `${span.start}px`,+ inlineSize: `${span.size}px`,+ boxSizing: 'border-box',+ boxShadow: 'none',+ opacity: MOVING_OPACITY,+ // It moves by translate from its first move. With its own will-change,+ // its animator reads no stylesheet to keep one.+ willChange: 'translate',+ });+ if (background != null) {+ preview.style.backgroundColor = background;+ }+ return preview;+}++/** The list's custom properties that place its insertion line. */+const LINE_Y = '--astryx-reorder-line-y';+const LINE_START = '--astryx-reorder-line-start';+const LINE_SIZE = '--astryx-reorder-line-size';++/**+ * Where the insertion line runs across a row, in list coordinates: its+ * inline start and its size.+ */+interface LineSpan {+ readonly start: number;+ readonly size: number;+}++/**+ * An extent that starts `left` px from the list's left edge, as an inline+ * start and size. In right-to-left, the start counts from the right edge.+ */+function inlineSpanOf(left: number, size: number, list: HTMLElement): LineSpan {+ const isRtl = getComputedStyle(list).direction === 'rtl';+ return {start: isRtl ? list.clientWidth - left - size : left, size};+}++/**+ * The span of `row` in `list`'s coordinates, read before anything in the+ * frame writes a style. The list may not be the row's offset parent yet.+ */+function lineSpanOf(row: HTMLElement, list: HTMLElement): LineSpan {+ return inlineSpanOf(layoutLeft(row, list), row.offsetWidth, list);+}++/**+ * The preview's span: `row`'s, from the list's padding edge, where the+ * preview sits once the list is positioned. Read before the drag writes.+ */+function previewSpanOf(row: HTMLElement, list: HTMLElement): LineSpan {+ const border = row.offsetParent === list ? 0 : list.clientLeft;+ return inlineSpanOf(layoutLeft(row, list) - border, row.offsetWidth, list);+}++/**+ * Shows the list's insertion line (its pseudo-element, reorderListStyle)+ * across `span`, centred on `center` in list coordinates. It only writes, so+ * a crossing lays nothing out.+ */+function showLine(list: HTMLElement, span: LineSpan, center: number): void {+ list.style.setProperty(LINE_START, `${span.start}px`);+ list.style.setProperty(LINE_SIZE, `${span.size}px`);+ list.style.setProperty(LINE_Y, `${center - INSERTION_LINE_THICKNESS / 2}px`);+ showReorderLine(list);+}++/** Hides the list's insertion line and clears what placed it. */+function hideLine(list: HTMLElement): void {+ hideReorderLine(list);+ for (const property of [LINE_Y, LINE_START, LINE_SIZE]) {+ list.style.removeProperty(property);+ }+}++/**+ * Where the insertion line's centre sits for the dragged row at `position`.+ * It sits in the gap before the row it would land above, or after the one it+ * would land below. Null at its own place: nothing moves.+ */+function lineCenter(+ geometry: ReorderGeometry,+ dragged: number,+ position: number,+): number | null {+ if (position === dragged) {+ return null;+ }+ const target = geometry.rows[position];+ return position < dragged+ ? target.top - geometry.gap / 2+ : target.top + target.height + geometry.gap / 2;+}++/** A row's layout top inside the list (transforms ignored). */+function layoutTop(row: HTMLElement, list: HTMLElement): number {+ const base = row.offsetParent === list ? 0 : list.offsetTop;+ return row.offsetTop - base;+}++/** A row's layout left inside the list (transforms ignored). */+function layoutLeft(row: HTMLElement, list: HTMLElement): number {+ const base = row.offsetParent === list ? 0 : list.offsetLeft;+ return row.offsetLeft - base;+}++function isTransparent(color: string): boolean {+ return (+ color === '' ||+ color === 'transparent' ||+ /^rgba\(.*,\s*0\)$/.test(color) ||+ /\/\s*0\)$/.test(color)+ );+}++/** The element autoscroll writes to and its visible band in the viewport. */+interface Scroller {+ readonly element: Element;+ readonly top: number;+ readonly bottom: number;+ readonly max: number;+ position: number;+}++function scrollerOf(list: HTMLElement): Scroller {+ const doc = list.ownerDocument;+ const element = nearestScroller(list);+ if (element !== (doc.scrollingElement ?? doc.documentElement)) {+ const rect = element.getBoundingClientRect();+ const top = rect.top + element.clientTop;+ return {+ element,+ top,+ bottom: top + element.clientHeight,+ max: element.scrollHeight - element.clientHeight,+ position: element.scrollTop,+ };+ }+ const view = doc.defaultView;+ const height = view?.innerHeight ?? element.clientHeight;+ return {+ element,+ top: 0,+ bottom: height,+ max: Math.max(0, element.scrollHeight - height),+ position: element.scrollTop,+ };+}++/** A drag in progress, from the pick-up to the drop. */+interface DragSession {+ readonly list: HTMLElement;+ /** The rows in order at the begin. */+ readonly rows: ReadonlyArray<HTMLElement>;+ /** Their layout tops at the begin, for the commit's rebase. */+ readonly tops: ReadonlyArray<number>;+ readonly geometry: ReorderGeometry;+ readonly dragged: number;+ /** The dragged row's span, where the insertion line runs. */+ readonly lineSpan: LineSpan;+ position: number;+ /** The offset each row is moving to. */+ readonly offsets: number[];+ /** The list's layout origin in the viewport at the begin. */+ readonly origin: number;+ /** The finger's distance from the dragged row's top. */+ readonly grabOffset: number;+ readonly scroller: Scroller;+ /** How far autoscroll has moved the content since the begin. */+ scrolled: number;+ lastY: number;+ /** The edge autoscroll's timer, on UIKit's 20 ms clock. */+ readonly edge: EdgeAutoscroll;+ /** Points per tick of the running autoscroll; 0 when none. */+ step: number;+ /** The dragged row's inline stacking before the drag. */+ readonly restore: RowRestore;+ /** The copy of the dragged row that follows the pointer. */+ readonly preview: HTMLElement;+ /** 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 inline values a drag overrides until its rows rest. */+interface RowRestore {+ /** The dragged row's stacking and background. */+ readonly zIndex: string;+ readonly backgroundColor: string;+ /** The dragged row's opacity, dimmed while the drag runs. */+ readonly opacity: string;+ /**+ * The dragged row's counter increment, off while its preview counts for it+ * (a numbered list's number).+ */+ readonly counterIncrement: string;+ /** The list's position, made a containing block for the overlays. */+ readonly listPosition: string;+ /** The session's rows, whose identity offsets go once they rest. */+ readonly rows: ReadonlyArray<HTMLElement>;+}++/** A drop reported through `onReorder`, waiting for its commit. */+interface PendingDrop {+ readonly list: HTMLElement;+ readonly rows: ReadonlyArray<HTMLElement>;+ readonly tops: ReadonlyArray<number>;+ readonly dragged: number;+ /** Where the preview was at the drop: the dragged row glides from there. */+ readonly droppedTop: number;+ /**+ * The release's y velocity, px/s: the dragged row's glide starts at it.+ */+ readonly velocity: number;+ readonly restore: RowRestore;+}++/** A reorder mode move, reported and waiting for its commit. */+interface PendingMove {+ readonly list: HTMLElement;+ readonly rows: ReadonlyArray<HTMLElement>;+ /** The rows' layout tops before it, for the slide to their new places. */+ readonly tops: ReadonlyArray<number>;+}++/**+ * What a move announces. `landed` plays once the consumer commits it, with+ * the row at `to` in the DOM. `kept` plays if the consumer keeps the order+ * instead. A screen reader never hears a move that did not happen.+ */+interface PendingAnnouncement {+ readonly row: HTMLElement;+ readonly to: number;+ /** Read as the move lands, so it names the rows as they are named then. */+ readonly landed: () => string;+ readonly kept: string;+ 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';+ /** The finger's (or pointer's) y in the viewport. */+ readonly y: number;+ /**+ * At a release, the finger's (or pointer's) y velocity in px/s, which the+ * dropped row's glide starts at.+ */+ readonly velocity?: 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.+ */+export class ListReorderController implements ListReorderSession {+ readonly Host = ListReorderHost;+ readonly Handle = ListReorderHandle;+ readonly RowName = ListReorderRowName;+ readonly rowStyle = reorderRowStyle;+ readonly listStyle = reorderListStyle;+ options: ListReorderOptions | null = null;+ announce: AnnounceFn = () => {};+ messages: ReorderMessages | null = null;+ /** Whether rows move on springs (`'uikit'`) or jump (`'theme'`). */+ presentation: 'uikit' | 'theme' = 'theme';+ /** Each of this list's handles, with its row's item key. */+ private readonly keys = new Map<Element, Key>();+ /**+ * The names the announcements give rows: each handle's (its row's label+ * text) and each handle-less row's own.+ */+ private readonly names = new Map<Element, string>();+ /** The handle whose row is in reorder mode, if any. */+ private modeHandle: HTMLElement | null = null;+ private readonly modeListeners = new Set<() => void>();+ /** Reorder mode's hint, while it shows: focus in it keeps the mode. */+ private hintElement: HTMLElement | null = null;+ /** The handle whose press became a drag, until its click is read. */+ private draggedHandle: Element | null = null;+ /** A reorder mode move, whose rows slide once it commits (under a finger). */+ private committedMove: PendingMove | null = null;+ private moveFallback: ReturnType<typeof setTimeout> | null = null;+ /**+ * Reorder mode's insertion line: after a key move it marks the edge the+ * row came in through, at its new place, until the mode ends.+ */+ private modeLine: {list: HTMLElement; listPosition: string} | null = null;+ /** The direction of the last key move in reorder mode, for its line. */+ private lastStep: -1 | 1 | null = null;+ /**+ * Until when the handle takes back the focus the UI that started the mode+ * with `start` hands back (a menu that closes restores its trigger's).+ */+ private claimFocusUntil = 0;+ private session: DragSession | null = null;+ private pending: PendingDrop | null = null;+ private fallback: ReturnType<typeof setTimeout> | null = null;+ /** The row whose handle keeps focus across a reorder mode move's commit. */+ private focusRow: HTMLElement | null = null;+ /** A move's announcement, waiting for its commit. */+ private announcement: PendingAnnouncement | null = null;+ private announcementFallback: ReturnType<typeof setTimeout> | null = null;+ /** Ends the mouse press in progress, if any, without reporting it. */+ private endMouse: (() => void) | null = null;+ /** This session's development warnings, each given once. */+ private readonly warn = createDevWarnings();++ constructor(+ private readonly getList: () => HTMLElement | null,+ readonly hintId: string,+ ) {}++ /** The List's latest options, announcer, strings and presentation. */+ configure(options: {+ options: ListReorderOptions;+ announce: AnnounceFn;+ messages: ReorderMessages;+ presentation: 'uikit' | 'theme';+ }): void {+ this.options = options.options;+ this.announce = options.announce;+ this.messages = options.messages;+ this.presentation = options.presentation;+ }++ private get animates(): boolean {+ 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+ * name is recorded apart, so a new name leaves the row in reorder mode.+ */+ registerHandle(handle: Element | null, key: Key): () => void {+ if (handle == null) {+ return () => {};+ }+ this.keys.set(handle, key);+ return () => {+ if (this.keys.get(handle) === key) {+ this.keys.delete(handle);+ if (this.modeHandle === handle) {+ this.setMode(null);+ }+ }+ };+ }++ /** Records the name of a row, or of its handle; returns the removal. */+ registerName(row: Element | null, name: string): () => void {+ if (row == null) {+ return () => {};+ }+ this.names.set(row, name);+ return () => {+ if (this.names.get(row) === name) {+ this.names.delete(row);+ }+ };+ }++ /** What the announcements call the row at `index`. */+ private nameOf(row: HTMLElement, index: number): string {+ const handle = this.handleIn(row);+ const name =+ (handle == null ? null : this.names.get(handle)) ??+ this.names.get(row) ??+ '';+ return name !== '' ? name : (this.messages?.itemAt(index + 1) ?? '');+ }++ // --- Reorder mode ----------------------------------------------------++ /** Whether `handle`'s row is in reorder mode: its `aria-pressed`. */+ isInMode(handle: Element | null): boolean {+ return handle != null && this.modeHandle === handle;+ }++ /** Calls `listener` when reorder mode starts, moves or ends. */+ subscribeMode = (listener: () => void): (() => void) => {+ this.modeListeners.add(listener);+ return () => {+ this.modeListeners.delete(listener);+ };+ };++ /** The handle whose row is in reorder mode, if any. */+ get modeTarget(): HTMLElement | null {+ return this.modeHandle;+ }++ private setMode(handle: HTMLElement | null): void {+ if (this.modeHandle === handle) {+ return;+ }+ this.modeHandle = handle;+ this.lastStep = null;+ this.clearModeLine();+ const list = this.getList();+ if (handle != null && list != null) {+ this.placeModeLine(list);+ }+ for (const listener of [...this.modeListeners]) {+ listener();+ }+ }++ /**+ * A handle was activated without a drag (a click, Space or Enter): its row+ * enters reorder mode, or leaves it.+ */+ toggleMode(handle: HTMLElement | null): void {+ if (handle == null || this.session != null) {+ return;+ }+ if (this.modeHandle === handle) {+ this.endMode();+ return;+ }+ if (this.handleOf(handle) === handle) {+ this.setMode(handle);+ // The arrows go to the handle (a click does not focus a button in+ // every browser).+ if (handle.ownerDocument.activeElement !== handle) {+ handle.focus({preventScroll: true});+ }+ }+ }++ /**+ * Ends reorder mode, keeping its moves, and announces where the row is+ * ("Done, Milk at position 3 of 5"). Escape, another activation of the+ * handle, the hint's Done, or a drag ends it so. Focus that a screen+ * reader moved into the hint goes back to the handle. The row leaving ends+ * it without a word.+ */+ endMode(): void {+ const handle = this.modeHandle;+ const list = this.getList();+ const row = this.rowOf(handle);+ const active = handle?.ownerDocument.activeElement;+ if (+ handle != null &&+ active != null &&+ this.hintElement?.contains(active)+ ) {+ handle.focus({preventScroll: true});+ }+ this.setMode(null);+ if (list == null || row == null) {+ return;+ }+ const rows = rowsOf(list);+ const index = rows.indexOf(row);+ this.announce(+ this.messages?.modeDone(+ this.nameOf(row, index),+ index + 1,+ rows.length,+ ) ?? '',+ );+ }++ /** Records reorder mode's hint element (null once it goes). */+ setHintElement(element: HTMLElement | null): void {+ this.hintElement = element;+ }++ /**+ * Reorder mode for the item with `key`, started from the app's own UI. The+ * focus moves to its handle, which scrolls into view, as activating it+ * does. Returns whether an item with that key can move here.+ */+ startByKey(key: Key): boolean {+ if (this.session != null) {+ return true;+ }+ for (const [handle, handleKey] of this.keys) {+ if (+ handleKey === key &&+ handle instanceof HTMLElement &&+ this.handleOf(handle) === handle+ ) {+ this.setMode(handle);+ handle.focus({preventScroll: true});+ this.rowOf(handle)?.scrollIntoView?.({+ block: 'nearest',+ inline: 'nearest',+ });+ this.claimFocusUntil = performance.now() + START_FOCUS_CLAIM_MS;+ return true;+ }+ }+ return false;+ }++ /**+ * Whether `handle`'s latest press dragged its row; reading it clears it.+ * A press that dragged does not toggle reorder mode with its click.+ */+ takeDrag(handle: Element | null): boolean {+ const dragged = handle != null && this.draggedHandle === handle;+ this.draggedHandle = null;+ return dragged;+ }++ /** This list's handle in `row`, if it has one: a nested list's are its own. */+ private handleIn(row: HTMLElement): Element | null {+ for (const handle of reorderHandlesIn(row)) {+ if (this.keys.has(handle)) {+ return handle;+ }+ }+ return null;+ }++ /** The item key `row` reports its moves with; none for a row that stays. */+ private keyOf(row: HTMLElement): Key | undefined {+ const handle = this.handleIn(row);+ return handle == null ? undefined : this.keys.get(handle);+ }++ // --- Listeners ---------------------------------------------------------++ /**+ * The handle `target` is in, if it is one of this list's and takes+ * gestures; a nested reorderable list's handles are that list's.+ */+ private handleOf(target: unknown): HTMLElement | null {+ const list = this.getList();+ if (list == null || !(target instanceof Element)) {+ return null;+ }+ const handle = closestReorderHandle(target);+ return handle != null &&+ this.keys.has(handle) &&+ list.contains(handle) &&+ handle.getAttribute('aria-disabled') !== 'true'+ ? handle+ : null;+ }++ /**+ * Lets a mouse, or a pen where the primary pointer is fine, drag rows by+ * their handles without a hold. There is one pointerdown listener on the+ * list. 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 the row once it has moved MOUSE_DRAG_SLOP from where it pressed.+ * Returns the detach.+ */+ attachMouse(): () => void {+ const list = this.getList();+ 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;+ }+ 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,+ });+ }+ };+ 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);+ return () => {+ this.endMouse?.();+ list.removeEventListener('pointerdown', onPointerDown);+ };+ }++ /**+ * Lets a finger held still on a handle pick up its row, under every primary+ * pointer, and a pen where the primary pointer is coarse. One recognizer on+ * the list receives only the touches that begin on its handles. Returns the+ * detach.+ */+ attachTouch(isCoarsePointer: boolean): () => void {+ const list = this.getList();+ 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,+ });+ }+ },+ target => this.handleOf(target) != null,+ );+ }++ // --- Pointer drags ---------------------------------------------------++ /** A gesture from a handle: begin, track, drop or cancel the drag. */+ gesture(row: HTMLElement | null, event: ReorderGestureEvent): void {+ switch (event.state) {+ case 'began':+ if (row != null) {+ this.begin(row, event.y);+ }+ break;+ case 'changed':+ this.track(event.y);+ break;+ case 'ended':+ this.drop(event.velocity ?? 0);+ break;+ case 'cancelled':+ this.cancel();+ break;+ }+ }++ /**+ * `handle` stopped taking gestures: its row is disabled or no longer+ * reorderable, or the handle is gone. A drag it started goes home, and its+ * reorder mode ends. The session owns that end, since a recognizer turned+ * off mid-gesture reports nothing.+ */+ release(handle: Element | null): void {+ if (handle == null) {+ return;+ }+ if (this.session != null && this.draggedHandle === handle) {+ this.endMouse?.();+ this.cancel();+ }+ if (this.modeHandle === handle) {+ this.setMode(null);+ }+ }++ /** Picks up `row` under a pointer at `y`. Returns whether it did. */+ private begin(row: HTMLElement, y: number): boolean {+ const list = this.getList();+ if (list == null || this.session != null) {+ return false;+ }+ // A drag ends reorder mode, keeping its moves, and says so.+ if (this.modeHandle != null) {+ this.endMode();+ }+ // A drop still waiting for its commit is settled where it is.+ this.flushPending();+ const rows = rowsOf(list);+ const dragged = rows.indexOf(row);+ const movable = rows.map(element => this.handleIn(element) != null);+ if (dragged < 0 || !movable[dragged]) {+ return false;+ }+ const at = motionNow();+ const tops = rows.map(element => layoutTop(element, list));+ const heights = rows.map(element => element.offsetHeight);+ const lineSpan = lineSpanOf(row, list);+ const previewSpan = previewSpanOf(row, list);+ const isStatic = getComputedStyle(list).position === 'static';+ const bounds = boundsOf(movable);+ const geometry: ReorderGeometry = {+ rows: rows.map((element, index) => ({+ top: tops[index],+ height: heights[index],+ isFixed: bounds[index],+ })),+ gap: rows.length > 1 ? Math.max(0, tops[1] - tops[0] - heights[0]) : 0,+ };+ // The list's layout origin in the viewport, from the dragged row's box+ // without the offset it may still be moving by.+ const shown = shownY(row, at);+ const origin = row.getBoundingClientRect().top - shown - tops[dragged];+ const scroller = scrollerOf(list);+ // Every row gets an identity offset for the session. Otherwise a row's+ // first offset changes how it paints in the middle of the drag, with a+ // layout and a paint. With one in place, neither a move nor a slide lays+ // out or paints. `will-change` would make each slide's start repaint its+ // row. The dragged row goes above its neighbours.+ const restore: RowRestore = {+ zIndex: row.style.zIndex,+ backgroundColor: row.style.backgroundColor,+ opacity: row.style.opacity,+ counterIncrement: row.style.counterIncrement,+ listPosition: list.style.position,+ rows,+ };+ // The rows stay where they are until the drop. The dragged row is dimmed+ // in its place, and a preview of it follows the pointer. An insertion line+ // marks where it would land. The preview has a background, as the row+ // does. A row without its own takes the surface's behind the list.+ const background = isTransparent(getComputedStyle(row).backgroundColor)+ ? paintedBackground(list)+ : null;+ // The copy reads the row's styles, so it is made before the first write.+ const copy = previewCopyOf(row);+ for (const element of rows) {+ if (element.style.translate === '') {+ element.style.translate = '0px 0px';+ }+ }+ if (isStatic) {+ list.style.position = 'relative';+ }+ const preview = previewOf(copy, tops[dragged], previewSpan, background);+ // Right before its source, the preview counts for it. So in a numbered+ // list it reads the source's number. Every other row keeps its place+ // among its siblings, and the last row keeps :last-child.+ row.before(preview);+ row.style.counterIncrement = 'none';+ markReorderSource(row);+ row.style.opacity = MOVING_OPACITY;+ markReordering(list);+ const session: DragSession = {+ list,+ rows,+ tops,+ geometry,+ dragged,+ lineSpan,+ position: dragged,+ offsets: rows.map((element, index) =>+ index === dragged ? 0 : shownY(element, at),+ ),+ origin,+ grabOffset: y - (origin + tops[dragged] + shown),+ 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,+ step: () => this.edgeStep(session),+ apply: delta => this.scrollBy(session, delta),+ }),+ step: 0,+ restore,+ preview,+ previewOffset: 0,+ scrollStale: false,+ ownScroll: false,+ wrote: true,+ foldArmed: false,+ stopScrollWatch: () => {},+ };+ 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);+ this.announce(+ this.messages?.pickedUp(dragged + 1, rows.length) ?? '',+ 'polite',+ );+ return true;+ }++ /** The dragged row's top in the viewport for the finger at `y`. */+ private draggedTop(session: DragSession, y: number): number {+ const {geometry, dragged, scroller} = session;+ const row = geometry.rows[dragged];+ const first = geometry.rows[0];+ const last = geometry.rows[geometry.rows.length - 1];+ const origin = session.origin - session.scrolled;+ return clampTop(y - session.grabOffset, row.height, {+ scrollTop: scroller.top,+ scrollBottom: scroller.bottom,+ listTop: origin + first.top,+ listBottom: origin + last.top + last.height,+ });+ }++ private track(y: number): void {+ const session = this.session;+ if (session == null) {+ return;+ }+ if (session.scrollStale) {+ this.syncScroll(session);+ }+ session.lastY = y;+ session.wrote = true;+ const {geometry, dragged} = session;+ const row = geometry.rows[dragged];+ const origin = session.origin - session.scrolled;+ const top = this.draggedTop(session, y);+ const offset = top - (origin + row.top);+ // The preview starts at its row's place, with no offset. Only a new+ // offset goes to its animator: writing none would read its style back.+ if (offset !== session.previewOffset) {+ session.previewOffset = offset;+ animatorFor(session.preview).set({y: offset});+ }+ const position = dropPosition(+ geometry,+ dragged,+ top + row.height / 2 - origin,+ );+ if (position !== session.position) {+ this.moveTo(position);+ }+ this.autoscroll(top, row.height);+ }++ /** Puts the insertion line where the dragged row would land at `position`. */+ private moveTo(position: number): void {+ const session = this.session;+ if (session == null) {+ return;+ }+ session.position = position;+ const center = lineCenter(session.geometry, session.dragged, position);+ if (center == null) {+ hideLine(session.list);+ } else {+ showLine(session.list, session.lineSpan, center);+ }+ // A pointer drag announces its pick-up and its drop, not each place it+ // passes: announcing each crossed position is noisy.+ }++ /**+ * Points per tick for the dragged row at `top`: positive down, negative+ * up. It is 0 when neither edge is near or the content cannot move that+ * way.+ */+ private stepFor(session: DragSession, top: number, height: number): number {+ const {scroller} = session;+ let step = 0;+ if (scroller.position < scroller.max) {+ step = autoscrollStep(top + height - scroller.bottom);+ }+ if (step === 0 && scroller.position > 0) {+ step = -autoscrollStep(scroller.top - top);+ }+ return step;+ }++ /** Starts or stops the edge autoscroll for the row at `top`. */+ private autoscroll(top: number, height: number): void {+ const session = this.session;+ if (session == null) {+ return;+ }+ session.step = Math.abs(this.stepFor(session, top, height));+ session.edge.update();+ }++ /** The autoscroll's next step for the finger where it last was. */+ private edgeStep(session: DragSession): number {+ if (this.session !== session) {+ return 0;+ }+ if (session.scrollStale) {+ this.syncScroll(session);+ }+ const {geometry, dragged} = session;+ const top = this.draggedTop(session, session.lastY);+ return this.stepFor(session, top, geometry.rows[dragged].height);+ }++ /**+ * One autoscroll step: the content moves by `delta` (inside its range) and+ * the row stays under the finger. Returns how far the content moved.+ */+ private scrollBy(session: DragSession, delta: number): number {+ if (this.session !== session) {+ return 0;+ }+ const {scroller} = session;+ const next = Math.min(scroller.max, Math.max(0, scroller.position + delta));+ const moved = next - scroller.position;+ if (moved === 0) {+ return 0;+ }+ 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;+ });+ 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;+ // The page's own scroll is reported on the document.+ const target =+ element === (doc.scrollingElement ?? doc.documentElement) ? doc : element;+ return subscribeInput(view, 'scroll', event => {+ if (event.target !== target || this.session !== session) {+ return;+ }+ if (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 position = scroller.element.scrollTop;+ session.scrolled += position - scroller.position;+ scroller.position = position;+ }++ private stopAutoscroll(session: DragSession): void {+ session.edge.stop();+ session.step = 0;+ }++ /**+ * The drop: the move is reported, and on its commit the row glides into+ * its place, starting at the release's y `velocity` in px/s.+ */+ private drop(velocity: number): void {+ const session = this.session;+ if (session == null) {+ return;+ }+ if (session.scrollStale) {+ this.track(session.lastY);+ }+ this.session = null;+ this.stopAutoscroll(session);+ session.stopScrollWatch();+ const {geometry, dragged, position, rows, list} = session;+ const element = rows[dragged];+ // Where the preview is now: on the commit the dragged row glides from+ // there into its new place, and the rows it passed to theirs.+ const droppedTop =+ geometry.rows[dragged].top + shownY(session.preview, motionNow());+ this.clearOverlays(session);+ const dropped = this.messages?.dropped(position + 1, rows.length) ?? '';+ const key = this.keyOf(element);+ const options = this.options;+ if (position === dragged || options == null || key == null) {+ if (position === dragged) {+ this.announce(dropped, 'polite');+ clearReordering(list);+ this.restWhenDone(element, session.restore);+ } else {+ this.springBack(list, rows, dragged, session.restore);+ }+ return;+ }+ this.announceWhenCommitted({+ row: element,+ to: position,+ landed: () => dropped,+ kept: this.messages?.cancelled(dragged + 1, rows.length) ?? '',+ politeness: 'polite',+ });+ this.pending = {+ list,+ rows,+ tops: session.tops,+ dragged,+ droppedTop,+ velocity,+ restore: session.restore,+ };+ options.onReorder({key, to: position});+ // A consumer that does not apply the move by the end of the task gets+ // its rows back where they were.+ this.fallback = setTimeout(() => {+ this.fallback = null;+ this.refuse();+ }, 0);+ }++ /**+ * The drag ends where it started: the browser took the touch (a pinch, a+ * scroll), or the handle left. Every row goes home and nothing is+ * reported.+ */+ cancel(): void {+ const session = this.session;+ if (session == null) {+ return;+ }+ this.session = null;+ this.stopAutoscroll(session);+ session.stopScrollWatch();+ // Nothing moved: the preview and the line go and the row is itself again+ // at once.+ this.clearOverlays(session);+ this.springBack(+ session.list,+ session.rows,+ session.dragged,+ session.restore,+ );+ this.announce(+ this.messages?.cancelled(session.dragged + 1, session.rows.length) ?? '',+ );+ }++ /** Takes the preview and the line away and undims the dragged row. */+ private clearOverlays(session: DragSession): void {+ session.preview.remove();+ hideLine(session.list);+ const row = session.rows[session.dragged];+ clearReorderSource(row);+ row.style.opacity = session.restore.opacity;+ row.style.counterIncrement = session.restore.counterIncrement;+ session.list.style.position = session.restore.listPosition;+ }++ private springBack(+ list: HTMLElement,+ rows: ReadonlyArray<HTMLElement>,+ dragged: number,+ restore: RowRestore,+ ): void {+ const at = motionNow();+ const away = rows.filter(+ element =>+ Math.abs(shownY(element, at)) >= MIN_MOVE_PX || isMoving(element),+ );+ // The spring is read once, before the first write.+ const spring =+ this.animates && away.length > 0 ? touchMotion.glideBase(list) : null;+ for (const element of away) {+ if (spring == null) {+ animatorFor(element).set({y: 0});+ releaseMotion(element, 'translate');+ continue;+ }+ // A row still in a drop's or a key move's glide goes on home. It plays+ // the shared settle role from where it is shown, at the speed it has.+ touchMotion.home(element, spring, at, false);+ }+ clearReordering(list);+ this.restWhenDone(rows[dragged], restore);+ }++ /** `onReorder` applied no new order: the rows return to their places. */+ private refuse(): void {+ const pending = this.pending;+ if (pending == null) {+ return;+ }+ const current = rowsOf(pending.list);+ if (!sameOrder(current, pending.rows)) {+ // The commit came but its layout effect has not run yet.+ return;+ }+ this.pending = null;+ this.springBack(+ pending.list,+ pending.rows,+ pending.dragged,+ pending.restore,+ );+ }++ /** Clears the dragged row's stacking once its motion has come to rest. */+ private restWhenDone(element: HTMLElement, restore: RowRestore): void {+ const settle = () => {+ if (this.session?.rows[this.session.dragged] === element) {+ return;+ }+ const running = motionOf(element, 'y');+ if (running != null) {+ // The drop's spring, or the rebase that continues it.+ void running.handle.finished.then(settle);+ return;+ }+ element.style.zIndex = restore.zIndex;+ element.style.backgroundColor = restore.backgroundColor;+ // Identity offsets go; a row still moving keeps its own.+ for (const row of restore.rows) {+ releaseMotion(row, 'translate');+ }+ };+ settle();+ }++ private flushPending(): void {+ if (this.pending == null) {+ return;+ }+ if (this.fallback != null) {+ clearTimeout(this.fallback);+ this.fallback = null;+ }+ this.refuse();+ this.pending = null;+ }++ // --- Commits ---------------------------------------------------------++ ownsCommit(): boolean {+ const list = this.getList();+ return list != null && isReordering(list);+ }++ commit(): void {+ const list = this.getList();+ if (list == null) {+ return;+ }+ if (+ this.keys.size === 0 &&+ this.options != null &&+ this.options.isReorderable == null &&+ list.children.length > 0+ ) {+ this.warn(+ 'List',+ '`reorderable` is set, but no ListItem has an `itemKey`: give each ' ++ 'row the key its moves report.',+ );+ }+ const session = this.session;+ if (session != null && !sameOrder(rowsOf(list), session.rows)) {+ // The rows changed under the drag.+ this.cancel();+ }+ const pending = this.pending;+ if (pending != null && !sameOrder(rowsOf(list), pending.rows)) {+ this.pending = null;+ if (this.fallback != null) {+ clearTimeout(this.fallback);+ this.fallback = null;+ }+ this.rebase(pending);+ }+ const announcement = this.announcement;+ if (+ announcement != null &&+ rowsOf(list).indexOf(announcement.row) === announcement.to+ ) {+ this.announcement = null;+ if (this.announcementFallback != null) {+ clearTimeout(this.announcementFallback);+ this.announcementFallback = null;+ }+ this.announce(announcement.landed(), announcement.politeness);+ }+ const move = this.committedMove;+ let slide: (() => void) | null = null;+ if (move != null && !sameOrder(rowsOf(list), move.rows)) {+ this.committedMove = null;+ if (this.moveFallback != null) {+ clearTimeout(this.moveFallback);+ this.moveFallback = null;+ }+ slide = this.slideCommitted(move);+ }+ // A reorder mode move has landed (or nothing waits): its handle keeps+ // the focus, and the insertion line marks the row's new place. Their+ // reads come before the slide's first write, so a move lays out once.+ if (this.announcement == null) {+ const placeLine = this.measureModeLine(list);+ this.restoreFocus();+ slide?.();+ placeLine();+ } else {+ slide?.();+ }+ }++ /**+ * A reorder mode move landed: each row slides from its old place to its new+ * one. Measures the slides, and returns the writes that start them.+ */+ private slideCommitted(move: PendingMove): () => void {+ const {list} = move;+ const at = motionNow();+ const shifts = move.rows.map((element, index) =>+ element.parentElement === list+ ? move.tops[index] - layoutTop(element, list)+ : 0,+ );+ const spring = shifts.some(shift => Math.abs(shift) >= MIN_MOVE_PX)+ ? touchMotion.glideBase(list)+ : null;+ return () => {+ for (const [index, element] of move.rows.entries()) {+ const shift = shifts[index];+ if (spring == null || Math.abs(shift) < MIN_MOVE_PX) {+ continue;+ }+ // A row still sliding from the previous move goes on from where it+ // is shown, as a drop's rows do.+ touchMotion.follow(element, shift, spring, at);+ }+ clearReordering(list);+ };+ }++ private rebase(pending: PendingDrop): void {+ const {list} = pending;+ const at = motionNow();+ // Every read comes before the first write, so the drop lays out once.+ const rows = pending.rows.map((element, index) => {+ if (element.parentElement !== list) {+ return null;+ }+ // The dragged row glides from where its preview was dropped, the rows+ // it passed from their old places.+ const from =+ index === pending.dragged ? pending.droppedTop : pending.tops[index];+ return {+ element,+ index,+ shift: from - layoutTop(element, list),+ value: shownY(element, at),+ moving: isMoving(element),+ };+ });+ // A row at rest where the drop leaves it settles there. A row the layout+ // moved glides from its old place.+ const settles = (row: {shift: number; value: number; moving: boolean}) =>+ Math.abs(row.value + row.shift) < MIN_MOVE_PX && !row.moving;+ const glides = (row: {shift: number; value: number; moving: boolean}) =>+ !settles(row) && Math.abs(row.shift) >= MIN_MOVE_PX;+ const spring =+ this.animates && rows.some(row => row != null && glides(row))+ ? touchMotion.glideBase(list)+ : null;+ for (const row of rows) {+ if (row == null) {+ continue;+ }+ const {element, index, shift, value, moving} = row;+ if (settles(row)) {+ settleAtRest(element, value, moving);+ continue;+ }+ if (!glides(row)) {+ continue;+ }+ if (spring != null && index === pending.dragged) {+ // The dragged row glides from where its preview was dropped into its+ // new layout place, starting at the release's velocity.+ touchMotion.glide(element, shift, spring, at, pending.velocity);+ } else if (spring != null) {+ // Every other row's place after the drop is its new layout place. So+ // its running glide goes on to 0 from the shifted value. Otherwise the+ // glide starts from rest.+ touchMotion.follow(element, shift, spring, at);+ } else {+ settleAtRest(element, value, moving);+ }+ }+ clearReordering(list);+ this.restWhenDone(pending.rows[pending.dragged], pending.restore);+ }++ /**+ * Reorder mode's insertion line, shared with the pointer drag's. It marks+ * the row's place for the whole mode. It sits at the edge the row came in+ * through on its last key move. That is the gap above it after a move up,+ * and below it after a move down. Before a move, it sits in the gap above+ * the row.+ */+ private placeModeLine(list: HTMLElement): void {+ this.measureModeLine(list)();+ }++ /**+ * Reads where reorder mode's insertion line goes, and returns the writes+ * that place it there.+ */+ private measureModeLine(list: HTMLElement): () => void {+ const row = this.rowOf(this.modeHandle);+ if (row == null) {+ return () => this.clearModeLine();+ }+ const step = this.lastStep ?? -1;+ const rows = rowsOf(list);+ const index = rows.indexOf(row);+ const top = layoutTop(row, list);+ const bottom = top + row.offsetHeight;+ const neighbour = rows[index + step];+ const gap =+ neighbour == null+ ? 0+ : step < 0+ ? Math.max(+ 0,+ top - (layoutTop(neighbour, list) + neighbour.offsetHeight),+ )+ : Math.max(0, layoutTop(neighbour, list) - bottom);+ const center = step < 0 ? top - gap / 2 : bottom + gap / 2;+ const span = lineSpanOf(row, list);+ const isNewList = this.modeLine?.list !== list;+ const isStatic = isNewList && getComputedStyle(list).position === 'static';+ return () => {+ if (isNewList) {+ this.clearModeLine();+ const listPosition = list.style.position;+ if (isStatic) {+ list.style.position = 'relative';+ }+ this.modeLine = {list, listPosition};+ }+ showLine(list, span, center);+ };+ }++ private clearModeLine(): void {+ const modeLine = this.modeLine;+ if (modeLine == null) {+ return;+ }+ this.modeLine = null;+ hideLine(modeLine.list);+ modeLine.list.style.position = modeLine.listPosition;+ }++ /**+ * The row that holds `element` (a handle): the list's child that contains+ * it, whatever its tag. Null outside the list.+ */+ rowOf(element: Element | null): HTMLElement | null {+ const list = this.getList();+ let node = element;+ while (node != null && node.parentElement !== list) {+ node = node.parentElement;+ }+ return list != null && node instanceof HTMLElement ? node : null;+ }++ /** The 1-based place of the row that holds `element`, or null. */+ positionOf(element: Element | null): number | null {+ const list = this.getList();+ const row = this.rowOf(element);+ return list == null || row == null ? null : rowsOf(list).indexOf(row) + 1;+ }++ // --- Keys ------------------------------------------------------------++ /**+ * A handle's key in reorder mode: the arrows move its+ * row a place at once, and Escape ends the mode, keeping the moves. Space+ * and Enter toggle the mode through the handle's click.+ */+ keyDown(handle: HTMLElement | null, event: KeyboardEvent): void {+ // A modified key is a browser or assistive-technology shortcut.+ if (+ handle == null ||+ handle !== this.modeHandle ||+ event.altKey ||+ event.ctrlKey ||+ event.metaKey+ ) {+ return;+ }+ switch (event.key) {+ case 'Escape':+ event.preventDefault();+ event.stopPropagation();+ this.endMode();+ return;+ case 'ArrowUp':+ case 'ArrowDown':+ event.preventDefault();+ this.step(handle, event.key === 'ArrowUp' ? -1 : 1);+ return;+ default:+ return;+ }+ }++ /**+ * Reorder mode's move. The row whose handle is in the mode goes a place up+ * (`-1`) or down (`1`) at once, with one report. It is announced with its+ * place and neighbours once it lands. Under a finger's presentation, the+ * rows then slide to their new places, as a UIKit table moves a row. A move+ * into a row that stays at either end is refused and announced. One past+ * the list's end does nothing.+ */+ step(handle: HTMLElement | null, delta: -1 | 1): void {+ const list = this.getList();+ const options = this.options;+ const row = this.rowOf(handle);+ const key = row == null ? undefined : this.keyOf(row);+ if (+ list == null ||+ options == null ||+ row == null ||+ key == null ||+ handle !== this.modeHandle ||+ this.session != null+ ) {+ return;+ }+ const rows = rowsOf(list);+ const index = rows.indexOf(row);+ const to = index + delta;+ if (to < 0 || to >= rows.length) {+ return;+ }+ if (boundsOf(rows.map(element => this.handleIn(element) != null))[to]) {+ this.announce(this.messages?.refused(this.nameOf(rows[to], to)) ?? '');+ return;+ }+ this.focusRow = row;+ this.lastStep = delta;+ this.announceWhenCommitted({+ row,+ to,+ landed: () => this.placeIn(rowsOf(list), to),+ kept: this.placeIn(rows, index),+ politeness: undefined,+ });+ if (this.animates) {+ this.committedMove = {+ list,+ rows,+ tops: rows.map(element => layoutTop(element, list)),+ };+ // The List's layout updates leave this commit to the reorder.+ markReordering(list);+ if (this.moveFallback != null) {+ clearTimeout(this.moveFallback);+ }+ // The caller kept the order: nothing slides.+ this.moveFallback = setTimeout(() => {+ this.moveFallback = null;+ if (this.committedMove != null) {+ this.committedMove = null;+ if (this.session == null && this.pending == null) {+ clearReordering(list);+ }+ }+ }, 0);+ }+ options.onReorder({key, to});+ }++ /** What reorder mode announces for the row at `at` in `order`. */+ private placeIn(order: ReadonlyArray<HTMLElement>, at: number): string {+ const name = (index: number) => this.nameOf(order[index], index);+ return (+ this.messages?.place(+ name(at),+ at + 1,+ order.length,+ at > 0 ? name(at - 1) : null,+ at < order.length - 1 ? name(at + 1) : null,+ ) ?? ''+ );+ }++ /**+ * Announces a move once it commits; if the consumer keeps the order by the+ * end of the task, announces that the row stayed instead.+ */+ private announceWhenCommitted(announcement: PendingAnnouncement): void {+ this.announcement = announcement;+ if (this.announcementFallback != null) {+ clearTimeout(this.announcementFallback);+ }+ this.announcementFallback = setTimeout(() => {+ this.announcementFallback = null;+ const pending = this.announcement;+ if (pending != null) {+ this.announcement = null;+ this.announce(pending.kept, pending.politeness);+ }+ this.restoreFocus();+ }, 0);+ }++ /**+ * A handle lost focus to `next`. Its row stays in reorder mode. When the UI+ * that started the mode hands its focus back at once, the handle takes it+ * again.+ */+ blur(handle: HTMLElement | null, next: EventTarget | null): void {+ // Focus a screen reader moves into the mode's hint keeps the mode.+ if (next instanceof Node && this.hintElement?.contains(next)) {+ return;+ }+ // The UI that started the mode handing its focus back (a closing menu+ // restoring its trigger's) at once: the handle takes it again.+ if (+ handle != null &&+ handle === this.modeHandle &&+ performance.now() < this.claimFocusUntil+ ) {+ setTimeout(() => {+ if (this.modeHandle === handle) {+ handle.focus({preventScroll: true});+ }+ }, 0);+ return;+ }+ // Focus leaving the handle does not end reorder mode: its exits are+ // Escape, Done, the handle again and its row going. Back on the handle,+ // its arrows move the row again.+ }++ /**+ * After a reorder mode move: the handle has the focus again (the commit+ * may have moved its element) and its row scrolls into view.+ */+ private restoreFocus(): void {+ const row = this.focusRow;+ if (row == null) {+ return;+ }+ this.focusRow = null;+ const handle = this.handleIn(row);+ const active = row.ownerDocument.activeElement;+ // The scroll reads layout, so it comes before the focus changes styles.+ if (handle === this.modeHandle) {+ row.scrollIntoView?.({block: 'nearest', inline: 'nearest'});+ }+ // Focus that went elsewhere meanwhile stays there; focus in the hint+ // (a screen reader's) goes back to the handle.+ if (+ handle instanceof HTMLElement &&+ handle === this.modeHandle &&+ (active == null ||+ active === row.ownerDocument.body ||+ this.hintElement?.contains(active) === true)+ ) {+ handle.focus({preventScroll: true});+ }+ }++ dispose(): void {+ this.endMouse?.();+ this.setMode(null);+ // A drag in progress goes home.+ this.cancel();+ if (this.moveFallback != null) {+ clearTimeout(this.moveFallback);+ this.moveFallback = null;+ }+ this.committedMove = null;+ if (this.fallback != null) {+ clearTimeout(this.fallback);+ this.fallback = null;+ }+ this.pending = null;+ if (this.announcementFallback != null) {+ clearTimeout(this.announcementFallback);+ this.announcementFallback = null;+ }+ this.announcement = null;+ }+}++function sameOrder(+ a: ReadonlyArray<HTMLElement>,+ b: ReadonlyArray<HTMLElement>,+): boolean {+ return (+ a.length === b.length && a.every((element, index) => element === b[index])+ );+}++/**+ * Renders beside a reorderable List's rows. It keeps its session's options,+ * strings and presentation current, and attaches the list's listeners. The+ * touch hold attaches under every primary pointer. It also renders the+ * handles' instructions.+ */+function ListReorderHost({reorder}: {reorder: ListReorderContextValue}) {+ const {options} = reorder;+ const controller = reorder.session as ListReorderController;+ const announce = useAnnounce();+ const t = useComponentTranslator();+ // UIKit's motion under a finger (one touch model on every touch device);+ // with a mouse, rows take their places at once.+ const isTouch = useTouchPresentation().isTouch;+ // Syncs the reorder session, which lives outside React, with this render's+ // options, strings and presentation.+ useIsomorphicLayoutEffect(() => {+ controller.configure({+ options,+ announce,+ messages: messagesFrom(t),+ presentation: isTouch ? 'uikit' : 'theme',+ });+ });+ // The list's own pointer listeners, on its DOM element.+ useIsomorphicLayoutEffect(() => controller.attachMouse(), [controller]);+ // Where the object's `start` finds this list.+ useIsomorphicLayoutEffect(+ () => mountSession(options, controller),+ [options, controller],+ );+ // The List stopped reordering, or unmounted: a drag goes home.+ useIsomorphicLayoutEffect(() => () => controller.dispose(), [controller]);+ // The gesture host's hold recognizer on the list. It takes a finger under+ // every primary pointer, and a pen where the primary pointer is coarse.+ useIsomorphicLayoutEffect(+ () => controller.attachTouch(isTouch),+ [controller, isTouch],+ );+ return (+ <>+ <span id={controller.hintId} hidden>+ {t('@astryx.list.reorderHint')}+ </span>+ <ListReorderModeHint controller={controller} />+ </>+ );+}++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 (+ <button+ ref={hitAreaRef}+ type="button"+ tabIndex={-1}+ aria-label={label}+ onPointerDown={event => event.preventDefault()}+ onMouseDown={event => event.preventDefault()}+ onClick={onPress}+ {...focusOutlineProps.focusVisible([+ hintStyles.button,+ isText && hintStyles.done,+ touchHitAreaStyles.layer,+ ])}>+ {children}+ </button>+ );+}++/**+ * 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.+ */+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 = useRef(layer);+ layerRef.current = layer;+ const hintRef = useRef<HTMLElement | null>(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 : (+ <span+ ref={element => {+ hintRef.current = element;+ controller.setHintElement(element);+ }}+ {...stylex.props(anchoredHintStyles.keys)}>+ <HintButton+ label={t('@astryx.list.reorderMoveUp')}+ onPress={() => controller.step(target, -1)}>+ <Kbd keys="up" aria-hidden />+ </HintButton>+ <HintButton+ label={t('@astryx.list.reorderMoveDown')}+ onPress={() => controller.step(target, 1)}>+ <Kbd keys="down" aria-hidden />+ </HintButton>+ <HintButton isText onPress={() => controller.endMode()}>+ {t('@astryx.list.reorderDone')}+ </HintButton>+ </span>+ ),+ {isInteractive: true},+ );+}++/** The machinery a reorderable object carries (createReorderable). */+export const listReorderEngine: ListReorderEngine = {+ createSession: (getList, hintId) =>+ new ListReorderController(getList, hintId),+ start: (options, key) => {+ const sessions = sessionsByOptions.get(options) ?? [];+ if (sessions.length > 1) {+ devWarn(+ 'createReorderable',+ '`start` was called on an object passed to more than one ' ++ 'collection: it starts reorder mode in the one mounted last.',+ );+ }+ const session = sessions.at(-1);+ if (session == null || !session.startByKey(key)) {+ devWarn(+ 'createReorderable',+ `\`start(${String(key)})\` found no mounted item with ` ++ 'that key that can be reordered, so it did nothing.',+ );+ }+ },+};diff --git a/packages/core/src/List/reorderModel.ts b/packages/core/src/List/reorderModel.tsnew file mode 100644index 0000000000..d1eb3b796a--- /dev/null+++ b/packages/core/src/List/reorderModel.ts@@ -0,0 +1,158 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file reorderModel.ts+ * @input A list's row geometry (layout tops and heights inside the list) and+ * the reorder values of the UIKit constants table (motion/uikit/reorder.ts)+ * @output Pure functions of a reorder's drag. They give the position a+ * dragged row proposes, where the insertion cue goes. They also give the+ * movable range that a fixed row at either end of the list bounds, the+ * autoscroll step and the tracking clamp+ * @position List internals. List/listReorderEngine.tsx drives a drag with+ * them. No DOM, no React: unit tested against the UIKit lab measurements+ *+ * The rows stay still during a drag while an insertion cue marks the drop+ * position. So the model proposes drop positions and moves no row. A row+ * below the dragged row changes places once the dragged row's centre passes+ * that row's far edge less the dragged row's height. It never changes before+ * that row's near edge. A row above mirrors it. Boundaries sit in the middle+ * of a gap, with no hysteresis. Measured on UIKit (iOS 26.2): a 44 pt row+ * moving down past 44 and 88 pt rows and back over them. Two cases stay a+ * GUESS until M-RO27 measures them (motion/MEASUREMENTS.md). They are a+ * short row moving up past a taller row above its place, and a tall row+ * moving past a shorter one. Autoscroll moves a whole number of points per+ * tick. It moves more the deeper the dragged row's edge is past the scroll+ * view's edge (measured).+ */++import {reorder} from '../motion/uikit/reorder';++/** One row: its layout top inside the list, its height, and whether it stays put. */+export interface ReorderRow {+ readonly top: number;+ readonly height: number;+ /**+ * A row with no handle, so no drag starts from it. A run of them at either+ * end of the list bounds a drag. One in the middle is passed over.+ */+ readonly isFixed: boolean;+}++export interface ReorderGeometry {+ readonly rows: ReadonlyArray<ReorderRow>;+ /** The space between two consecutive rows. */+ readonly gap: number;+}++/**+ * The positions `dragged` can take: all of them but those of the fixed rows that+ * end the list. A run of fixed rows at either end bounds the range. A fixed row+ * in the middle is passed over, as reorder mode's keys pass it.+ */+export function movableRange(+ rows: ReadonlyArray<ReorderRow>,+ dragged: number,+): {start: number; end: number} {+ let start = 0;+ while (start < dragged && rows[start].isFixed) {+ start += 1;+ }+ let end = rows.length - 1;+ while (end > dragged && rows[end].isFixed) {+ end -= 1;+ }+ return {start, end};+}++/**+ * The position the dragged row proposes for its centre, in list coordinates.+ * The insertion cue goes there. A row below it changes places once the centre+ * passes that row's far edge less the dragged row's height. For equal rows,+ * that is the neighbour's near edge, half a row. For a 44 pt row passing an+ * 88 pt row below its place, it is that row's height (both measured). A row+ * above mirrors it (GUESS for unequal rows, M-RO27). Either way the centre+ * must first pass the neighbour's near edge. So a tall row never starts past+ * a short neighbour: its centre travels at least half its own height (GUESS,+ * M-RO27). Boundaries sit in the middle of a gap.+ */+export function dropPosition(+ geometry: ReorderGeometry,+ dragged: number,+ center: number,+): number {+ const {rows, gap} = geometry;+ const height = rows[dragged].height;+ let position = 0;+ for (let index = 0; index < rows.length; index += 1) {+ if (index === dragged) {+ continue;+ }+ const {top, height: rowHeight} = rows[index];+ const boundary =+ index < dragged+ ? Math.min(top + height, top + rowHeight) + gap / 2+ : Math.max(top + rowHeight - height, top) - gap / 2;+ if (boundary < center) {+ position += 1;+ }+ }+ const {start, end} = movableRange(rows, dragged);+ return Math.min(end, Math.max(start, position));+}++/**+ * Points per autoscroll tick with the dragged row's edge `depth` points past+ * the scroll edge (negative inside). There are none further inside than the+ * start inset. Then UIKit's measured steps apply, interpolated and rounded.+ */+export function autoscrollStep(depth: number): number {+ const {depths, stepsPt, startInset} = reorder.autoscroll;+ if (depth < -startInset) {+ return 0;+ }+ if (depth <= depths[0]) {+ return stepsPt[0];+ }+ const last = depths.length - 1;+ if (depth >= depths[last]) {+ return stepsPt[last];+ }+ let index = 1;+ while (depths[index] < depth) {+ index += 1;+ }+ const d0 = depths[index - 1];+ const d1 = depths[index];+ const s0 = stepsPt[index - 1];+ const s1 = stepsPt[index];+ return Math.round(s0 + ((s1 - s0) * (depth - d0)) / (d1 - d0));+}++/** Where a dragged row may go: the scroller's visible edges and the list's ends. */+export interface ReorderBounds {+ /** The scroller's visible top and bottom. */+ readonly scrollTop: number;+ readonly scrollBottom: number;+ /** The list's first row top and last row bottom. */+ readonly listTop: number;+ readonly listBottom: number;+}++/**+ * The dragged row's top. At the scroller's visible edge the row stops with its+ * centre on the edge, as UIKit stops a row on the table's edge. At the list's+ * own end it stops with its edge there. So a row never hangs over the content+ * after an embedded list, such as a TransferList's next panel.+ */+export function clampTop(+ top: number,+ height: number,+ bounds: ReorderBounds,+): number {+ const min = Math.max(bounds.scrollTop - height / 2, bounds.listTop);+ const max = Math.min(+ bounds.scrollBottom - height / 2,+ bounds.listBottom - height,+ );+ return Math.min(max, Math.max(min, top));+}diff --git a/packages/core/src/hooks/anchoredHint.tsx b/packages/core/src/hooks/anchoredHint.tsxnew file mode 100644index 0000000000..955324e988--- /dev/null+++ b/packages/core/src/hooks/anchoredHint.tsx@@ -0,0 +1,105 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file anchoredHint.tsx+ * @input A context layer (Layer/useLayer.tsx) and the theme's tokens+ * @output renderAnchoredHint and anchoredHintStyles: the anchored hint layer+ * Core's keyboard hints share. It is a small surface in the top layer,+ * below the start of the element it is anchored to. It has the popover+ * background, the element radius, the low shadow and supporting text. It+ * holds a row of key glyphs and a label+ * @position Internal to Core, not exported from the package. The keyboard+ * hint (hooks/useKeyboardHint.tsx) renders its passive hint with it. A+ * reorderable List (List/listReorderEngine.tsx) renders the hint of its+ * reorder mode with it, whose glyphs are buttons+ *+ * SYNC: When modified, update hooks/useKeyboardHint.tsx and+ * List/listReorderEngine.tsx.+ */++import type {ReactNode} from 'react';+import * as stylex from '@stylexjs/stylex';+import {+ colorVars,+ radiusVars,+ shadowVars,+ spacingVars,+ typeScaleVars,+} from '../theme/tokens.stylex';+import type {ContextLayerReturn} from '../Layer/useLayer';++const styles = stylex.create({+ hint: {+ // Top layer + anchor positioned+ position: 'fixed',+ inset: 'auto',+ margin: 0,+ borderWidth: 0,+ borderStyle: 'none',++ // Surface+ backgroundColor: colorVars['--color-background-popover'],+ borderRadius: radiusVars['--radius-element'],+ boxShadow: shadowVars['--shadow-low'],+ paddingBlockStart: spacingVars['--spacing-1'],+ paddingBlockEnd: spacingVars['--spacing-1'],+ paddingInlineStart: spacingVars['--spacing-2'],+ paddingInlineEnd: spacingVars['--spacing-2'],++ // Typography+ fontSize: typeScaleVars['--text-supporting-size'],+ lineHeight: typeScaleVars['--text-supporting-leading'],+ color: colorVars['--color-text-secondary'],+ whiteSpace: 'nowrap',++ // Animation+ opacity: {+ default: 0,+ ':popover-open': 1,+ },+ transitionProperty: 'opacity, display, overlay',+ transitionDuration: '150ms',+ transitionBehavior: 'allow-discrete',+ },+ // A hint that only teaches floats above the content without taking its+ // pointer events.+ passive: {+ pointerEvents: 'none',+ },+ keys: {+ display: 'inline-flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-1'],+ },+ label: {+ marginInlineStart: spacingVars['--spacing-1'],+ },+});++/** The hint's row of key glyphs, and the label after it. */+export const anchoredHintStyles = {+ keys: styles.keys,+ label: styles.label,+};++/**+ * Renders `content` as an anchored hint in `layer` (a context layer whose+ * `ref` holds the anchor). A passive hint lets pointer events through; an+ * interactive one (`isInteractive`) takes them, for glyphs that are buttons.+ */+export function renderAnchoredHint(+ layer: ContextLayerReturn,+ content: ReactNode,+ {isInteractive = false}: {isInteractive?: boolean} = {},+): ReactNode {+ return layer.render(content, {+ placement: 'below',+ alignment: 'start',+ xstyle: [styles.hint, !isInteractive && styles.passive],+ style: {+ marginBlockStart: spacingVars['--spacing-2'],+ },+ });+}diff --git a/packages/core/src/hooks/useKeyboardHint.test.tsx b/packages/core/src/hooks/useKeyboardHint.test.tsxindex 4789c93f4c..fbc574880b 100644--- a/packages/core/src/hooks/useKeyboardHint.test.tsx+++ b/packages/core/src/hooks/useKeyboardHint.test.tsx@@ -67,7 +67,8 @@ describe('useKeyboardHint', () => {const {container} = render(<TestHint />);const hint = container.querySelector('[popover="manual"]') as HTMLElement;- expect(hint.className).toContain('useKeyboardHint__styles.hint');+ // The surface of the anchored hint Core's keyboard hints share.+ expect(hint.className).toContain('anchoredHint__styles.hint');});it('renders the "to navigate" label from the i18n catalog', () => {diff --git a/packages/core/src/hooks/useKeyboardHint.tsx b/packages/core/src/hooks/useKeyboardHint.tsxindex d87338cac1..0b2709ad90 100644--- a/packages/core/src/hooks/useKeyboardHint.tsx+++ b/packages/core/src/hooks/useKeyboardHint.tsx@@ -4,12 +4,14 @@/*** @file useKeyboardHint.tsx- * @input Uses React, StyleX, Kbd, useLayer, i18n (useComponentTranslator)+ * @input Uses React, StyleX, Kbd, useLayer, the shared anchored hint+ * (hooks/anchoredHint.tsx), i18n (useComponentTranslator)* @output Exports useKeyboardHint hook — ephemeral arrow-key navigation hint* @position Core hook; shows sighted keyboard users how to navigate composite* widgets that use roving tabindex (single Tab stop, arrows inside)** SYNC: When modified, update:+ * - /packages/core/src/hooks/anchoredHint.tsx* - /packages/core/src/hooks/index.ts* - /packages/core/src/hooks/useKeyboardHint.doc.mjs* - /apps/storybook/stories/useKeyboardHint.stories.tsx@@ -18,13 +20,6 @@import React, {useCallback, useEffect, useRef, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';-import {- colorVars,- radiusVars,- shadowVars,- spacingVars,- typeScaleVars,-} from '../theme/tokens.stylex';import {Kbd} from '../Kbd';import {useLayer} from '../Layer/useLayer';import {@@ -32,6 +27,7 @@ import {useComponentTranslator,} from '../i18n/useComponentTranslator';import english from '../i18n/generated-english/hooks/useKeyboardHint.generated';+import {anchoredHintStyles, renderAnchoredHint} from './anchoredHint';registerEnglishFallback(english);@@ -109,52 +105,6 @@ const ARROW_HINT_KEYS: Record<both: ['left', 'right', 'up', 'down'],};-const styles = stylex.create({- hint: {- // Top layer + anchor positioned- position: 'fixed',- inset: 'auto',- margin: 0,- borderWidth: 0,- borderStyle: 'none',-- // Surface- backgroundColor: colorVars['--color-background-popover'],- borderRadius: radiusVars['--radius-element'],- boxShadow: shadowVars['--shadow-low'],- paddingBlockStart: spacingVars['--spacing-1'],- paddingBlockEnd: spacingVars['--spacing-1'],- paddingInlineStart: spacingVars['--spacing-2'],- paddingInlineEnd: spacingVars['--spacing-2'],-- // Typography- fontSize: typeScaleVars['--text-supporting-size'],- lineHeight: typeScaleVars['--text-supporting-leading'],- color: colorVars['--color-text-secondary'],- whiteSpace: 'nowrap',-- // Animation- opacity: {- default: 0,- ':popover-open': 1,- },- transitionProperty: 'opacity, display, overlay',- transitionDuration: '150ms',- transitionBehavior: 'allow-discrete',-- // Don't capture pointer events (hint floats above content)- pointerEvents: 'none',- },- keys: {- display: 'inline-flex',- alignItems: 'center',- gap: spacingVars['--spacing-1'],- },- label: {- marginInlineStart: spacingVars['--spacing-1'],- },-});-// ---------------------------------------------------------------------------// Hook// ---------------------------------------------------------------------------@@ -321,28 +271,21 @@ export function useKeyboardHint(// --- Render the hint element ---const arrowContent = (- <span {...stylex.props(styles.keys)}>+ <span {...stylex.props(anchoredHintStyles.keys)}>{ARROW_HINT_KEYS[orientation].map(key => (<Kbd key={key} keys={key} />))}</span>);- const hintElement = layer.render(+ const hintElement = renderAnchoredHint(+ layer,<span aria-hidden="true">{arrowContent}- <span {...stylex.props(styles.label)}>+ <span {...stylex.props(anchoredHintStyles.label)}>{t('@astryx.keyboardHint.toNavigate')}</span></span>,- {- placement: 'below',- alignment: 'start',- xstyle: styles.hint,- style: {- marginBlockStart: spacingVars['--spacing-2'],- },- },);return {hintElement, onFocus, onBlur, onKeyDown};diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex f3326ae9a3..756f03e663 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -195,6 +195,14 @@ export {type DragToSnapPointsOptions,} from './dragToSnapPoints/createDragToSnapPoints';+// Reorder (a collection's `reorderable` prop)+export {+ createReorderable,+ type Reorderable,+ type ReorderableOptions,+ type ReorderMove,+} from './reorderable/createReorderable';+// Hooksexport * from './hooks';diff --git a/packages/core/src/keyboard/keyboardTarget.ts b/packages/core/src/keyboard/keyboardTarget.tsindex 4b5d41d1cf..f448d38fde 100644--- a/packages/core/src/keyboard/keyboardTarget.ts+++ b/packages/core/src/keyboard/keyboardTarget.ts@@ -16,7 +16,7 @@ import {animatorFor, type Animator} from '../motion/animator';import {isCoarsePointer} from '../utils/coarsePointer';import {subscribeInput} from '../utils/inputStream';import {layoutViewportHeight} from '../utils/layoutViewport';-import {scrollingAncestor} from '../utils/scrollingAncestor';+import {nearestScroller, scrollingAncestor} from '../utils/scrollingAncestor';import {KEYBOARD_EPSILON,claimTapFocus,@@ -58,6 +58,8 @@ export function registerKeyboardTarget(element: Element): () => void {};}+export {nearestScroller};+/** Whether a registered target holds `element`. */export function isInsideKeyboardTarget(element: Element): boolean {for (@@ -72,20 +74,6 @@ export function isInsideKeyboardTarget(element: Element): boolean {return false;}-/**- * The element that scrolls `element` into view: its nearest ancestor that- * scrolls on the block axis, or else the document's scroller.- */-export function nearestScroller(element: Element): Element {- const doc = element.ownerDocument;- const scroller = scrollingAncestor(element);- return scroller == null ||- scroller === doc.body ||- scroller === doc.documentElement- ? (doc.scrollingElement ?? doc.documentElement)- : scroller;-}-// The element's bottom edge where layout puts it, without the ride's move.function restingBottom(element: Element, animator: Animator): number {return element.getBoundingClientRect().bottom - animator.get('y');diff --git a/packages/core/src/motion/MEASUREMENTS.md b/packages/core/src/motion/MEASUREMENTS.mdindex 52e044c1fd..129bc96cf7 100644--- a/packages/core/src/motion/MEASUREMENTS.md+++ b/packages/core/src/motion/MEASUREMENTS.md@@ -367,3 +367,17 @@ since only an exit may play a measured spring (`spec:AST-094` FR4).| M-ZM2 | Maximum zoom | Photos: pinch a 4032 × 3024 and a 1200 × 800 photo as far as it goes | the zoom it settles on against the photo's pixel size and the fitted size | B, C || M-ZM3 | Dismiss cancel distance | Photos: pull a photo down 6–19 pt, bring it back to N pt and lift without moving | the largest N that still cancels | B, C || M-ZM5 | Dismiss flick projection | Photos: flick a photo down from rest, lifting after 6–19 pt at a range of speeds | the shortest travel that still dismisses at each speed: the projection's rate | B, C |++## Reorder (UITableView edit-mode reorder)++Subject "table T": a plain `UITableView` in editing mode with reorder controls+only, 40 rows of 44 pt (rows 6 and 9 at 88 pt where noted), in the UIKit lab+app. Measured so far: the claim, tracking, the crossing rule for a 44 pt row+moving past 44 and 88 pt rows below its place and back, the slides, the drop,+the autoscroll steps, Reduce Motion.++| ID | Scene | Gesture | Extract | Method |+| ------ | ------------------------------ | ------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- | ------ |+| M-RO26 | table T, one row at 88 pt | drag the 88 pt row to edge depths 0 to 44 pt and hold; 44 pt rows held 4, 6, 8, 10 pt inside the bottom edge | autoscroll step per 20 ms tick by depth: indexed by the edge depth in points or by a fraction of the row; the exact start inset | C |+| M-RO07 | table T | a system touch cancel mid-drag (a call or Control Center); `reloadData` mid-drag | does the row return to its origin or move to its slot; positions per frame | C |+| M-RO27 | table T, rows 6 and 9 at 88 pt | drag row 7 (44 pt) up past row 6; drag row 6 (88 pt) down past row 7 and back | the dragged row's centre travel at each change of the proposed slot, against `List/reorderModel.ts`'s slot rule (GUESS for these) | C |diff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.mdindex d21e026ea6..ec824d0b31 100644--- a/packages/core/src/motion/README.md+++ b/packages/core/src/motion/README.md@@ -29,6 +29,7 @@ roles through `resolveMotion`.| `uikit/sheet.ts` | UISheetPresentationController: the flick speed, how near a detent counts as on it, how far ahead a release is projected, and the speed below which it is not. || `uikit/switch.ts` | UISwitch on iOS 26.2: geometry, the lift, settle, travel and tracking springs, the flip distance, the track colour. || `uikit/datePicker.ts` | UIDatePicker: the rules it adds to its wheels. |+| `uikit/reorder.ts` | UITableView edit-mode reorder: the reorder control's claim and the edge autoscroll (the glides play `springs.settle`). || `android/keyboard.ts` | Android's software keyboard (Chrome with Gboard): its slides' durations and curves (no theme's) and when they start against Chrome's report and a blur. || `uikit/zoomMedia.ts` | UIScrollView zooming for a photo viewer: overshoot past the limits, double-tap and maximum zoom. || `roles.ts` | The internal motion roles: the springs, durations and curves `spec:AST-094` FR4 names, registered by the shared tables, and a role's CSS form read back. |diff --git a/packages/core/src/motion/animatedLayout.boundary.test.ts b/packages/core/src/motion/animatedLayout.boundary.test.tsindex 176b909778..4df883db29 100644--- a/packages/core/src/motion/animatedLayout.boundary.test.ts+++ b/packages/core/src/motion/animatedLayout.boundary.test.ts@@ -149,6 +149,20 @@ describe('architecture:react-component-runtime INV12 source boundary', () => {]);});+ it("keeps the inert clone to the copy mechanism and the reorder's preview", () => {+ const users = sourceFiles(coreSrc)+ .filter(path =>+ /from '[./]+(motion\/)?inertClone'/.test(readFileSync(path, 'utf8')),+ )+ .map(path => relative(coreSrc, path))+ .sort();+ expect(users).toEqual([+ 'List/listReorderEngine.tsx',+ 'motion/animatedLayout.ts',+ 'motion/transientCopy.ts',+ ]);+ });+it('is used only by the hook and the components that adopt it', () => {const users = sourceFiles(coreSrc).filter(path => path !== join(here, 'animatedLayout.ts'))diff --git a/packages/core/src/motion/animatedLayout.ts b/packages/core/src/motion/animatedLayout.tsindex 923697d7bb..e6449a649b 100644--- a/packages/core/src/motion/animatedLayout.ts+++ b/packages/core/src/motion/animatedLayout.ts@@ -83,10 +83,10 @@import {LATE_START_MS} from './frameBlock';import {sharedKey} from '../utils/sharedRealm';+import {paintedBackground} from './inertClone';import {inertCopy,isCopyable,- paintedBackground,placeOver,visiblePartCopy,wrapText,diff --git a/packages/core/src/motion/animator.ts b/packages/core/src/motion/animator.tsindex 8fe4e30e07..2f831304ed 100644--- a/packages/core/src/motion/animator.ts+++ b/packages/core/src/motion/animator.ts@@ -1018,7 +1018,7 @@ const IDENTITY_TEXT: Record<Channel, string> = {};/** Whether a computed value (or an unset one) is the channel's identity. */-function isIdentityText(channel: Channel, text: string): boolean {+export function isIdentityText(channel: Channel, text: string): boolean {const value = text.trim();if (value === '' || value === 'none') {return true;@@ -1047,7 +1047,8 @@ function expand(values: MotionValues): Partial<Record<MotionProperty, number>> {return out;}-function defaultNow(): number {+/** The time the motion clock reads (`performance.now()`'s time base). */+export function motionNow(): number {return typeof performance === 'undefined' ? Date.now() : performance.now();}@@ -1104,7 +1105,7 @@ export function createMotionEngine(element: HTMLElement | null,options: AnimatorOptions = {},): Animator {- const now = options.now ?? defaultNow;+ const now = options.now ?? motionNow;const frameSource =options.requestFrame ??(typeof requestAnimationFrame === 'function'diff --git a/packages/core/src/motion/inertClone.ts b/packages/core/src/motion/inertClone.tsnew file mode 100644index 0000000000..ddff717c18--- /dev/null+++ b/packages/core/src/motion/inertClone.ts@@ -0,0 +1,127 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @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+ * @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 listed controls a form can own. */+const FORM_CONTROLS =+ 'button, fieldset, input, object, output, select, textarea';++function isFormAssociated(+ node: Element,+ registry: CustomElementRegistry | undefined,+): boolean {+ if (!node.localName.includes('-')) {+ return false;+ }+ const definition = registry?.get(node.localName) as+ {formAssociated?: boolean} | undefined;+ return definition?.formAssociated === true;+}++/**+ * Paints `canvas` with `source`'s pixels at its own size. False when they+ * read back empty: unreadable (a WebGL canvas without+ * `preserveDrawingBuffer`, a tainted one) or blank.+ */+function paintCanvas(+ canvas: HTMLCanvasElement,+ source: HTMLCanvasElement,+): boolean {+ if (canvas.width === 0 || canvas.height === 0) {+ return true;+ }+ const context = canvas.getContext('2d', {willReadFrequently: true});+ if (context == null) {+ // No 2D canvas here (a test environment): nothing to paint or tell.+ return true;+ }+ try {+ context.drawImage(source, 0, 0);+ const {data} = context.getImageData(0, 0, canvas.width, canvas.height);+ for (let index = 3; index < data.length; index += 4) {+ if (data[index] !== 0) {+ return true;+ }+ }+ return false;+ } catch {+ return false;+ }+}++/**+ * A deep clone of `element` that takes no part in the page. It has no ids or+ * test ids and joins no form or radio group: a copied checked radio would+ * uncheck the live one. No copied label names a live control, copied frames+ * and media load nothing, and copied elements carry no anchor name. It is+ * inert and hidden from assistive technology. Content holding a canvas whose+ * pixels read back empty is not cloned: the result is null.+ */+export function inertClone(element: HTMLElement): HTMLElement | null {+ const copy = element.cloneNode(true) as HTMLElement;+ 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']) {+ node.removeAttribute(name);+ }+ }+ // A second element with a live anchor's name makes the engine lay out+ // every frame while the copy moves.+ const view = element.ownerDocument.defaultView;+ sourceNodes.forEach((source, index) => {+ const name = view?.getComputedStyle(source).getPropertyValue('anchor-name');+ if (name != null && name !== '' && name !== 'none') {+ (copyNodes[index] as Partial<ElementCSSInlineStyle>).style?.setProperty(+ 'anchor-name',+ 'none',+ );+ }+ });+ // A copy laid inside a `<form>` would join it, and a copied empty+ // `required` field would block its submit. `form=""` matches no form's id,+ // so no form owns a copied control, a form-associated custom element too.+ const registry = element.ownerDocument.defaultView?.customElements;+ for (const node of copyNodes) {+ if (node.matches(FORM_CONTROLS) || isFormAssociated(node, registry)) {+ node.setAttribute('form', '');+ }+ }+ for (const node of copy.querySelectorAll(+ 'iframe, video, audio, source, embed, object',+ )) {+ for (const name of ['src', 'srcdoc', 'data', 'autoplay']) {+ node.removeAttribute(name);+ }+ }+ // A clone's canvas is blank: paint each with its source's pixels. Content+ // with a canvas that reads back empty is not copied.+ const sources = element.querySelectorAll('canvas');+ const canvases = Array.from(copy.querySelectorAll('canvas'));+ if (!canvases.every((canvas, index) => paintCanvas(canvas, sources[index]))) {+ return null;+ }+ copy.setAttribute('aria-hidden', 'true');+ copy.setAttribute('inert', '');+ copy.style.pointerEvents = 'none';+ return copy;+}++/** 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) {+ const color = getComputedStyle(node).backgroundColor;+ if (color !== 'transparent' && !/^rgba\(.*,\s*0\)$/.test(color)) {+ return color;+ }+ }+ return 'Canvas';+}diff --git a/packages/core/src/motion/transientCopy.ts b/packages/core/src/motion/transientCopy.tsindex cf7c8b0292..b1afe45462 100644--- a/packages/core/src/motion/transientCopy.ts+++ b/packages/core/src/motion/transientCopy.ts@@ -4,8 +4,8 @@* @file transientCopy.ts* @input The DOM* @output Exports `isCopyable`, `inertCopy`, `restoreScrollOffsets`,- * `visiblePartCopy`, `placeOver`, `paintedBackground` and `wrapText`: how- * Core makes, lays out and fades one transient copy of old content+ * `visiblePartCopy`, `placeOver` and `wrapText`: how Core makes, lays out+ * and fades one transient copy of old content, on inertClone.ts's clone* @position Motion foundation, internal to core; the copy mechanism the* in-place swap uses (`spec:AST-105` FR8,* `architecture:component-style-authoring` INV7). It also makes the@@ -39,6 +39,7 @@ import {saveAnimations,type SavedAnimations,} from './carryAnimations';+import {inertClone} from './inertClone';/** Above this many elements, old content is not copied: the new one enters. */const MAX_COPIED_ELEMENTS = 1500;@@ -48,37 +49,6 @@ export function isCopyable(element: Element): boolean {return element.getElementsByTagName('*').length <= MAX_COPIED_ELEMENTS;}-/**- * Paints `canvas` with `source`'s pixels at its own size; false when they- * read back empty: unreadable (a WebGL canvas without- * `preserveDrawingBuffer`, a tainted one) or blank.- */-function paintCanvas(- canvas: HTMLCanvasElement,- source: HTMLCanvasElement,-): boolean {- if (canvas.width === 0 || canvas.height === 0) {- return true;- }- const context = canvas.getContext('2d', {willReadFrequently: true});- if (context == null) {- // No 2D canvas here (a test environment): nothing to paint or tell.- return true;- }- try {- context.drawImage(source, 0, 0);- const {data} = context.getImageData(0, 0, canvas.width, canvas.height);- for (let index = 3; index < data.length; index += 4) {- if (data[index] !== 0) {- return true;- }- }- return false;- } catch {- return false;- }-}-/** Inherited properties a copy carries when laid outside its ancestors. */const INHERITED_PROPERTIES = ['color',@@ -158,22 +128,6 @@ function readInherited(element: Element): Map<string, string> {return values;}-/** The listed controls a form can own. */-const FORM_CONTROLS =- 'button, fieldset, input, object, output, select, textarea';--function isFormAssociated(- node: Element,- registry: CustomElementRegistry | undefined,-): boolean {- if (!node.localName.includes('-')) {- return false;- }- const definition = registry?.get(node.localName) as- {formAssociated?: boolean} | undefined;- return definition?.formAssociated === true;-}-/** Scroll offsets a copy restores once laid out (a clone carries none). */const scrollOffsets = new WeakMap<HTMLElement,@@ -199,7 +153,10 @@ const carriedMotion = new WeakMap<* is laid out (`placeOver`).*/export function inertCopy(element: HTMLElement): HTMLElement | null {- const copy = element.cloneNode(true) as HTMLElement;+ const copy = inertClone(element);+ if (copy == null) {+ return null;+ }const sourceNodes = [element, ...element.querySelectorAll('*')];const copyNodes = [copy, ...copy.querySelectorAll('*')];const offsets: [Element, number, number][] = [];@@ -214,49 +171,6 @@ export function inertCopy(element: HTMLElement): HTMLElement | null {saved: saveAnimations(element),copyOf: new Map(sourceNodes.map((node, index) => [node, copyNodes[index]])),});- for (const node of copyNodes) {- for (const name of ['id', 'data-testid', 'name', 'for', 'autofocus']) {- node.removeAttribute(name);- }- }- // A second element with a live anchor's name makes the engine lay out- // every frame while the copy moves.- const view = element.ownerDocument.defaultView;- sourceNodes.forEach((source, index) => {- const name = view?.getComputedStyle(source).getPropertyValue('anchor-name');- if (name != null && name !== '' && name !== 'none') {- (copyNodes[index] as Partial<ElementCSSInlineStyle>).style?.setProperty(- 'anchor-name',- 'none',- );- }- });- // A copy laid inside a `<form>` would join it, and a copied empty- // `required` field would block its submit. `form=""` matches no form's id,- // so no form owns a copied control, a form-associated custom element too.- const registry = element.ownerDocument.defaultView?.customElements;- for (const node of copyNodes) {- if (node.matches(FORM_CONTROLS) || isFormAssociated(node, registry)) {- node.setAttribute('form', '');- }- }- for (const node of copy.querySelectorAll(- 'iframe, video, audio, source, embed, object',- )) {- for (const name of ['src', 'srcdoc', 'data', 'autoplay']) {- node.removeAttribute(name);- }- }- // A clone's canvas is blank: paint each with its source's pixels. Content- // with a canvas that reads back empty is not copied.- const sources = element.querySelectorAll('canvas');- const canvases = Array.from(copy.querySelectorAll('canvas'));- if (!canvases.every((canvas, index) => paintCanvas(canvas, sources[index]))) {- return null;- }- copy.setAttribute('aria-hidden', 'true');- copy.setAttribute('inert', '');- copy.style.pointerEvents = 'none';return copy;}@@ -276,17 +190,6 @@ export function restoreScrollOffsets(copy: HTMLElement): void {}}-/** 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) {- const color = getComputedStyle(node).backgroundColor;- if (color !== 'transparent' && !/^rgba\(.*,\s*0\)$/.test(color)) {- return color;- }- }- return 'Canvas';-}-/*** Writes on a copy what it inherited where its element was, where its new* parent `host` passes something else.diff --git a/packages/core/src/motion/uikit/index.ts b/packages/core/src/motion/uikit/index.tsindex b2b4dd1797..9c99b9162a 100644--- a/packages/core/src/motion/uikit/index.ts+++ b/packages/core/src/motion/uikit/index.ts@@ -7,8 +7,9 @@* (`SHEET_PRESENT_SPRING`, …), and the `scroll`, `timing`, `navigation`,* `picker`, `popover`, `progressBar`, `segmentedControl`, `datePicker`,* `sheet`, `slider`, `switchControl` and `zoomMedia` domains. It also- * re-exports the gesture thresholds: one `UIKIT_*` group per recognizer,- * their union `UIKIT_GESTURES`, and the haptic tables+ * re-exports a table's reorder (`reorder`), the gesture thresholds (one+ * `UIKIT_*` group per recognizer and their union `UIKIT_GESTURES`), and the+ * haptic tables* @position Entry of the UIKit constants table (motion/uikit). Internal to* core: not exported from the package entry point*@@ -46,6 +47,7 @@ export {navigation, registerNavigationTable} from './navigation';export {picker} from './picker';export {popover} from './popover';export {progressBar, registerProgressBarTable} from './progressBar';+export {reorder} from './reorder';export {registerScrollTable, scroll} from './scroll';export {segmentedControl} from './segmented';export {sheet} from './sheet';diff --git a/packages/core/src/motion/uikit/reorder.ts b/packages/core/src/motion/uikit/reorder.tsnew file mode 100644index 0000000000..e15c2c23b4--- /dev/null+++ b/packages/core/src/motion/uikit/reorder.ts@@ -0,0 +1,101 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file reorder.ts+ * @input `scroll` (the content-touch delay) and `UIKIT_GESTURES` (the pan+ * hysteresis)+ * @output Exports `reorder`: the values of a UIKit table's edit-mode reorder+ * that a reorder plays. They are the reorder control's claim and the edge+ * autoscroll. Neither is a spring or a curve. The rows' glides play the+ * shared settle role (`springs.settle`)+ * @position The reorder domain of the UIKit constants table (motion/uikit).+ * Read by List/reorderModel.ts, List/listReorderEngine.tsx and+ * List/ListReorderTouch.ts+ *+ * Measured on a `UITableView` in editing mode with reorder controls only, in+ * an instrumented UIKit app on the iOS 26.2 simulator. The table had 40 rows+ * of 44 pt, with two of 88 pt in the second run. Every animation, offset and+ * recognizer state was logged per frame while real HID touches dragged the+ * reorder control. Some findings need no value below. There is no lift: a+ * held or dragged row changes neither scale, opacity, z position nor shadow.+ * The dragged row follows the finger one to one with the grab offset kept.+ * The drop goes to the current drop position with no velocity projection,+ * and no haptic plays. UIKit's rows also slide out of the way during a drag,+ * on springDuration 0.3 s with bounce 0. That is 0.03 s shorter per point of+ * autoscroll step. Its drop springs from rest on a springDuration of 0.3 s+ * times min(1, the distance left / half the row's height). Astryx's reorder+ * departs from both by its design record. The rows stay still behind an+ * insertion cue until the drop, and every glide plays the shared settle+ * role. So neither is a value here.+ *+ * Every leaf carries one or more `@source` (apple-docs | wwdc | webkit |+ * measured | GUESS). GUESS values also carry the `@measure` task that will+ * confirm or replace them (MEASUREMENTS.md, M-RO rows). uikit.test.ts+ * enforces both. Durations are in ms. Lengths are in points, one CSS px+ * each.+ *+ * Plain data, with no side effect on import.+ *+ * SYNC: When modified, update /packages/core/src/motion/MEASUREMENTS.md.+ */++import {UIKIT_GESTURES} from './gestures';+import {scroll} from './scroll';++export const reorder = {+ claim: {+ /**+ * A still touch on the reorder control claims the drag after the scroll+ * view's content-touch delay. Once it has passed, the table stops+ * scrolling: `isScrollEnabled` turns false.+ * @source measured: UIKit lab, iOS 26.2 sim iPhone 17 Pro, table reorder+ * (isScrollEnabled false 148–149 ms after touch-down on the reorder+ * control), Oct 23 2026+ */+ delayMs: scroll.delaysContentTouchesMs,+ /**+ * Travel before the claim that hands the touch to the scroll view. A flick+ * that starts on the reorder control scrolls the table with momentum, and+ * the row does not move. The scroll view's pan begins at its hysteresis.+ * @source measured: UIKit lab, iOS 26.2 sim iPhone 17 Pro, table reorder+ * (a 120 pt flick in 80 ms from the reorder control scrolled the table.+ * The row stayed), Oct 23 2026+ */+ allowableMovement: UIKIT_GESTURES.pan.hysteresis.value,+ },+ autoscroll: {+ /**+ * Autoscroll is a timer: the offset moves by a whole number of points+ * every 20 ms (50 Hz), constant at a given depth.+ * @source measured: UIKit lab, iOS 26.2 sim iPhone 17 Pro, table reorder+ * autoscroll (contentOffset per tick), Oct 23 2026+ */+ tickMs: 20,+ /**+ * The depths of the samples: how far the dragged row's edge (not the+ * finger) is past the scroll view's edge, negative inside. Between+ * samples the step is interpolated and rounded to a whole point. Deeper+ * than the last sample it stays at the last (the row is clamped with its+ * centre on the edge there).+ * @source measured: UIKit lab, iOS 26.2 sim iPhone 17 Pro, table reorder+ * autoscroll with 44 pt rows (bottom edge. The top edge agreed within a+ * point: 2 at 4 inside, 9 at 20 beyond), Oct 23 2026+ */+ depths: [-3, 6, 8, 10, 12, 16, 20, 22],+ /**+ * Points per tick at each of `depths`: 100 pt/s at the start, 500 pt/s at+ * the deepest.+ * @source measured: UIKit lab, iOS 26.2 sim iPhone 17 Pro, table reorder+ * autoscroll with 44 pt rows, Oct 23 2026+ */+ stepsPt: [2, 2, 3, 3, 4, 6, 8, 10],+ /**+ * How far inside the edge autoscroll starts, at the first sample's step.+ * There is none with the row's edge 12 pt inside, and 2 pt per tick at+ * 3 pt inside.+ * @source GUESS — a point inside the measured bracket (12 to 3 pt)+ * @measure M-RO26+ */+ startInset: 8,+ },+} as const;diff --git a/packages/core/src/privateAttributes/leaving.stylex.ts b/packages/core/src/privateAttributes/leaving.stylex.tsindex 37e43789be..8145dc86f2 100644--- a/packages/core/src/privateAttributes/leaving.stylex.ts+++ b/packages/core/src/privateAttributes/leaving.stylex.ts@@ -2,12 +2,14 @@/*** @file privateAttributes/leaving.stylex.ts- * @input A List row put back in the document for its exit+ * @input A List row put back in the document for its exit, or an element a+ * reorder's drag draws over the list* @output markLeaving, which marks such a row, and isLeaving, which reads the* mark* @position Owner module of the private leaving attribute: the only file that- * writes its name. List/listLayoutUpdates.ts marks a row it puts back, so no- * later commit counts it as a row. No package entry exports it.+ * writes its name. List/listLayoutUpdates.ts marks a row it puts back. The+ * reorder (List/listReorderEngine.tsx) marks what a drag draws over the+ * list. So no later commit counts them as rows. No package entry exports it.*/const LEAVING = 'data-astryx-leaving';diff --git a/packages/core/src/privateAttributes/listReorder.stylex.ts b/packages/core/src/privateAttributes/listReorder.stylex.tsnew file mode 100644index 0000000000..32d530343f--- /dev/null+++ b/packages/core/src/privateAttributes/listReorder.stylex.ts@@ -0,0 +1,29 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file privateAttributes/listReorder.stylex.ts+ * @input A reorderable List row's reorder handle+ * @output listReorderHandleProps, which marks a handle, and+ * closestReorderHandle and reorderHandlesIn, which find marked handles+ * @position Owner module of the private list-reorder attribute: the only+ * file that writes its name. List/ListReorderHandle.tsx marks each handle,+ * and the reorder machinery (List/listReorderEngine.tsx) finds them. No+ * package entry exports it.+ */++const LIST_REORDER = 'data-astryx-list-reorder';++/** Spread on each reorder handle. */+export const listReorderHandleProps: Readonly<Record<string, string>> = {+ [LIST_REORDER]: '',+};++/** The reorder handle that holds `target`, or null. */+export function closestReorderHandle(target: Element): HTMLElement | null {+ return target.closest<HTMLElement>(`[${LIST_REORDER}]`);+}++/** The reorder handles inside `root`. */+export function reorderHandlesIn(root: ParentNode): Element[] {+ return Array.from(root.querySelectorAll(`[${LIST_REORDER}]`));+}diff --git a/packages/core/src/privateAttributes/ownRing.stylex.ts b/packages/core/src/privateAttributes/ownRing.stylex.tsnew file mode 100644index 0000000000..414a68e777--- /dev/null+++ b/packages/core/src/privateAttributes/ownRing.stylex.ts@@ -0,0 +1,56 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file privateAttributes/ownRing.stylex.ts+ * @input The focus tokens (theme/tokens.stylex.ts)+ * @output ownRingProps, which marks a control that rings itself, and+ * ownRingContainerStyles: a reorderable List row's focus-within ring,+ * which leaves such a control alone+ * @position Owner module of the private own-ring attribute: the only file+ * that writes its name. ListReorderHandle marks the handle and composes the+ * row's ring, and only createReorderable's engine imports it, so a List+ * without `reorderable` carries none of it. No package entry exports it.+ *+ * SYNC: When modified, keep the ring equal to utils/focusOutline.stylex.ts's+ * focus outline.+ */++import * as stylex from '@stylexjs/stylex';+import {focusVars} from '../theme/tokens.stylex';++/** A focused descendant that is not a control ringing itself. */+const OTHER_FOCUS = ':has(:focus-visible:not([data-astryx-own-ring]))';++/** Spread on a control that rings itself. */+export const ownRingProps: Readonly<Record<string, string>> = {+ 'data-astryx-own-ring': '',+};++/**+ * A container that rings itself on focus within. A focused descendant marked+ * `data-astryx-own-ring` is left alone: a control that rings itself, such as+ * a List row's reorder handle. Without it the two rings stack for one tab+ * stop. An ancestor that clips its inline overflow (List) also cuts the+ * container's ring to two lines. It is its own object, so only the reorder+ * that uses it carries it.+ */+export const ownRingContainerStyles = stylex.create({+ focusWithin: {+ outlineWidth: {+ default: '0',+ [OTHER_FOCUS]: focusVars['--focus-outline-width'],+ },+ outlineStyle: {+ default: 'none',+ [OTHER_FOCUS]: focusVars['--focus-outline-style'],+ },+ outlineColor: {+ default: null,+ [OTHER_FOCUS]: focusVars['--focus-outline-color'],+ },+ outlineOffset: {+ default: '0',+ [OTHER_FOCUS]: focusVars['--focus-outline-offset'],+ },+ },+});diff --git a/packages/core/src/privateAttributes/reorderLine.stylex.ts b/packages/core/src/privateAttributes/reorderLine.stylex.tsnew file mode 100644index 0000000000..467d6d821f--- /dev/null+++ b/packages/core/src/privateAttributes/reorderLine.stylex.ts@@ -0,0 +1,39 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file privateAttributes/reorderLine.stylex.ts+ * @input A reorderable List's root while its insertion line shows+ * @output showReorderLine and hideReorderLine, which mark the list, and+ * reorderLineStyles, which shows the list's line while it is marked+ * @position Owner module of the private reorder-line attribute: the only+ * file that writes its name. The reorder machinery+ * (List/listReorderEngine.tsx) marks the list, and the list's own+ * pseudo-element (List/ListReorderHandle.tsx) is the line. No package+ * entry exports it.+ */++import * as stylex from '@stylexjs/stylex';++const REORDER_LINE = 'data-astryx-reorder-line';++/** Shows `list`'s insertion line. */+export function showReorderLine(list: Element): void {+ list.setAttribute(REORDER_LINE, '');+}++/** Hides `list`'s insertion line. */+export function hideReorderLine(list: Element): void {+ list.removeAttribute(REORDER_LINE);+}++export const reorderLineStyles = stylex.create({+ // The line is the list's `::after`, drawn only while the list is marked.+ list: {+ '::after': {+ display: {+ default: 'none',+ '[data-astryx-reorder-line]': 'block',+ },+ },+ },+});diff --git a/packages/core/src/privateAttributes/reorderPreview.stylex.ts b/packages/core/src/privateAttributes/reorderPreview.stylex.tsnew file mode 100644index 0000000000..eaffc53caf--- /dev/null+++ b/packages/core/src/privateAttributes/reorderPreview.stylex.ts@@ -0,0 +1,18 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file privateAttributes/reorderPreview.stylex.ts+ * @input The copy of a dragged row that follows the pointer+ * @output markReorderPreview, which marks that copy+ * @position Owner module of the private reorder-preview attribute: the only+ * file that writes its name. The reorder machinery+ * (List/listReorderEngine.tsx) marks the preview it draws. No package+ * entry exports it.+ */++const REORDER_PREVIEW = 'data-astryx-reorder-preview';++/** Marks `element` as the preview of the dragged row. */+export function markReorderPreview(element: Element): void {+ element.setAttribute(REORDER_PREVIEW, '');+}diff --git a/packages/core/src/privateAttributes/reorderSource.stylex.ts b/packages/core/src/privateAttributes/reorderSource.stylex.tsnew file mode 100644index 0000000000..0a2e27664f--- /dev/null+++ b/packages/core/src/privateAttributes/reorderSource.stylex.ts@@ -0,0 +1,23 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file privateAttributes/reorderSource.stylex.ts+ * @input The row a reorder drag picked up+ * @output markReorderSource and clearReorderSource, which mark that row+ * @position Owner module of the private reorder-source attribute: the only+ * file that writes its name. The reorder machinery+ * (List/listReorderEngine.tsx) marks the dragged row, dimmed in its place+ * while the drag runs. No package entry exports it.+ */++const REORDER_SOURCE = 'data-astryx-reorder-source';++/** Marks `row` as the row a drag picked up. */+export function markReorderSource(row: Element): void {+ row.setAttribute(REORDER_SOURCE, '');+}++/** Removes the mark from `row`. */+export function clearReorderSource(row: Element): void {+ row.removeAttribute(REORDER_SOURCE);+}diff --git a/packages/core/src/privateAttributes/reordering.stylex.ts b/packages/core/src/privateAttributes/reordering.stylex.tsnew file mode 100644index 0000000000..65c9e0d32e--- /dev/null+++ b/packages/core/src/privateAttributes/reordering.stylex.ts@@ -0,0 +1,46 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file privateAttributes/reordering.stylex.ts+ * @input A reorderable List's root while a drag or a reorder-mode move owns+ * its rows+ * @output markReordering and clearReordering, which mark the list, and+ * isReordering, which reads the mark. reorderingHandleStyles shows a+ * handle's grabbing cursor while its list is marked.+ * @position Owner module of the private reordering attribute: the only file+ * that writes its name. The reorder machinery (List/listReorderEngine.tsx)+ * marks the list, and List's layout updates leave its commits alone while+ * it is marked. No package entry exports it.+ */++import * as stylex from '@stylexjs/stylex';++const REORDERING = 'data-astryx-reordering';++/** Marks `list` while the reorder owns its rows. */+export function markReordering(list: Element): void {+ list.setAttribute(REORDERING, '');+}++/** Removes the mark from `list`. */+export function clearReordering(list: Element): void {+ list.removeAttribute(REORDERING);+}++/** Whether the reorder owns `list`'s rows. */+export function isReordering(list: Element): boolean {+ return list.hasAttribute(REORDERING);+}++export const reorderingHandleStyles = stylex.create({+ // Grabbing while its list reorders: a drag holds the pointer. Not+ // `:active`: that is the touch press controller's arm, and the handle+ // paints no press.+ cursor: {+ cursor: {+ default: 'grab',+ ':is([data-astryx-reordering] *)': 'grabbing',+ ':is(:disabled,[aria-disabled="true"])': 'default',+ },+ },+});diff --git a/packages/core/src/reorderable/createReorderable.doc.mjs b/packages/core/src/reorderable/createReorderable.doc.mjsnew file mode 100644index 0000000000..1cb18fba30--- /dev/null+++ b/packages/core/src/reorderable/createReorderable.doc.mjs@@ -0,0 +1,106 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').HookDoc} */+export const docs = {+ name: 'createReorderable',+ displayName: 'createReorderable',+ // A factory documented as a hook: listed with the utilities, as useLayer+ // is, not as a tile in the components gallery.+ group: 'Utilities',+ keywords: [+ 'reorder',+ 'reorderable',+ 'drag',+ 'sort',+ 'list',+ 'handle',+ 'grip',+ 'move',+ 'UIKit',+ 'UITableView',+ 'touch',+ 'keyboard',+ ],+ params: [+ {+ name: 'onReorder',+ type: '(move: {key: Key; to: number}) => void',+ description:+ "Called once per committed move (a drop, or each move in reorder mode) with the moved item's key and its index after the move, in the full order of the collection's items. Apply it by rendering the items in their new order. A cancelled move calls nothing. The latest function given is the one called, so the object may be made on every render.",+ required: true,+ },+ {+ name: 'isReorderable',+ type: '(key: Key) => boolean',+ description:+ 'Whether the item with this key can move. An item it rejects shows no handle and cannot be picked up; one at either end of the collection also bounds the others, so nothing drops beyond it and a keyboard move into it is refused. Every item moves without it.',+ },+ ],+ returns: [+ {+ name: 'reorderable',+ type: 'Reorderable',+ description:+ "The collection's reorder behavior: pass it as `List`'s `reorderable` prop, with an `itemKey` on each `ListItem`. Make it once per collection (with useMemo); one made on every render still works. Its one method, `start(key)`, enters reorder mode for that item from your own UI (a Move item in its context menu, a toolbar button): the focus moves to its handle, as activating it does; a key that cannot move or is not mounted does nothing and warns in development. One object may serve several collections, each reordering on its own; `start` then uses the one mounted last.",+ },+ ],+ usage: {+ description:+ "Makes a collection's rows reorderable. On a touch screen a finger held still on a row's handle for a moment picks it up (a flick on the handle still scrolls): the row stays in its place, dimmed, while a copy of it follows the finger and an accent line marks where it would land; the other rows stay still, the page scrolls near its edges, and on release the rows rearrange. A pen held still on a handle where the primary pointer is coarse picks the row up as a finger does. A mouse, or a pen where the primary pointer is fine, drags a handle at once the same way, and the rows take their places without motion; a cancelled drag puts everything back at once. Without a drag, the handle toggles reorder mode for its row (a click, Space or Enter): each arrow key moves the row a place at once, and Escape or another activation ends the mode, keeping the moves; screen readers hear each move with the row's place and neighbours, and a hint shows the moves and Done as buttons, for taps alone. The reorder code ships with this function: a collection without the prop loads none of it.",+ bestPractices: [+ {+ guidance: true,+ description:+ 'Give each row a stable key from your data, a string or a number (`itemKey={item.id}`), and apply each move by rendering the items in their new order in the same task.',+ },+ {+ guidance: true,+ description:+ 'Use `isReorderable` for rows that must stay put, such as a pinned first row.',+ },+ {+ guidance: true,+ description:+ "Offer reorder mode from your own UI too, such as a row's context menu, with `reorderable.start(item.id)`.",+ },+ {+ guidance: false,+ description:+ "Use React's `key` as the reorder key, or index-based keys: a move changes every index after it.",+ },+ ],+ },+ relatedComponents: ['List'],+ importPath: '@astryxdesign/core',+ category: 'interaction',+};++/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */+export const docsDense = {+ description:+ "A collection's reorder behavior, for List's reorderable prop; ListItem itemKey on each row.",+ paramDescriptions: {+ onReorder:+ '({key, to}) once per committed move; to is the index after the move.',+ isReorderable:+ '(key) => boolean; a rejected row has no handle, and at an end bounds the drop.',+ },+ returnDescriptions: {+ reorderable:+ "pass as List's reorderable prop; start(key) enters reorder mode from your own UI.",+ },+ usage: {+ description:+ 'UIKit edit-mode reorder: hold then drag (finger; pen on a coarse primary pointer), drag at once (mouse; pen on a fine one); without a drag, the handle toggles reorder mode (click, Space, Enter), arrows move, Escape ends.',+ bestPractices: [+ {+ guidance: true,+ description: 'Stable data keys as itemKey; apply the move at once.',+ },+ {+ guidance: false,+ description: "React's key or indexes as reorder keys.",+ },+ ],+ },+};diff --git a/packages/core/src/reorderable/createReorderable.ts b/packages/core/src/reorderable/createReorderable.tsnew file mode 100644index 0000000000..5622dcea05--- /dev/null+++ b/packages/core/src/reorderable/createReorderable.ts@@ -0,0 +1,123 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file createReorderable.ts+ * @input The reorder's options, and List's reorder machinery+ * (List/listReorderEngine.ts: the session, its handle and its touch layer)+ * @output `createReorderable`, which makes the object a collection's+ * `reorderable` prop takes, whose one public method, `start(key)`, enters+ * reorder mode from the app's own UI. And its types: `Reorderable`,+ * `ReorderableOptions`, `ReorderMove`+ * @position Public Core API, exported from the package root.+ * The machinery ships here, on the object: a collection imports only the+ * object's type, so one without `reorderable` loads no reorder code+ *+ * SYNC: When modified, update reorderable/createReorderable.doc.mjs,+ * List/listReorderContext.ts and List/List.doc.mjs.+ */++import {+ REORDER_ENGINE,+ type ListReorderOptions,+ type ReorderableInternals,+} from '../List/listReorderContext';+import {listReorderEngine} from '../List/listReorderEngine';++/** A committed move: the item that moved and where it went. */+export interface ReorderMove<+ TKey extends string | number = string | number,+ TTo = number,+> {+ /**+ * The moved item's key: its ListItem's `itemKey`. A collection built from+ * data takes it through its `idKey`, a field name or a function of the+ * item, as Table's does.+ */+ readonly key: TKey;+ /**+ * Its index after the move, in the full order of the collection's items,+ * mounted or not. A tree reports `{parent, index}`.+ */+ readonly to: TTo;+}++/** What `createReorderable` takes. */+export interface ReorderableOptions<+ TKey extends string | number = string | number,+ TTo = number,+> {+ /**+ * Called once per committed move: a drop, or each move in reorder mode.+ * Apply it by rendering the items in their new order. A cancelled move calls nothing. The latest function given is the one+ * called, so the object may be made on every render.+ */+ onReorder: (move: ReorderMove<TKey, TTo>) => void;+ /**+ * Whether the item with `key` can move. An item it rejects shows no handle+ * and cannot be picked up. One at either end of the collection also bounds+ * the others, so nothing drops beyond it and a keyboard move into it is+ * refused. Every item moves without it.+ */+ isReorderable?: (key: TKey) => boolean;+}++declare const reorderableBrand: unique symbol;++/**+ * A collection's reorder behavior, made by `createReorderable` and passed as+ * its `reorderable` prop. It applies to the whole collection; each item's key+ * and `isReorderable` decide which items move.+ */+export interface Reorderable<+ TKey extends string | number = string | number,+ TTo = number,+> {+ /** The keys and places it reports; a type, not a value. */+ readonly [reorderableBrand]: {readonly key: TKey; readonly to: TTo};+ /**+ * Enters reorder mode for the item with `key` from the app's own UI, as+ * activating its handle does. A Move item in a context menu or a toolbar+ * button can call it. The focus moves to the handle, which scrolls into+ * view, and the mode's keys, hint, announcements and exits follow. A key+ * that cannot move, or whose item is not mounted, does nothing. It warns in+ * development. On an object passed to two collections, it starts the mode+ * in the one mounted last.+ */+ start(key: TKey): void;+}++/**+ * Makes a collection's rows reorderable: pass the result as the collection's+ * `reorderable` prop (`<List reorderable={createReorderable({onReorder})}>`),+ * with an `itemKey` on each ListItem. Make it once per collection (with+ * `useMemo`); one made again on each render still works.+ *+ * @example+ * ```+ * const reorderable = useMemo(+ * () =>+ * createReorderable({+ * onReorder: ({key, to}) => setTasks(tasks => moveItem(tasks, key, to)),+ * }),+ * [],+ * );+ * <List reorderable={reorderable}>+ * {tasks.map(task => (+ * <ListItem key={task.id} itemKey={task.id} label={task.title} />+ * ))}+ * </List>+ * ```+ */+export function createReorderable<+ TKey extends string | number = string | number,+ TTo = number,+>(options: ReorderableOptions<TKey, TTo>): Reorderable<TKey, TTo> {+ const internals: ReorderableInternals = {+ options: options as unknown as ListReorderOptions,+ [REORDER_ENGINE]: listReorderEngine,+ start: key => listReorderEngine.start(internals.options, key),+ };+ return internals as unknown as Reorderable<TKey, TTo>;+}diff --git a/packages/core/src/utils/rowMotion.ts b/packages/core/src/utils/rowMotion.tsnew file mode 100644index 0000000000..b95f50b165--- /dev/null+++ b/packages/core/src/utils/rowMotion.ts@@ -0,0 +1,138 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file rowMotion.ts+ * @input The motion foundation's animator+ * @output The moves a reorder makes on list rows, through one animator per+ * element (`animatorFor`). `animateRow` starts a recorded spring.+ * `motionOf` and `isMoving` read the running one. `releaseMotion` clears+ * the identity inline values once it rests. `motionNow` is the motion+ * clock+ * @position Internal utility for List's reorder (List/listReorderEngine.tsx+ * and List/ListReorderTouch.ts). Every motion goes through the motion+ * foundation's shared per-element `animatorFor`, so a drop and a slide+ * never drive one row through two animators.+ *+ * FLIP, compositor only. When a commit moves a row, its old place is put back+ * with an inverse `translate` in the same frame. The animator springs it+ * home. A row moved again mid-motion keeps its velocity.+ *+ * SYNC: When modified, update List/listReorderEngine.tsx and+ * List/ListReorderTouch.ts.+ */++import {+ animatorFor,+ isIdentityText,+ motionNow,+ type MotionHandle,+} from '../motion/animator';+import type {SpringDescription} from '../motion/spring';++type RowProperty = 'y' | 'rotate' | 'opacity';++/** A motion started through this module: its handle and the spring it runs. */+export interface RowMotion {+ handle: MotionHandle;+ spring: SpringDescription;+}++/** The running motion of each element, per property, until it rests. */+const motions = new WeakMap<HTMLElement, Map<RowProperty, RowMotion>>();++/** The element's shared animator (one per element, for all its motions). */+export {animatorFor, motionNow};++/** Whether a motion started here still runs on the element. */+export function isMoving(element: HTMLElement): boolean {+ return (motions.get(element)?.size ?? 0) > 0;+}++/**+ * The motion running on the element's `property`, started here, with the+ * spring it runs on; undefined once it rests.+ */+export function motionOf(+ element: HTMLElement,+ property: RowProperty = 'y',+): RowMotion | undefined {+ return motions.get(element)?.get(property);+}++function track(+ element: HTMLElement,+ properties: ReadonlyArray<RowProperty>,+ handle: MotionHandle,+ spring: SpringDescription,+): MotionHandle {+ let running = motions.get(element);+ if (running == null) {+ running = new Map();+ motions.set(element, running);+ }+ const motion = {handle, spring};+ for (const property of properties) {+ running.set(property, motion);+ }+ const record = running;+ void handle.finished.then(() => {+ for (const property of properties) {+ if (record.get(property) === motion) {+ record.delete(property);+ }+ }+ });+ return handle;+}++/**+ * Starts a spring on the element's shared animator and records it, so a+ * later move reads its curve (`motionOf`). For a drop, or a slide to make+ * room.+ */+export function animateRow(+ element: HTMLElement,+ to: Partial<Record<RowProperty, number>>,+ spring: SpringDescription,+ options: {+ at?: number;+ velocity?: Partial<Record<RowProperty, number>>;+ },+): MotionHandle {+ const properties = Object.keys(to) as RowProperty[];+ return track(+ element,+ properties,+ animatorFor(element).animate(+ to,+ {spring, velocity: options.velocity},+ {at: options.at},+ ),+ spring,+ );+}++/**+ * Clears the element's identity inline values once it rests, so a resting+ * row carries no `translate`. A transform makes it a containing block for+ * fixed descendants. The animator stays: other code may hold it, and its+ * state still reads the resting value. Nothing is cleared while a newer+ * motion runs on the element.+ */+export function releaseMotion(+ element: HTMLElement,+ ...properties: ReadonlyArray<'translate' | 'rotate' | 'opacity'>+): void {+ if (isMoving(element)) {+ return;+ }+ for (const property of properties) {+ // Other code may hold the same channel off rest, such as a swipe's x on+ // `translate`. Only identity values are ours to clear.+ if (isIdentityText(property, element.style.getPropertyValue(property))) {+ element.style.removeProperty(property);+ }+ }+}diff --git a/packages/core/src/utils/scrollingAncestor.ts b/packages/core/src/utils/scrollingAncestor.tsindex 47369dc251..3d90ba283c 100644--- a/packages/core/src/utils/scrollingAncestor.ts+++ b/packages/core/src/utils/scrollingAncestor.ts@@ -3,8 +3,10 @@/*** @file scrollingAncestor.ts* @input An element, and an optional ancestor where the walk stops.- * @output The element's nearest ancestor that scrolls on the block axis.- * @position Shared by the keyboard module's reveals and Outline's scroll spy.+ * @output The element's nearest ancestor that scrolls on the block axis, and+ * `nearestScroller`, which falls back to the document's scroller.+ * @position Shared by the keyboard module's reveals, Outline's scroll spy+ * and the List reorder's edge autoscroll.*/import {SCROLLABLE_OVERFLOW} from './scrollView';@@ -40,3 +42,17 @@ export function scrollingAncestor(}return null;}++/**+ * The element that scrolls `element` into view: its nearest ancestor that+ * scrolls on the block axis, or else the document's scroller.+ */+export function nearestScroller(element: Element): Element {+ const doc = element.ownerDocument;+ const scroller = scrollingAncestor(element);+ return scroller == null ||+ scroller === doc.body ||+ scroller === doc.documentElement+ ? (doc.scrollingElement ?? doc.documentElement)+ : scroller;+}