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-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/.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..2c73025f7994a 100644 --- a/apps/storybook/stories/List.stories.tsx +++ b/apps/storybook/stories/List.stories.tsx @@ -7,10 +7,11 @@ * @position Storybook demonstrations for List consumers */ -import {useEffect, useRef, useState} from 'react'; +import {useEffect, useMemo, useRef, useState} from 'react'; import * as stylex from '@stylexjs/stylex'; import type {Meta, StoryObj} from '@storybook/react'; import {List, ListItem} from '@astryxdesign/core/List'; +import {createReorderable} from '@astryxdesign/core'; import {Avatar} from '@astryxdesign/core/Avatar'; import {Badge} from '@astryxdesign/core/Badge'; import {Button} from '@astryxdesign/core/Button'; @@ -21,6 +22,7 @@ import {Heading, Text} from '@astryxdesign/core/Text'; import {VStack} from '@astryxdesign/core/Layout'; import {useAnimatedLayout} from '@astryxdesign/core/hooks'; import {rtlStyles} from '@astryxdesign/core/utils'; +import {ContextMenu} from '@astryxdesign/core/ContextMenu'; import { Cog6ToothIcon, BellIcon, @@ -914,3 +916,178 @@ export const AnimatedChangesSwipe: Story = { }, }, }; + +function moveKey( + rows: ReadonlyArray, + 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, or ' + + 'each move in the hint below the handle, moves it a place, and ' + + 'Escape or Done ends the mode.', + }, + }, + }, +}; + +export const ReorderFlush: Story = { + render: () => ( + + ), + 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('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); + }); + + 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('writes no offset to a row a drop leaves at rest at 0, and leaves it no inline offset', () => { + stubPrimaryPointer(false); + render(); + const list = screen.getByRole('list'); + layOut(list); + const d = list.querySelectorAll('li')[3]; + // A glide that ended leaves this identity offset until its release runs. + d.style.setProperty('translate', 'none'); + const set = vi.spyOn(animatorFor(d), 'set'); + try { + const handle = handleOf('A'); + mouseDrag(handle, 322, 322 + 70); + act(() => { + fireEvent.pointerUp(handle, {...MOUSE, clientY: 322 + 70}); + }); + expect(labels()).toEqual(['B', 'C', 'A', 'D']); + expect(set).not.toHaveBeenCalled(); + expect(d.style.getPropertyValue('translate')).toBe(''); + } finally { + set.mockRestore(); + } + }); + + it("reads every row's layout before a drop's first glide, and the glide's spring once", () => { + stubPrimaryPointer(true); + const events: string[] = []; + const glide = vi + .spyOn(touchMotion, 'glide') + .mockImplementation(() => events.push('write')); + const follow = vi + .spyOn(touchMotion, 'follow') + .mockImplementation(() => events.push('write')); + const spring = vi.spyOn(touchMotion, 'glideBase'); + try { + render(); + const list = screen.getByRole('list'); + layOut(list, () => events.push('read')); + const handle = handleOf('A'); + mouseDrag(handle, 322, 322 + 70); + events.length = 0; + act(() => { + fireEvent.pointerUp(handle, {...MOUSE, clientY: 322 + 70}); + }); + expect(labels()).toEqual(['B', 'C', 'A', 'D']); + expect(glide).toHaveBeenCalledTimes(1); + expect(follow).toHaveBeenCalledTimes(2); + expect(events.slice(events.indexOf('write'))).not.toContain('read'); + expect(spring).toHaveBeenCalledTimes(1); + } finally { + glide.mockRestore(); + follow.mockRestore(); + spring.mockRestore(); + } + }); + + it("reads a key move's glide spring once, however many rows slide", async () => { + stubPrimaryPointer(true); + const follow = vi.spyOn(touchMotion, 'follow'); + const spring = vi.spyOn(touchMotion, 'glideBase'); + try { + const user = userEvent.setup(); + render(); + const list = screen.getByRole('list'); + layOut(list); + handleOf('A').focus(); + await user.keyboard(' {ArrowDown}'); + await waitFor(() => expect(labels()).toEqual(['B', 'A', 'C', 'D'])); + expect(follow).toHaveBeenCalledTimes(2); + expect(spring).toHaveBeenCalledTimes(1); + } finally { + follow.mockRestore(); + spring.mockRestore(); + } + }); + + it("plays a committed move's glide on the shared settle role, springs.settle (spec:AST-105 FR4)", async () => { + stubPrimaryPointer(true); + const glide = vi.spyOn(touchMotion, 'glideBase'); + const user = userEvent.setup(); + render(); + const list = screen.getByRole('list'); + layOut(list); + const handle = handleOf('A'); + handle.focus(); + await user.keyboard(' {ArrowDown}'); + await waitFor(() => expect(glide).toHaveBeenCalled()); + expect(glide.mock.results[0]?.value).toEqual({duration: 0.5, bounce: 0}); + expect(motionRole('springs.settle')).toBeDefined(); + glide.mockRestore(); + }); + + it('sends a still-gliding row home on the shared settle role, keeping its velocity (spec:AST-094 FR4, FR6)', async () => { + stubPrimaryPointer(true); + const home = vi.spyOn(touchMotion, 'home'); + const spring = vi.spyOn(touchMotion, 'glideBase'); + const user = userEvent.setup(); + render(); + const list = screen.getByRole('list'); + layOut(list); + // A key move commits, and its rows glide on springs.settle. + handleOf('A').focus(); + await user.keyboard(' {ArrowDown}{Escape}'); + await waitFor(() => expect(labels()).toEqual(['B', 'A', 'C'])); + layOut(list); + // Picked up again while it still glides, then cancelled. It goes home on + // the same role from where it is shown, at the speed it has. + const handle = handleOf('A'); + mouseDrag(handle, 344, 344 + 30); + spring.mockClear(); + fireEvent.pointerCancel(handle, {...MOUSE, clientY: 344 + 30}); + // Both rows of the move still glide, and the spring is read once. + expect(home).toHaveBeenCalledTimes(2); + expect(spring).toHaveBeenCalledTimes(1); + const draggedRow = handle.closest('li'); + const calls = home.mock.calls.filter(([element]) => element === draggedRow); + expect(calls.length).toBeGreaterThan(0); + for (const [, spring, , fromRest] of calls) { + expect(spring).toEqual({duration: 0.5, bounce: 0}); + expect(fromRest).toBe(false); + } + home.mockRestore(); + spring.mockRestore(); + }); + + it('puts its listeners on the list: none on a row or a handle', () => { + stubPrimaryPointer(true); + const add = vi.spyOn(EventTarget.prototype, 'addEventListener'); + render(); + 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, so the hold takes the window's touches. + stubPrimaryPointer(true); + // A window of its own, so no earlier test has touched it, whose primary + // pointer is the page's. The gesture host listens in the window's capture + // phase. + const frame = document.createElement('iframe'); + document.body.append(frame); + const doc = frame.contentDocument as Document; + Object.defineProperty(frame.contentWindow, 'matchMedia', { + configurable: true, + value: (query: string) => window.matchMedia(query), + }); + const view = frame.contentWindow as Window; + const touches = new Set([ + 'touchstart', + 'touchmove', + 'touchcancel', + 'pointerdown', + 'pointermove', + 'pointerup', + 'pointercancel', + ]); + const added = vi.spyOn(view, 'addEventListener'); + const removed = vi.spyOn(view, 'removeEventListener'); + const mount = () => { + const container = doc.createElement('div'); + doc.body.append(container); + return render(, { + 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__/ListReorderMode.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListReorderMode.interaction.browser.spec.ts new file mode 100644 index 0000000000000..5d44aa8680696 --- /dev/null +++ b/packages/core/src/List/__tests__/ListReorderMode.interaction.browser.spec.ts @@ -0,0 +1,743 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file ListReorderMode.interaction.browser.spec.ts + * @input The built List "Reorderable" and "Reorder From Your UI" stories, + * with a mouse and in the touch phone context, and the interaction + * harness's touch driver + * @output Browser proofs of reorder mode and its hint, in each engine. A + * mouse click on a handle turns the mode on and shows the hint's moves and + * Done. The focus stays on the handle, and no drop is announced. Space or + * Enter turns it on. Each arrow commits a move at once with the focus on + * the handle. Escape ends it, keeps the moves and announces where the row + * is. An Escape with the focus in the hint ends the mode too, and the focus + * goes back to the handle. A start(key) call from a button or context menu + * enters the same mode with the focus on the handle. Under a finger, taps + * alone reorder: the handle, the moves, then Done. A drag leaves the mode + * off. Each of the hint's buttons is a 44 px target centered on what it + * shows, and none covers its neighbour. A key move measures the rows in + * one pass, before their glides start + * @position Interaction evidence for List/listReorderEngine.tsx (reorder + * mode and its hint) and List/ListReorderHandle.tsx + */ + +import { + expect, + test, + type Locator, + type Page, +} from '@astryxdesign/a11y-spec/playwright'; +import { + drag, + openStory, + tap, + touchDriver, + waitForRest, + withStorybook, + type Point, +} from '@astryxdesign/interaction-harness'; +import {reorder} from '../../motion/uikit/reorder'; +import {describePasses, forcedPassesDuring, passesUnder} from './forcedPasses'; + +const storybook = withStorybook(test); + +const STORY = 'core-list--reorderable'; +const START_STORY = 'core-list--reorder-from-your-ui'; +const ROWS = ['Inbox', 'Sent', 'Drafts', 'Archive', 'Spam', 'Trash']; +const HOLD_MS = reorder.claim.delayMs + 80; + +/** + * The list's rows, without the reorder's insertion line and drag preview: + * inert, aria-hidden ghosts of the list (`data-astryx-leaving`). + */ +const ROW = '#storybook-root li:not([data-astryx-leaving])'; + +const row = (page: Page, label: string) => + page.locator(ROW).filter({hasText: label}).first(); + +const handle = (page: Page, label: string) => + page.getByRole('button', {name: `Reorder ${label}`, exact: true}); + +const labels = async (page: Page) => + page + .locator(ROW) + .evaluateAll(rows => rows.map(element => element.textContent ?? '')); + +const translateY = async (element: Locator) => + element.evaluate(el => { + const value = getComputedStyle(el).translate; + if (value === 'none' || value === '') { + return 0; + } + const [, y = '0px'] = value.split(' '); + return Number.parseFloat(y); + }); + +/** Everything the page's live regions say right now. */ +const announced = async (page: Page) => + page.evaluate(() => + Array.from(document.querySelectorAll('[aria-live], [role="status"]')) + .map(element => element.textContent ?? '') + .join(' '), + ); + +async function centerOf(element: Locator): Promise { + 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('a key move measures the rows in one pass, before their glides start', async ({ + page, + browser, + browserName, + }) => { + test.skip(browserName !== 'chromium', 'the layout trace is Chromium CDP'); + await open(page); + await expect(page.locator(ROW)).toHaveCount(ROWS.length); + await handle(page, 'Inbox').focus(); + await page.keyboard.press('Space'); + await expect(handle(page, 'Inbox')).toHaveAttribute('aria-pressed', 'true'); + const move = async (key: string, order: ReadonlyArray) => + forcedPassesDuring(browser, page, async () => { + await page.keyboard.press(key); + await expect.poll(async () => labels(page)).toEqual(order); + // The commit's glides start before the next frame. + await page.evaluate( + async () => + new Promise(resolve => { + requestAnimationFrame(() => requestAnimationFrame(resolve)); + }), + ); + }); + // The first move: Inbox and Sent glide for the first time. + const first = await move('ArrowDown', [ + 'Sent', + 'Inbox', + 'Drafts', + 'Archive', + 'Spam', + 'Trash', + ]); + expect(first.events.has('keydown')).toBe(true); + expect(first.rounds).toBeGreaterThan(0); + // The reorder's own reads, in the key's move and in its commit, are one + // measurement pass at most. The shared animator reads a row's will-change + // on its first glide, a cost of its own. Two rows glide here for the first + // time, so it adds two passes at most. + const moves = passesUnder(first.passes, ['step', 'commit']); + const animators = moves.filter(pass => + pass.sources[0]?.includes('animator'), + ); + const firstReport = describePasses(first.passes); + expect(moves.length - animators.length, firstReport).toBeLessThanOrEqual(1); + expect(animators.length, firstReport).toBeLessThanOrEqual(2); + // Once the glides end, a move back over the same rows counts every read. + await waitForRest(row(page, 'Inbox')); + await waitForRest(row(page, 'Sent')); + // The animator lets each row's layer go once its glide has lingered, and + // then reads the stylesheet's will-change in a zero-delay task. A move + // before that read would make it itself, so the case waits for both. + await expect + .poll( + async () => + page + .locator(ROW) + .evaluateAll(rows => + rows.every( + element => + !(element as HTMLElement).style.willChange.includes( + 'translate', + ), + ), + ), + {message: 'the animator lets the gliding rows go', timeout: 5000}, + ) + .toBe(true); + await page.evaluate( + async () => + new Promise(resolve => { + setTimeout(resolve, 0); + }), + ); + const back = await move('ArrowUp', ROWS); + expect(back.events.has('keydown')).toBe(true); + expect(back.rounds).toBeGreaterThan(0); + expect( + passesUnder(back.passes, ['step', 'commit']).length, + describePasses(back.passes), + ).toBeLessThanOrEqual(1); + }); + + test("a key move at the screen's bottom edge brings the row's new place into view", async ({ + page, + }) => { + await openStory(page, storybook(), 'core-list--reorder-long-list'); + const touch = await page.evaluate( + () => matchMedia('(pointer: coarse)').matches, + ); + test.skip(!touch, 'the rows slide where the primary pointer is coarse'); + await expect(page.locator(ROW)).toHaveCount(30); + const moved = handle(page, 'Item 20'); + const row = moved.locator('xpath=ancestor::li[1]'); + // The row's bottom sits on the screen's bottom edge, the page scrolled. + await row.evaluate(element => { + element.scrollIntoView({block: 'end'}); + }); + expect(await page.evaluate(() => window.scrollY)).toBeGreaterThan(0); + await moved.focus(); + await page.keyboard.press('Space'); + await expect(moved).toHaveAttribute('aria-pressed', 'true'); + expect((await labels(page)).indexOf('Item 20')).toBe(19); + await page.keyboard.press('ArrowDown'); + // The row moves one place down, glides there, then rests. + await expect + .poll(async () => (await labels(page)).indexOf('Item 20'), { + message: 'Item 20 moves one place down', + timeout: 5000, + }) + .toBe(20); + await waitForRest(row); + const box = await row.boundingBox(); + const height = page.viewportSize()?.height ?? 0; + expect(box).not.toBeNull(); + expect(Math.round((box?.y ?? 0) + (box?.height ?? 0))).toBeLessThanOrEqual( + height, + ); + }); + + test("taps alone reorder: the handle turns on reorder mode, the hint's moves move the row, and Done ends the mode", async ({ + page, + browserName, + }) => { + // Linux WebKit's injected touches dispatch pointer and touch events but + // no click, so a tap cannot activate a button there (iOS Safari's tap + // does). + test.skip(browserName === 'webkit', 'injected touches synthesize no click'); + await open(page); + const before = await labels(page); + const driver = await touchDriver(page); + await driver.play(tap(await centerOf(handle(page, 'Inbox')))); + await expect(handle(page, 'Inbox')).toHaveAttribute('aria-pressed', 'true'); + const down = page.getByRole('button', {name: 'Move down'}); + await expect(down).toBeVisible(); + await driver.play(tap(await centerOf(down))); + await expect + .poll(async () => labels(page)) + .toEqual([before[1], before[0], ...before.slice(2)]); + // The focus stayed on the handle through the taps. + await expect(handle(page, 'Inbox')).toBeFocused(); + await driver.play( + tap(await centerOf(page.getByRole('button', {name: 'Done'}))), + ); + await expect(handle(page, 'Inbox')).toHaveAttribute( + 'aria-pressed', + 'false', + ); + await expect(down).toBeHidden(); + expect(await labels(page)).toEqual([ + before[1], + before[0], + ...before.slice(2), + ]); + }); + + test('a drag does not also turn on reorder mode', async ({page}) => { + await open(page); + const pitch = await row(page, 'Inbox').evaluate(element => { + const next = element.nextElementSibling as HTMLElement | null; + return next == null + ? (element as HTMLElement).offsetHeight + : next.offsetTop - (element as HTMLElement).offsetTop; + }); + const from = await centerOf(handle(page, 'Inbox')); + const driver = await touchDriver(page); + await driver.play( + drag( + from, + {x: from.x, y: from.y + 1.2 * pitch}, + {holdMs: HOLD_MS, durationMs: 300, restMs: 150}, + ), + ); + await page.waitForTimeout(400); + await expect(handle(page, 'Inbox')).toHaveAttribute( + 'aria-pressed', + 'false', + ); + await expect(page.getByRole('button', {name: 'Done'})).toBeHidden(); + }); + + test("each of the hint's buttons keeps its size, and its touch target grows toward 44 px without covering its neighbour", async ({ + page, + browser, + browserName, + }) => { + // No control grows for a finger. Where the primary pointer is coarse, a + // target reaches toward 44 px through an invisible hit layer. Each side + // stops at half the gap to a neighbouring target, so a tap always goes to + // the nearer one. + await open(page); + await handle(page, 'Sent').focus(); + await page.keyboard.press('Enter'); + await expect(handle(page, 'Sent')).toHaveAttribute('aria-pressed', 'true'); + const names = ['Move up', 'Move down', 'Done']; + for (const name of names) { + await expect(page.getByRole('button', {name})).toBeVisible(); + } + // The hit layer's insets are written a frame after the hint shows. + await expect + .poll(async () => + page + .getByRole('button', {name: 'Move up'}) + .evaluate(element => + getComputedStyle(element) + .getPropertyValue('--astryx-hit-inset-top') + .trim(), + ), + ) + .not.toBe(''); + const targets = await page.evaluate( + list => + list.map(name => { + const element = Array.from(document.querySelectorAll('button')).find( + button => + button.getAttribute('aria-label') === name || + button.textContent?.trim() === name, + ); + if (element == null) { + throw new Error(`no ${name}`); + } + const style = getComputedStyle(element); + const inset = (side: string) => + parseFloat(style.getPropertyValue(`--astryx-hit-inset-${side}`)) || + 0; + const box = element.getBoundingClientRect(); + const glyph = ( + element.firstElementChild ?? element + ).getBoundingClientRect(); + // What the button adds around what it shows: its glyph's box, or + // its text's. + // A text's height is its line's, which the button's height holds. + const range = document.createRange(); + range.selectNodeContents(element); + const glyphBox = element.firstElementChild?.getBoundingClientRect(); + const lineHeight = parseFloat(getComputedStyle(element).lineHeight); + const content = glyphBox ?? { + width: range.getBoundingClientRect().width, + height: Number.isFinite(lineHeight) + ? lineHeight + : range.getBoundingClientRect().height, + }; + return { + name, + chrome: { + x: box.width - content.width, + y: box.height - content.height, + }, + box: { + left: box.left, + right: box.right, + top: box.top, + bottom: box.bottom, + }, + hit: { + left: box.left - inset('left'), + right: box.right + inset('right'), + top: box.top - inset('top'), + bottom: box.bottom + inset('bottom'), + }, + glyph: {left: glyph.left, right: glyph.right}, + }; + }), + names, + ); + // The same hint where the primary pointer is fine. Each button adds the + // same space around what it shows, since no control grows for a finger. + // Only the invisible hit layer reaches further. The theme's type scale may + // set larger text where the primary pointer is coarse, so the comparison + // leaves the text's own size out. + const fineContext = await browser.newContext({ + viewport: page.viewportSize() ?? {width: 390, height: 844}, + hasTouch: false, + isMobile: false, + }); + const fine = await fineContext.newPage(); + await openStory(fine, storybook(), STORY); + expect( + await fine.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + await handle(fine, 'Sent').focus(); + await fine.keyboard.press('Enter'); + await expect(handle(fine, 'Sent')).toHaveAttribute('aria-pressed', 'true'); + const fineSizes = await fine.evaluate( + list => + list.map(name => { + const element = Array.from(document.querySelectorAll('button')).find( + button => + button.getAttribute('aria-label') === name || + button.textContent?.trim() === name, + ); + if (element == null) { + throw new Error(`no ${name}`); + } + const box = element.getBoundingClientRect(); + // A text's height is its line's, which the button's height holds. + const range = document.createRange(); + range.selectNodeContents(element); + const glyphBox = element.firstElementChild?.getBoundingClientRect(); + const lineHeight = parseFloat(getComputedStyle(element).lineHeight); + const content = glyphBox ?? { + width: range.getBoundingClientRect().width, + height: Number.isFinite(lineHeight) + ? lineHeight + : range.getBoundingClientRect().height, + }; + return { + x: box.width - content.width, + y: box.height - content.height, + }; + }), + names, + ); + await fineContext.close(); + for (const [index, {name, box, hit, chrome}] of targets.entries()) { + // Its own size around what it shows: the same as under a fine pointer. + expect( + Math.abs(chrome.x - fineSizes[index].x), + `${name} adds no width for a finger`, + ).toBeLessThanOrEqual(0.5); + expect( + Math.abs(chrome.y - fineSizes[index].y), + `${name} adds no height for a finger`, + ).toBeLessThanOrEqual(0.5); + // The hit layer only grows, and never past 44 px unless the button + // itself is larger. + const width = box.right - box.left; + const height = box.bottom - box.top; + expect( + hit.right - hit.left, + `${name} target width`, + ).toBeGreaterThanOrEqual(width); + expect(hit.bottom - hit.top).toBeGreaterThanOrEqual(height); + expect(hit.right - hit.left).toBeLessThanOrEqual( + Math.max(44, width) + 0.5, + ); + expect(hit.bottom - hit.top).toBeLessThanOrEqual( + Math.max(44, height) + 0.5, + ); + } + // Neighbouring targets meet at most halfway: none covers the next. + for (let index = 0; index + 1 < targets.length; index += 1) { + expect( + targets[index].hit.right, + `${targets[index].name} stops short of ${targets[index + 1].name}`, + ).toBeLessThanOrEqual(targets[index + 1].hit.left + 0.5); + } + // Every point of each glyph, and the edge of each target, hits its own + // button. + for (const {name, box, hit, glyph} of targets) { + const y = (box.top + box.bottom) / 2; + for (const x of [ + glyph.left + 1, + glyph.right - 1, + hit.left + 1, + hit.right - 1, + ]) { + const label = await page.evaluate( + ([px, py]) => { + const button = document.elementFromPoint(px, py)?.closest('button'); + return ( + button?.getAttribute('aria-label') ?? + button?.textContent?.trim() ?? + null + ); + }, + [x, y] as const, + ); + expect(label, `${name} at x=${x.toFixed(1)}`).toBe(name); + } + } + // A tap in Move up's target just past its visible edge, nearer it than + // Move down, moves the row up. A tap activates a button in every engine, + // except under Linux WebKit's injected touches. + if (browserName === 'webkit') { + return; + } + const [up] = targets; + const driver = await touchDriver(page); + await driver.play( + tap({x: up.hit.right - 1, y: (up.box.top + up.box.bottom) / 2}), + ); + await expect + .poll(async () => labels(page)) + .toEqual(['Sent', 'Inbox', 'Drafts', 'Archive', 'Spam', 'Trash']); + }); +}); diff --git a/packages/core/src/List/__tests__/ListReorderPointer.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListReorderPointer.interaction.browser.spec.ts new file mode 100644 index 0000000000000..8e3d164eae656 --- /dev/null +++ b/packages/core/src/List/__tests__/ListReorderPointer.interaction.browser.spec.ts @@ -0,0 +1,740 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file ListReorderPointer.interaction.browser.spec.ts + * @input The built List "Reorderable" story in two contexts: one with no + * touch screen, so the primary pointer is fine, and the touch phone. A real + * mouse and the harness's real engine pen drive it (the pen in Chromium) + * @output Browser proofs of who drags a row without a hold. A mouse drags a + * row from its handle at once. So does a pen where the primary pointer is + * fine. A pen where the primary pointer is coarse keeps the hold, as a + * finger does. A quick stroke moves nothing, and a held one moves the row. + * A row held near a scroll edge scrolls the page, or the box the list + * scrolls in, and stops at the end. A wheel during a drag scrolls the + * page, and the preview and the drop stay under the pointer. Each scrolled + * frame reads the scroll offset once at most and forces no layout. A drop + * measures the rows in one pass, before its writes, whatever their count. The + * preview and the insertion line run along a row set in from the list's + * start, in either direction. A checked radio in the dragged row stays + * checked through the drag + * @position Beside ListReorderTouch.interaction.browser.spec.ts, which proves + * the hold under a finger + */ + +import { + expect, + test, + type Browser, + type Page, +} from '@astryxdesign/a11y-spec/playwright'; +import { + openStory, + PEN_SKIP, + webInputDriver, + withStorybook, + type PenPoint, +} from '@astryxdesign/interaction-harness'; +import {reorder} from '../../motion/uikit/reorder'; +import {describePasses, forcedPassesDuring, passesUnder} from './forcedPasses'; + +const storybook = withStorybook(test); + +const STORY = 'core-list--reorderable'; + +const LONG_STORY = 'core-list--reorder-long-list'; + +/** Past the claim delay: the hold claims the drag. */ +const HOLD_MS = reorder.claim.delayMs + 150; + +/** The story's row labels, in order. */ +async function labels(page: Page): Promise { + 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, story = STORY) { + const context = await browser.newContext({ + viewport: {width: 800, height: 900}, + deviceScaleFactor: 1, + isMobile: false, + hasTouch: false, + }); + const page = await context.newPage(); + await openStory(page, storybook(), story); + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + return {page, close: async () => context.close()}; +} + +/** A stroke from `at` straight down `distance`, a point every 16 ms. */ +function strokeDown( + at: {x: number; y: number}, + distance: number, + startMs = 0, +): PenPoint[] { + const steps = 16; + return Array.from({length: steps + 1}, (_, step) => ({ + x: at.x, + y: at.y + (distance * step) / steps, + t: startMs + step * 16, + })); +} + +test('a mouse drags a row from its handle at once, where the primary pointer is fine', async ({ + browser, +}) => { + const story = await openFinePointerStory(browser); + try { + const {page} = story; + const before = await labels(page); + expect(before.length).toBeGreaterThanOrEqual(3); + const {at, rowHeight} = await handleOf(page, before[0]); + await page.mouse.move(at.x, at.y); + await page.mouse.down(); + await page.mouse.move(at.x, at.y + rowHeight * 2.5, {steps: 12}); + await page.mouse.up(); + await expect.poll(async () => labels(page)).toEqual(movedTwoDown(before)); + } finally { + await story.close(); + } +}); + +test('a row held near the bottom of the page scrolls the page', async ({ + browser, +}) => { + const story = await openFinePointerStory(browser, LONG_STORY); + try { + const {page} = story; + const order = await labels(page); + // Item 4: an earlier one's name is a prefix of a later row's. + const {at} = await handleOf(page, order[3]); + const bottom = await page.evaluate(() => window.innerHeight); + expect(await page.evaluate(() => window.scrollY)).toBe(0); + await page.mouse.move(at.x, at.y); + await page.mouse.down(); + await page.mouse.move(at.x, bottom - 4, {steps: 12}); + await expect + .poll(async () => page.evaluate(() => window.scrollY), {timeout: 3000}) + .toBeGreaterThan(0); + await page.keyboard.press('Escape'); + await page.mouse.up(); + } finally { + await story.close(); + } +}); + +test('a row held at the bottom of the page stops at its end, under the pointer', async ({ + browser, +}) => { + const story = await openFinePointerStory(browser, LONG_STORY); + try { + const {page} = story; + const order = await labels(page); + // Item 4: an earlier one's name is a prefix of a later row's. + const {at} = await handleOf(page, order[3]); + const viewport = page.viewportSize(); + await page.mouse.move(at.x, at.y); + await page.mouse.down(); + await page.mouse.move(at.x, (viewport?.height ?? 0) - 4, {steps: 12}); + // The page scrolls until the list's end is in view, then stops. + let last = Number.NaN; + await expect + .poll( + async () => { + const y = await page.evaluate(() => window.scrollY); + const isStill = y > 0 && y === last; + last = y; + return isStill; + }, + {intervals: [250], timeout: 8000}, + ) + .toBe(true); + const listBottom = await page.evaluate( + () => + document.querySelector('#storybook-root ul')?.getBoundingClientRect() + .bottom ?? Number.NaN, + ); + expect(listBottom).toBeLessThanOrEqual(viewport?.height ?? 0); + const previewTop = async () => + page.evaluate( + () => + document + .querySelector('[data-astryx-reorder-preview]') + ?.getBoundingClientRect().top ?? Number.NaN, + ); + const atEnd = await previewTop(); + await page.waitForTimeout(300); + // Held at the end, nothing moves: the page stays where it stopped, and + // the preview stays where the pointer holds it. + expect(await page.evaluate(() => window.scrollY)).toBe(last); + expect(Math.abs((await previewTop()) - atEnd)).toBeLessThan(1); + await page.keyboard.press('Escape'); + await page.mouse.up(); + } finally { + await story.close(); + } +}); + +test('a wheel during a drag scrolls the page, and the preview and the drop stay under the pointer', async ({ + browser, +}) => { + const story = await openFinePointerStory(browser, LONG_STORY); + try { + const {page} = story; + const order = await labels(page); + // Item 4: an earlier one's name is a prefix of a later row's. + const {at, rowHeight} = await handleOf(page, order[3]); + const pitch = await page.evaluate(() => { + const rows = document.querySelectorAll('#storybook-root ul > li'); + return ( + rows[1].getBoundingClientRect().top - + rows[0].getBoundingClientRect().top + ); + }); + // The preview's top and the insertion line's y, in the viewport. + const placed = async () => + page.evaluate(() => { + const list = document.querySelector('#storybook-root ul'); + const preview = document.querySelector('[data-astryx-reorder-preview]'); + const line = parseFloat( + list == null + ? '' + : getComputedStyle(list).getPropertyValue( + '--astryx-reorder-line-y', + ), + ); + return { + preview: preview?.getBoundingClientRect().top ?? Number.NaN, + line: (list?.getBoundingClientRect().top ?? Number.NaN) + line, + }; + }); + await page.mouse.move(at.x, at.y); + await page.mouse.down(); + await page.mouse.move(at.x, at.y + rowHeight * 1.5, {steps: 8}); + await expect(page.locator('[data-astryx-reorder-preview]')).toHaveCount(1); + const before = await placed(); + // Counts rendered frames from the last scroll to the first frame that + // shows the preview and the line under the pointer again. + await page.evaluate(target => { + const state = {frame: 0, lastScroll: -1, settledAt: -1}; + Object.assign(window, {c06Frames: state}); + const check = () => { + if (state.lastScroll < 0 || state.settledAt >= 0) { + return; + } + const list = document.querySelector('#storybook-root ul'); + const preview = document.querySelector('[data-astryx-reorder-preview]'); + if (list == null || preview == null) { + return; + } + const line = + list.getBoundingClientRect().top + + parseFloat( + getComputedStyle(list).getPropertyValue('--astryx-reorder-line-y'), + ); + const top = preview.getBoundingClientRect().top; + if ( + Math.abs(top - target.preview) < 1 && + Math.abs(line - target.line) < 1 + ) { + state.settledAt = state.frame; + } + }; + const tick = () => { + state.frame += 1; + // After the frame renders. + setTimeout(check, 0); + requestAnimationFrame(tick); + }; + requestAnimationFrame(tick); + document.addEventListener( + 'scroll', + () => { + // The scroll steps come before the frame's callbacks. + state.lastScroll = state.frame + 1; + state.settledAt = -1; + }, + {passive: true}, + ); + }, before); + await page.mouse.wheel(0, pitch * 3); + // The wheel's scroll animates: wait for it to rest. + let last = Number.NaN; + await expect + .poll( + async () => { + const y = await page.evaluate(() => window.scrollY); + const isStill = y > 0 && y === last; + last = y; + return isStill; + }, + {intervals: [100], timeout: 5000}, + ) + .toBe(true); + const frames = async () => + page.evaluate( + () => + ( + window as unknown as { + c06Frames: {lastScroll: number; settledAt: number}; + } + ).c06Frames, + ); + // The preview and the line come back under the pointer. + await expect + .poll(async () => (await frames()).settledAt >= 0, {timeout: 100}) + .toBe(true); + const {lastScroll, settledAt} = await frames(); + // Within two frames of the scroll, as a native drag follows it. + expect(settledAt - lastScroll).toBeLessThanOrEqual(2); + await page.mouse.up(); + // The drop lands under the pointer, past the rows the wheel scrolled by. + await expect + .poll(async () => (await labels(page)).indexOf(order[3]), { + timeout: 600, + }) + .toBe(4 + Math.round(last / pitch)); + } finally { + await story.close(); + } +}); + +test('a wheel during a drag forces no layout, and reads the scroll offset once a scrolled frame at most', async ({ + browser, + browserName, +}) => { + test.skip(browserName !== 'chromium', 'the layout trace is Chromium CDP'); + const story = await openFinePointerStory(browser, LONG_STORY); + try { + const {page} = story; + const order = await labels(page); + // Item 4: an earlier one's name is a prefix of a later row's. + const {at, rowHeight} = await handleOf(page, order[3]); + await page.mouse.move(at.x, at.y); + await page.mouse.down(); + await page.mouse.move(at.x, at.y + rowHeight * 1.5, {steps: 8}); + await expect(page.locator('[data-astryx-reorder-preview]')).toHaveCount(1); + // Counts reads of the page scroller's offset, and the frames a scroll + // lands in. + await page.evaluate(() => { + const scroller = document.scrollingElement as Element; + const own = Object.getOwnPropertyDescriptor( + Element.prototype, + 'scrollTop', + ); + const counts = {reads: 0, frames: 0}; + Object.assign(window, {c06Counts: counts}); + Object.defineProperty(scroller, 'scrollTop', { + configurable: true, + get() { + counts.reads += 1; + return own?.get?.call(this) as number; + }, + set(value: number) { + own?.set?.call(this, value); + }, + }); + let isCounted = false; + document.addEventListener( + 'scroll', + () => { + if (!isCounted) { + isCounted = true; + counts.frames += 1; + requestAnimationFrame(() => { + isCounted = false; + }); + } + }, + {passive: true}, + ); + }); + await browser.startTracing(page, { + categories: [ + 'devtools.timeline', + 'disabled-by-default-devtools.timeline', + 'disabled-by-default-devtools.timeline.stack', + ], + }); + await page.mouse.wheel(0, rowHeight * 3); + // The pointer moves too, so moves and scrolls share frames. + for (let step = 1; step <= 16; step += 1) { + await page.mouse.move(at.x, at.y + rowHeight * 1.5 + step); + await page.waitForTimeout(16); + } + await page.waitForTimeout(400); + const trace = JSON.parse((await browser.stopTracing()).toString()) as { + traceEvents: { + name: string; + ph: string; + pid: number; + tid: number; + args?: { + name?: string; + beginData?: {stackTrace?: {functionName?: string}[]}; + }; + }[]; + }; + const counts = await page.evaluate( + () => + (window as unknown as {c06Counts: {reads: number; frames: number}}) + .c06Counts, + ); + await page.mouse.up(); + const mainThreads = new Set( + trace.traceEvents + .filter(e => e.ph === 'M' && e.name === 'thread_name') + .filter(e => e.args?.name === 'CrRendererMain') + .map(e => `${e.pid}:${e.tid}`), + ); + // A style or layout pass with a script stack ran inside script: a read + // after a write forced it, instead of the frame's own pass. + const forced = trace.traceEvents.filter( + e => + (e.name === 'Layout' || e.name === 'UpdateLayoutTree') && + mainThreads.has(`${e.pid}:${e.tid}`) && + (e.args?.beginData?.stackTrace ?? []).length > 0, + ); + expect( + forced.map( + e => + `${e.name} in ${e.args?.beginData?.stackTrace?.[0]?.functionName ?? '?'}`, + ), + ).toEqual([]); + expect(counts.frames).toBeGreaterThan(0); + expect(counts.reads).toBeGreaterThan(0); + expect(counts.reads).toBeLessThanOrEqual(counts.frames); + } finally { + await story.close(); + } +}); + +test('a drop measures the rows in one pass, before its writes, whatever their count', async ({ + browser, + browserName, +}) => { + test.skip(browserName !== 'chromium', 'the layout trace is Chromium CDP'); + const story = await openFinePointerStory(browser, LONG_STORY); + try { + const {page} = story; + const order = await labels(page); + expect(order.length).toBeGreaterThanOrEqual(20); + const {at, rowHeight} = await handleOf(page, order[3]); + await page.mouse.move(at.x, at.y); + await page.mouse.down(); + await page.mouse.move(at.x, at.y + rowHeight * 4.5, {steps: 12}); + await expect(page.locator('[data-astryx-reorder-preview]')).toHaveCount(1); + const {passes, events, rounds} = await forcedPassesDuring( + browser, + page, + async () => { + await page.mouse.up(); + await expect.poll(async () => labels(page)).not.toEqual(order); + // The commit's rebase runs before the next frame. + await page.evaluate( + async () => + new Promise(resolve => { + requestAnimationFrame(() => requestAnimationFrame(resolve)); + }), + ); + }, + ); + // The trace saw the drop: its release, and the page's rendering after it. + expect(events.has('pointerup')).toBe(true); + expect(rounds).toBeGreaterThan(0); + // The reorder's own reads, in the drop and in its commit, are one + // measurement pass at most. Moving the focused row makes React and the + // browser force passes of their own, outside the reorder. + const reorders = passesUnder(passes, ['drop', 'commit']); + expect(reorders.length, describePasses(passes)).toBeLessThanOrEqual(1); + } finally { + await story.close(); + } +}); + +test('a row held near the bottom of a box the list scrolls in scrolls that box, not the page', async ({ + browser, +}) => { + const story = await openFinePointerStory(browser, LONG_STORY); + try { + const {page} = story; + // The list scrolls in a 400 px box instead of the page. + const boxBottom = await page.evaluate(() => { + const root = document.querySelector('#storybook-root'); + if (root == null) { + return null; + } + root.style.blockSize = '400px'; + root.style.overflowY = 'auto'; + return ( + root.getBoundingClientRect().top + root.clientTop + root.clientHeight + ); + }); + expect(boxBottom).not.toBeNull(); + const order = await labels(page); + // Item 4: an earlier one's name is a prefix of a later row's. + const {at} = await handleOf(page, order[3]); + await page.mouse.move(at.x, at.y); + await page.mouse.down(); + await page.mouse.move(at.x, (boxBottom ?? 0) - 4, {steps: 12}); + await expect + .poll( + async () => + page.evaluate( + () => document.querySelector('#storybook-root')?.scrollTop ?? 0, + ), + {timeout: 3000}, + ) + .toBeGreaterThan(0); + expect(await page.evaluate(() => window.scrollY)).toBe(0); + await page.keyboard.press('Escape'); + await page.mouse.up(); + } finally { + await story.close(); + } +}); + +test('a checked radio in the dragged row stays checked through the drag and a drop in place', async ({ + browser, +}) => { + const story = await openFinePointerStory(browser); + try { + const {page} = story; + // Each row holds a radio of one group, and the first row's is checked. + await page.evaluate(() => { + const rows = document.querySelectorAll('#storybook-root ul > li'); + rows.forEach((row, index) => { + const radio = document.createElement('input'); + radio.type = 'radio'; + radio.name = 'pick'; + radio.value = String(index); + radio.checked = index === 0; + row.append(radio); + }); + }); + const checked = async () => + page.evaluate(() => + Array.from( + document.querySelectorAll( + '#storybook-root ul > li:not([data-astryx-leaving]) input[type="radio"]', + ), + radio => radio.checked, + ), + ); + const order = await labels(page); + const {at, rowHeight} = await handleOf(page, order[0]); + await page.mouse.move(at.x, at.y); + await page.mouse.down(); + await page.mouse.move(at.x, at.y + rowHeight * 0.4, {steps: 4}); + await expect(page.locator('[data-astryx-reorder-preview]')).toHaveCount(1); + const during = await checked(); + // Back to its place, and dropped there. + await page.mouse.move(at.x, at.y, {steps: 4}); + await page.mouse.up(); + await expect(page.locator('[data-astryx-reorder-preview]')).toHaveCount(0); + const after = await checked(); + expect(await labels(page)).toEqual(order); + expect(during[0], 'during the drag').toBe(true); + expect(after[0], 'after the drop').toBe(true); + expect(after.filter(Boolean)).toHaveLength(1); + } finally { + await story.close(); + } +}); + +for (const dir of ['ltr', 'rtl'] as const) { + test(`${dir}: the preview and the insertion line run along a dragged row set in from the list's start`, async ({ + browser, + }) => { + const story = await openFinePointerStory(browser); + try { + const {page} = story; + // Each row is set in 32 px from the list's inline start. + await page.evaluate(direction => { + const list = document.querySelector('#storybook-root ul'); + if (list == null) { + return; + } + list.dir = direction; + for (const row of Array.from(list.children)) { + (row as HTMLElement).style.marginInlineStart = '32px'; + } + }, dir); + const before = await labels(page); + const {at, rowHeight} = await handleOf(page, before[0]); + await page.mouse.move(at.x, at.y); + await page.mouse.down(); + await page.mouse.move(at.x, at.y + rowHeight * 1.5, {steps: 8}); + const edges = await page.evaluate(() => { + const list = document.querySelector('#storybook-root ul'); + const row = document.querySelector( + '#storybook-root [data-astryx-reorder-source]', + ); + const preview = document.querySelector( + '#storybook-root [data-astryx-reorder-preview]', + ); + if (list == null || row == null || preview == null) { + return null; + } + const after = getComputedStyle(list, '::after'); + const listBox = list.getBoundingClientRect(); + const start = parseFloat(after.insetInlineStart); + const width = parseFloat(after.width); + // The line's own edges in the viewport, from its inline start. + const lineLeft = + list.dir === 'rtl' + ? listBox.right - list.clientLeft - start - width + : listBox.left + list.clientLeft + start; + const rowBox = row.getBoundingClientRect(); + const previewBox = preview.getBoundingClientRect(); + return { + row: [rowBox.left, rowBox.right], + preview: [previewBox.left, previewBox.right], + line: [lineLeft, lineLeft + width], + }; + }); + await page.keyboard.press('Escape'); + await page.mouse.up(); + expect(edges).not.toBeNull(); + for (const part of ['preview', 'line'] as const) { + const [left, right] = edges?.[part] ?? [NaN, NaN]; + const [rowLeft, rowRight] = edges?.row ?? [NaN, NaN]; + expect(Math.abs(left - rowLeft), `${part} left`).toBeLessThan(1); + expect(Math.abs(right - rowRight), `${part} right`).toBeLessThan(1); + } + } finally { + await story.close(); + } + }); +} + +for (const dir of ['ltr', 'rtl'] as const) { + test(`${dir}: the insertion line runs along the dragged row in a list set in from its container`, async ({ + browser, + }) => { + const story = await openFinePointerStory(browser); + try { + const {page} = story; + // The list sits 40 px in from its container, which stays its offset + // parent until a drag positions the list. + await page.evaluate(direction => { + const list = document.querySelector('#storybook-root ul'); + if (list != null) { + list.dir = direction; + list.style.marginInlineStart = '40px'; + } + }, dir); + const before = await labels(page); + const {at, rowHeight} = await handleOf(page, before[0]); + await page.mouse.move(at.x, at.y); + await page.mouse.down(); + await page.mouse.move(at.x, at.y + rowHeight * 1.5, {steps: 8}); + const line = await page.evaluate(() => { + const list = document.querySelector('#storybook-root ul'); + const row = document.querySelector( + '#storybook-root [data-astryx-reorder-source]', + ); + if (list == null || row == null) { + return null; + } + const after = getComputedStyle(list, '::after'); + const listBox = list.getBoundingClientRect(); + const rowBox = row.getBoundingClientRect(); + const start = parseFloat(after.insetInlineStart); + const width = parseFloat(after.width); + // The line's own edges in the viewport, from its inline start. + const left = + list.dir === 'rtl' + ? listBox.right - list.clientLeft - start - width + : listBox.left + list.clientLeft + start; + return { + left, + right: left + width, + rowLeft: rowBox.left, + rowRight: rowBox.right, + }; + }); + await page.keyboard.press('Escape'); + await page.mouse.up(); + expect(line).not.toBeNull(); + expect( + Math.abs((line?.left ?? NaN) - (line?.rowLeft ?? NaN)), + ).toBeLessThan(1); + expect( + Math.abs((line?.right ?? NaN) - (line?.rowRight ?? NaN)), + ).toBeLessThan(1); + } finally { + await story.close(); + } + }); +} + +test('a pen drags a row from its handle at once, as a mouse does, where the primary pointer is fine', async ({ + browser, +}) => { + const story = await openFinePointerStory(browser); + try { + const {page} = story; + const driver = await webInputDriver(page); + test.skip(!driver.pens, PEN_SKIP); + const before = await labels(page); + expect(before.length).toBeGreaterThanOrEqual(3); + const {at, rowHeight} = await handleOf(page, before[0]); + await driver.pen(strokeDown(at, rowHeight * 2.5)); + await expect.poll(async () => labels(page)).toEqual(movedTwoDown(before)); + } finally { + await story.close(); + } +}); + +test('a pen keeps the hold where the primary pointer is coarse: a quick stroke moves nothing, and a held one moves the row', async ({ + page, +}) => { + await openStory(page, storybook(), STORY); + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(true); + const driver = await webInputDriver(page); + test.skip(!driver.pens, PEN_SKIP); + const before = await labels(page); + expect(before.length).toBeGreaterThanOrEqual(3); + const {at, rowHeight} = await handleOf(page, before[0]); + await driver.pen(strokeDown(at, rowHeight * 2.5)); + await page.waitForTimeout(300); + expect(await labels(page)).toEqual(before); + // The same stroke, after the pen rests on the handle past the claim delay. + await driver.pen([ + {x: at.x, y: at.y, t: 0}, + ...strokeDown(at, rowHeight * 2.5, HOLD_MS), + ]); + await expect.poll(async () => labels(page)).toEqual(movedTwoDown(before)); +}); diff --git a/packages/core/src/List/__tests__/ListReorderSelectionLock.test.tsx b/packages/core/src/List/__tests__/ListReorderSelectionLock.test.tsx new file mode 100644 index 0000000000000..813b4b8449c14 --- /dev/null +++ b/packages/core/src/List/__tests__/ListReorderSelectionLock.test.tsx @@ -0,0 +1,114 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file ListReorderSelectionLock.test.tsx + * @input A reorderable List (createReorderable), the iOS WebKit query + * stubbed per test, Testing Library + * @output jsdom proofs that a finger held on a reorder handle locks text + * selection on the whole list from its touch-down until it lifts. On iOS + * WebKit the lock writes the list's selection and callout styles; + * elsewhere it refuses `selectstart`. A mouse press never locks + * @position Tests for List/ListReorderTouch.ts's selection lock + */ + +import {afterEach, describe, expect, it, vi} from 'vitest'; +import {fireEvent, render, screen} from '@testing-library/react'; +import {List} from '../List'; +import {ListItem} from '../ListItem'; +import {createReorderable} from '../../reorderable/createReorderable'; +import type * as TouchQueries from '../../utils/touchQueries'; + +const ios = vi.hoisted(() => ({value: false})); + +vi.mock('../../utils/touchQueries', async importOriginal => ({ + ...(await importOriginal()), + isIosWebKit: () => ios.value, +})); + +const ITEMS = ['Inbox', 'Sent', 'Drafts']; + +function Rows() { + const reorderable = createReorderable({onReorder: () => {}}); + return ( + + {ITEMS.map(item => ( + + ))} + + ); +} + +const FINGER = { + pointerType: 'touch', + pointerId: 7, + button: 0, + clientX: 280, + clientY: 320, +}; +const MOUSE = {...FINGER, pointerType: 'mouse', pointerId: 1}; + +const handleOf = (label: string) => + screen.getByRole('button', {name: `Reorder ${label}`}); + +/** Whether a selection that starts on the row's label is refused. */ +function refusesSelection(label: string): boolean { + const event = new Event('selectstart', {bubbles: true, cancelable: true}); + screen.getByText(label).dispatchEvent(event); + return event.defaultPrevented; +} + +afterEach(() => { + ios.value = false; +}); + +describe('a reorderable List under a held finger', () => { + it("writes the list's selection and callout styles on iOS WebKit from the touch-down on a handle until the lift", () => { + ios.value = true; + render(); + const list = screen.getByRole('list'); + const setProperty = vi.spyOn(list.style, 'setProperty'); + const removeProperty = vi.spyOn(list.style, 'removeProperty'); + fireEvent.pointerDown(handleOf('Sent'), FINGER); + for (const name of [ + '-webkit-touch-callout', + '-webkit-user-select', + 'user-select', + ]) { + expect(setProperty).toHaveBeenCalledWith(name, 'none'); + } + expect(removeProperty).not.toHaveBeenCalled(); + fireEvent.pointerUp(handleOf('Sent'), FINGER); + for (const name of [ + '-webkit-touch-callout', + '-webkit-user-select', + 'user-select', + ]) { + expect(removeProperty).toHaveBeenCalledWith(name); + } + }); + + it('refuses a selection on any row elsewhere from the touch-down on a handle until the lift, and a cancel ends it too', () => { + render(); + expect(refusesSelection('Inbox')).toBe(false); + fireEvent.pointerDown(handleOf('Sent'), FINGER); + // The row beside the held handle too: the lock covers the whole list. + expect(refusesSelection('Inbox')).toBe(true); + expect(refusesSelection('Drafts')).toBe(true); + fireEvent.pointerUp(handleOf('Sent'), FINGER); + expect(refusesSelection('Inbox')).toBe(false); + fireEvent.pointerDown(handleOf('Sent'), FINGER); + expect(refusesSelection('Inbox')).toBe(true); + fireEvent.pointerCancel(handleOf('Sent'), FINGER); + expect(refusesSelection('Inbox')).toBe(false); + }); + + it('takes no lock for a mouse press on a handle, nor for a finger on a row away from its handle', () => { + render(); + fireEvent.pointerDown(handleOf('Sent'), MOUSE); + expect(refusesSelection('Inbox')).toBe(false); + fireEvent.pointerUp(handleOf('Sent'), MOUSE); + fireEvent.pointerDown(screen.getByText('Sent'), FINGER); + expect(refusesSelection('Inbox')).toBe(false); + fireEvent.pointerUp(screen.getByText('Sent'), FINGER); + }); +}); diff --git a/packages/core/src/List/__tests__/ListReorderTouch.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListReorderTouch.interaction.browser.spec.ts new file mode 100644 index 0000000000000..ccef259b76342 --- /dev/null +++ b/packages/core/src/List/__tests__/ListReorderTouch.interaction.browser.spec.ts @@ -0,0 +1,687 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file ListReorderTouch.interaction.browser.spec.ts + * @input The built List reorder stories and real touch input through the + * interaction harness (Chromium CDP or WebKit's input command). Also the + * claim delay from the UIKit constants table (motion/uikit/reorder.ts) + * @output Interaction proofs for a reorderable List under a finger. A hold on + * a handle then a drag moves the row, and the drop settles it into its new + * place. While the finger holds the drag, the rows stay still, the source + * dims, a preview follows and an insertion line marks the drop position. A + * flick on a handle scrolls and moves nothing. A cancelled drag puts the + * row back. With Reduce Motion the drop takes its place without travel. A + * flush row's handle stays inside the list. A finger held on a handle + * refuses text selection on the list until it lifts. A drag that crosses + * rows forces no style or layout pass, and neither does the pick-up. A + * drop measures the rows in one pass, before their glides start + * @position Interaction evidence for List's reorder (List/listReorderEngine.tsx, + * List/ListReorderTouch.ts, List/ListReorderHandle.tsx) in the touch phone + * context + */ + +import { + expect, + test, + type CDPSession, + type Page, +} from '@astryxdesign/a11y-spec/playwright'; +import { + flick, + holdThenDrag, + openStory, + toTouchEvents, + touchDriver, + withStorybook, +} from '@astryxdesign/interaction-harness'; +import {solveSpring, toSpring} from '../../motion/spring'; +import {reorder} from '../../motion/uikit/reorder'; +import {springs} from '../../motion/uikit/springs'; +import {describePasses, forcedPassesDuring, passesUnder} from './forcedPasses'; + +const storybook = withStorybook(test); + +/** Past the claim delay: the hold claims the drag. */ +const HOLD_MS = reorder.claim.delayMs + 150; +/** + * Long enough for a drop's glide to settle: it plays the shared settle role, + * springs.settle (spec:AST-105 FR4). + */ +const SETTLE_MS = + solveSpring(toSpring(springs.settle), {from: 0, to: 1}).settleTime(0.001) * + 1000 + + 300; + +const isTouch = async (page: Page) => + page.evaluate(() => matchMedia('(pointer: coarse)').matches); + +/** The story's row labels, in order. */ +async function labels(page: Page): Promise { + 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('picking a row up forces no style or layout pass before its first frame', async ({ + page, + browser, + browserName, + }) => { + test.skip( + browserName !== 'chromium', + 'the layout trace and the held finger go through Chromium CDP', + ); + const {at} = await handleOf(page, 'Inbox'); + const cdp = await page.context().newCDPSession(page); + const touch = async ( + type: 'touchStart' | 'touchMove' | 'touchEnd', + y?: number, + ) => + cdp.send('Input.dispatchTouchEvent', { + type, + touchPoints: + y == null + ? [] + : [{x: at.x, y, id: 1, radiusX: 1, radiusY: 1, force: 1}], + }); + await touch('touchStart', at.y); + // The trace starts after the touch lands, and before the hold picks the + // row up. + await browser.startTracing(page, { + categories: [ + 'devtools.timeline', + 'disabled-by-default-devtools.timeline', + 'disabled-by-default-devtools.timeline.stack', + ], + }); + await page.waitForTimeout(HOLD_MS); + await touch('touchMove', at.y + 4); + await expect(page.locator('[data-astryx-reorder-preview]')).toHaveCount(1); + await page.waitForTimeout(100); + const trace = JSON.parse((await browser.stopTracing()).toString()) as { + traceEvents: { + name: string; + ph: string; + pid: number; + tid: number; + args?: { + name?: string; + beginData?: {stackTrace?: {functionName?: string}[]}; + }; + }[]; + }; + await touch('touchEnd'); + await page.waitForTimeout(SETTLE_MS); + const mainThreads = new Set( + trace.traceEvents + .filter(e => e.ph === 'M' && e.name === 'thread_name') + .filter(e => e.args?.name === 'CrRendererMain') + .map(e => `${e.pid}:${e.tid}`), + ); + // A style or layout pass with a script stack ran inside script: a read + // after a write forced it, instead of the frame's own pass. + const forced = trace.traceEvents.filter( + e => + (e.name === 'Layout' || e.name === 'UpdateLayoutTree') && + mainThreads.has(`${e.pid}:${e.tid}`) && + (e.args?.beginData?.stackTrace ?? []).length > 0, + ); + expect( + forced.map( + e => + `${e.name} in ${e.args?.beginData?.stackTrace?.[0]?.functionName ?? '?'}`, + ), + ).toEqual([]); + }); + + test('a drag forces no style or layout pass as it crosses rows', async ({ + page, + browser, + browserName, + }) => { + test.skip( + browserName !== 'chromium', + 'the layout trace and the held finger go through Chromium CDP', + ); + const {at, rowHeight} = await handleOf(page, 'Inbox'); + const cdp = await page.context().newCDPSession(page); + const touch = async ( + type: 'touchStart' | 'touchMove' | 'touchEnd', + y?: number, + ) => + cdp.send('Input.dispatchTouchEvent', { + type, + touchPoints: + y == null + ? [] + : [{x: at.x, y, id: 1, radiusX: 1, radiusY: 1, force: 1}], + }); + await touch('touchStart', at.y); + await page.waitForTimeout(HOLD_MS); + await touch('touchMove', at.y + 4); + await expect(page.locator('[data-astryx-reorder-preview]')).toHaveCount(1); + // Only the crossings are traced: the pick-up reads the rows once. + await browser.startTracing(page, { + categories: [ + 'devtools.timeline', + 'disabled-by-default-devtools.timeline', + 'disabled-by-default-devtools.timeline.stack', + ], + }); + for (let step = 1; step <= 24; step += 1) { + await touch('touchMove', at.y + 4 + (rowHeight * 3 * step) / 24); + await page.waitForTimeout(16); + } + await page.waitForTimeout(150); + const trace = JSON.parse((await browser.stopTracing()).toString()) as { + traceEvents: { + name: string; + ph: string; + pid: number; + tid: number; + args?: { + name?: string; + beginData?: {stackTrace?: {functionName?: string}[]}; + }; + }[]; + }; + await touch('touchEnd'); + await page.waitForTimeout(SETTLE_MS); + const mainThreads = new Set( + trace.traceEvents + .filter(e => e.ph === 'M' && e.name === 'thread_name') + .filter(e => e.args?.name === 'CrRendererMain') + .map(e => `${e.pid}:${e.tid}`), + ); + // A style or layout pass with a script stack ran inside script: a read + // after a write forced it, instead of the frame's own pass. + const forced = trace.traceEvents.filter( + e => + (e.name === 'Layout' || e.name === 'UpdateLayoutTree') && + mainThreads.has(`${e.pid}:${e.tid}`) && + (e.args?.beginData?.stackTrace ?? []).length > 0, + ); + expect( + forced.map( + e => + `${e.name} in ${e.args?.beginData?.stackTrace?.[0]?.functionName ?? '?'}`, + ), + ).toEqual([]); + // The drag did cross: Inbox lands three rows down. + expect((await labels(page)).indexOf('Inbox')).toBe(3); + }); + + test('a drop measures the rows in one pass, before their glides start', async ({ + page, + browser, + browserName, + }) => { + test.skip(browserName !== 'chromium', 'the layout trace is Chromium CDP'); + const {at, rowHeight} = await handleOf(page, 'Inbox'); + const driver = await touchDriver(page); + const {passes, events, rounds} = await forcedPassesDuring( + browser, + page, + async () => { + await driver.play( + holdThenDrag( + at, + {x: at.x, y: at.y + rowHeight * 3}, + {holdMs: HOLD_MS, durationMs: 400, restMs: 120}, + ), + ); + await expect.poll(async () => (await labels(page))[0]).toBe('Sent'); + // The commit's glides start before the next frame. + await page.evaluate( + async () => + new Promise(resolve => { + requestAnimationFrame(() => requestAnimationFrame(resolve)); + }), + ); + }, + ); + // The trace saw the drop: the finger's lift, and the rendering after it. + expect(events.has('pointerup')).toBe(true); + expect(rounds).toBeGreaterThan(0); + // The drop's own reads, in the drop and in the commit that applies it, + // are one measurement pass at most. + expect( + passesUnder(passes, ['drop', 'commit']).length, + describePasses(passes), + ).toBeLessThanOrEqual(1); + }); + + test('a cancelled drag puts the row back and moves nothing', async ({ + page, + browserName, + }) => { + test.skip( + browserName !== 'chromium', + 'the cancel is a touchcancel through Chromium CDP', + ); + const before = await settledTops(page); + const {at, rowHeight} = await handleOf(page, 'Inbox'); + // The cancel comes when the lift would have. + const cdp = await holdAndDragWithoutLift(page, at, { + x: at.x, + y: at.y + rowHeight * 2, + }); + await cdp.send('Input.dispatchTouchEvent', { + type: 'touchCancel', + touchPoints: [], + }); + await page.waitForTimeout(SETTLE_MS); + expect(await labels(page)).toEqual([ + 'Inbox', + 'Sent', + 'Drafts', + 'Archive', + 'Spam', + 'Trash', + ]); + expect((await settledTops(page)).Inbox).toBe(before.Inbox); + }); + + test('with Reduce Motion the drop takes its place without travel', async ({ + page, + }) => { + await page.emulateMedia({reducedMotion: 'reduce'}); + const before = await settledTops(page); + const {at, rowHeight} = await handleOf(page, 'Inbox'); + const driver = await touchDriver(page); + await driver.play( + holdThenDrag( + at, + {x: at.x, y: at.y + rowHeight * 2}, + {holdMs: HOLD_MS, durationMs: 400, restMs: 120}, + ), + ); + // Two frames after the lift: already in place, nothing travelling. + await page.evaluate( + async () => + new Promise(resolve => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ), + ); + expect(await labels(page)).toEqual([ + 'Sent', + 'Drafts', + 'Inbox', + 'Archive', + 'Spam', + 'Trash', + ]); + expect((await settledTops(page)).Inbox).toBe(before.Drafts); + // Nothing travels. A running animation may only fade: the rows the drop + // passed take Reduce Motion's opacity dip in their new places + // (design:reduced-motion), and none moves. + expect( + await page + .locator('#storybook-root li') + .evaluateAll(rows => + rows.some(row => + row + .getAnimations({subtree: true}) + .some( + animation => + animation.playState === 'running' && + animation.effect instanceof KeyframeEffect && + animation.effect + .getKeyframes() + .some(frame => + ['translate', 'transform', 'top', 'insetBlockStart'].some( + property => frame[property] != null, + ), + ), + ), + ), + ), + ).toBe(false); + }); +}); + +test.describe('a row that reorders and has a menu', () => { + test.beforeEach(async ({page, browserName}) => { + await openStory(page, storybook(), 'core-list--reorder-from-your-ui'); + test.skip( + !(await isTouch(page)), + 'this engine reports a fine primary pointer; the touch hold applies under (pointer: coarse)', + ); + test.skip( + browserName !== 'chromium', + 'the held finger lifts through Chromium CDP', + ); + }); + + /** A finger held still at `at` for `ms`, read while it is down, then lifted. */ + async function holdStill( + page: Page, + at: {x: number; y: number}, + ms: number, + ): Promise<{picked: boolean; menu: boolean}> { + const cdp = await page.context().newCDPSession(page); + await cdp.send('Input.dispatchTouchEvent', { + type: 'touchStart', + touchPoints: [ + {x: at.x, y: at.y, id: 0, radiusX: 1, radiusY: 1, force: 1}, + ], + }); + await page.waitForTimeout(ms); + const held = await page.evaluate(() => ({ + picked: document.querySelector('[data-astryx-reorder-preview]') != null, + menu: Array.from(document.querySelectorAll('[role="menu"]')).some( + element => element.getBoundingClientRect().height > 0, + ), + })); + await cdp.send('Input.dispatchTouchEvent', { + type: 'touchEnd', + touchPoints: [], + }); + return held; + } + + const menuShown = async (page: Page) => + page.evaluate(() => + Array.from(document.querySelectorAll('[role="menu"]')).some( + element => element.getBoundingClientRect().height > 0, + ), + ); + + test('a finger held on a handle refuses a text selection on the list from its touch-down until it lifts', async ({ + page, + browserName, + }) => { + test.skip( + browserName !== 'chromium', + 'the held finger lifts through Chromium CDP', + ); + const {at} = await handleOf(page, 'Inbox'); + // A selection that starts on another row: the lock covers the whole list. + const refused = async () => + page.evaluate(() => { + const row = Array.from( + document.querySelectorAll('#storybook-root li'), + ).find(element => element.textContent?.trim() === 'Sent'); + const event = new Event('selectstart', { + bubbles: true, + cancelable: true, + }); + row?.dispatchEvent(event); + return event.defaultPrevented; + }); + expect(await refused()).toBe(false); + const cdp = await page.context().newCDPSession(page); + await cdp.send('Input.dispatchTouchEvent', { + type: 'touchStart', + touchPoints: [ + {x: at.x, y: at.y, id: 0, radiusX: 1, radiusY: 1, force: 1}, + ], + }); + // Before the hold claims the drag, as when iOS starts its own selection. + expect(await refused()).toBe(true); + await page.waitForTimeout(HOLD_MS); + expect(await refused()).toBe(true); + await cdp.send('Input.dispatchTouchEvent', { + type: 'touchEnd', + touchPoints: [], + }); + await page.waitForTimeout(SETTLE_MS); + expect(await refused()).toBe(false); + }); + + test('a hold on the reorder handle picks the row up and opens no menu', async ({ + page, + }) => { + const order = await labels(page); + const {at} = await handleOf(page, 'Inbox'); + // Held still past the row menu's long press (500 ms). + const held = await holdStill(page, at, 800); + expect(held.picked).toBe(true); + expect(held.menu).toBe(false); + await page.waitForTimeout(SETTLE_MS); + expect(await menuShown(page)).toBe(false); + expect(await labels(page)).toEqual(order); + }); + + test('a hold anywhere else on the row opens its menu and picks nothing up', async ({ + page, + }) => { + const row = page + .locator('#storybook-root li:not([data-astryx-leaving])') + .filter({hasText: 'Inbox'}) + .first(); + const box = await row.boundingBox(); + if (box == null) { + throw new Error('no row'); + } + const held = await holdStill( + page, + {x: box.x + 40, y: box.y + box.height / 2}, + 800, + ); + expect(held.picked).toBe(false); + expect(held.menu).toBe(true); + await page.keyboard.press('Escape'); + }); +}); + +test('a flick on a handle scrolls the page and moves nothing', async ({ + page, +}) => { + await openStory(page, storybook(), 'core-list--reorder-long-list'); + test.skip( + !(await isTouch(page)), + 'this engine reports a fine primary pointer; the touch hold applies under (pointer: coarse)', + ); + const order = await labels(page); + const {at} = await handleOf(page, 'Item 8'); + const driver = await touchDriver(page); + test.skip( + !driver.drivesNativeGestures, + "this engine's injected touches drive no native scroll (the harness's drivesNativeGestures)", + ); + const scrolled = await page.evaluate(() => window.scrollY); + await driver.play(flick(at, {velocity: {x: 0, y: -1500}})); + await page.waitForTimeout(SETTLE_MS); + expect(await page.evaluate(() => window.scrollY)).toBeGreaterThan(scrolled); + expect(await labels(page)).toEqual(order); +}); + +test('a flush row keeps its handle inside the list', async ({page}) => { + await openStory(page, storybook(), 'core-list--reorder-flush'); + const handle = page.getByRole('button', {name: 'Reorder Inbox'}); + await expect(handle).toBeVisible(); + const [handleBox, listBox] = await Promise.all([ + handle.boundingBox(), + page.locator('#storybook-root ul').first().boundingBox(), + ]); + if (handleBox == null || listBox == null) { + throw new Error('no handle or list'); + } + expect(handleBox.x + handleBox.width).toBeLessThanOrEqual( + listBox.x + listBox.width + 0.5, + ); +}); diff --git a/packages/core/src/List/__tests__/forcedPasses.ts b/packages/core/src/List/__tests__/forcedPasses.ts new file mode 100644 index 0000000000000..3d575f6b06a54 --- /dev/null +++ b/packages/core/src/List/__tests__/forcedPasses.ts @@ -0,0 +1,174 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file forcedPasses.ts + * @input A Chromium page, its browser, and an action to trace + * @output `forcedPassesDuring`: the measurement passes that script forced + * while the action ran, each with the functions and sources on its stack. + * Also the DOM events dispatched and every style and layout round, so a + * case can show the trace saw the action + * @position A helper for the List reorder interaction specs, in Chromium, + * the engine with a rendering trace + */ + +import type {Browser, Page} from '@astryxdesign/a11y-spec/playwright'; + +interface StackFrame { + functionName?: string; + url?: string; + lineNumber?: number; + columnNumber?: number; +} + +interface TraceEvent { + name: string; + ph: string; + pid: number; + tid: number; + ts?: number; + args?: { + name?: string; + beginData?: {stackTrace?: StackFrame[]}; + data?: {stackTrace?: StackFrame[]; type?: string}; + }; +} + +/** + * The style and layout work one read forced. One read can run several + * rounds of both, for example when anchored elements are laid out again. + */ +export interface ForcedPass { + /** Each round, in order: `UpdateLayoutTree` or `Layout`. */ + readonly rounds: ReadonlyArray; + /** The functions on the reading script's stack, innermost first. */ + readonly frames: ReadonlyArray; + /** The script source of each of those functions. */ + readonly sources: ReadonlyArray; +} + +const FORCED = new Set(['Layout', 'UpdateLayoutTree']); +const INVALIDATIONS = new Set([ + 'ScheduleStyleRecalculation', + 'InvalidateLayout', +]); + +const keyOf = (stack: ReadonlyArray) => + stack + .map( + frame => + `${frame.functionName}@${frame.url}:${frame.lineNumber}:${frame.columnNumber}`, + ) + .join(' < '); + +/** What the trace of an action saw on the page's main thread. */ +export interface ActionTrace { + /** The measurement passes that script forced. */ + readonly passes: ForcedPass[]; + /** The type of each DOM event dispatched, such as `pointerup`. */ + readonly events: ReadonlySet; + /** Every style and layout round, forced or not. */ + readonly rounds: number; +} + +/** + * Traces `action`, then returns each measurement pass that script forced on + * the page's main thread. A round with the reading script's stack is forced. + * A round joins the pass before it when the same read caused it: same + * stack, and no write from another stack in between. + */ +export async function forcedPassesDuring( + browser: Browser, + page: Page, + action: () => Promise, +): Promise { + await browser.startTracing(page, { + categories: [ + 'devtools.timeline', + 'disabled-by-default-devtools.timeline', + 'disabled-by-default-devtools.timeline.stack', + ], + }); + let buffer: Buffer | undefined; + try { + await action(); + } finally { + buffer = await browser.stopTracing(); + } + const {traceEvents} = JSON.parse(String(buffer)) as { + traceEvents: TraceEvent[]; + }; + const mainThreads = new Set( + traceEvents + .filter(e => e.ph === 'M' && e.name === 'thread_name') + .filter(e => e.args?.name === 'CrRendererMain') + .map(e => `${e.pid}:${e.tid}`), + ); + const events = traceEvents + .filter(e => mainThreads.has(`${e.pid}:${e.tid}`) && e.ts != null) + .sort((a, b) => (a.ts ?? 0) - (b.ts ?? 0)); + const passes: (ForcedPass & {key: string; rounds: string[]})[] = []; + const dispatched = new Set(); + let rounds = 0; + let wroteSince = false; + for (const e of events) { + if (e.name === 'EventDispatch' && e.args?.data?.type != null) { + dispatched.add(e.args.data.type); + } + if (FORCED.has(e.name)) { + rounds += 1; + } + if (INVALIDATIONS.has(e.name)) { + const stack = e.args?.data?.stackTrace ?? []; + if (stack.length > 0 && keyOf(stack) !== passes[passes.length - 1]?.key) { + wroteSince = true; + } + continue; + } + const stack = e.args?.beginData?.stackTrace ?? []; + if (!FORCED.has(e.name) || stack.length === 0) { + continue; + } + const key = keyOf(stack); + const last = passes[passes.length - 1]; + if (last != null && last.key === key && !wroteSince) { + last.rounds.push(e.name); + continue; + } + passes.push({ + key, + rounds: [e.name], + frames: stack.map(frame => frame.functionName ?? ''), + sources: stack.map(frame => frame.url ?? ''), + }); + wroteSince = false; + } + return { + passes: passes.map(pass => ({ + rounds: pass.rounds, + frames: pass.frames, + sources: pass.sources, + })), + events: dispatched, + rounds, + }; +} + +/** The passes forced under one of `functions`. */ +export function passesUnder( + passes: ReadonlyArray, + functions: ReadonlyArray, +): ForcedPass[] { + return passes.filter(pass => + pass.frames.some(frame => functions.includes(frame)), + ); +} + +/** One line per pass, for an assertion's message. */ +export function describePasses(passes: ReadonlyArray): string { + return passes + .map( + pass => + `${pass.rounds.join('+')} in ${pass.frames.slice(0, 4).join(' < ')}`, + ) + .join('; '); +} diff --git a/packages/core/src/List/__tests__/reorderModel.test.ts b/packages/core/src/List/__tests__/reorderModel.test.ts new file mode 100644 index 0000000000000..67082c6149630 --- /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..50e675cb83188 --- /dev/null +++ b/packages/core/src/List/listReorderEngine.tsx @@ -0,0 +1,2334 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file listReorderEngine.tsx + * @input A List's element and its reorderable object's options, through + * List/listReorderContext.ts. Also the reorder model (List/reorderModel.ts), + * the touch layer (List/ListReorderTouch.ts) and the row moves of + * utils/rowMotion.ts. Also the edge autoscroll, the touch presentation, + * the shared announcer, and the anchored hint that Core's keyboard hints + * share (hooks/anchoredHint.tsx) + * @output `listReorderEngine`, the machinery a reorderable object carries: + * the reorder session of a List, its Host and its handle. A drag from a + * handle leaves the rows in place. The row dims where it is, and a preview + * of it follows the pointer. An insertion line marks where it would land, + * and the list autoscrolls near the scroll edges. The drop reports the move + * once and the rows rearrange. The dragged row glides from where its + * preview was. A cancelled drag restores everything at once. Activating a + * handle without a drag turns on reorder mode for its row. Each arrow + * moves it a place at once, with one report, and announces its place and + * neighbours. Escape or another activation ends the mode, keeping the moves. + * While the mode is on, a hint anchored to the handle shows the moves and + * Done as buttons that do what the keys do + * @position Internal to the reorder. Only createReorderable imports it, so a + * List without `reorderable` loads none of it. ListReorderHandle drives it + * from each row's handle + * + * The drag's look follows the reorder design. The surrounding rows stay + * still until the drop, and the source is dimmed in place. A preview follows + * the pointer one to one, its centre stopping at the scroll view's edges. An + * accent insertion line, shared by pointer and keyboard, marks the candidate + * position. UIKit's edit-mode reorder (iOS 26.2, measured) supplies the + * clocks. They are the hold, the rows' glide to their new places after the + * drop, and autoscroll. Autoscroll is a 20 ms timer whose step grows with how + * far the preview's edge is past the scroll edge. With a mouse (the theme's + * presentation) or Reduce Motion, the rows jump to their new places. + * + * HOW IT RUNS. Everything after the drag begins is imperative: no React + * render and no layout read until the drop, but one. After a scroll the + * engine did not cause, a later frame reads the scroller's offset once, + * before it writes. The begin reads each row's + * layout once. Each move writes one `translate` on the preview, through the + * shared per-element animator's `set`. A position change writes one on the + * insertion line. The list root carries `data-astryx-reordering` from the + * begin until the commit that applies the drop. So the List's layout updates + * (List/listLayoutUpdates.ts) leave that commit to the reorder. After it, + * each row's old layout place is put back with an inverse offset that glides + * to 0. For the dragged row, that is where its preview was dropped. The + * commit reads every row before its first write, so it lays out once. If + * `onReorder` does not commit a new order by the end of the task, nothing + * moves. Reorder mode reports each key's move at once. Once it commits, + * under a finger's presentation, the rows slide to their new places. The + * listeners are the list's, not each row's. There is one pointerdown + * listener for a mouse, and for a pen where the primary pointer is fine. + * There is one hold recognizer for a finger, and for a pen where the primary + * pointer is coarse. It receives only the touches that begin on this list's + * handles. A row moves when it holds a handle registered here with + * its item key. The others keep their places, and those at either end bound + * the rest. What runs only on a touch screen is in ListReorderTouch.ts, + * imported here alone. + * + * SYNC: When modified, update List/listReorderContext.ts, List/List.tsx, + * List/ListReorderHandle.tsx and List/ListReorderTouch.ts. + */ + +import { + useRef, + useSyncExternalStore, + type Key, + type KeyboardEvent, + type ReactNode, +} from 'react'; +import * as stylex from '@stylexjs/stylex'; +import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; +import { + useAnnounce, + type AnnounceFn, + type AnnouncePoliteness, +} from '../hooks/useAnnounce'; +import type {TranslatorFn} from '../i18n/useTranslator'; +import { + registerEnglishFallback, + useComponentTranslator, +} from '../i18n/useComponentTranslator'; +import english from '../i18n/generated-english/List/listReorderEngine.generated'; +import {useLayer} from '../Layer/useLayer'; +import {useLayerDismissal} from '../Layer/useLayerDismissal'; +import {Kbd} from '../Kbd/Kbd'; +import {anchoredHintStyles, renderAnchoredHint} from '../hooks/anchoredHint'; +import {spacingVars} from '../theme/tokens.stylex'; +import {focusOutlineProps} from '../utils/focusOutline.stylex'; +import type {LongPressGestureRecognizer} from '../gestures/LongPressGestureRecognizer'; +import {VelocityTracker} from '../gestures/VelocityTracker'; +import {inertClone, paintedBackground} from '../motion/inertClone'; +import {reorder} from '../motion/uikit/reorder'; +import { + animatorFor, + isMoving, + motionNow, + motionOf, + releaseMotion, +} from '../utils/rowMotion'; +import {edgeAutoscroll, type EdgeAutoscroll} from '../utils/edgeAutoscroll'; +import {subscribeInput} from '../utils/inputStream'; +import {nearestScroller} from '../utils/scrollingAncestor'; +import {useTouchPresentation} from '../utils/touchPresentation'; +import {useTouchHitArea} from '../utils/touchHitArea'; +import {touchHitAreaStyles} from '../internal/touchHitArea.stylex'; +import {createDevWarnings, devWarn} from '../utils/devWarning'; +import {isLeaving, markLeaving} from '../privateAttributes/leaving.stylex'; +import { + closestReorderHandle, + reorderHandlesIn, +} from '../privateAttributes/listReorder.stylex'; +import { + clearReorderSource, + markReorderSource, +} from '../privateAttributes/reorderSource.stylex'; +import {markReorderPreview} from '../privateAttributes/reorderPreview.stylex'; +import { + hideReorderLine, + showReorderLine, +} from '../privateAttributes/reorderLine.stylex'; +import { + clearReordering, + isReordering, + markReordering, +} from '../privateAttributes/reordering.stylex'; +import { + INSERTION_LINE_THICKNESS, + ListReorderHandle, + ListReorderRowName, + reorderListStyle, + reorderRowStyle, +} from './ListReorderHandle'; +import {attachTouchHold, touchMotion} from './ListReorderTouch'; +import type { + ListReorderContextValue, + ListReorderEngine, + ListReorderOptions, + ListReorderSession, +} from './listReorderContext'; +import { + autoscrollStep, + clampTop, + dropPosition, + type ReorderGeometry, +} from './reorderModel'; + +registerEnglishFallback(english); + +/** + * A mouse's travel, in px, before its press drags the row: below it the + * press stays a click. A mouse shifts a pixel or two under the press of the + * button itself. The date wheel's mouse drag uses the same value + * (DateInput/usePointerDragScroll.ts `DRAG_SLOP`); a test keeps them equal. + */ +export const MOUSE_DRAG_SLOP = 4; + +/** Moves under half a pixel are layout noise. */ +const MIN_MOVE_PX = 0.5; + +/** + * How long after `start` the handle takes back the focus that the UI hands + * back, in ms. A menu restores its trigger's focus as it closes, within a + * task or two. No person moves the focus that fast. + */ +const START_FOCUS_CLAIM_MS = 150; + +/** + * The sessions each reorderable object (by its options) is mounted on, in + * the order they mounted: `start` uses the last. + */ +const sessionsByOptions = new WeakMap< + ListReorderOptions, + ListReorderController[] +>(); + +/** Records `controller` as mounted with `options`; returns the removal. */ +function mountSession( + options: ListReorderOptions, + controller: ListReorderController, +): () => void { + const sessions = sessionsByOptions.get(options) ?? []; + sessionsByOptions.set(options, [ + ...sessions.filter(session => session !== controller), + controller, + ]); + return () => { + const rest = (sessionsByOptions.get(options) ?? []).filter( + session => session !== controller, + ); + if (rest.length > 0) { + sessionsByOptions.set(options, rest); + } else { + sessionsByOptions.delete(options); + } + }; +} + +/** + * Where a row's `y` is on screen at `at`: its shared animator's value, which + * the drag writes directly (`set`) as well as through springs. + */ +function shownY(element: HTMLElement, at: number): number { + return animatorFor(element).get('y', at); +} + +/** + * Puts a row at rest at 0 at once. A row already at rest there takes no + * write. The animator's `set` reads the row's style back after its write, so + * one `set` per row forces a style pass per row. + */ +function settleAtRest( + element: HTMLElement, + value: number, + moving: boolean, +): void { + if (value !== 0 || moving) { + animatorFor(element).set({y: 0}); + } + releaseMotion(element, 'translate'); +} + +/** + * The list's rows: its element children. A removed row put back for its exit + * holds no place in the order, so it is left out (`markLeaving`). + */ +function rowsOf(list: HTMLElement): HTMLElement[] { + return Array.from(list.children).filter( + (child): child is HTMLElement => + child instanceof HTMLElement && !isLeaving(child), + ); +} + +/** + * Which rows bound the drop range: the rows that cannot move at either end + * of the list, each run of them. One in the middle is passed like any other + * row; it only has no handle. + */ +function boundsOf(movable: ReadonlyArray): boolean[] { + const bounds = movable.map(() => false); + for (let index = 0; index < movable.length && !movable[index]; index += 1) { + bounds[index] = true; + } + for ( + let index = movable.length - 1; + index >= 0 && !movable[index]; + index -= 1 + ) { + bounds[index] = true; + } + return bounds; +} + +/** + * The temporary reduced emphasis the dragged row and its preview share: + * the same item, moving, and + * not raised. + */ +const MOVING_OPACITY = '0.6'; + +/** + * An element the drag draws over the list: no row to the list's order or + * its layout updates (`markLeaving`), inert and hidden from assistive + * technology. + */ +function overlay(element: HTMLElement): HTMLElement { + markLeaving(element); + element.setAttribute('aria-hidden', 'true'); + element.inert = true; + Object.assign(element.style, { + position: 'absolute', + margin: '0', + pointerEvents: 'none', + zIndex: '2', + translate: '0px 0px', + }); + return element; +} + +/** + * A copy of `row` that takes no part in the page (`inertClone`). It has no + * ids, names or form, so a copied checked radio leaves the row's checked. A + * row holding a canvas that reads back empty is not copied: its bare box is. + */ +function previewCopyOf(row: HTMLElement): HTMLElement { + const copy = inertClone(row); + if (copy != null) { + return copy; + } + const box = row.cloneNode(false) as HTMLElement; + for (const name of ['id', 'data-testid', 'name', 'for', 'autofocus']) { + box.removeAttribute(name); + } + return box; +} + +/** + * Makes `preview`, a copy of the dragged row, its preview at its place, with + * the same reduced emphasis as the row and no elevation. It only writes. + */ +function previewOf( + preview: HTMLElement, + top: number, + span: LineSpan, + background: string | null, +) { + markReorderPreview(preview); + overlay(preview); + Object.assign(preview.style, { + top: `${top}px`, + insetInlineStart: `${span.start}px`, + inlineSize: `${span.size}px`, + boxSizing: 'border-box', + boxShadow: 'none', + opacity: MOVING_OPACITY, + // It moves by translate from its first move. With its own will-change, + // its animator reads no stylesheet to keep one. + willChange: 'translate', + }); + if (background != null) { + preview.style.backgroundColor = background; + } + return preview; +} + +/** The list's custom properties that place its insertion line. */ +const LINE_Y = '--astryx-reorder-line-y'; +const LINE_START = '--astryx-reorder-line-start'; +const LINE_SIZE = '--astryx-reorder-line-size'; + +/** + * Where the insertion line runs across a row, in list coordinates: its + * inline start and its size. + */ +interface LineSpan { + readonly start: number; + readonly size: number; +} + +/** + * An extent that starts `left` px from the list's left edge, as an inline + * start and size. In right-to-left, the start counts from the right edge. + */ +function inlineSpanOf(left: number, size: number, list: HTMLElement): LineSpan { + const isRtl = getComputedStyle(list).direction === 'rtl'; + return {start: isRtl ? list.clientWidth - left - size : left, size}; +} + +/** + * The span of `row` in `list`'s coordinates, read before anything in the + * frame writes a style. The list may not be the row's offset parent yet. + */ +function lineSpanOf(row: HTMLElement, list: HTMLElement): LineSpan { + return inlineSpanOf(layoutLeft(row, list), row.offsetWidth, list); +} + +/** + * The preview's span: `row`'s, from the list's padding edge, where the + * preview sits once the list is positioned. Read before the drag writes. + */ +function previewSpanOf(row: HTMLElement, list: HTMLElement): LineSpan { + const border = row.offsetParent === list ? 0 : list.clientLeft; + return inlineSpanOf(layoutLeft(row, list) - border, row.offsetWidth, list); +} + +/** + * Shows the list's insertion line (its pseudo-element, reorderListStyle) + * across `span`, centred on `center` in list coordinates. It only writes, so + * a crossing lays nothing out. + */ +function showLine(list: HTMLElement, span: LineSpan, center: number): void { + list.style.setProperty(LINE_START, `${span.start}px`); + list.style.setProperty(LINE_SIZE, `${span.size}px`); + list.style.setProperty(LINE_Y, `${center - INSERTION_LINE_THICKNESS / 2}px`); + showReorderLine(list); +} + +/** Hides the list's insertion line and clears what placed it. */ +function hideLine(list: HTMLElement): void { + hideReorderLine(list); + for (const property of [LINE_Y, LINE_START, LINE_SIZE]) { + list.style.removeProperty(property); + } +} + +/** + * Where the insertion line's centre sits for the dragged row at `position`. + * It sits in the gap before the row it would land above, or after the one it + * would land below. Null at its own place: nothing moves. + */ +function lineCenter( + geometry: ReorderGeometry, + dragged: number, + position: number, +): number | null { + if (position === dragged) { + return null; + } + const target = geometry.rows[position]; + return position < dragged + ? target.top - geometry.gap / 2 + : target.top + target.height + geometry.gap / 2; +} + +/** A row's layout top inside the list (transforms ignored). */ +function layoutTop(row: HTMLElement, list: HTMLElement): number { + const base = row.offsetParent === list ? 0 : list.offsetTop; + return row.offsetTop - base; +} + +/** A row's layout left inside the list (transforms ignored). */ +function layoutLeft(row: HTMLElement, list: HTMLElement): number { + const base = row.offsetParent === list ? 0 : list.offsetLeft; + return row.offsetLeft - base; +} + +function isTransparent(color: string): boolean { + return ( + color === '' || + color === 'transparent' || + /^rgba\(.*,\s*0\)$/.test(color) || + /\/\s*0\)$/.test(color) + ); +} + +/** The element autoscroll writes to and its visible band in the viewport. */ +interface Scroller { + readonly element: Element; + readonly top: number; + readonly bottom: number; + readonly max: number; + position: number; +} + +function scrollerOf(list: HTMLElement): Scroller { + const doc = list.ownerDocument; + const element = nearestScroller(list); + if (element !== (doc.scrollingElement ?? doc.documentElement)) { + const rect = element.getBoundingClientRect(); + const top = rect.top + element.clientTop; + return { + element, + top, + bottom: top + element.clientHeight, + max: element.scrollHeight - element.clientHeight, + position: element.scrollTop, + }; + } + const view = doc.defaultView; + const height = view?.innerHeight ?? element.clientHeight; + return { + element, + top: 0, + bottom: height, + max: Math.max(0, element.scrollHeight - height), + position: element.scrollTop, + }; +} + +/** A drag in progress, from the pick-up to the drop. */ +interface DragSession { + readonly list: HTMLElement; + /** The rows in order at the begin. */ + readonly rows: ReadonlyArray; + /** Their layout tops at the begin, for the commit's rebase. */ + readonly tops: ReadonlyArray; + readonly geometry: ReorderGeometry; + readonly dragged: number; + /** The dragged row's span, where the insertion line runs. */ + readonly lineSpan: LineSpan; + position: number; + /** The offset each row is moving to. */ + readonly offsets: number[]; + /** The list's layout origin in the viewport at the begin. */ + readonly origin: number; + /** The finger's distance from the dragged row's top. */ + readonly grabOffset: number; + readonly scroller: Scroller; + /** How far autoscroll has moved the content since the begin. */ + scrolled: number; + lastY: number; + /** The edge autoscroll's timer, on UIKit's 20 ms clock. */ + readonly edge: EdgeAutoscroll; + /** Points per tick of the running autoscroll; 0 when none. */ + step: number; + /** The dragged row's inline stacking before the drag. */ + readonly restore: RowRestore; + /** The copy of the dragged row that follows the pointer. */ + readonly preview: HTMLElement; + /** The preview's offset from its row's place, as last written. */ + previewOffset: number; + /** + * A scroll the engine did not cause moved the scroller since its offset + * was last read (`syncScroll`). + */ + scrollStale: boolean; + /** The engine's own scroll still waits for its scroll event. */ + ownScroll: boolean; + /** The engine wrote since the last frame that renders its writes. */ + wrote: boolean; + /** A fold waits for a later frame (`foldInFrame`). */ + foldArmed: boolean; + /** Stops watching the scroller's scroll events. */ + stopScrollWatch: () => void; +} + +/** The inline values a drag overrides until its rows rest. */ +interface RowRestore { + /** The dragged row's stacking and background. */ + readonly zIndex: string; + readonly backgroundColor: string; + /** The dragged row's opacity, dimmed while the drag runs. */ + readonly opacity: string; + /** + * The dragged row's counter increment, off while its preview counts for it + * (a numbered list's number). + */ + readonly counterIncrement: string; + /** The list's position, made a containing block for the overlays. */ + readonly listPosition: string; + /** The session's rows, whose identity offsets go once they rest. */ + readonly rows: ReadonlyArray; +} + +/** 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; + /** Read as the move lands, so it names the rows as they are named then. */ + readonly landed: () => string; + readonly kept: string; + readonly politeness: AnnouncePoliteness | undefined; +} + +/** The strings the controller announces, from the translator. */ +interface ReorderMessages { + /** + * A row's place in reorder mode: its name, place and count. Also the names + * of the rows before and after it, null at the top or the end. + */ + place: ( + label: string, + position: number, + total: number, + previous: string | null, + next: string | null, + ) => string; + /** A reorder mode move refused by the row that stays where it would go. */ + refused: (label: string) => string; + /** A row's name when it shows no text: its place. */ + itemAt: (position: number) => string; + /** Reorder mode ended: the row's name and its place. */ + modeDone: (label: string, position: number, total: number) => string; + pickedUp: (position: number, total: number) => string; + dropped: (position: number, total: number) => string; + cancelled: (position: number, total: number) => string; +} + +function messagesFrom(t: TranslatorFn): ReorderMessages { + return { + place: (label, position, total, previous, next) => + previous == null + ? t('@astryx.list.reorderPlaceTop', {label, position, total, next}) + : next == null + ? t('@astryx.list.reorderPlaceEnd', { + label, + position, + total, + previous, + }) + : t('@astryx.list.reorderPlace', { + label, + position, + total, + previous, + next, + }), + refused: label => t('@astryx.list.reorderRefused', {label}), + itemAt: position => t('@astryx.list.reorderItemAt', {position}), + modeDone: (label, position, total) => + t('@astryx.list.reorderModeDone', {label, position, total}), + pickedUp: (position, total) => + t('@astryx.list.reorderPickedUp', {position, total}), + dropped: (position, total) => + t('@astryx.list.reorderDropped', {position, total}), + cancelled: (position, total) => + t('@astryx.list.reorderCancelled', {position, total}), + }; +} + +/** What a gesture listener hands the controller. */ +export interface ReorderGestureEvent { + readonly state: 'began' | 'changed' | 'ended' | 'cancelled'; + /** The finger's (or pointer's) y in the viewport. */ + readonly y: number; + /** + * At a release, the finger's (or pointer's) y velocity in px/s, which the + * dropped row's glide starts at. + */ + readonly velocity?: number; +} + +/** A long press's state as a reorder gesture's; null while it waits. */ +function gestureStateOf( + recognizer: LongPressGestureRecognizer, +): ReorderGestureEvent['state'] | null { + switch (recognizer.state) { + case 'began': + case 'changed': + case 'ended': + case 'cancelled': + return recognizer.state; + case 'failed': + return 'cancelled'; + case 'possible': + return null; + } +} + +/** + * The reorder session of one List. One instance per List; its listeners are + * on the list, and every handle in it reports its keys here. + */ +export class ListReorderController implements ListReorderSession { + readonly Host = ListReorderHost; + readonly Handle = ListReorderHandle; + readonly RowName = ListReorderRowName; + readonly rowStyle = reorderRowStyle; + readonly listStyle = reorderListStyle; + options: ListReorderOptions | null = null; + announce: AnnounceFn = () => {}; + messages: ReorderMessages | null = null; + /** Whether rows move on springs (`'uikit'`) or jump (`'theme'`). */ + presentation: 'uikit' | 'theme' = 'theme'; + /** Each of this list's handles, with its row's item key. */ + private readonly keys = new Map(); + /** + * 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>(); + /** Reorder mode's hint, while it shows: focus in it keeps the mode. */ + private hintElement: HTMLElement | null = null; + /** The handle whose press became a drag, until its click is read. */ + private draggedHandle: Element | null = null; + /** A reorder mode move, whose rows slide once it commits (under a finger). */ + private committedMove: PendingMove | null = null; + private moveFallback: ReturnType | 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; + /** This session's development warnings, each given once. */ + private readonly warn = createDevWarnings(); + + constructor( + private readonly getList: () => HTMLElement | null, + readonly hintId: string, + ) {} + + /** The List's latest options, announcer, strings and presentation. */ + configure(options: { + options: ListReorderOptions; + announce: AnnounceFn; + messages: ReorderMessages; + presentation: 'uikit' | 'theme'; + }): void { + this.options = options.options; + this.announce = options.announce; + this.messages = options.messages; + this.presentation = options.presentation; + } + + private get animates(): boolean { + return this.presentation === 'uikit'; + } + + /** + * Whether a pointer drags from a handle without a hold: a mouse, or a pen + * where the primary pointer is fine. A finger, and a pen where the primary + * pointer is coarse, keep the hold. The touch presentation is the coarse + * primary pointer. + */ + private dragsAtOnce(pointerType: string): boolean { + return ( + pointerType === 'mouse' || + (pointerType === 'pen' && this.presentation !== 'uikit') + ); + } + + /** + * Records a row's handle and the row's item key (ListItem `itemKey`); + * returns the removal. A row moves only with a handle recorded here. Its + * name is recorded apart, so a new name leaves the row in reorder mode. + */ + registerHandle(handle: Element | null, key: Key): () => void { + if (handle == null) { + return () => {}; + } + this.keys.set(handle, key); + return () => { + if (this.keys.get(handle) === key) { + this.keys.delete(handle); + if (this.modeHandle === handle) { + this.setMode(null); + } + } + }; + } + + /** Records the name of a row, or of its handle; returns the removal. */ + registerName(row: Element | null, name: string): () => void { + if (row == null) { + return () => {}; + } + this.names.set(row, name); + return () => { + if (this.names.get(row) === name) { + this.names.delete(row); + } + }; + } + + /** What the announcements call the row at `index`. */ + private nameOf(row: HTMLElement, index: number): string { + const handle = this.handleIn(row); + const name = + (handle == null ? null : this.names.get(handle)) ?? + this.names.get(row) ?? + ''; + return name !== '' ? name : (this.messages?.itemAt(index + 1) ?? ''); + } + + // --- Reorder mode ---------------------------------------------------- + + /** Whether `handle`'s row is in reorder mode: its `aria-pressed`. */ + isInMode(handle: Element | null): boolean { + return handle != null && this.modeHandle === handle; + } + + /** Calls `listener` when reorder mode starts, moves or ends. */ + subscribeMode = (listener: () => void): (() => void) => { + this.modeListeners.add(listener); + return () => { + this.modeListeners.delete(listener); + }; + }; + + /** The handle whose row is in reorder mode, if any. */ + get modeTarget(): HTMLElement | null { + return this.modeHandle; + } + + private setMode(handle: HTMLElement | null): void { + if (this.modeHandle === handle) { + return; + } + this.modeHandle = handle; + this.lastStep = null; + this.clearModeLine(); + const list = this.getList(); + if (handle != null && list != null) { + this.placeModeLine(list); + } + for (const listener of [...this.modeListeners]) { + listener(); + } + } + + /** + * A handle was activated without a drag (a click, Space or Enter): its row + * enters reorder mode, or leaves it. + */ + toggleMode(handle: HTMLElement | null): void { + if (handle == null || this.session != null) { + return; + } + if (this.modeHandle === handle) { + this.endMode(); + return; + } + if (this.handleOf(handle) === handle) { + this.setMode(handle); + // The arrows go to the handle (a click does not focus a button in + // every browser). + if (handle.ownerDocument.activeElement !== handle) { + handle.focus({preventScroll: true}); + } + } + } + + /** + * Ends reorder mode, keeping its moves, and announces where the row is + * ("Done, Milk at position 3 of 5"). Escape, another activation of the + * handle, the hint's Done, or a drag ends it so. Focus that a screen + * reader moved into the hint goes back to the handle. The row leaving ends + * it without a word. + */ + endMode(): void { + const handle = this.modeHandle; + const list = this.getList(); + const row = this.rowOf(handle); + const active = handle?.ownerDocument.activeElement; + if ( + handle != null && + active != null && + this.hintElement?.contains(active) + ) { + handle.focus({preventScroll: true}); + } + this.setMode(null); + if (list == null || row == null) { + return; + } + const rows = rowsOf(list); + const index = rows.indexOf(row); + this.announce( + this.messages?.modeDone( + this.nameOf(row, index), + index + 1, + rows.length, + ) ?? '', + ); + } + + /** Records reorder mode's hint element (null once it goes). */ + setHintElement(element: HTMLElement | null): void { + this.hintElement = element; + } + + /** + * Reorder mode for the item with `key`, started from the app's own UI. The + * focus moves to its handle, which scrolls into view, as activating it + * does. Returns whether an item with that key can move here. + */ + startByKey(key: Key): boolean { + if (this.session != null) { + return true; + } + for (const [handle, handleKey] of this.keys) { + if ( + handleKey === key && + handle instanceof HTMLElement && + this.handleOf(handle) === handle + ) { + this.setMode(handle); + handle.focus({preventScroll: true}); + this.rowOf(handle)?.scrollIntoView?.({ + block: 'nearest', + inline: 'nearest', + }); + this.claimFocusUntil = performance.now() + START_FOCUS_CLAIM_MS; + return true; + } + } + return false; + } + + /** + * Whether `handle`'s latest press dragged its row; reading it clears it. + * A press that dragged does not toggle reorder mode with its click. + */ + takeDrag(handle: Element | null): boolean { + const dragged = handle != null && this.draggedHandle === handle; + this.draggedHandle = null; + return dragged; + } + + /** This list's handle in `row`, if it has one: a nested list's are its own. */ + private handleIn(row: HTMLElement): Element | null { + for (const handle of reorderHandlesIn(row)) { + if (this.keys.has(handle)) { + return handle; + } + } + return null; + } + + /** The item key `row` reports its moves with; none for a row that stays. */ + private keyOf(row: HTMLElement): Key | undefined { + const handle = this.handleIn(row); + return handle == null ? undefined : this.keys.get(handle); + } + + // --- Listeners --------------------------------------------------------- + + /** + * The handle `target` is in, if it is one of this list's and takes + * gestures; a nested reorderable list's handles are that list's. + */ + private handleOf(target: unknown): HTMLElement | null { + const list = this.getList(); + if (list == null || !(target instanceof Element)) { + return null; + } + const handle = closestReorderHandle(target); + return handle != null && + this.keys.has(handle) && + list.contains(handle) && + handle.getAttribute('aria-disabled') !== 'true' + ? handle + : null; + } + + /** + * Lets a mouse, or a pen where the primary pointer is fine, drag rows by + * their handles without a hold. There is one pointerdown listener on the + * list. While a press is down, its move and lift listeners sit there too. + * The press is the handle's until it lifts, through pointer capture. It + * drags the row once it has moved MOUSE_DRAG_SLOP from where it pressed. + * Returns the detach. + */ + attachMouse(): () => void { + const list = this.getList(); + if (list == null) { + return () => {}; + } + const onPointerDown = (event: PointerEvent) => { + if (!this.dragsAtOnce(event.pointerType) || event.button !== 0) { + return; + } + const handle = this.handleOf(event.target); + if (handle == null) { + return; + } + this.endMouse?.(); + this.draggedHandle = null; + const {pointerId, clientX: x, clientY: y} = event; + let isDragging = false; + // The pointer's velocity, for the glide a release hands it to. + const velocity = new VelocityTracker(); + velocity.add(x, y, event.timeStamp); + const end = () => { + list.removeEventListener('pointermove', onMove); + list.removeEventListener('pointerup', onUp); + list.removeEventListener('pointercancel', onCancel); + list.removeEventListener('lostpointercapture', onCancel); + if (handle.hasPointerCapture?.(pointerId)) { + handle.releasePointerCapture(pointerId); + } + if (this.endMouse === end) { + this.endMouse = null; + } + }; + const onMove = (move: PointerEvent) => { + if (move.pointerId !== pointerId) { + return; + } + velocity.add(move.clientX, move.clientY, move.timeStamp); + if (!isDragging) { + if ( + Math.hypot(move.clientX - x, move.clientY - y) < MOUSE_DRAG_SLOP + ) { + return; + } + isDragging = true; + this.draggedHandle = handle; + this.gesture(this.rowOf(handle), {state: 'began', y}); + } + this.gesture(null, {state: 'changed', y: move.clientY}); + }; + const onUp = (up: PointerEvent) => { + if (up.pointerId !== pointerId) { + return; + } + end(); + if (isDragging) { + velocity.add(up.clientX, up.clientY, up.timeStamp); + this.gesture(null, { + state: 'ended', + y: up.clientY, + velocity: velocity.velocity(up.timeStamp).y, + }); + } + }; + const onCancel = (cancel: PointerEvent) => { + if (cancel.pointerId !== pointerId) { + return; + } + end(); + if (isDragging) { + this.gesture(null, {state: 'cancelled', y: cancel.clientY}); + } + }; + list.addEventListener('pointermove', onMove); + list.addEventListener('pointerup', onUp); + list.addEventListener('pointercancel', onCancel); + list.addEventListener('lostpointercapture', onCancel); + handle.setPointerCapture?.(pointerId); + this.endMouse = end; + }; + list.addEventListener('pointerdown', onPointerDown); + return () => { + this.endMouse?.(); + list.removeEventListener('pointerdown', onPointerDown); + }; + } + + /** + * Lets a finger held still on a handle pick up its row, under every primary + * pointer, and a pen where the primary pointer is coarse. One recognizer on + * the list receives only the touches that begin on its handles. Returns the + * detach. + */ + attachTouch(isCoarsePointer: boolean): () => void { + const list = this.getList(); + if (list == null) { + return () => {}; + } + let held: HTMLElement | null = null; + // The finger's velocity, for the glide a release hands it to. + const velocity = new VelocityTracker(); + return attachTouchHold( + list, + isCoarsePointer ? ['touch', 'pen'] : ['touch'], + target => { + const handle = this.handleOf(target); + if (handle != null) { + held = handle; + } + return handle != null; + }, + recognizer => { + const state = gestureStateOf(recognizer); + if (state === 'began') { + this.draggedHandle = held; + velocity.reset(); + } + // One sample per event, at the event's time. + const touch = recognizer.trackedTouches[0]; + if (touch != null && state != null && state !== 'cancelled') { + velocity.add(touch.x, touch.y, touch.time); + } + if (state != null) { + this.gesture(state === 'began' ? this.rowOf(held) : null, { + state, + y: recognizer.location().y, + velocity: + state === 'ended' && touch != null + ? velocity.velocity(touch.time).y + : undefined, + }); + } + }, + target => this.handleOf(target) != null, + ); + } + + // --- Pointer drags --------------------------------------------------- + + /** A gesture from a handle: begin, track, drop or cancel the drag. */ + gesture(row: HTMLElement | null, event: ReorderGestureEvent): void { + switch (event.state) { + case 'began': + if (row != null) { + this.begin(row, event.y); + } + break; + case 'changed': + this.track(event.y); + break; + case 'ended': + this.drop(event.velocity ?? 0); + break; + case 'cancelled': + this.cancel(); + break; + } + } + + /** + * `handle` stopped taking gestures: its row is disabled or no longer + * reorderable, or the handle is gone. A drag it started goes home, and its + * reorder mode ends. The session owns that end, since a recognizer turned + * off mid-gesture reports nothing. + */ + release(handle: Element | null): void { + if (handle == null) { + return; + } + if (this.session != null && this.draggedHandle === handle) { + this.endMouse?.(); + this.cancel(); + } + if (this.modeHandle === handle) { + this.setMode(null); + } + } + + /** Picks up `row` under a pointer at `y`. Returns whether it did. */ + private begin(row: HTMLElement, y: number): boolean { + const list = this.getList(); + if (list == null || this.session != null) { + return false; + } + // A drag ends reorder mode, keeping its moves, and says so. + if (this.modeHandle != null) { + this.endMode(); + } + // A drop still waiting for its commit is settled where it is. + this.flushPending(); + const rows = rowsOf(list); + const dragged = rows.indexOf(row); + const movable = rows.map(element => this.handleIn(element) != null); + if (dragged < 0 || !movable[dragged]) { + return false; + } + const at = motionNow(); + const tops = rows.map(element => layoutTop(element, list)); + const heights = rows.map(element => element.offsetHeight); + const lineSpan = lineSpanOf(row, list); + const previewSpan = previewSpanOf(row, list); + const isStatic = getComputedStyle(list).position === 'static'; + const bounds = boundsOf(movable); + const geometry: ReorderGeometry = { + rows: rows.map((element, index) => ({ + top: tops[index], + height: heights[index], + isFixed: bounds[index], + })), + gap: rows.length > 1 ? Math.max(0, tops[1] - tops[0] - heights[0]) : 0, + }; + // The list's layout origin in the viewport, from the dragged row's box + // without the offset it may still be moving by. + const shown = shownY(row, at); + const origin = row.getBoundingClientRect().top - shown - tops[dragged]; + const scroller = scrollerOf(list); + // Every row gets an identity offset for the session. Otherwise a row's + // first offset changes how it paints in the middle of the drag, with a + // layout and a paint. With one in place, neither a move nor a slide lays + // out or paints. `will-change` would make each slide's start repaint its + // row. The dragged row goes above its neighbours. + const restore: RowRestore = { + zIndex: row.style.zIndex, + backgroundColor: row.style.backgroundColor, + opacity: row.style.opacity, + counterIncrement: row.style.counterIncrement, + listPosition: list.style.position, + rows, + }; + // The rows stay where they are until the drop. The dragged row is dimmed + // in its place, and a preview of it follows the pointer. An insertion line + // marks where it would land. The preview has a background, as the row + // does. A row without its own takes the surface's behind the list. + const background = isTransparent(getComputedStyle(row).backgroundColor) + ? paintedBackground(list) + : null; + // The copy reads the row's styles, so it is made before the first write. + const copy = previewCopyOf(row); + for (const element of rows) { + if (element.style.translate === '') { + element.style.translate = '0px 0px'; + } + } + if (isStatic) { + list.style.position = 'relative'; + } + const preview = previewOf(copy, tops[dragged], previewSpan, background); + // Right before its source, the preview counts for it. So in a numbered + // list it reads the source's number. Every other row keeps its place + // among its siblings, and the last row keeps :last-child. + row.before(preview); + row.style.counterIncrement = 'none'; + markReorderSource(row); + row.style.opacity = MOVING_OPACITY; + markReordering(list); + const session: DragSession = { + list, + rows, + tops, + geometry, + dragged, + lineSpan, + position: dragged, + offsets: rows.map((element, index) => + index === dragged ? 0 : shownY(element, at), + ), + origin, + grabOffset: y - (origin + tops[dragged] + shown), + scroller, + scrolled: 0, + lastY: y, + edge: edgeAutoscroll({ + intervalMs: reorder.autoscroll.tickMs, + // UIKit's run-loop timer: a late fire catches up one tick, and a + // longer stall is skipped. Engines fire a 20 ms interval every 20 to + // 25 ms. + catchUp: true, + now: motionNow, + step: () => this.edgeStep(session), + apply: delta => this.scrollBy(session, delta), + }), + step: 0, + restore, + preview, + previewOffset: 0, + scrollStale: false, + ownScroll: false, + wrote: true, + foldArmed: false, + stopScrollWatch: () => {}, + }; + this.session = session; + session.stopScrollWatch = this.watchScroll(session); + // Rows still sliding from an earlier drag go to their places. + this.moveTo(dragged); + this.track(y); + this.announce( + this.messages?.pickedUp(dragged + 1, rows.length) ?? '', + 'polite', + ); + return true; + } + + /** The dragged row's top in the viewport for the finger at `y`. */ + private draggedTop(session: DragSession, y: number): number { + const {geometry, dragged, scroller} = session; + const row = geometry.rows[dragged]; + const first = geometry.rows[0]; + const last = geometry.rows[geometry.rows.length - 1]; + const origin = session.origin - session.scrolled; + return clampTop(y - session.grabOffset, row.height, { + scrollTop: scroller.top, + scrollBottom: scroller.bottom, + listTop: origin + first.top, + listBottom: origin + last.top + last.height, + }); + } + + private track(y: number): void { + const session = this.session; + if (session == null) { + return; + } + if (session.scrollStale) { + this.syncScroll(session); + } + session.lastY = y; + session.wrote = true; + const {geometry, dragged} = session; + const row = geometry.rows[dragged]; + const origin = session.origin - session.scrolled; + const top = this.draggedTop(session, y); + const offset = top - (origin + row.top); + // The preview starts at its row's place, with no offset. Only a new + // offset goes to its animator: writing none would read its style back. + if (offset !== session.previewOffset) { + session.previewOffset = offset; + animatorFor(session.preview).set({y: offset}); + } + const position = dropPosition( + geometry, + dragged, + top + row.height / 2 - origin, + ); + if (position !== session.position) { + this.moveTo(position); + } + this.autoscroll(top, row.height); + } + + /** Puts the insertion line where the dragged row would land at `position`. */ + private moveTo(position: number): void { + const session = this.session; + if (session == null) { + return; + } + session.position = position; + const center = lineCenter(session.geometry, session.dragged, position); + if (center == null) { + hideLine(session.list); + } else { + showLine(session.list, session.lineSpan, center); + } + // A pointer drag announces its pick-up and its drop, not each place it + // passes: announcing each crossed position is noisy. + } + + /** + * Points per tick for the dragged row at `top`: positive down, negative + * up. It is 0 when neither edge is near or the content cannot move that + * way. + */ + private stepFor(session: DragSession, top: number, height: number): number { + const {scroller} = session; + let step = 0; + if (scroller.position < scroller.max) { + step = autoscrollStep(top + height - scroller.bottom); + } + if (step === 0 && scroller.position > 0) { + step = -autoscrollStep(scroller.top - top); + } + return step; + } + + /** Starts or stops the edge autoscroll for the row at `top`. */ + private autoscroll(top: number, height: number): void { + const session = this.session; + if (session == null) { + return; + } + session.step = Math.abs(this.stepFor(session, top, height)); + session.edge.update(); + } + + /** The autoscroll's next step for the finger where it last was. */ + private edgeStep(session: DragSession): number { + if (this.session !== session) { + return 0; + } + if (session.scrollStale) { + this.syncScroll(session); + } + const {geometry, dragged} = session; + const top = this.draggedTop(session, session.lastY); + return this.stepFor(session, top, geometry.rows[dragged].height); + } + + /** + * One autoscroll step: the content moves by `delta` (inside its range) and + * the row stays under the finger. Returns how far the content moved. + */ + private scrollBy(session: DragSession, delta: number): number { + if (this.session !== session) { + return 0; + } + const {scroller} = session; + const next = Math.min(scroller.max, Math.max(0, scroller.position + delta)); + const moved = next - scroller.position; + if (moved === 0) { + return 0; + } + scroller.element.scrollTop = next; + session.scrolled += moved; + scroller.position = next; + // Its scroll event comes in the next frame, before that frame's + // callbacks. A write that moves nothing sends none. + session.ownScroll = true; + requestAnimationFrame(() => { + session.ownScroll = false; + }); + this.track(session.lastY); + return moved; + } + + /** + * Watches the scroller for a scroll the engine did not cause, such as a + * wheel or a key. A later frame folds it in (`armFold`). + */ + private watchScroll(session: DragSession): () => void { + const doc = session.list.ownerDocument; + const view = doc.defaultView; + if (view == null) { + return () => {}; + } + const {element} = session.scroller; + // The page's own scroll is reported on the document. + const target = + element === (doc.scrollingElement ?? doc.documentElement) ? doc : element; + return subscribeInput(view, 'scroll', event => { + if (event.target !== target || this.session !== session) { + return; + } + if (session.ownScroll) { + session.ownScroll = false; + return; + } + session.scrollStale = true; + this.armFold(session); + }); + } + + /** + * Folds a scroll into the drag in the next frame without a move or a tick. + * The writes made so far render first, so its one read forces no layout. + */ + private armFold(session: DragSession): void { + if (session.foldArmed) { + return; + } + session.foldArmed = true; + requestAnimationFrame(() => { + // Everything written so far renders after this frame's callbacks. + session.wrote = false; + requestAnimationFrame(() => this.foldInFrame(session)); + }); + } + + private foldInFrame(session: DragSession): void { + session.foldArmed = false; + if (this.session !== session || !session.scrollStale) { + return; + } + if (session.wrote) { + // The engine wrote in this frame, so the read waits another frame. + session.wrote = false; + session.foldArmed = true; + requestAnimationFrame(() => this.foldInFrame(session)); + return; + } + this.track(session.lastY); + } + + /** + * Reads the scroller's offset once and adds what a scroll the engine did + * not cause moved to the drag. It runs before any write in its frame or + * task. + */ + private syncScroll(session: DragSession): void { + session.scrollStale = false; + const {scroller} = session; + const position = scroller.element.scrollTop; + session.scrolled += position - scroller.position; + scroller.position = position; + } + + private stopAutoscroll(session: DragSession): void { + session.edge.stop(); + session.step = 0; + } + + /** + * The drop: the move is reported, and on its commit the row glides into + * its place, starting at the release's y `velocity` in px/s. + */ + private drop(velocity: number): void { + const session = this.session; + if (session == null) { + return; + } + if (session.scrollStale) { + this.track(session.lastY); + } + this.session = null; + this.stopAutoscroll(session); + session.stopScrollWatch(); + const {geometry, dragged, position, rows, list} = session; + const element = rows[dragged]; + // Where the preview is now: on the commit the dragged row glides from + // there into its new place, and the rows it passed to theirs. + const droppedTop = + geometry.rows[dragged].top + shownY(session.preview, motionNow()); + this.clearOverlays(session); + const dropped = this.messages?.dropped(position + 1, rows.length) ?? ''; + const key = this.keyOf(element); + const options = this.options; + if (position === dragged || options == null || key == null) { + if (position === dragged) { + this.announce(dropped, 'polite'); + clearReordering(list); + this.restWhenDone(element, session.restore); + } else { + this.springBack(list, rows, dragged, session.restore); + } + return; + } + this.announceWhenCommitted({ + row: element, + to: position, + landed: () => dropped, + kept: this.messages?.cancelled(dragged + 1, rows.length) ?? '', + politeness: 'polite', + }); + this.pending = { + list, + rows, + tops: session.tops, + dragged, + droppedTop, + velocity, + restore: session.restore, + }; + options.onReorder({key, to: position}); + // A consumer that does not apply the move by the end of the task gets + // its rows back where they were. + this.fallback = setTimeout(() => { + this.fallback = null; + this.refuse(); + }, 0); + } + + /** + * The drag ends where it started: the browser took the touch (a pinch, a + * scroll), or the handle left. Every row goes home and nothing is + * reported. + */ + cancel(): void { + const session = this.session; + if (session == null) { + return; + } + this.session = null; + this.stopAutoscroll(session); + session.stopScrollWatch(); + // Nothing moved: the preview and the line go and the row is itself again + // at once. + this.clearOverlays(session); + this.springBack( + session.list, + session.rows, + session.dragged, + session.restore, + ); + this.announce( + this.messages?.cancelled(session.dragged + 1, session.rows.length) ?? '', + ); + } + + /** Takes the preview and the line away and undims the dragged row. */ + private clearOverlays(session: DragSession): void { + session.preview.remove(); + hideLine(session.list); + const row = session.rows[session.dragged]; + clearReorderSource(row); + row.style.opacity = session.restore.opacity; + row.style.counterIncrement = session.restore.counterIncrement; + session.list.style.position = session.restore.listPosition; + } + + private springBack( + list: HTMLElement, + rows: ReadonlyArray, + dragged: number, + restore: RowRestore, + ): void { + const at = motionNow(); + const away = rows.filter( + element => + Math.abs(shownY(element, at)) >= MIN_MOVE_PX || isMoving(element), + ); + // The spring is read once, before the first write. + const spring = + this.animates && away.length > 0 ? touchMotion.glideBase(list) : null; + for (const element of away) { + if (spring == null) { + animatorFor(element).set({y: 0}); + releaseMotion(element, 'translate'); + continue; + } + // A row still in a drop's or a key move's glide goes on home. It plays + // the shared settle role from where it is shown, at the speed it has. + touchMotion.home(element, spring, at, false); + } + clearReordering(list); + this.restWhenDone(rows[dragged], restore); + } + + /** `onReorder` applied no new order: the rows return to their places. */ + private refuse(): void { + const pending = this.pending; + if (pending == null) { + return; + } + const current = rowsOf(pending.list); + if (!sameOrder(current, pending.rows)) { + // The commit came but its layout effect has not run yet. + return; + } + this.pending = null; + this.springBack( + pending.list, + pending.rows, + pending.dragged, + pending.restore, + ); + } + + /** Clears the dragged row's stacking once its motion has come to rest. */ + private restWhenDone(element: HTMLElement, restore: RowRestore): void { + const settle = () => { + if (this.session?.rows[this.session.dragged] === element) { + return; + } + const running = motionOf(element, 'y'); + if (running != null) { + // The drop's spring, or the rebase that continues it. + void running.handle.finished.then(settle); + return; + } + element.style.zIndex = restore.zIndex; + element.style.backgroundColor = restore.backgroundColor; + // Identity offsets go; a row still moving keeps its own. + for (const row of restore.rows) { + releaseMotion(row, 'translate'); + } + }; + settle(); + } + + private flushPending(): void { + if (this.pending == null) { + return; + } + if (this.fallback != null) { + clearTimeout(this.fallback); + this.fallback = null; + } + this.refuse(); + this.pending = null; + } + + // --- Commits --------------------------------------------------------- + + ownsCommit(): boolean { + const list = this.getList(); + return list != null && isReordering(list); + } + + commit(): void { + const list = this.getList(); + if (list == null) { + return; + } + if ( + this.keys.size === 0 && + this.options != null && + this.options.isReorderable == null && + list.children.length > 0 + ) { + this.warn( + 'List', + '`reorderable` is set, but no ListItem has an `itemKey`: give each ' + + 'row the key its moves report.', + ); + } + const session = this.session; + if (session != null && !sameOrder(rowsOf(list), session.rows)) { + // The rows changed under the drag. + this.cancel(); + } + const pending = this.pending; + if (pending != null && !sameOrder(rowsOf(list), pending.rows)) { + this.pending = null; + if (this.fallback != null) { + clearTimeout(this.fallback); + this.fallback = null; + } + this.rebase(pending); + } + const announcement = this.announcement; + if ( + announcement != null && + rowsOf(list).indexOf(announcement.row) === announcement.to + ) { + this.announcement = null; + if (this.announcementFallback != null) { + clearTimeout(this.announcementFallback); + this.announcementFallback = null; + } + this.announce(announcement.landed(), announcement.politeness); + } + const move = this.committedMove; + let slide: (() => void) | null = null; + if (move != null && !sameOrder(rowsOf(list), move.rows)) { + this.committedMove = null; + if (this.moveFallback != null) { + clearTimeout(this.moveFallback); + this.moveFallback = null; + } + slide = this.slideCommitted(move); + } + // A reorder mode move has landed (or nothing waits): its handle keeps + // the focus, and the insertion line marks the row's new place. Their + // reads come before the slide's first write, so a move lays out once. + if (this.announcement == null) { + const placeLine = this.measureModeLine(list); + this.restoreFocus(); + slide?.(); + placeLine(); + } else { + slide?.(); + } + } + + /** + * A reorder mode move landed: each row slides from its old place to its new + * one. Measures the slides, and returns the writes that start them. + */ + private slideCommitted(move: PendingMove): () => void { + const {list} = move; + const at = motionNow(); + const shifts = move.rows.map((element, index) => + element.parentElement === list + ? move.tops[index] - layoutTop(element, list) + : 0, + ); + const spring = shifts.some(shift => Math.abs(shift) >= MIN_MOVE_PX) + ? touchMotion.glideBase(list) + : null; + return () => { + for (const [index, element] of move.rows.entries()) { + const shift = shifts[index]; + if (spring == null || Math.abs(shift) < MIN_MOVE_PX) { + continue; + } + // A row still sliding from the previous move goes on from where it + // is shown, as a drop's rows do. + touchMotion.follow(element, shift, spring, at); + } + clearReordering(list); + }; + } + + private rebase(pending: PendingDrop): void { + const {list} = pending; + const at = motionNow(); + // Every read comes before the first write, so the drop lays out once. + const rows = pending.rows.map((element, index) => { + if (element.parentElement !== list) { + return null; + } + // The dragged row glides from where its preview was dropped, the rows + // it passed from their old places. + const from = + index === pending.dragged ? pending.droppedTop : pending.tops[index]; + return { + element, + index, + shift: from - layoutTop(element, list), + value: shownY(element, at), + moving: isMoving(element), + }; + }); + // A row at rest where the drop leaves it settles there. A row the layout + // moved glides from its old place. + const settles = (row: {shift: number; value: number; moving: boolean}) => + Math.abs(row.value + row.shift) < MIN_MOVE_PX && !row.moving; + const glides = (row: {shift: number; value: number; moving: boolean}) => + !settles(row) && Math.abs(row.shift) >= MIN_MOVE_PX; + const spring = + this.animates && rows.some(row => row != null && glides(row)) + ? touchMotion.glideBase(list) + : null; + for (const row of rows) { + if (row == null) { + continue; + } + const {element, index, shift, value, moving} = row; + if (settles(row)) { + settleAtRest(element, value, moving); + continue; + } + if (!glides(row)) { + continue; + } + if (spring != null && index === pending.dragged) { + // The dragged row glides from where its preview was dropped into its + // new layout place, starting at the release's velocity. + touchMotion.glide(element, shift, spring, at, pending.velocity); + } else if (spring != null) { + // Every other row's place after the drop is its new layout place. So + // its running glide goes on to 0 from the shifted value. Otherwise the + // glide starts from rest. + touchMotion.follow(element, shift, spring, at); + } else { + settleAtRest(element, value, moving); + } + } + clearReordering(list); + this.restWhenDone(pending.rows[pending.dragged], pending.restore); + } + + /** + * Reorder mode's insertion line, shared with the pointer drag's. It marks + * the row's place for the whole mode. It sits at the edge the row came in + * through on its last key move. That is the gap above it after a move up, + * and below it after a move down. Before a move, it sits in the gap above + * the row. + */ + private placeModeLine(list: HTMLElement): void { + this.measureModeLine(list)(); + } + + /** + * Reads where reorder mode's insertion line goes, and returns the writes + * that place it there. + */ + private measureModeLine(list: HTMLElement): () => void { + const row = this.rowOf(this.modeHandle); + if (row == null) { + return () => this.clearModeLine(); + } + const step = this.lastStep ?? -1; + const rows = rowsOf(list); + const index = rows.indexOf(row); + const top = layoutTop(row, list); + const bottom = top + row.offsetHeight; + const neighbour = rows[index + step]; + const gap = + neighbour == null + ? 0 + : step < 0 + ? Math.max( + 0, + top - (layoutTop(neighbour, list) + neighbour.offsetHeight), + ) + : Math.max(0, layoutTop(neighbour, list) - bottom); + const center = step < 0 ? top - gap / 2 : bottom + gap / 2; + const span = lineSpanOf(row, list); + const isNewList = this.modeLine?.list !== list; + const isStatic = isNewList && getComputedStyle(list).position === 'static'; + return () => { + if (isNewList) { + this.clearModeLine(); + const listPosition = list.style.position; + if (isStatic) { + list.style.position = 'relative'; + } + this.modeLine = {list, listPosition}; + } + showLine(list, span, center); + }; + } + + private clearModeLine(): void { + const modeLine = this.modeLine; + if (modeLine == null) { + return; + } + this.modeLine = null; + hideLine(modeLine.list); + modeLine.list.style.position = modeLine.listPosition; + } + + /** + * The row that holds `element` (a handle): the list's child that contains + * it, whatever its tag. Null outside the list. + */ + rowOf(element: Element | null): HTMLElement | null { + const list = this.getList(); + let node = element; + while (node != null && node.parentElement !== list) { + node = node.parentElement; + } + return list != null && node instanceof HTMLElement ? node : null; + } + + /** The 1-based place of the row that holds `element`, or null. */ + positionOf(element: Element | null): number | null { + const list = this.getList(); + const row = this.rowOf(element); + return list == null || row == null ? null : rowsOf(list).indexOf(row) + 1; + } + + // --- Keys ------------------------------------------------------------ + + /** + * A handle's key in reorder mode: the arrows move its + * row a place at once, and Escape ends the mode, keeping the moves. Space + * and Enter toggle the mode through the handle's click. + */ + keyDown(handle: HTMLElement | null, event: KeyboardEvent): void { + // A modified key is a browser or assistive-technology shortcut. + if ( + handle == null || + handle !== this.modeHandle || + event.altKey || + event.ctrlKey || + event.metaKey + ) { + return; + } + switch (event.key) { + case 'Escape': + event.preventDefault(); + event.stopPropagation(); + this.endMode(); + return; + case 'ArrowUp': + case 'ArrowDown': + event.preventDefault(); + this.step(handle, event.key === 'ArrowUp' ? -1 : 1); + return; + default: + return; + } + } + + /** + * Reorder mode's move. The row whose handle is in the mode goes a place up + * (`-1`) or down (`1`) at once, with one report. It is announced with its + * place and neighbours once it lands. Under a finger's presentation, the + * rows then slide to their new places, as a UIKit table moves a row. A move + * into a row that stays at either end is refused and announced. One past + * the list's end does nothing. + */ + step(handle: HTMLElement | null, delta: -1 | 1): void { + const list = this.getList(); + const options = this.options; + const row = this.rowOf(handle); + const key = row == null ? undefined : this.keyOf(row); + if ( + list == null || + options == null || + row == null || + key == null || + handle !== this.modeHandle || + this.session != null + ) { + return; + } + const rows = rowsOf(list); + const index = rows.indexOf(row); + const to = index + delta; + if (to < 0 || to >= rows.length) { + return; + } + if (boundsOf(rows.map(element => this.handleIn(element) != null))[to]) { + this.announce(this.messages?.refused(this.nameOf(rows[to], to)) ?? ''); + return; + } + this.focusRow = row; + this.lastStep = delta; + this.announceWhenCommitted({ + row, + to, + landed: () => this.placeIn(rowsOf(list), to), + kept: this.placeIn(rows, index), + politeness: undefined, + }); + if (this.animates) { + this.committedMove = { + list, + rows, + tops: rows.map(element => layoutTop(element, list)), + }; + // The List's layout updates leave this commit to the reorder. + markReordering(list); + if (this.moveFallback != null) { + clearTimeout(this.moveFallback); + } + // The caller kept the order: nothing slides. + this.moveFallback = setTimeout(() => { + this.moveFallback = null; + if (this.committedMove != null) { + this.committedMove = null; + if (this.session == null && this.pending == null) { + clearReordering(list); + } + } + }, 0); + } + options.onReorder({key, to}); + } + + /** What reorder mode announces for the row at `at` in `order`. */ + private placeIn(order: ReadonlyArray, at: number): string { + const name = (index: number) => this.nameOf(order[index], index); + return ( + this.messages?.place( + name(at), + at + 1, + order.length, + at > 0 ? name(at - 1) : null, + at < order.length - 1 ? name(at + 1) : null, + ) ?? '' + ); + } + + /** + * Announces a move once it commits; if the consumer keeps the order by the + * end of the task, announces that the row stayed instead. + */ + private announceWhenCommitted(announcement: PendingAnnouncement): void { + this.announcement = announcement; + if (this.announcementFallback != null) { + clearTimeout(this.announcementFallback); + } + this.announcementFallback = setTimeout(() => { + this.announcementFallback = null; + const pending = this.announcement; + if (pending != null) { + this.announcement = null; + this.announce(pending.kept, pending.politeness); + } + this.restoreFocus(); + }, 0); + } + + /** + * A handle lost focus to `next`. Its row stays in reorder mode. When the UI + * that started the mode hands its focus back at once, the handle takes it + * again. + */ + blur(handle: HTMLElement | null, next: EventTarget | null): void { + // Focus a screen reader moves into the mode's hint keeps the mode. + if (next instanceof Node && this.hintElement?.contains(next)) { + return; + } + // The UI that started the mode handing its focus back (a closing menu + // restoring its trigger's) at once: the handle takes it again. + if ( + handle != null && + handle === this.modeHandle && + performance.now() < this.claimFocusUntil + ) { + setTimeout(() => { + if (this.modeHandle === handle) { + handle.focus({preventScroll: true}); + } + }, 0); + return; + } + // Focus leaving the handle does not end reorder mode: its exits are + // Escape, Done, the handle again and its row going. Back on the handle, + // its arrows move the row again. + } + + /** + * After a reorder mode move: the handle has the focus again (the commit + * may have moved its element) and its row scrolls into view. + */ + private restoreFocus(): void { + const row = this.focusRow; + if (row == null) { + return; + } + this.focusRow = null; + const handle = this.handleIn(row); + const active = row.ownerDocument.activeElement; + // The scroll reads layout, so it comes before the focus changes styles. + if (handle === this.modeHandle) { + row.scrollIntoView?.({block: 'nearest', inline: 'nearest'}); + } + // Focus that went elsewhere meanwhile stays there; focus in the hint + // (a screen reader's) goes back to the handle. + if ( + handle instanceof HTMLElement && + handle === this.modeHandle && + (active == null || + active === row.ownerDocument.body || + this.hintElement?.contains(active) === true) + ) { + handle.focus({preventScroll: true}); + } + } + + dispose(): void { + this.endMouse?.(); + this.setMode(null); + // A drag in progress goes home. + this.cancel(); + if (this.moveFallback != null) { + clearTimeout(this.moveFallback); + this.moveFallback = null; + } + this.committedMove = null; + if (this.fallback != null) { + clearTimeout(this.fallback); + this.fallback = null; + } + this.pending = null; + if (this.announcementFallback != null) { + clearTimeout(this.announcementFallback); + this.announcementFallback = null; + } + this.announcement = null; + } +} + +function sameOrder( + a: ReadonlyArray, + 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 ( + <> + + + + ); +} + +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}, + ); +} + +/** 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/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,