From cad762b60f45a8460ee949c1bd39dc376108c704 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 25 Oct 2026 19:02:40 -0700 Subject: [PATCH 01/20] feat(core): createReorderable makes List rows reorderable 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. Under a finger, a 150 ms hold on a handle picks its row up, and a flick on it still scrolls. The rows stay still while a dimmed source, a preview and an insertion line show the move. On release they glide on the shared settle role. A pen holds 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. A click, Space or Enter turns on reorder mode: the insertion line marks the row's place, the arrow keys move the row and announce its place, and Escape ends the mode. The reorder's machinery ships with the object, so a List without `reorderable` loads none of it. The UIKit table's reorder values and the drop model come in here with their first user. With an animatedLayout handle, a drag's commits stay the reorder's own. The CLI lists createReorderable with the hooks. --- .changeset/cli-hook-docs-create.md | 7 + .changeset/list-reorderable.md | 7 + apps/storybook/stories/List.stories.tsx | 178 +- docs/specs/AST-103-reorderable/spec.md | 5 +- docs/specs/components/List/List.spec.md | 7 +- internal/shadcn-registry/routes.lock.json | 5 + .../foundation/discovery/hook-discovery.mjs | 13 +- .../discovery/hook-discovery.test.mjs | 20 + .../no-icon-set/search-icon-set.json | 2 +- .../no-icon-set/search-icon-set.txt | 2 +- packages/core/api-report.md | 11 + packages/core/locales/en.json | 52 + packages/core/src/Item/Item.tsx | 58 +- packages/core/src/Item/ItemLabelContext.tsx | 39 + .../core/src/Item/ItemTrailingContext.tsx | 31 + packages/core/src/List/List.doc.mjs | 9 + packages/core/src/List/List.tsx | 96 +- packages/core/src/List/ListContext.tsx | 18 +- packages/core/src/List/ListItem.doc.mjs | 6 +- packages/core/src/List/ListItem.tsx | 105 +- packages/core/src/List/ListReorderHandle.tsx | 439 ++++ packages/core/src/List/ListReorderTouch.ts | 165 ++ .../src/List/__tests__/ListReorder.test.tsx | 1469 +++++++++++++ .../List/__tests__/ListReorderLayout.test.tsx | 111 + ...ReorderPointer.interaction.browser.spec.ts | 159 ++ ...stReorderTouch.interaction.browser.spec.ts | 452 ++++ .../src/List/__tests__/reorderModel.test.ts | 224 ++ packages/core/src/List/listReorderContext.ts | 137 ++ packages/core/src/List/listReorderEngine.tsx | 1926 +++++++++++++++++ packages/core/src/List/reorderModel.ts | 158 ++ packages/core/src/index.ts | 8 + packages/core/src/motion/MEASUREMENTS.md | 14 + packages/core/src/motion/README.md | 1 + packages/core/src/motion/animator.ts | 7 +- packages/core/src/motion/uikit/index.ts | 6 +- packages/core/src/motion/uikit/reorder.ts | 102 + .../src/privateAttributes/leaving.stylex.ts | 8 +- .../privateAttributes/listReorder.stylex.ts | 29 + .../src/privateAttributes/ownRing.stylex.ts | 56 + .../privateAttributes/reorderLine.stylex.ts | 39 + .../reorderPreview.stylex.ts | 18 + .../privateAttributes/reorderSource.stylex.ts | 23 + .../privateAttributes/reordering.stylex.ts | 46 + .../src/reorderable/createReorderable.doc.mjs | 106 + .../core/src/reorderable/createReorderable.ts | 123 ++ packages/core/src/utils/rowMotion.ts | 138 ++ 46 files changed, 6575 insertions(+), 60 deletions(-) create mode 100644 .changeset/cli-hook-docs-create.md create mode 100644 .changeset/list-reorderable.md create mode 100644 packages/core/src/Item/ItemLabelContext.tsx create mode 100644 packages/core/src/Item/ItemTrailingContext.tsx create mode 100644 packages/core/src/List/ListReorderHandle.tsx create mode 100644 packages/core/src/List/ListReorderTouch.ts create mode 100644 packages/core/src/List/__tests__/ListReorder.test.tsx create mode 100644 packages/core/src/List/__tests__/ListReorderLayout.test.tsx create mode 100644 packages/core/src/List/__tests__/ListReorderPointer.interaction.browser.spec.ts create mode 100644 packages/core/src/List/__tests__/ListReorderTouch.interaction.browser.spec.ts create mode 100644 packages/core/src/List/__tests__/reorderModel.test.ts create mode 100644 packages/core/src/List/listReorderContext.ts create mode 100644 packages/core/src/List/listReorderEngine.tsx create mode 100644 packages/core/src/List/reorderModel.ts create mode 100644 packages/core/src/motion/uikit/reorder.ts create mode 100644 packages/core/src/privateAttributes/listReorder.stylex.ts create mode 100644 packages/core/src/privateAttributes/ownRing.stylex.ts create mode 100644 packages/core/src/privateAttributes/reorderLine.stylex.ts create mode 100644 packages/core/src/privateAttributes/reorderPreview.stylex.ts create mode 100644 packages/core/src/privateAttributes/reorderSource.stylex.ts create mode 100644 packages/core/src/privateAttributes/reordering.stylex.ts create mode 100644 packages/core/src/reorderable/createReorderable.doc.mjs create mode 100644 packages/core/src/reorderable/createReorderable.ts create mode 100644 packages/core/src/utils/rowMotion.ts diff --git a/.changeset/cli-hook-docs-create.md b/.changeset/cli-hook-docs-create.md new file mode 100644 index 0000000000000..bfce77fd953c0 --- /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. + +@vjeux diff --git a/.changeset/list-reorderable.md b/.changeset/list-reorderable.md new file mode 100644 index 0000000000000..47f7a9140aa7f --- /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. + +@vjeux diff --git a/apps/storybook/stories/List.stories.tsx b/apps/storybook/stories/List.stories.tsx index 34a26bdbff615..cda519e7064ff 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,177 @@ export const AnimatedChangesSwipe: Story = { }, }, }; + +function moveKey( + rows: ReadonlyArray, + 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; + pinned?: ReadonlyArray; + edge?: 'padded' | 'flush'; +}) { + const [rows, setRows] = useState(initial); + return ( + setRows(current => moveKey(current, key, to)), + isReorderable: key => !pinned.includes(key as string), + })}> + {rows.map(label => ( + + ))} + + ); +} + +export const Reorderable: Story = { + render: () => ( + + ), + 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 ' + + 'moves it a place, and Escape ends the mode.', + }, + }, + }, +}; + +export const ReorderFlush: Story = { + render: () => ( + + ), + 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: () => ( + + ), + 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 ( + + + + {items.map(item => ( + + ))} + + + ); + } + + 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( + , + ); + 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( + , + ); + 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( + , + ); + 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( + <> + + + + + + + , + ); + 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("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(); + 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(); + 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( + '[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(); + 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(); + 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; + fixed?: ReadonlyArray; + isReorderable?: boolean; + }, + ) => { + stubPrimaryPointer(false); + const onReorder = vi.fn(); + const rows = ({ + isDisabled = NONE, + fixed = NONE, + isReorderable = true, + }: typeof change) => ( + !fixed.includes(key as string), + }) + : undefined + }> + {['A', 'B', 'C'].map(item => ( + + ))} + + ); + 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("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(); + 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 user = userEvent.setup(); + render(); + 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); + fireEvent.pointerCancel(handle, {...MOUSE, clientY: 344 + 30}); + 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(); + }); + + it('puts its listeners on the list: none on a row or a handle', () => { + stubPrimaryPointer(true); + const add = vi.spyOn(EventTarget.prototype, 'addEventListener'); + render(); + 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( + , + ); + 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(); + 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(); + 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: the hold attaches where the primary pointer is coarse. + 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(, { + 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( + + {}})}> + + + + , + ); + 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( + + {}})}> + + + + , + ); + 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( + {}})}> + + , + ); + 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.tsx new file mode 100644 index 0000000000000..9fe3ecc33ca77 --- /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()), + useListLayoutUpdates: () => measureRows, +})); + +function moveKey(items: ReadonlyArray, 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(null); + const animatedLayout = useAnimatedLayout({containerRef}); + const [items, setItems] = useState>(['A', 'B', 'C']); + addRow = label => setItems(previous => [...previous, label]); + return ( +
+ + setItems(previous => moveKey(previous, key, to)), + })}> + {items.map(item => ( + + ))} + +
+ ); +} + +/** 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(); + 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__/ListReorderPointer.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListReorderPointer.interaction.browser.spec.ts new file mode 100644 index 0000000000000..715e81f8b909e --- /dev/null +++ b/packages/core/src/List/__tests__/ListReorderPointer.interaction.browser.spec.ts @@ -0,0 +1,159 @@ +// 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 + * @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'; + +const storybook = withStorybook(test); + +const STORY = 'core-list--reorderable'; + +/** 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 { + 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[] { + 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) { + 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 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__/ListReorderTouch.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListReorderTouch.interaction.browser.spec.ts new file mode 100644 index 0000000000000..0a4f427cba462 --- /dev/null +++ b/packages/core/src/List/__tests__/ListReorderTouch.interaction.browser.spec.ts @@ -0,0 +1,452 @@ +// 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 + * @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'; + +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 { + 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 { + 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> { + return page + .locator('#storybook-root li:not([data-astryx-leaving])') + .evaluateAll(rows => { + const tops: Record = {}; + 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( + '[data-astryx-reorder-source]', + ); + const preview = document.querySelector( + '[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('#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('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(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 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__/reorderModel.test.ts b/packages/core/src/List/__tests__/reorderModel.test.ts new file mode 100644 index 0000000000000..8751cbd9f07b7 --- /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, + {gap = 0, fixed = []}: {gap?: number; fixed?: ReadonlyArray} = {}, +): 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.ts new file mode 100644 index 0000000000000..5a971e2aa648c --- /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; + /** 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; + /** Names a row without a handle for the announcements; renders nothing. */ + readonly RowName: ComponentType; + /** 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.tsx new file mode 100644 index 0000000000000..13938cda014ea --- /dev/null +++ b/packages/core/src/List/listReorderEngine.tsx @@ -0,0 +1,1926 @@ +// 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 and + * the shared announcer + * @output `listReorderEngine`, the machinery a reorderable object carries: + * the reorder session of a List, its Host and its handle. A drag from a + * handle leaves the rows in place. The row dims where it is, and a preview + * 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 + * @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. 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. 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 type {Key, KeyboardEvent} from 'react'; +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 type {LongPressGestureRecognizer} from '../gestures/LongPressGestureRecognizer'; +import {VelocityTracker} from '../gestures/VelocityTracker'; +import {reorder} from '../motion/uikit/reorder'; +import { + animatorFor, + isMoving, + motionNow, + motionOf, + releaseMotion, +} from '../utils/rowMotion'; +import {edgeAutoscroll, type EdgeAutoscroll} from '../utils/edgeAutoscroll'; +import {isScrollCapableOverflow} from '../hooks/scrollGeometry'; +import {useTouchPresentation} from '../utils/touchPresentation'; +import {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); +} + +/** + * 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[] { + 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; +} + +/** + * The preview: a copy of `row` at its place, with the same reduced emphasis + * as the row and no elevation. + */ +function previewOf(row: HTMLElement, top: number, background: string | null) { + const preview = row.cloneNode(true) as HTMLElement; + preview.removeAttribute('id'); + for (const element of preview.querySelectorAll('[id]')) { + element.removeAttribute('id'); + } + markReorderPreview(preview); + overlay(preview); + Object.assign(preview.style, { + top: `${top}px`, + insetInlineStart: `${row.offsetLeft}px`, + inlineSize: `${row.offsetWidth}px`, + boxSizing: 'border-box', + boxShadow: 'none', + opacity: MOVING_OPACITY, + }); + 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'; + +/** + * Shows the list's insertion line (its pseudo-element, reorderListStyle) + * across `row`'s width, centred on `center` in list coordinates. + */ +function showLine(list: HTMLElement, row: HTMLElement, center: number): void { + list.style.setProperty(LINE_START, `${row.offsetLeft}px`); + list.style.setProperty(LINE_SIZE, `${row.offsetWidth}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; +} + +function isScrollContainer(element: HTMLElement): boolean { + return ( + isScrollCapableOverflow(getComputedStyle(element).overflowY) && + element.scrollHeight > element.clientHeight + ); +} + +function isTransparent(color: string): boolean { + return ( + color === '' || + color === 'transparent' || + /^rgba\(.*,\s*0\)$/.test(color) || + /\/\s*0\)$/.test(color) + ); +} + +/** + * The background a row is drawn on: the nearest opaque background behind + * the list, else the page's canvas. + */ +function surfaceColor(list: HTMLElement): string { + for ( + let node: HTMLElement | null = list; + node != null; + node = node.parentElement + ) { + const color = getComputedStyle(node).backgroundColor; + if (!isTransparent(color)) { + return color; + } + } + return 'Canvas'; +} + +/** 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 { + for ( + let node = list.parentElement; + node != null && node !== node.ownerDocument.body; + node = node.parentElement + ) { + if (isScrollContainer(node)) { + const rect = node.getBoundingClientRect(); + const top = rect.top + node.clientTop; + return { + element: node, + top, + bottom: top + node.clientHeight, + max: node.scrollHeight - node.clientHeight, + position: node.scrollTop, + }; + } + } + const doc = list.ownerDocument; + const element = doc.scrollingElement ?? doc.documentElement; + 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; + /** Their layout tops at the begin, for the commit's rebase. */ + readonly tops: ReadonlyArray; + readonly geometry: ReorderGeometry; + readonly dragged: number; + 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 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; +} + +/** A drop reported through `onReorder`, waiting for its commit. */ +interface PendingDrop { + readonly list: HTMLElement; + readonly rows: ReadonlyArray; + readonly tops: ReadonlyArray; + 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; + /** The rows' layout tops before it, for the slide to their new places. */ + readonly tops: ReadonlyArray; +} + +/** + * 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; + 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(); + /** + * 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(); + /** The handle whose row is in reorder mode, if any. */ + private modeHandle: HTMLElement | null = null; + private readonly modeListeners = new Set<() => void>(); + /** 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 | 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 | 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 | null = null; + /** Ends the mouse press in progress, if any, without reporting it. */ + private endMouse: (() => void) | null = null; + /** Whether a list whose rows have no item key has been warned about. */ + private warnedUnkeyed = false; + + 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, the row's item key (ListItem `itemKey`) and its + * name; returns the removal. A row moves only with a handle recorded here. + */ + registerHandle(handle: Element | null, key: Key, name: string): () => void { + if (handle == null) { + return () => {}; + } + this.keys.set(handle, key); + this.names.set(handle, name); + return () => { + if (this.keys.get(handle) === key) { + this.keys.delete(handle); + this.names.delete(handle); + if (this.modeHandle === handle) { + this.setMode(null); + } + } + }; + } + + /** Records the name of a row without a 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, or the hint's Done ends it so. A drag or the row leaving ends it + * without a word. + */ + endMode(): void { + const handle = this.modeHandle; + const list = this.getList(); + const row = this.rowOf(handle); + 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, + ) ?? '', + ); + } + + /** + * 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, + }); + } + }, + ); + } + + // --- 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 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) + ? surfaceColor(list) + : null; + for (const element of rows) { + if (element.style.translate === '') { + element.style.translate = '0px 0px'; + } + } + if (getComputedStyle(list).position === 'static') { + list.style.position = 'relative'; + } + const preview = previewOf(row, tops[dragged], 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, + 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 (engines fire a 20 ms interval + // every 20 to 25 ms) catches up one tick, a longer stall is skipped. + catchUp: true, + now: motionNow, + step: () => this.edgeStep(session), + apply: delta => this.scrollBy(session, delta), + }), + step: 0, + restore, + preview, + }; + this.session = 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; + } + session.lastY = y; + const {geometry, dragged} = session; + const row = geometry.rows[dragged]; + const origin = session.origin - session.scrolled; + const top = this.draggedTop(session, y); + animatorFor(session.preview).set({y: top - (origin + row.top)}); + 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.rows[session.dragged], 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, 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; + } + 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; + this.track(session.lastY); + return moved; + } + + 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; + } + this.session = null; + this.stopAutoscroll(session); + 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); + // 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, + dragged: number, + restore: RowRestore, + ): void { + const at = motionNow(); + for (const element of rows) { + const value = shownY(element, at); + if (Math.abs(value) < MIN_MOVE_PX && !isMoving(element)) { + continue; + } + if (!this.animates) { + 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, touchMotion.glideBase(list), 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.warnedUnkeyed && + this.keys.size === 0 && + this.options != null && + this.options.isReorderable == null && + list.children.length > 0 + ) { + this.warnedUnkeyed = true; + devWarn( + '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; + if (move != null && !sameOrder(rowsOf(list), move.rows)) { + this.committedMove = null; + if (this.moveFallback != null) { + clearTimeout(this.moveFallback); + this.moveFallback = null; + } + 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. + if (this.announcement == null) { + this.restoreFocus(); + this.placeModeLine(list); + } + } + + /** A reorder mode move landed: each row slides from its old place to its new one. */ + private slideCommitted(move: PendingMove): void { + const {list} = move; + const at = motionNow(); + for (const [index, element] of move.rows.entries()) { + if (element.parentElement !== list) { + continue; + } + const shift = move.tops[index] - layoutTop(element, list); + if (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, touchMotion.glideBase(list), at); + } + clearReordering(list); + } + + private rebase(pending: PendingDrop): void { + const {list} = pending; + const at = motionNow(); + for (const [index, element] of pending.rows.entries()) { + if (element.parentElement !== list) { + continue; + } + // 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]; + const shift = from - layoutTop(element, list); + const value = shownY(element, at); + if (Math.abs(value + shift) < MIN_MOVE_PX && !isMoving(element)) { + animatorFor(element).set({y: 0}); + releaseMotion(element, 'translate'); + continue; + } + if (Math.abs(shift) < MIN_MOVE_PX) { + continue; + } + if (this.animates && 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, + touchMotion.glideBase(list), + at, + pending.velocity, + ); + } else if (this.animates) { + // 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, touchMotion.glideBase(list), at); + } else { + animatorFor(element).set({y: 0}); + releaseMotion(element, 'translate'); + } + } + 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 { + const row = this.rowOf(this.modeHandle); + if (row == null) { + this.clearModeLine(); + return; + } + 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; + if (this.modeLine?.list !== list) { + this.clearModeLine(); + const listPosition = list.style.position; + if (getComputedStyle(list).position === 'static') { + list.style.position = 'relative'; + } + this.modeLine = {list, listPosition}; + } + showLine(list, row, 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; + } + const order = rows.filter(element => element !== row); + order.splice(to, 0, row); + this.focusRow = row; + this.lastStep = delta; + this.announceWhenCommitted({ + row, + to, + landed: this.placeIn(order, 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, 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 { + // 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; + // Focus that went elsewhere meanwhile stays there. + if ( + handle instanceof HTMLElement && + handle === this.modeHandle && + (active == null || active === row.ownerDocument.body) + ) { + handle.focus({preventScroll: true}); + } + if (handle === this.modeHandle) { + row.scrollIntoView?.({block: 'nearest', inline: 'nearest'}); + } + } + + 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, + b: ReadonlyArray, +): 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 ( + + ); +} + +/** 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.ts new file mode 100644 index 0000000000000..d1eb3b796a1ea --- /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; + /** 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, + 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/index.ts b/packages/core/src/index.ts index f3326ae9a3f74..756f03e663132 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'; + // Hooks export * from './hooks'; diff --git a/packages/core/src/motion/MEASUREMENTS.md b/packages/core/src/motion/MEASUREMENTS.md index 1040ffd008315..7da29b5d267d1 100644 --- a/packages/core/src/motion/MEASUREMENTS.md +++ b/packages/core/src/motion/MEASUREMENTS.md @@ -359,3 +359,17 @@ since its main interaction is a gesture (`spec:AST-094` FR45). | ID | What | App and gesture | Extract | Method | | ----- | ------------ | -------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------ | | 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 | + +## 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 (F4 batches 32, 32b, 32c): 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.md index d21e026ea6d8e..ec824d0b316b4 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/animator.ts b/packages/core/src/motion/animator.ts index 002d2779c3940..c40044c0fd92d 100644 --- a/packages/core/src/motion/animator.ts +++ b/packages/core/src/motion/animator.ts @@ -957,7 +957,7 @@ const IDENTITY_TEXT: Record = { }; /** 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; @@ -986,7 +986,8 @@ function expand(values: MotionValues): Partial> { 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(); } @@ -1043,7 +1044,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/uikit/index.ts b/packages/core/src/motion/uikit/index.ts index b75b5db1eca49..de8c10fe4d842 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.ts new file mode 100644 index 0000000000000..a488fabd3d7fa --- /dev/null +++ b/packages/core/src/motion/uikit/reorder.ts @@ -0,0 +1,102 @@ +// 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), F4 batch 32b, 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), F4 batch 32b, 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), F4 batches 32b and 32c, 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), F4 batches 32b and 32c, 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, F4 batches 32b and 32c, 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): + * none with the row's edge 12 pt inside, 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.ts index 37e43789be8dc..8145dc86f238f 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.ts new file mode 100644 index 0000000000000..32d530343f9d2 --- /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> = { + [LIST_REORDER]: '', +}; + +/** The reorder handle that holds `target`, or null. */ +export function closestReorderHandle(target: Element): HTMLElement | null { + return target.closest(`[${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.ts new file mode 100644 index 0000000000000..414a68e777d4a --- /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> = { + '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.ts new file mode 100644 index 0000000000000..467d6d821fa50 --- /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.ts new file mode 100644 index 0000000000000..eaffc53cafa25 --- /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.ts new file mode 100644 index 0000000000000..0a2e27664fe66 --- /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.ts new file mode 100644 index 0000000000000..65c9e0d32ea31 --- /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.mjs new file mode 100644 index 0000000000000..0dde39827ed60 --- /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. 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.ts new file mode 100644 index 0000000000000..5622dcea0541f --- /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) => 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 (``), + * 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)), + * }), + * [], + * ); + * + * {tasks.map(task => ( + * + * ))} + * + * ``` + */ +export function createReorderable< + TKey extends string | number = string | number, + TTo = number, +>(options: ReorderableOptions): Reorderable { + 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; +} diff --git a/packages/core/src/utils/rowMotion.ts b/packages/core/src/utils/rowMotion.ts new file mode 100644 index 0000000000000..b95f50b165014 --- /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>(); + +/** 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, + 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>, + spring: SpringDescription, + options: { + at?: number; + velocity?: Partial>; + }, +): 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); + } + } +} From d0c1590ee219e61647a18d098d6e4ee90769ed9f Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 25 Oct 2026 21:37:51 -0700 Subject: [PATCH 02/20] feat(List): reorder mode's hint, its moves and Done as buttons While a reorderable List row is in reorder mode, a hint anchored below its handle shows Move up, Move down and Done until the mode ends. Each move does what its key does, with the same announcement, and leaves the focus on the handle. Done ends the mode as Escape does, keeping the moves. So a pointer or a finger can reorder by taps alone, as WCAG 2.5.7 asks. A screen reader that moves its focus into the hint keeps the mode, and the focus goes back to the handle. The hint shares the keyboard hint's layer: hooks/anchoredHint.tsx holds the anchored hint both render, and useKeyboardHint renders its hint through it unchanged. The hint joins the shared dismissal stack, so an Escape in it ends the mode and leaves a Dialog below it open. --- .changeset/list-reorder-mode-hint.md | 7 + apps/storybook/stories/List.stories.tsx | 9 +- docs/families/overlay-dismissal.md | 6 +- docs/specs/components/List/List.spec.md | 3 +- packages/core/locales/en.json | 12 + packages/core/src/List/List.doc.mjs | 5 +- packages/core/src/List/List.tsx | 2 + .../src/List/__tests__/ListReorder.test.tsx | 190 +++++- ...istReorderMode.interaction.browser.spec.ts | 621 ++++++++++++++++++ packages/core/src/List/listReorderEngine.tsx | 208 +++++- packages/core/src/hooks/anchoredHint.tsx | 105 +++ .../core/src/hooks/useKeyboardHint.test.tsx | 3 +- packages/core/src/hooks/useKeyboardHint.tsx | 73 +- .../src/reorderable/createReorderable.doc.mjs | 2 +- 14 files changed, 1159 insertions(+), 87 deletions(-) create mode 100644 .changeset/list-reorder-mode-hint.md create mode 100644 packages/core/src/List/__tests__/ListReorderMode.interaction.browser.spec.ts create mode 100644 packages/core/src/hooks/anchoredHint.tsx diff --git a/.changeset/list-reorder-mode-hint.md b/.changeset/list-reorder-mode-hint.md new file mode 100644 index 0000000000000..a5dad52a05089 --- /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. + +@vjeux diff --git a/apps/storybook/stories/List.stories.tsx b/apps/storybook/stories/List.stories.tsx index cda519e7064ff..2c73025f7994a 100644 --- a/apps/storybook/stories/List.stories.tsx +++ b/apps/storybook/stories/List.stories.tsx @@ -968,8 +968,9 @@ export const Reorderable: Story = { '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 ' + - 'moves it a place, and Escape ends the mode.', + '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.', }, }, }, @@ -1067,8 +1068,8 @@ export const ReorderFromYourUI: Story = { 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 and Escape ' + - 'work as they do from the handle.', + 'focus moves to the row’s handle, and its arrow keys, hint and ' + + 'Done work as they do from the handle.', }, }, }, diff --git a/docs/families/overlay-dismissal.md b/docs/families/overlay-dismissal.md index bf3c1efa64c18..acc9c375f3907 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/components/List/List.spec.md b/docs/specs/components/List/List.spec.md index e6c6fdcc214e3..44ab99b5aa8e0 100644 --- a/docs/specs/components/List/List.spec.md +++ b/docs/specs/components/List/List.spec.md @@ -23,6 +23,7 @@ verified_by: 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, @@ -59,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 `
  • ` 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 stable; its hint, `labels` and `positions` are unbuilt. `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). | diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json index fd44f1585c480..da81a3227b51e 100644 --- a/packages/core/locales/en.json +++ b/packages/core/locales/en.json @@ -635,6 +635,18 @@ "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\")." diff --git a/packages/core/src/List/List.doc.mjs b/packages/core/src/List/List.doc.mjs index 091368b162c6d..2a337da1a3901 100644 --- a/packages/core/src/List/List.doc.mjs +++ b/packages/core/src/List/List.doc.mjs @@ -59,7 +59,7 @@ export const docs = { 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. 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.", + "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', @@ -128,6 +128,7 @@ export const docs = { {name: 'List items', required: true, description: 'Individual entries, which may include icons or images.'}, {name: 'Item description', 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."}, ], }, }; @@ -151,6 +152,7 @@ export const docsZh = { {name: 'List items', required: true, description: 'Individual entries, which may include icons or images.'}, {name: 'Item description', 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."}, ], }, }; @@ -177,6 +179,7 @@ export const docsDense = { {name: 'List items', required: true, description: 'Individual entries, which may include icons or images.'}, {name: 'Item description', 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.tsx index c041e68e11a81..3e87a4e3cd402 100644 --- a/packages/core/src/List/List.tsx +++ b/packages/core/src/List/List.tsx @@ -107,6 +107,8 @@ export interface ListProps extends BaseProps< * 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; diff --git a/packages/core/src/List/__tests__/ListReorder.test.tsx b/packages/core/src/List/__tests__/ListReorder.test.tsx index 57b1061920542..2e6de9d950311 100644 --- a/packages/core/src/List/__tests__/ListReorder.test.tsx +++ b/packages/core/src/List/__tests__/ListReorder.test.tsx @@ -12,7 +12,9 @@ * once and reports its key and its index after the move. Each move is * announced with its place and neighbours once it lands. A move into a row * that stays at either end is refused and announced. Escape, another - * activation or a lost focus ends the mode and keeps the moves. The + * activation or a lost focus ends the mode and keeps the moves. + * 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 @@ -26,7 +28,7 @@ */ import {readFileSync} from 'node:fs'; -import {useState, type Key} from 'react'; +import {useState, type Key, type ReactNode} from 'react'; import {afterEach, describe, expect, it, vi} from 'vitest'; import { act, @@ -49,6 +51,8 @@ import { } 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 {motionRole} from '../../motion/roles'; import {getGestureHost} from '../../gestures/GestureHost'; import {pointerQuery} from '../../gestures/__tests__/pointerQuery'; @@ -150,6 +154,13 @@ const labels = () => 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. @@ -998,6 +1009,181 @@ describe('List reorderable', () => { warn.mockRestore(); }); + it('shows a hint with the moves and Done while a row is in reorder mode', async () => { + const user = userEvent.setup(); + render(); + 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(); + 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( + , + ); + 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(); + 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 {children}; + } + render( + + + , + ); + 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( + , + ); + 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( + , + ); + 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( + , + ); + 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); }); diff --git a/packages/core/src/List/__tests__/ListReorderMode.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListReorderMode.interaction.browser.spec.ts new file mode 100644 index 0000000000000..a61ae166087c2 --- /dev/null +++ b/packages/core/src/List/__tests__/ListReorderMode.interaction.browser.spec.ts @@ -0,0 +1,621 @@ +// 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. start(key) from a button or a 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 + * @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, + withStorybook, + type Point, +} from '@astryxdesign/interaction-harness'; +import {reorder} from '../../motion/uikit/reorder'; + +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 { + 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('[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('*'), + ).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("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/listReorderEngine.tsx b/packages/core/src/List/listReorderEngine.tsx index 13938cda014ea..e4a289d3fa660 100644 --- a/packages/core/src/List/listReorderEngine.tsx +++ b/packages/core/src/List/listReorderEngine.tsx @@ -7,8 +7,9 @@ * @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 and - * the shared announcer + * 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 @@ -18,7 +19,9 @@ * 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 + * 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 @@ -58,7 +61,14 @@ * List/ListReorderHandle.tsx and List/ListReorderTouch.ts. */ -import type {Key, KeyboardEvent} from 'react'; +import { + useRef, + useSyncExternalStore, + type Key, + type KeyboardEvent, + type ReactNode, +} from 'react'; +import * as stylex from '@stylexjs/stylex'; import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; import { useAnnounce, @@ -71,6 +81,12 @@ import { 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 {reorder} from '../motion/uikit/reorder'; @@ -84,6 +100,8 @@ import { import {edgeAutoscroll, type EdgeAutoscroll} from '../utils/edgeAutoscroll'; import {isScrollCapableOverflow} from '../hooks/scrollGeometry'; import {useTouchPresentation} from '../utils/touchPresentation'; +import {useTouchHitArea} from '../utils/touchHitArea'; +import {touchHitAreaStyles} from '../utils/touchHitArea.stylex'; import {devWarn} from '../utils/devWarning'; import {isLeaving, markLeaving} from '../privateAttributes/leaving.stylex'; import { @@ -584,6 +602,8 @@ export class ListReorderController implements ListReorderSession { /** 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). */ @@ -754,13 +774,22 @@ export class ListReorderController implements ListReorderSession { /** * 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, or the hint's Done ends it so. A drag or the row leaving ends it + * handle, or the hint's Done ends it so. Focus that a screen reader moved + * into the hint goes back to the handle. A drag or 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; @@ -776,6 +805,11 @@ export class ListReorderController implements ListReorderSession { ); } + /** 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 @@ -1778,7 +1812,11 @@ export class ListReorderController implements ListReorderSession { * that started the mode hands its focus back at once, the handle takes it * again. */ - blur(handle: HTMLElement | null, _next: EventTarget | null): void { + 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 ( @@ -1810,11 +1848,14 @@ export class ListReorderController implements ListReorderSession { this.focusRow = null; const handle = this.handleIn(row); const active = row.ownerDocument.activeElement; - // Focus that went elsewhere meanwhile stays there. + // 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) + (active == null || + active === row.ownerDocument.body || + this.hintElement?.contains(active) === true) ) { handle.focus({preventScroll: true}); } @@ -1895,9 +1936,154 @@ function ListReorderHost({reorder}: {reorder: ListReorderContextValue}) { [controller, isTouch], ); return ( - + <> + + + + ); +} + +const hintStyles = stylex.create({ + // A glyph or Done: the hint's text, with nothing of a button's own, the + // same size under every pointer. A finger's 44 px target is the shared + // touch hit layer, which stops short of a neighbouring target. + button: { + position: 'relative', + display: 'inline-flex', + alignItems: 'center', + justifyContent: 'center', + margin: 0, + padding: 0, + borderWidth: 0, + borderRadius: 4, + backgroundColor: 'transparent', + color: 'inherit', + fontFamily: 'inherit', + fontSize: 'inherit', + lineHeight: 'inherit', + cursor: { + default: 'pointer', + ':is(:disabled,[aria-disabled="true"])': 'default', + }, + }, + done: { + paddingInline: spacingVars['--spacing-1'], + }, +}); + +/** + * One of the hint's buttons: it never takes the focus from the handle (a + * press does not move it), and does what its key does. + */ +function HintButton({ + label, + onPress, + isText = false, + children, +}: { + label?: string; + onPress: () => void; + isText?: boolean; + children: ReactNode; +}) { + // A finger's target: the shared touch hit area grows the button's hit + // layer where the primary pointer is coarse. + const hitAreaRef = useTouchHitArea(true); + return ( + + ); +} + +/** + * Reorder mode's hint. It is anchored below the start of the handle whose + * row is in the mode, in Core's keyboard hint's layer and theme roles. It + * shows the moves for the list's axis and Done until the mode ends. Each + * move is a button that does what its key does, with the same announcement, + * and the focus stays on the handle. Done ends the mode as Escape does. So + * a pointer or a finger can reorder by tapping the handle, the moves, then + * Done. + */ +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(null); + // External system: the hint's popover in the top layer (useLayer), + // anchored to the handle of the row in reorder mode. Shown while that row + // is in the mode; hidden and unanchored when the mode ends or moves on. + useIsomorphicLayoutEffect(() => { + if (target == null) { + return undefined; + } + const shown = layerRef.current; + shown.ref(target); + shown.show(); + return () => { + shown.hide(); + shown.ref(null); + }; + }, [target]); + // The shared dismissal stack. While the hint is up, an Escape that reaches + // the stack, with the focus in the hint, ends reorder mode. A layer below + // it, such as a Dialog, stays open. The handle claims its own Escape first. + useLayerDismissal({ + isActive: target != null, + onDismiss: () => controller.endMode(), + getContainer: () => hintRef.current, + }); + return renderAnchoredHint( + layer, + target == null ? null : ( + { + hintRef.current = element; + controller.setHintElement(element); + }} + {...stylex.props(anchoredHintStyles.keys)}> + controller.step(target, -1)}> + + + controller.step(target, 1)}> + + + controller.endMode()}> + {t('@astryx.list.reorderDone')} + + + ), + {isInteractive: true}, ); } diff --git a/packages/core/src/hooks/anchoredHint.tsx b/packages/core/src/hooks/anchoredHint.tsx new file mode 100644 index 0000000000000..955324e9884a7 --- /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.tsx index 4789c93f4cb03..fbc574880bfbe 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(); 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.tsx index d87338cac19ba..0b2709ad90657 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 = ( - + {ARROW_HINT_KEYS[orientation].map(key => ( ))} ); - const hintElement = layer.render( + const hintElement = renderAnchoredHint( + layer,