An open source design system that's fully customizable and agent ready
TypeScript
feat(Item): swipe actions on the row, per spec:AST-057 (#6821)
Christopher Chedeaub3d9a89e5781
diff --git a/.changeset/item-swipe-actions.md b/.changeset/item-swipe-actions.mdnew file mode 100644index 0000000000..682c769dda--- /dev/null+++ b/.changeset/item-swipe-actions.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] `Item` gains swipe actions for touch, per `spec:AST-057`. `swipeActions` declares, per side, the verbs a sideways drag uncovers as `ItemSwipeAction[]` (`{id?, label, icon?, onActivate, isDisabled?, variant?: 'neutral' | 'accent' | 'destructive', hasRemoval?}`, outermost last); `swipeBehavior` is `reveal` (the row rests open with every entry a real button; a long drag or a fling fires the outermost) or `commit` (the row slides out and the outermost fires; nothing rests). After an entry fires the row springs back, or holds out when the entry has `hasRemoval`. A mouse never starts the drag, a mostly vertical drag stays the scroller's, a resting row closes on a pointer outside it. Available on a row whose role permits interactive descendants (a `listitem`, a role-less row); `ListItem` passes both props through. No element is added to a row: its root translates and its panels counter-translate. `List` clips its rows in the inline axis (`overflow-inline: clip`). Types `ItemSwipeAction`, `ItemSwipeActions`, `ItemSwipeActionVariant` and `ItemSwipeBehavior` are exported.++@vjeuxdiff --git a/apps/storybook/stories/Item.stories.tsx b/apps/storybook/stories/Item.stories.tsxindex b1242b3b3a..f8b29b3743 100644--- a/apps/storybook/stories/Item.stories.tsx+++ b/apps/storybook/stories/Item.stories.tsx@@ -9,6 +9,7 @@ import {Badge} from '@astryxdesign/core/Badge';import {Icon} from '@astryxdesign/core/Icon';import {Text} from '@astryxdesign/core/Text';import {Stack} from '@astryxdesign/core/Layout';+import {List, ListItem} from '@astryxdesign/core/List';const storyStyles = stylex.create({iconCircle: {@@ -29,6 +30,9 @@ import {BellIcon,ChatBubbleLeftIcon,MagnifyingGlassIcon,+ ArchiveBoxIcon,+ EnvelopeIcon,+ TrashIcon,} from '@heroicons/react/24/outline';const meta: Meta<typeof Item> = {@@ -274,3 +278,119 @@ export const AlignStart: Story = {/>),};++/**+ * Swipe actions, as a mail list uses them: on a touch screen a drag toward+ * the inline start uncovers Archive and Delete (Delete outermost, so a long+ * drag or a fling fires it); a drag toward the inline end uncovers a+ * read/unread toggle. Under `reveal` (the default) the row rests open with+ * every entry a real button. Every verb is also in the row's own content, so+ * a mouse and a keyboard reach it without the gesture. `List` clips the rows+ * in the inline axis for the slide.+ */+export const SwipeActions: Story = {+ render: () => {+ const [rows, setRows] = useState(() =>+ Array.from({length: 6}, (_, index) => ({+ id: index,+ isUnread: index % 2 === 0,+ label: `Message ${index + 1}`,+ })),+ );+ const remove = (id: number) =>+ setRows(current => current.filter(row => row.id !== id));+ const toggleRead = (id: number) =>+ setRows(current =>+ current.map(row =>+ row.id === id ? {...row, isUnread: !row.isUnread} : row,+ ),+ );+ return (+ <List>+ {rows.map(row => (+ <ListItem+ key={row.id}+ label={row.label}+ description={row.isUnread ? 'Unread' : 'Read'}+ onClick={() => {}}+ endContent={+ <Text color="secondary">+ {row.isUnread ? 'Mark read' : 'Mark unread'} · Archive · Delete+ </Text>+ }+ swipeActions={{+ leading: [+ {+ label: row.isUnread ? 'Read' : 'Unread',+ icon: <Icon icon={EnvelopeIcon} size="sm" />,+ onActivate: () => toggleRead(row.id),+ },+ ],+ trailing: [+ {+ label: 'Archive',+ icon: <Icon icon={ArchiveBoxIcon} size="sm" />,+ onActivate: () => remove(row.id),+ variant: 'neutral',+ hasRemoval: true,+ },+ {+ label: 'Delete',+ icon: <Icon icon={TrashIcon} size="sm" />,+ onActivate: () => remove(row.id),+ variant: 'destructive',+ hasRemoval: true,+ },+ ],+ }}+ />+ ))}+ {rows.length === 0 && <ListItem label="All done." />}+ </List>+ );+ },+};++/**+ * `swipeBehavior="commit"`: one verb per side; a release past the commit+ * point slides the row out and fires it, and nothing rests. The panel is+ * presentational.+ */+export const SwipeCommit: Story = {+ render: () => {+ const [rows, setRows] = useState(() =>+ Array.from({length: 5}, (_, index) => ({+ id: index,+ label: `Notification ${index + 1}`,+ })),+ );+ const remove = (id: number) =>+ setRows(current => current.filter(row => row.id !== id));+ return (+ <List>+ {rows.map(row => (+ <ListItem+ key={row.id}+ label={row.label}+ description="Swipe toward the start to dismiss"+ onClick={() => {}}+ endContent={<Text color="secondary">Dismiss</Text>}+ swipeBehavior="commit"+ swipeActions={{+ trailing: [+ {+ label: 'Dismiss',+ icon: <Icon icon={TrashIcon} size="sm" />,+ onActivate: () => remove(row.id),+ variant: 'destructive',+ hasRemoval: true,+ },+ ],+ }}+ />+ ))}+ {rows.length === 0 && <ListItem label="All caught up." />}+ </List>+ );+ },+};diff --git a/packages/core/src/Item/Item.doc.mjs b/packages/core/src/Item/Item.doc.mjsindex 58d5614428..5aaa7f2431 100644--- a/packages/core/src/Item/Item.doc.mjs+++ b/packages/core/src/Item/Item.doc.mjs@@ -26,7 +26,11 @@ export const docs = {},},theming: {- targets: [{className: 'astryx-item', visualProps: ['density', 'align']}],+ targets: [+ {className: 'astryx-item', visualProps: ['density', 'align']},+ {className: 'astryx-item-swipe-panel', visualProps: ['side']},+ {className: 'astryx-item-swipe-action', visualProps: ['variant']},+ ],vars: [{name: '--_item-label-color',@@ -190,6 +194,19 @@ export const docs = {description: 'Disabled state.',default: 'false',},+ {+ name: 'swipeActions',+ type: '{leading?: ItemSwipeAction[]; trailing?: ItemSwipeAction[]}',+ description:+ "Swipe actions for touch: the verbs a sideways drag uncovers on each side, outermost last, each `{id?, label, icon?, onActivate, isDisabled?, variant?: 'neutral' | 'accent' | 'destructive', hasRemoval?}`. `leading` is uncovered by a drag toward the inline end, `trailing` toward the inline start. A mouse never starts the drag and a mostly vertical drag stays the scroller's. The gesture is a touch accelerator and never a row's only path to a verb: a verb reachable only by swipe is unreachable by keyboard and by mouse, so every entry must also be reachable through the row's own content. Served on a row whose role permits interactive descendants (a listitem, a row with no role) and not on an option, a menu item, or a row that is the enlarged target of a native radio. The element containing the rows clips in the inline axis with overflow-inline: clip — List does; any other host does it once. `hasRemoval` only says the row holds out after the action fires instead of springing back.",+ },+ {+ name: 'swipeBehavior',+ type: "'reveal' | 'commit'",+ description:+ 'What a swipe does. `reveal` rests the row open with every entry a real button and fires the outermost on a long drag or a fling; `commit` slides the row out and fires the outermost on release, with nothing resting and a presentational panel. `commit` fits one entry per side.',+ default: "'reveal'",+ },{name: 'ref',type: 'React.Ref<HTMLDivElement>',@@ -233,6 +250,11 @@ export const docs = {description:'Use align="start" when start or end content is taller than a single line of text.',},+ {+ guidance: true,+ description:+ 'Give a swipe action a second home in the row (a menu or a button in endContent): the swipe is a touch accelerator, and a verb reachable only by swipe is unreachable by keyboard and by mouse.',+ },{guidance: false,description:diff --git a/packages/core/src/Item/Item.test.tsx b/packages/core/src/Item/Item.test.tsxindex fb6b794825..3b46964b6f 100644--- a/packages/core/src/Item/Item.test.tsx+++ b/packages/core/src/Item/Item.test.tsx@@ -10,8 +10,9 @@*/import {use, useRef} from 'react';-import {describe, it, expect, vi} from 'vitest';-import {render, screen} from '@testing-library/react';+import {afterEach, beforeEach, describe, it, expect, vi} from 'vitest';+import {act, fireEvent, render, screen} from '@testing-library/react';+import {rulesDeclaredFor} from '../__tests__/pressState';import userEvent from '@testing-library/user-event';import {Item} from './Item';import {ItemDescriptionContext} from './ItemDescriptionContext';@@ -604,3 +605,598 @@ describe('Item', () => {expect(screen.getByText('Private')).toBeInTheDocument();});});++describe('swipeActions', () => {+ beforeEach(() => {+ // The gesture reads the clock for its fling test and its settle timers:+ // fake both, and space the moves out the way a finger does.+ vi.useFakeTimers({+ toFake: [+ 'setTimeout',+ 'clearTimeout',+ 'requestAnimationFrame',+ 'cancelAnimationFrame',+ 'Date',+ 'performance',+ ],+ });+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ function touch(+ element: Element,+ type: 'pointerDown' | 'pointerMove' | 'pointerUp' | 'pointerCancel',+ x: number,+ y = 10,+ ) {+ vi.advanceTimersByTime(50);+ fireEvent[type](element, {+ clientX: x,+ clientY: y,+ pointerId: 7,+ pointerType: 'touch',+ });+ }++ /** The time a settle takes, plus the frame before it. */+ const settled = () => void act(() => vi.advanceTimersByTime(250));++ const travelOf = (row: HTMLElement) =>+ row.style.getPropertyValue('--_item-swipe-travel');++ /** The panel of a side: the out-of-flow child on the root carrying it. */+ const panelOf = (row: HTMLElement, side: 'leading' | 'trailing') =>+ row.querySelector(`[data-swipe-panel="${side}"]`);++ /**+ * jsdom lays nothing out: give the row a width and each side's entries a+ * natural width of 72 px per entry, as the real panel measures them.+ */+ function layOut(row: HTMLElement) {+ Object.defineProperty(row, 'clientWidth', {configurable: true, value: 300});+ for (const panel of row.querySelectorAll('[data-swipe-panel]')) {+ const entries = panel.firstElementChild as HTMLElement;+ Object.defineProperty(entries, 'offsetWidth', {+ configurable: true,+ value: 72 * entries.childElementCount,+ });+ }+ }++ type Entry = {+ label: string;+ onActivate: () => void;+ hasRemoval?: boolean;+ isDisabled?: boolean;+ variant?: 'neutral' | 'accent' | 'destructive';+ };++ function renderRow({+ leading = [{label: 'Unread', onActivate: vi.fn()}],+ trailing,+ behavior,+ onClick = vi.fn(),+ }: {+ leading?: Entry[];+ trailing?: Entry[];+ behavior?: 'reveal' | 'commit';+ onClick?: () => void;+ } = {}) {+ render(+ <Item+ label="Conversation"+ onClick={onClick}+ data-testid="row"+ swipeActions={{leading, trailing}}+ swipeBehavior={behavior}+ />,+ );+ const row = screen.getByTestId('row');+ layOut(row);+ return {row, onClick};+ }++ it('is served on a role-less row and a listitem, and not on a row whose role forbids interactive descendants', () => {+ const actions = {leading: [{label: 'Unread', onActivate: vi.fn()}]};+ const {rerender} = render(+ <Item label="A" data-testid="row" swipeActions={actions} />,+ );+ expect(panelOf(screen.getByTestId('row'), 'leading')).not.toBeNull();+ rerender(+ <Item as="li" label="A" data-testid="row" swipeActions={actions} />,+ );+ expect(panelOf(screen.getByTestId('row'), 'leading')).not.toBeNull();+ for (const role of [+ 'option',+ 'menuitem',+ 'menuitemcheckbox',+ 'menuitemradio',+ ]) {+ rerender(+ <Item role={role} label="A" data-testid="row" swipeActions={actions} />,+ );+ expect(panelOf(screen.getByTestId('row'), 'leading')).toBeNull();+ }+ });++ it('is not served on a row that is the enlarged target of a nested control, nor on a disabled row', () => {+ const actions = {leading: [{label: 'Unread', onActivate: vi.fn()}]};+ function Delegating() {+ const inputRef = useRef<HTMLInputElement>(null);+ return (+ <Item+ label="A"+ data-testid="row"+ interactiveRef={inputRef}+ startContent={<input ref={inputRef} type="radio" />}+ swipeActions={actions}+ />+ );+ }+ const {unmount} = render(<Delegating />);+ expect(panelOf(screen.getByTestId('row'), 'leading')).toBeNull();+ unmount();+ render(+ <Item label="A" data-testid="row" isDisabled swipeActions={actions} />,+ );+ expect(panelOf(screen.getByTestId('row'), 'leading')).toBeNull();+ });++ it('adds no element to a row without swipe actions, and no wrapper to one with them', () => {+ const {rerender} = render(+ <ul data-testid="list">+ <Item as="li" label="A" data-testid="row" />+ </ul>,+ );+ const before = screen.getByTestId('row').childElementCount;+ rerender(+ <ul data-testid="list">+ <Item+ as="li"+ label="A"+ data-testid="row"+ swipeActions={{trailing: [{label: 'Archive', onActivate: vi.fn()}]}}+ />+ </ul>,+ );+ const row = screen.getByTestId('row');+ // The root is the row; the list is its parent, so the `li` stays the+ // list's direct child. The panel is the one child the actions add.+ expect(row.tagName).toBe('LI');+ expect(row.parentElement).toBe(screen.getByTestId('list'));+ expect(row.childElementCount).toBe(before + 1);+ expect(panelOf(row, 'trailing')).toBe(row.lastElementChild);+ expect(panelOf(row, 'leading')).toBeNull();+ });++ it('keeps the panel out of the accessibility tree and the tab order at rest, with no pixel of it painted', () => {+ const {row} = renderRow();+ const panel = panelOf(row, 'leading') as HTMLElement;+ // Inert: not in the tree, not in the tab order, so the row keeps one tab+ // stop and a pointer that can hover never meets it.+ expect(panel).toHaveAttribute('inert');+ expect(+ screen.getByRole('button', {name: 'Unread'}).closest('[inert]'),+ ).toBe(panel);+ // Zero width with no padding of its own: a padded box at `width: 0` is+ // still as wide as its padding and would paint a sliver of the colour.+ expect(rulesDeclaredFor(panel).some(r => r.includes('padding'))).toBe(+ false,+ );+ // Its width is the travel toward its side, floored at zero; at rest the+ // travel is unset.+ expect(+ rulesDeclaredFor(panel).some(r => r.includes('width: max(0px')),+ ).toBe(true);+ expect(travelOf(row)).toBe('');+ });++ it('claims a sideways drag, writes the travel on the root, and tells the browser the row owns the drag', () => {+ const {row} = renderRow();+ const touchMove = (x: number, y = 10) =>+ fireEvent.touchMove(row, {+ cancelable: true,+ touches: [{clientX: x, clientY: y}],+ });+ touch(row, 'pointerDown', 10);+ // Before the axis is decided the scroller may still take the gesture:+ // the default stands (fireEvent answers false once it is prevented).+ expect(touchMove(14)).toBe(true);+ touch(row, 'pointerMove', 14);+ expect(touchMove(14)).toBe(true);+ expect(travelOf(row)).toBe('');+ // Past the lock and more horizontal than vertical: the row's. Every+ // further touchmove is cancelled, which is what keeps iOS Safari's pan+ // from taking a drag that is not perfectly level.+ touch(row, 'pointerMove', 22, 18);+ expect(touchMove(22, 18)).toBe(false);+ void act(() => vi.advanceTimersByTime(20));+ expect(travelOf(row)).toBe('12px');+ expect(row.style.getPropertyValue('--_item-swipe-dir')).toBe('1');+ expect(row.style.getPropertyValue('--_item-swipe-duration')).toBe('0s');+ touch(row, 'pointerMove', 50, 20);+ void act(() => vi.advanceTimersByTime(20));+ expect(travelOf(row)).toBe('40px');+ touch(row, 'pointerUp', 50, 20);+ settled();+ });++ it('leaves a mostly vertical drag to the scroller and never cancels its touchmove', () => {+ const {row} = renderRow();+ touch(row, 'pointerDown', 10, 10);+ touch(row, 'pointerMove', 14, 40);+ expect(+ fireEvent.touchMove(row, {+ cancelable: true,+ touches: [{clientX: 14, clientY: 40}],+ }),+ ).toBe(true);+ touch(row, 'pointerMove', 120, 200);+ expect(travelOf(row)).toBe('');+ touch(row, 'pointerUp', 120, 200);+ });++ it('ignores a mouse', () => {+ const {row} = renderRow();+ fireEvent.pointerDown(row, {+ clientX: 10,+ clientY: 10,+ pointerId: 1,+ pointerType: 'mouse',+ });+ fireEvent.pointerMove(row, {+ clientX: 60,+ clientY: 10,+ pointerId: 1,+ pointerType: 'mouse',+ });+ void act(() => vi.advanceTimersByTime(20));+ expect(travelOf(row)).toBe('');+ fireEvent.pointerUp(row, {+ clientX: 60,+ clientY: 10,+ pointerId: 1,+ pointerType: 'mouse',+ });+ });++ it('does not move toward a side without entries', () => {+ const {row} = renderRow({+ leading: [{label: 'Unread', onActivate: vi.fn()}],+ });+ touch(row, 'pointerDown', 200);+ touch(row, 'pointerMove', 150);+ void act(() => vi.advanceTimersByTime(20));+ expect(travelOf(row)).toBe('');+ touch(row, 'pointerUp', 150);+ });++ describe('reveal (the default)', () => {+ it('springs back when released short of half the panel, on the settle clock', () => {+ const {row} = renderRow();+ touch(row, 'pointerDown', 10);+ touch(row, 'pointerMove', 30);+ touch(row, 'pointerMove', 40);+ touch(row, 'pointerUp', 40);+ // 30 px of a 72 px panel: short. The spring back runs on the clock the+ // transforms read, then every inline property is gone.+ expect(row.style.getPropertyValue('--_item-swipe-duration')).toBe(+ '200ms',+ );+ expect(travelOf(row)).toBe('0px');+ settled();+ expect(travelOf(row)).toBe('');+ expect(row.style.getPropertyValue('--_item-swipe-dir')).toBe('');+ expect(panelOf(row, 'leading')).toHaveAttribute('inert');+ });++ it('rests open past half the panel, with every entry a real button, and fires a tapped entry', () => {+ const onActivate = vi.fn();+ const onClick = vi.fn();+ const {row} = renderRow({+ leading: [{label: 'Unread', onActivate}],+ onClick,+ });+ touch(row, 'pointerDown', 10);+ touch(row, 'pointerMove', 30);+ touch(row, 'pointerMove', 45);+ touch(row, 'pointerMove', 60);+ touch(row, 'pointerUp', 60);+ settled();+ // Resting at the panel's width; the panel is live.+ expect(travelOf(row)).toBe('72px');+ const panel = panelOf(row, 'leading') as HTMLElement;+ expect(panel).not.toHaveAttribute('inert');+ const button = screen.getByRole('button', {name: 'Unread'});+ expect(button).toBeVisible();+ // A tap fires it at once; without `hasRemoval` the row closes.+ fireEvent.click(button);+ expect(onActivate).toHaveBeenCalledTimes(1);+ settled();+ expect(travelOf(row)).toBe('');+ expect(panel).toHaveAttribute('inert');+ // The row's own primary never fired.+ expect(onClick).not.toHaveBeenCalled();+ });++ it('holds the row out after a tapped entry with hasRemoval', () => {+ const onActivate = vi.fn();+ const {row} = renderRow({+ trailing: [{label: 'Archive', onActivate, hasRemoval: true}],+ leading: [],+ });+ touch(row, 'pointerDown', 200);+ touch(row, 'pointerMove', 180);+ touch(row, 'pointerMove', 160);+ touch(row, 'pointerMove', 140);+ touch(row, 'pointerUp', 140);+ settled();+ expect(travelOf(row)).toBe('-72px');+ fireEvent.click(screen.getByRole('button', {name: 'Archive'}));+ expect(onActivate).toHaveBeenCalledTimes(1);+ settled();+ // Out past the edge it travelled toward, and staying there: the+ // caller removes the row, or it sits off-screen (their bug).+ expect(travelOf(row)).toBe('-324px');+ settled();+ expect(travelOf(row)).toBe('-324px');+ });++ it('closes a resting row on a pointer outside it, and on Escape with focus inside', () => {+ const {row} = renderRow();+ const open = () => {+ touch(row, 'pointerDown', 10);+ touch(row, 'pointerMove', 30);+ touch(row, 'pointerMove', 45);+ touch(row, 'pointerMove', 60);+ touch(row, 'pointerUp', 60);+ settled();+ expect(travelOf(row)).toBe('72px');+ };+ open();+ // A drag on a neighbour is a pointer outside this row.+ fireEvent.pointerDown(document.body, {+ pointerId: 9,+ pointerType: 'touch',+ });+ settled();+ expect(travelOf(row)).toBe('');+ open();+ const button = screen.getByRole('button', {name: 'Unread'});+ button.focus();+ fireEvent.keyDown(button, {key: 'Escape'});+ settled();+ expect(travelOf(row)).toBe('');+ // Focus lands on the row's own content, not on a now-inert button.+ expect(document.activeElement).toBe(+ screen.getByRole('button', {name: 'Conversation'}),+ );+ });++ it('fires the outermost entry and no other on a drag past the commit point, then springs back', () => {+ const inner = vi.fn();+ const outer = vi.fn();+ const {row} = renderRow({+ leading: [+ {label: 'Unread', onActivate: inner},+ {label: 'Pin', onActivate: outer},+ ],+ });+ touch(row, 'pointerDown', 10);+ touch(row, 'pointerMove', 40);+ // Two entries: a 144 px panel; the commit point is 192 (panel + 48),+ // past half the 300 px row.+ touch(row, 'pointerMove', 210);+ touch(row, 'pointerUp', 210);+ expect(outer).not.toHaveBeenCalled();+ // One beat: the slide out, then the entry fires.+ expect(travelOf(row)).toBe('324px');+ settled();+ expect(outer).toHaveBeenCalledTimes(1);+ expect(inner).not.toHaveBeenCalled();+ // No `hasRemoval`: back home.+ settled();+ expect(travelOf(row)).toBe('');+ });++ it('commits on a fling short of the commit point', () => {+ const onActivate = vi.fn();+ const {row} = renderRow({leading: [{label: 'Unread', onActivate}]});+ touch(row, 'pointerDown', 10);+ touch(row, 'pointerMove', 30);+ // 50 px in the 50 ms step: well past the fling speed.+ touch(row, 'pointerMove', 80);+ touch(row, 'pointerUp', 80);+ settled();+ expect(onActivate).toHaveBeenCalledTimes(1);+ });++ it('lays the entries outermost last: at the leading edge the row of entries runs in reverse', () => {+ const {row} = renderRow({+ leading: [+ {label: 'Unread', onActivate: vi.fn()},+ {label: 'Pin', onActivate: vi.fn()},+ ],+ trailing: [+ {label: 'Archive', onActivate: vi.fn()},+ {label: 'Delete', onActivate: vi.fn(), variant: 'destructive'},+ ],+ });+ const leading = panelOf(row, 'leading')?.firstElementChild as HTMLElement;+ const trailing = panelOf(row, 'trailing')+ ?.firstElementChild as HTMLElement;+ expect(+ rulesDeclaredFor(leading).some(r =>+ r.includes('flex-direction: row-reverse'),+ ),+ ).toBe(true);+ expect(+ rulesDeclaredFor(trailing).some(r =>+ r.includes('flex-direction: row-reverse'),+ ),+ ).toBe(false);+ // The panel wears its outermost entry's colour, so a slide-out fills+ // the row with it.+ const outerVariant = (panelOf(row, 'trailing') as HTMLElement).className;+ const deleteVariant = (trailing.lastElementChild as HTMLElement)+ .className;+ expect(outerVariant.split(' ').some(c => deleteVariant.includes(c))).toBe(+ true,+ );+ });+ });++ describe('commit', () => {+ it('slides out and fires on a release past the commit point; nothing rests', () => {+ const onActivate = vi.fn();+ const {row} = renderRow({+ behavior: 'commit',+ leading: [{label: 'Unread', onActivate}],+ });+ const panel = panelOf(row, 'leading') as HTMLElement;+ // Presentational at all times: nothing in it is ever tappable.+ expect(panel).toHaveAttribute('aria-hidden', 'true');+ expect(panel.querySelector('button')).toBeNull();+ touch(row, 'pointerDown', 10);+ touch(row, 'pointerMove', 40);+ // One entry: 72 px panel; the commit point is half the 300 px row.+ touch(row, 'pointerMove', 160);+ touch(row, 'pointerUp', 160);+ expect(travelOf(row)).toBe('324px');+ settled();+ expect(onActivate).toHaveBeenCalledTimes(1);+ settled();+ expect(travelOf(row)).toBe('');+ expect(panel).toHaveAttribute('aria-hidden', 'true');+ });++ it('springs back from any release short of the commit point, even past the panel', () => {+ const onActivate = vi.fn();+ const {row} = renderRow({+ behavior: 'commit',+ leading: [{label: 'Unread', onActivate}],+ });+ touch(row, 'pointerDown', 10);+ touch(row, 'pointerMove', 40);+ touch(row, 'pointerMove', 65);+ touch(row, 'pointerMove', 90);+ touch(row, 'pointerMove', 100);+ touch(row, 'pointerUp', 100);+ settled();+ expect(onActivate).not.toHaveBeenCalled();+ expect(travelOf(row)).toBe('');+ });++ it('holds out after a committed entry with hasRemoval', () => {+ const onActivate = vi.fn();+ const {row} = renderRow({+ behavior: 'commit',+ leading: [{label: 'Archive', onActivate, hasRemoval: true}],+ });+ touch(row, 'pointerDown', 10);+ touch(row, 'pointerMove', 40);+ touch(row, 'pointerMove', 160);+ touch(row, 'pointerUp', 160);+ settled();+ expect(onActivate).toHaveBeenCalledTimes(1);+ settled();+ expect(travelOf(row)).toBe('324px');+ });++ it('warns in development when a committing side has more than one entry', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ try {+ renderRow({+ behavior: 'commit',+ leading: [+ {label: 'Unread', onActivate: vi.fn()},+ {label: 'Pin', onActivate: vi.fn()},+ ],+ });+ expect(warn).toHaveBeenCalledWith(+ expect.stringContaining('swipeBehavior="commit"'),+ );+ } finally {+ warn.mockRestore();+ }+ });+ });++ it('swallows the click the browser synthesizes after a drag, so the primary does not fire', () => {+ const onClick = vi.fn();+ const {row} = renderRow({onClick});+ touch(row, 'pointerDown', 10);+ touch(row, 'pointerMove', 30);+ touch(row, 'pointerMove', 40);+ touch(row, 'pointerUp', 40);+ fireEvent.click(screen.getByRole('button', {name: 'Conversation'}));+ expect(onClick).not.toHaveBeenCalled();+ settled();+ // A later tap is a tap.+ vi.advanceTimersByTime(500);+ fireEvent.click(screen.getByRole('button', {name: 'Conversation'}));+ expect(onClick).toHaveBeenCalledTimes(1);+ });++ it('reads the direction logically under RTL: leading is toward the inline end, and the sign rides the root', () => {+ // jsdom resolves `direction` only on the element that carries `dir`; a+ // browser inherits it down to the row, so resolve that inheritance by+ // hand for this test.+ const original = window.getComputedStyle.bind(window);+ const spy = vi+ .spyOn(window, 'getComputedStyle')+ .mockImplementation((element, pseudo) => {+ const style = original(element, pseudo ?? undefined);+ if (element.closest('[dir="rtl"]') != null) {+ Object.defineProperty(style, 'direction', {+ configurable: true,+ value: 'rtl',+ });+ }+ return style;+ });+ try {+ const onActivate = vi.fn();+ render(+ <div dir="rtl">+ <Item+ label="Conversation"+ onClick={vi.fn()}+ data-testid="row"+ swipeActions={{leading: [{label: 'Unread', onActivate}]}}+ />+ </div>,+ );+ const row = screen.getByTestId('row');+ layOut(row);+ // Toward the inline end is leftward: the finger moves to smaller x.+ touch(row, 'pointerDown', 200);+ touch(row, 'pointerMove', 180);+ touch(row, 'pointerMove', 160);+ touch(row, 'pointerMove', 140);+ void act(() => vi.advanceTimersByTime(20));+ expect(row.style.getPropertyValue('--_item-swipe-dir')).toBe('-1');+ // Physical travel is negative; the transforms multiply by the sign.+ expect(travelOf(row)).toBe('-60px');+ touch(row, 'pointerUp', 140);+ settled();+ expect(travelOf(row)).toBe('-72px');+ // Rightward from a closed row is toward the inline start: no trailing+ // entries, so it is not claimed.+ fireEvent.pointerDown(document.body, {+ pointerId: 9,+ pointerType: 'touch',+ });+ settled();+ touch(row, 'pointerDown', 10);+ touch(row, 'pointerMove', 60);+ void act(() => vi.advanceTimersByTime(20));+ expect(travelOf(row)).toBe('');+ touch(row, 'pointerUp', 60);+ } finally {+ spy.mockRestore();+ }+ });+});diff --git a/packages/core/src/Item/Item.tsx b/packages/core/src/Item/Item.tsxindex d7bf5a72b6..231b9dbbab 100644--- a/packages/core/src/Item/Item.tsx+++ b/packages/core/src/Item/Item.tsx@@ -19,6 +19,8 @@import {useId, useRef, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import {+ fontWeightVars,+ typographyVars,colorVars,radiusVars,spacingVars,@@ -37,7 +39,13 @@ import {useDevWarning} from '../hooks/useDevWarning';import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {useMediaQuery} from '../hooks/useMediaQuery';import {usePressFeedback} from '../hooks/usePressFeedback';+import {+ useSwipeAction,+ type SwipeBehavior,+ type SwipeSide,+} from './useSwipeAction';// =============================================================================// Types@@ -46,6 +54,56 @@ import {usePressFeedback} from '../hooks/usePressFeedback';export type ItemAlign = 'center' | 'start';export type ItemDensity = 'compact' | 'balanced' | 'spacious';+/**+ * How a swipe action looks: ordinary, the one you mean, the dangerous one.+ * Three flavours of verb, not a status set.+ */+export type ItemSwipeActionVariant = 'neutral' | 'accent' | 'destructive';++/** One verb a sideways drag uncovers. Every field is known before the gesture begins. */+export interface ItemSwipeAction {+ id?: string;+ /**+ * The verb's name, and the button's accessible name while the row rests+ * open. Names the state the verb reaches ("Unread"), since the gesture+ * already supplies the verb.+ */+ label: string;+ /** Drawn above the label. */+ icon?: ReactNode;+ /**+ * Fires at activation: a tap on a resting entry, the full-swipe+ * accelerator, or a `commit` release. May return a Promise; the row+ * waits for nothing.+ */+ onActivate: () => void | Promise<void>;+ isDisabled?: boolean;+ /** @default 'accent' */+ variant?: ItemSwipeActionVariant;+ /**+ * After this action fires the row holds out at the edge it travelled+ * toward instead of springing back. Only that: not a promise the caller+ * removes the row, not an animation, not a timing rule.+ * @default false+ */+ hasRemoval?: boolean;+}++export interface ItemSwipeActions {+ /** Uncovered by a drag toward the inline end (rightward in LTR); outermost last. */+ leading?: ItemSwipeAction[];+ /** Uncovered by a drag toward the inline start (leftward in LTR); outermost last. */+ trailing?: ItemSwipeAction[];+}++/**+ * `reveal`: past half the panel the row rests open with every entry a real+ * button; a long drag or a fling fires the outermost. `commit`: a release+ * past the commit point slides the row out and fires the outermost entry;+ * nothing rests, and the panel is presentational.+ */+export type ItemSwipeBehavior = SwipeBehavior;+export interface ItemProps extends BaseProps<HTMLElement> {/** Ref forwarded to the root element. */ref?: React.Ref<HTMLElement>;@@ -187,6 +245,32 @@ export interface ItemProps extends BaseProps<HTMLElement> {*/isDisabled?: boolean;+ /**+ * Swipe actions for touch: the verbs a sideways drag uncovers on each side,+ * declared as data so the row paints the panel from them. A coarse pointer+ * drags the row aside and uncovers the side's panel; a mouse never starts+ * the drag, and a mostly vertical drag stays the scroller's. The gesture is+ * a touch accelerator and never a row's only path to a verb: a verb+ * reachable only by swipe is unreachable by keyboard and by mouse, so every+ * entry must also be reachable through the row's own content (a menu or a+ * button in `endContent`).+ *+ * Available on a row whose role permits interactive descendants — a+ * `listitem`, a row with no role — and not served on one whose role forbids+ * them (`option`, `menuitem*`, a row that is the enlarged target of a native+ * radio). The element containing the rows clips in the inline axis+ * (`overflow-inline: clip`): `List` does; any other host does it once.+ */+ swipeActions?: ItemSwipeActions;++ /**+ * What a swipe does: `reveal` rests the row open with every entry tappable+ * and fires the outermost on a long drag; `commit` slides the row out and+ * fires the outermost on release. `commit` fits one entry per side.+ * @default 'reveal'+ */+ swipeBehavior?: ItemSwipeBehavior;+/*** Test ID for testing frameworks.*/@@ -211,6 +295,22 @@ const ARIA_SELECTED_ROLES = new Set(['treeitem',]);+/**+ * Roles whose content model permits interactive descendants, so a swipe+ * panel's buttons may live inside the row. A row with no role at all+ * qualifies too; `option`, the `menuitem*` roles and the rest do not.+ */+const SWIPE_ROLES = new Set(['listitem']);++/** The travel a drag writes on the row root, in physical px (see useSwipeAction). */+const SWIPE_TRAVEL = 'var(--_item-swipe-travel, 0px)';+/** +1 when the inline end is to the right, -1 under RTL; written beside the travel. */+const SWIPE_DIR = 'var(--_item-swipe-dir, 1)';+/** The settle clock, `0s` while the finger drives the row. */+const SWIPE_DURATION = 'var(--_item-swipe-duration, 0s)';+/** The travel measured toward the inline end. */+const SWIPE_LOGICAL_TRAVEL = `calc(${SWIPE_TRAVEL} * ${SWIPE_DIR})`;+// =============================================================================// Styles// =============================================================================@@ -357,6 +457,107 @@ const styles = stylex.create({display: 'flex',marginInlineStart: 'auto',},+ // Swipe actions. The root translates by the drag's travel and settles on+ // the clock the gesture writes; `pan-y` lets the browser keep scrolling the+ // list while the row owns horizontal movement. The hover transition keeps+ // its own clock beside the transform's.+ swipeRoot: {+ isolation: 'isolate',+ touchAction: 'pan-y',+ transform: `translate3d(${SWIPE_TRAVEL}, 0, 0)`,+ transitionProperty: 'background-color, transform',+ transitionDuration: `${durationVars['--duration-fast-min']}, ${SWIPE_DURATION}`,+ transitionTimingFunction: `${easeVars['--ease-standard']}, ease-out`,+ },+ // A side's panel: an out-of-flow child of the root at the inline start or+ // end, counter-translated so it appears fixed in the space the row+ // vacates, and exactly as wide as the travel toward its side — a padded box+ // at `width: 0` would still paint its padding, so the panel has none; its+ // entries carry their own. Not a pixel of it shows at rest.+ swipePanel: {+ position: 'absolute',+ top: 0,+ bottom: 0,+ width: 0,+ display: 'flex',+ alignItems: 'stretch',+ boxSizing: 'border-box',+ overflow: 'hidden',+ borderRadius: 'inherit',+ transform: `translate3d(calc(-1 * ${SWIPE_TRAVEL}), 0, 0)`,+ transitionProperty: 'transform, width',+ transitionDuration: `${SWIPE_DURATION}, ${SWIPE_DURATION}`,+ transitionTimingFunction: 'ease-out, ease-out',+ },+ swipePanelLeading: {+ insetInlineStart: 0,+ justifyContent: 'flex-start',+ width: `max(0px, ${SWIPE_LOGICAL_TRAVEL})`,+ },+ swipePanelTrailing: {+ insetInlineEnd: 0,+ justifyContent: 'flex-end',+ width: `max(0px, calc(-1 * ${SWIPE_LOGICAL_TRAVEL}))`,+ },+ // The entries at their natural width; the panel clips them to the travel.+ // The outermost entry is the last, at the panel's outer edge: on the leading+ // side that is the inline start, so the row of entries runs in reverse.+ swipeEntries: {+ display: 'flex',+ flexShrink: 0,+ height: '100%',+ // The entries sit on the surface, not on the panel's own colour: the+ // neutral variant is translucent and would otherwise take the outermost+ // entry's colour through it.+ backgroundColor: colorVars['--color-background-surface'],+ },+ swipeEntriesLeading: {+ flexDirection: 'row-reverse',+ },+ swipeEntry: {+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ gap: spacingVars['--spacing-1'],+ minWidth: 72,+ height: '100%',+ paddingInline: spacingVars['--spacing-3'],+ boxSizing: 'border-box',+ margin: 0,+ borderWidth: 0,+ borderStyle: 'none',+ appearance: 'none',+ cursor: {+ default: 'pointer',+ ':is(:disabled,[aria-disabled="true"])': 'default',+ },+ fontFamily: typographyVars['--font-family-body'],+ fontSize: typeScaleVars['--text-supporting-size'],+ fontWeight: fontWeightVars['--font-weight-medium'],+ lineHeight: typeScaleVars['--text-supporting-leading'],+ whiteSpace: 'nowrap',+ },+ swipeEntryDisabled: {+ opacity: 0.5,+ },+});++// A verb's colour: ordinary, the one you mean, the dangerous one. The panel+// wears its outermost entry's, so a slide-out fills the row with it.+const swipeVariantStyles = stylex.create({+ neutral: {+ backgroundColor: colorVars['--color-neutral'],+ color: colorVars['--color-text-primary'],+ },+ accent: {+ backgroundColor: colorVars['--color-accent'],+ color: colorVars['--color-on-accent'],+ },+ destructive: {+ backgroundColor: colorVars['--color-error'],+ color: colorVars['--color-on-error'],+ },});const dynamicStyles = stylex.create({@@ -418,6 +619,8 @@ export function Item({isHighlighted = false,isSelected = false,isDisabled = false,+ swipeActions,+ swipeBehavior = 'reveal',xstyle,className,style,@@ -459,6 +662,59 @@ export function Item({// component means the root itself is the anchor, so the address rides it// and the invisible anchor below is not rendered.const isLinkRoot = typeof Component !== 'string' && href != null;++ // Swipe actions exist where the row's role permits interactive descendants+ // (a swipe panel's buttons are such descendants): a `listitem`, or no role+ // at all. A root that is itself a link, a row whose role forbids them, and+ // a row that is the enlarged target of a nested control are not served.+ const leadingSwipe = swipeActions?.leading ?? [];+ const trailingSwipe = swipeActions?.trailing ?? [];+ const hasSwipe =+ swipeActions != null &&+ (leadingSwipe.length > 0 || trailingSwipe.length > 0) &&+ !isDisabled &&+ !isDelegate &&+ !isLinkRoot &&+ (role == null || SWIPE_ROLES.has(role));+ useDevWarning(+ 'Item',+ '`swipeBehavior="commit"` fires only the outermost entry of a side; the ' ++ 'other entries have no touch path. Give a committing side one entry, ' ++ 'or use `swipeBehavior="reveal"`.',+ hasSwipe &&+ swipeBehavior === 'commit' &&+ (leadingSwipe.length > 1 || trailingSwipe.length > 1),+ );+ const swipeRootRef = useRef<HTMLElement | null>(null);+ const leadingEntriesRef = useRef<HTMLDivElement | null>(null);+ const trailingEntriesRef = useRef<HTMLDivElement | null>(null);+ const isReducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)');+ const outermost = (side: SwipeSide): ItemSwipeAction | undefined => {+ const entries = side === 'leading' ? leadingSwipe : trailingSwipe;+ return entries[entries.length - 1];+ };+ const swipe = useSwipeAction({+ isEnabled: hasSwipe,+ behavior: swipeBehavior,+ sides: {+ leading: leadingSwipe.length > 0,+ trailing: trailingSwipe.length > 0,+ },+ measurePanel: side =>+ (side === 'leading' ? leadingEntriesRef : trailingEntriesRef).current+ ?.offsetWidth ?? 0,+ fireOutermost: side => {+ const entry = outermost(side);+ if (entry == null || entry.isDisabled === true) {+ return false;+ }+ void entry.onActivate();+ return entry.hasRemoval === true;+ },+ isReducedMotion,+ rootRef: swipeRootRef,+ });+ const isSwipeResting = swipe.state.phase === 'resting';const linkRootProps = isLinkRoot? {// A disabled row keeps its place in the tree but goes nowhere.@@ -617,11 +873,121 @@ export function Item({);const mergedRef = useMergedRefs(ref, containerRef);+ const rootRef = useMergedRefs(+ (isDelegate ? mergedRef : ref) as React.Ref<HTMLElement>,+ hasSwipe ? swipeRootRef : undefined,+ );++ // The row's own primary, which the click the browser synthesizes after a+ // drag must not fire.+ const primaryOnClick = isDelegate+ ? delegatedOnClick+ : hasParentRole+ ? onClick+ : isInteractive+ ? handleContainerClick+ : undefined;+ const rootOnClick =+ hasSwipe && primaryOnClick != null+ ? (event: React.MouseEvent<HTMLElement>) => {+ if (swipe.shouldSuppressClick()) {+ return;+ }+ primaryOnClick(event);+ }+ : primaryOnClick;++ // A side's panel: entries as real buttons under `reveal`, presentational+ // blocks under `commit`. Out of the accessibility tree and the tab order+ // except while the row rests open, so the row keeps one tab stop and a+ // pointer that can hover never meets it.+ const renderSwipePanel = (side: SwipeSide, entries: ItemSwipeAction[]) => {+ if (entries.length === 0) {+ return null;+ }+ const outer = entries[entries.length - 1];+ const isCommit = swipeBehavior === 'commit';+ const isLive = isSwipeResting && !isCommit;+ return (+ <div+ key={side}+ data-swipe-panel={side}+ inert={isLive ? undefined : true}+ aria-hidden={isCommit ? true : undefined}+ {...mergeProps(+ themeProps('item-swipe-panel', {side}),+ stylex.props(+ styles.swipePanel,+ side === 'leading'+ ? styles.swipePanelLeading+ : styles.swipePanelTrailing,+ swipeVariantStyles[outer.variant ?? 'accent'],+ ),+ )}>+ <div+ ref={side === 'leading' ? leadingEntriesRef : trailingEntriesRef}+ {...stylex.props(+ styles.swipeEntries,+ side === 'leading' && styles.swipeEntriesLeading,+ )}>+ {entries.map(entry => {+ const variant = entry.variant ?? 'accent';+ const content = (+ <>+ {entry.icon}+ <span>{entry.label}</span>+ </>+ );+ const entryStyle = stylex.props(+ styles.swipeEntry,+ swipeVariantStyles[variant],+ entry.isDisabled === true && styles.swipeEntryDisabled,+ );+ if (isCommit) {+ return (+ <span+ key={entry.id ?? entry.label}+ {...mergeProps(+ themeProps('item-swipe-action', {variant}),+ entryStyle,+ )}>+ {content}+ </span>+ );+ }+ return (+ <button+ key={entry.id ?? entry.label}+ type="button"+ disabled={entry.isDisabled === true}+ onClick={() =>+ swipe.activateEntry(() => {+ void entry.onActivate();+ return entry.hasRemoval === true;+ })+ }+ {...mergeProps(+ themeProps('item-swipe-action', {variant}),+ focusOutlineProps.focusVisible(+ styles.swipeEntry,+ swipeVariantStyles[variant],+ entry.isDisabled === true && styles.swipeEntryDisabled,+ ),+ )}>+ {content}+ </button>+ );+ })}+ </div>+ </div>+ );+ };return (<Component- ref={(isDelegate ? mergedRef : ref) as React.Ref<never>}+ ref={rootRef as React.Ref<never>}{...restProps}+ {...(hasSwipe ? swipe.handlers : undefined)}{...linkRootProps}aria-selected={(allowsAriaSelected && isSelected) || undefined}// aria-selected is invalid on roles that don't permit it (listitem, a@@ -646,25 +1012,20 @@ export function Item({isHighlighted && styles.highlighted,isSelected && styles.selected,isDisabled && !hasParentRole && styles.disabled,+ hasSwipe && styles.swipeRoot,xstyle,),className,style,)}role={role}- onClick={- isDelegate- ? delegatedOnClick- : hasParentRole- ? onClick- : isInteractive- ? handleContainerClick- : undefined- }>+ onClick={rootOnClick}><ItemDescriptionContextvalue={hasRenderableDescription ? descriptionID : null}>{innerContent}</ItemDescriptionContext>+ {hasSwipe && renderSwipePanel('leading', leadingSwipe)}+ {hasSwipe && renderSwipePanel('trailing', trailingSwipe)}</Component>);}diff --git a/packages/core/src/Item/__tests__/ItemSwipeActions.a11y.chromium.spec.ts b/packages/core/src/Item/__tests__/ItemSwipeActions.a11y.chromium.spec.tsnew file mode 100644index 0000000000..7c37800458--- /dev/null+++ b/packages/core/src/Item/__tests__/ItemSwipeActions.a11y.chromium.spec.ts@@ -0,0 +1,331 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ItemSwipeActions.a11y.chromium.spec.ts+ * @input The checked-in Core/Item › Swipe Actions story, a built Storybook and+ * real Chromium touch input on a phone-sized viewport+ * @output Pixel and geometry proof of Item's swipe actions: no pixel of a+ * panel at rest, the panel fixed in the space the row vacates while the row+ * translates, none again when the drag comes back to its start without+ * lifting, the row resting open with a real button that fires on a tap and+ * closes the row, the panel shrinking with the row on the spring back, and a+ * fling toward the trailing side firing the outermost entry+ * @position Browser-only regression test for Item's swipeActions. jsdom can+ * hold the declared rules but not the paint or the geometry, and a real+ * device has already disagreed with jsdom once on this gesture.+ */++import {expect, test, type Locator} from '@playwright/test';+// @ts-expect-error -- pngjs ships no declarations; runtime support is pinned.+import {PNG} from 'pngjs';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;++test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});++test.afterAll(async () => {+ await storybook?.close();+});++// The gesture is touch only: Chromium accepts dispatched touch points only on+// a context that has a touchscreen. A phone-sized viewport keeps the commit+// point within a finger's reach.+test.use({hasTouch: true, viewport: {height: 800, width: 420}});++type Rgb = [number, number, number];++/** The leading panel sits at the inline start: in this LTR story, the left edge. */+const EDGE_BAND_PX = 8;+/** Per-channel distance beyond which two pixels are different colours. */+const DISTINCT = 24;++interface Shot {+ width: number;+ height: number;+ data: Uint8Array;+}++function decode(buffer: Buffer): Shot {+ const png = PNG.sync.read(buffer);+ return {width: png.width, height: png.height, data: png.data};+}++function pixel(shot: Shot, x: number, y: number): Rgb {+ const i = (y * shot.width + x) * 4;+ return [shot.data[i], shot.data[i + 1], shot.data[i + 2]];+}++function isDistinct(a: Rgb, b: Rgb): boolean {+ return (+ Math.abs(a[0] - b[0]) > DISTINCT ||+ Math.abs(a[1] - b[1]) > DISTINCT ||+ Math.abs(a[2] - b[2]) > DISTINCT+ );+}++/**+ * How many pixels in the row's leading edge band are not the row's own+ * background. The background is sampled at the row's bottom-right corner,+ * which holds neither text nor the panel.+ */+function paintedAtEdge(buffer: Buffer): number {+ const shot = decode(buffer);+ const ground = pixel(shot, shot.width - 2, shot.height - 2);+ let count = 0;+ for (let y = 0; y < shot.height; y += 1) {+ for (let x = 0; x < Math.min(EDGE_BAND_PX, shot.width); x += 1) {+ if (isDistinct(pixel(shot, x, y), ground)) {+ count += 1;+ }+ }+ }+ return count;+}++/** The row's horizontal translation, from its computed transform. */+async function translationOf(row: Locator): Promise<number> {+ return row.evaluate(node => {+ const matrix = new DOMMatrix(getComputedStyle(node).transform);+ return matrix.e;+ });+}++interface Box {+ x: number;+ y: number;+ width: number;+ height: number;+}++async function boxOf(locator: Locator): Promise<Box> {+ const box = await locator.boundingBox();+ if (box == null) {+ throw new Error('the element has no box');+ }+ return box;+}++test('paints no panel at rest, keeps the panel fixed while the row moves, rests open on a real button, and springs back with the panel', async ({+ page,+}) => {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-item--swipe-actions&viewMode=story`,+ {waitUntil: 'load'},+ );+ const row = page.locator('.astryx-item').first();+ await expect(row).toBeVisible();+ const panel = row.locator('[data-swipe-panel="leading"]');+ await expect(panel).toBeAttached();+ // The row's resting footprint: every paint sample is of this rectangle,+ // which the row vacates as it moves.+ const rest = await boxOf(row);+ const shoot = async () => page.screenshot({clip: rest});++ // At rest: inert, and the row's leading edge is nothing but its own+ // background — no sliver of a padding box.+ await expect(panel).toHaveAttribute('inert', '');+ expect(paintedAtEdge(await shoot())).toBe(0);++ const y = rest.y + rest.height / 2;+ const startX = rest.x + 24;+ const cdp = await page.context().newCDPSession(page);+ const touch = async (+ type: 'touchStart' | 'touchMove' | 'touchEnd',+ x?: number,+ ) =>+ cdp.send('Input.dispatchTouchEvent', {+ touchPoints: x == null ? [] : [{x, y}],+ type,+ });+ const dragTo = async (offsets: number[]) => {+ for (const dx of offsets) {+ await touch('touchMove', startX + dx);+ await page.waitForTimeout(40);+ }+ };++ await touch('touchStart', startX);+ // Past the axis lock and clearly horizontal, short of the commit point.+ await dragTo([6, 14, 28, 44, 60]);++ // Under the drag: the row has moved by the travel, the panel is fixed at+ // the row's resting edge (counter-translated) and exactly as wide as the+ // travel, and its colour fills the vacated edge.+ await expect.poll(async () => translationOf(row)).toBeGreaterThan(50);+ const dragged = await boxOf(panel);+ expect(Math.abs(dragged.x - rest.x)).toBeLessThanOrEqual(1);+ expect(+ Math.abs(dragged.width - (await translationOf(row))),+ ).toBeLessThanOrEqual(1);+ expect(paintedAtEdge(await shoot())).toBeGreaterThan(0);++ // Back to the start and past it without lifting: the row is home and the+ // panel is a zero-width box again, so nothing of it paints.+ await dragTo([40, 20, 4, -6]);+ await expect.poll(async () => translationOf(row)).toBe(0);+ await expect.poll(async () => paintedAtEdge(await shoot())).toBe(0);++ // Out again past half the panel, then released: the row rests open at the+ // panel's width with its entry a real, focusable button.+ await dragTo([10, 30, 45, 60]);+ await touch('touchEnd');+ await expect(panel).not.toHaveAttribute('inert');+ const entry = panel.getByRole('button', {name: 'Read'});+ await expect(entry).toBeVisible();+ await expect.poll(async () => translationOf(row)).toBe(72);+ expect(Math.abs((await boxOf(panel)).width - 72)).toBeLessThanOrEqual(1);+ await entry.focus();+ await expect(entry).toBeFocused();++ // A tap on the entry fires it (the story toggles the row's read state) and,+ // without `hasRemoval`, closes the row.+ const entryBox = await boxOf(entry);+ await cdp.send('Input.dispatchTouchEvent', {+ touchPoints: [+ {x: entryBox.x + entryBox.width / 2, y: entryBox.y + entryBox.height / 2},+ ],+ type: 'touchStart',+ });+ await cdp.send('Input.dispatchTouchEvent', {+ touchPoints: [],+ type: 'touchEnd',+ });+ await expect(row.getByText('Read', {exact: true})).toBeVisible();+ await expect(panel).toHaveAttribute('inert', '');+ await expect.poll(async () => translationOf(row)).toBe(0);+ // Focus moved to the row's own content when its panel closed under it, and+ // the row's focus ring is the one thing allowed at its edge: drop it before+ // sampling for the panel.+ await page.evaluate(() => {+ (document.activeElement as HTMLElement | null)?.blur();+ });+ await expect.poll(async () => paintedAtEdge(await shoot())).toBe(0);++ // The spring back: a short drag released before half the panel. The row+ // slides home on its clock and the panel's width runs on the same one, so+ // mid-flight the gap the row has not yet covered is still the panel.+ await touch('touchStart', startX);+ await dragTo([8, 16, 24, 30]);+ await expect.poll(async () => translationOf(row)).toBeGreaterThan(20);+ await touch('touchEnd');+ const midFlight = await row.evaluate(+ async (node, selector) =>+ new Promise<{rowX: number; panelWidth: number}>(resolve => {+ setTimeout(() => {+ const panelEl = node.querySelector(selector) as HTMLElement;+ const matrix = new DOMMatrix(getComputedStyle(node).transform);+ resolve({+ panelWidth: parseFloat(getComputedStyle(panelEl).width),+ rowX: Math.abs(matrix.e),+ });+ }, 60);+ }),+ '[data-swipe-panel="leading"]',+ );+ expect(midFlight.rowX).toBeGreaterThan(2);+ expect(Math.abs(midFlight.panelWidth - midFlight.rowX)).toBeLessThanOrEqual(+ 6,+ );+ await expect.poll(async () => translationOf(row)).toBe(0);+ await expect.poll(async () => paintedAtEdge(await shoot())).toBe(0);+});++test('fires the outermost trailing entry on a fling and the row leaves', async ({+ page,+}) => {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-item--swipe-actions&viewMode=story`,+ {waitUntil: 'load'},+ );+ const rows = page.locator('.astryx-item');+ const row = rows.first();+ await expect(row.getByText('Message 1')).toBeVisible();+ const before = await rows.count();+ const rest = await boxOf(row);+ const y = rest.y + rest.height / 2;+ const startX = rest.x + rest.width - 24;+ const cdp = await page.context().newCDPSession(page);+ const at = async (x: number, type: 'touchStart' | 'touchMove') =>+ cdp.send('Input.dispatchTouchEvent', {touchPoints: [{x, y}], type});++ // Toward the inline start: the trailing panel, Delete outermost. A slow+ // start claims the drag; the last step is quick, so the release is a fling+ // short of the commit point.+ await at(startX, 'touchStart');+ for (const dx of [6, 14, 28]) {+ await at(startX - dx, 'touchMove');+ await page.waitForTimeout(40);+ }+ await at(startX - 44, 'touchMove');+ await at(startX - 90, 'touchMove');+ await cdp.send('Input.dispatchTouchEvent', {+ touchPoints: [],+ type: 'touchEnd',+ });++ // One beat: the slide out, then the entry fires; the story removes the row.+ await expect(page.getByText('Message 1')).toHaveCount(0);+ await expect(rows).toHaveCount(before - 1);+});++test('the trailing panel: Delete is outermost and the panel wears its colour', async ({+ page,+}) => {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-item--swipe-actions&viewMode=story`,+ {waitUntil: 'load'},+ );+ const row = page.locator('.astryx-item').first();+ const panel = row.locator('[data-swipe-panel="trailing"]');+ const rest = await boxOf(row);+ const y = rest.y + rest.height / 2;+ const startX = rest.x + rest.width - 24;+ const cdp = await page.context().newCDPSession(page);+ await cdp.send('Input.dispatchTouchEvent', {+ touchPoints: [{x: startX, y}],+ type: 'touchStart',+ });+ for (const dx of [6, 14, 28, 44, 60, 80]) {+ await cdp.send('Input.dispatchTouchEvent', {+ touchPoints: [{x: startX - dx, y}],+ type: 'touchMove',+ });+ await page.waitForTimeout(40);+ }+ await expect.poll(async () => translationOf(row)).toBeLessThan(-60);+ // Fixed at the row's resting trailing edge, as wide as the travel.+ const dragged = await boxOf(panel);+ expect(+ Math.abs(dragged.x + dragged.width - (rest.x + rest.width)),+ ).toBeLessThanOrEqual(1);+ // The entries run Archive then Delete toward the outer edge; the panel's+ // own background is Delete's.+ const [panelColor, deleteColor, archiveColor] = await panel.evaluate(node => {+ const buttons = Array.from(node.querySelectorAll('button'));+ const last = buttons[buttons.length - 1];+ const first = buttons[0];+ return [+ getComputedStyle(node).backgroundColor,+ getComputedStyle(last).backgroundColor,+ getComputedStyle(first).backgroundColor,+ ];+ });+ expect(panelColor).toBe(deleteColor);+ expect(archiveColor).not.toBe(deleteColor);+ const deleteBox = await boxOf(panel.getByRole('button', {name: 'Delete'}));+ const archiveBox = await boxOf(panel.getByRole('button', {name: 'Archive'}));+ expect(deleteBox.x).toBeGreaterThan(archiveBox.x);+ await cdp.send('Input.dispatchTouchEvent', {+ touchPoints: [],+ type: 'touchEnd',+ });+});diff --git a/packages/core/src/Item/index.ts b/packages/core/src/Item/index.tsindex 3cb50e9857..b44df5be1f 100644--- a/packages/core/src/Item/index.ts+++ b/packages/core/src/Item/index.ts@@ -10,4 +10,12 @@*/export {Item} from './Item';-export type {ItemProps, ItemAlign, ItemDensity} from './Item';+export type {+ ItemProps,+ ItemAlign,+ ItemDensity,+ ItemSwipeAction,+ ItemSwipeActions,+ ItemSwipeActionVariant,+ ItemSwipeBehavior,+} from './Item';diff --git a/packages/core/src/Item/useSwipeAction.ts b/packages/core/src/Item/useSwipeAction.tsnew file mode 100644index 0000000000..bf143fe69c--- /dev/null+++ b/packages/core/src/Item/useSwipeAction.ts@@ -0,0 +1,656 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useSwipeAction.ts+ * @input Pointer events on a row's root; the root element to translate+ * @output Exports useSwipeAction — the gesture behind Item's `swipeActions`+ * @position Internal to Item; tested through Item.test.tsx+ *+ * A native-list swipe: drag a row sideways and the side's panel is uncovered.+ * Under `reveal` a release past half the panel leaves the row resting open+ * with every entry tappable, and a long drag or a fling fires the outermost+ * entry; under `commit` a release past the commit point slides the row out+ * and fires the outermost entry, and nothing rests. After an entry fires the+ * row springs back, or holds out when the entry has `hasRemoval`. A release+ * short of the threshold springs back under both.+ *+ * Touch only, by pointer type rather than by breakpoint: a mouse has the+ * row's own controls and a keyboard has the verb already; the gesture is an+ * accelerator for a verb the row exposes elsewhere, never the only way to+ * reach one.+ *+ * The axis is decided once, at 10 px of travel: a drag more vertical than+ * horizontal belongs to the scroller and is never claimed. The claim is told+ * to the browser: `touch-action: pan-y` is not enough on iOS Safari, whose+ * scroller takes any drag with a vertical component as a pan (a 4:1 drag got+ * `pointercancel` 40 px in; the same drag after a one-second hold, which+ * fails the native pan, ran to the end), so a non-passive `touchmove`+ * listener cancels the default while the row owns the drag, which is the one+ * signal WebKit honours. Before the axis is decided, and for a drag the+ * scroller got, nothing is cancelled.+ *+ * The drag's travel is one custom property written on the root, coalesced to+ * one write per frame; the root's transform reads it and the panels'+ * transforms read its negation, so the row moves and the panel appears fixed+ * in the space the row vacates. Settling (the spring back, the slide out)+ * writes a duration the same elements read as their transition clock, so+ * everything derived from the travel moves together. A drag costs no React+ * render; the claim and the settle each cost one.+ *+ * Directions are logical: `leading` is a drag toward the inline end and+ * `trailing` a drag toward the inline start, read against the root's computed+ * `direction` at the touch and written beside the travel as a sign the+ * transforms multiply by, so under `dir="rtl"` the finger, the uncovered edge+ * and the panel's logical inset agree.+ */++import {useCallback, useEffect, useRef, useState} from 'react';+import type {+ PointerEvent as ReactPointerEvent,+ KeyboardEvent as ReactKeyboardEvent,+ MouseEvent as ReactMouseEvent,+} from 'react';+import {isRtlElement} from '../hooks/isRtlElement';++/** The travel, in physical px, written on the row root during a drag. */+export const SWIPE_TRAVEL_PROPERTY = '--_item-swipe-travel';+/** +1 when the inline end is to the right (LTR), -1 under RTL. */+export const SWIPE_DIRECTION_PROPERTY = '--_item-swipe-dir';+/** The clock a settle runs on; `0s` while the finger drives the row. */+export const SWIPE_DURATION_PROPERTY = '--_item-swipe-duration';++/** Travel before the axis is decided. */+const AXIS_LOCK_PX = 10;+/** The commit point: this far past the side's panel, or this fraction of the row, whichever is greater. */+const COMMIT_PAST_PANEL_PX = 48;+const COMMIT_FRACTION = 0.5;+/** Under `reveal`, a release this far into the panel rests the row open. */+const REST_FRACTION = 0.5;+/** Travel past the commit point moves the row this much per pixel of finger. */+const OVERSHOOT_RESISTANCE = 0.35;+/** A release at this speed commits from FLING_MIN_PX, short of the commit point. */+const FLING_VELOCITY_PX_PER_MS = 0.6;+const FLING_MIN_PX = 44;+/** How far past the row's edge a slide-out travels. */+const SLIDE_OUT_OVERSHOOT_PX = 24;+/** The slide-out after a commit, and the spring back after a release. */+export const SWIPE_SETTLE_MS = 200;+/** A click the browser synthesizes after a swipe is not a tap on the row. */+const CLICK_SUPPRESS_MS = 400;++export type SwipeSide = 'leading' | 'trailing';+export type SwipeBehavior = 'reveal' | 'commit';+export type SwipePhase =+ /** At rest, closed. */+ | 'idle'+ /** The finger drives the row. */+ | 'dragging'+ /** Springing back or sliding out, on the settle clock. */+ | 'settling'+ /** Resting open with the side's panel tappable (`reveal` only). */+ | 'resting'+ /** Slid out after an entry with `hasRemoval` fired. */+ | 'held';++export interface SwipeState {+ phase: SwipePhase;+ /** The side whose panel is uncovered, or will be. */+ side: SwipeSide;+ /** Past the commit point: letting go now fires the outermost entry. */+ isArmed: boolean;+}++export interface UseSwipeActionOptions {+ /** Off: the handlers do nothing and no row moves. */+ isEnabled: boolean;+ behavior: SwipeBehavior;+ /** Which sides have entries. A drag toward a side without any is not claimed. */+ sides: {leading: boolean; trailing: boolean};+ /** The natural width of a side's panel, read when a drag begins. */+ measurePanel: (side: SwipeSide) => number;+ /**+ * Fire the side's outermost entry. Returns whether the row holds out+ * afterwards (the entry's `hasRemoval`).+ */+ fireOutermost: (side: SwipeSide) => boolean;+ /** Skip the slide and spring animations. */+ isReducedMotion?: boolean;+ /** The row root: the gesture's target and the element that translates. */+ rootRef: React.RefObject<HTMLElement | null>;+}++export interface SwipeHandlers {+ onPointerDown: (event: ReactPointerEvent) => void;+ onPointerMove: (event: ReactPointerEvent) => void;+ onPointerUp: (event: ReactPointerEvent) => void;+ onPointerCancel: (event: ReactPointerEvent) => void;+ onClickCapture: (event: ReactMouseEvent) => void;+ onKeyDown: (event: ReactKeyboardEvent) => void;+}++export interface UseSwipeActionResult {+ state: SwipeState;+ handlers: SwipeHandlers;+ /**+ * A resting panel's entry was tapped: fire it, then hold the row out+ * (`hasRemoval`) or close.+ */+ activateEntry: (fire: () => boolean) => void;+ /** Close a resting row. */+ close: () => void;+ /** Whether a click arriving now is the one the browser synthesized after a drag. */+ shouldSuppressClick: () => boolean;+}++interface DragState {+ pointerId: number;+ startX: number;+ startY: number;+ /** The travel the row already had when the finger landed (a resting row). */+ baseTravel: number;+ /** null until the axis is decided; false once it went to the scroller. */+ claimed: boolean | null;+ side: SwipeSide;+ panelWidth: number;+ commitPx: number;+ lastX: number;+ lastTime: number;+ prevX: number;+ prevTime: number;+ /** Logical travel toward the side, before resistance. */+ travel: number;+ inlineSign: 1 | -1;+}++const IDLE_STATE: SwipeState = {isArmed: false, phase: 'idle', side: 'leading'};++/** The logical sign of a side: +1 toward the inline end, -1 toward the start. */+function signOf(side: SwipeSide): number {+ return side === 'trailing' ? -1 : 1;+}++function now(): number {+ return typeof performance === 'undefined' ? Date.now() : performance.now();+}++/**+ * The first focusable thing in the row outside its swipe panels, for focus to+ * land on when a resting panel closes under it.+ */+function focusRowContent(root: HTMLElement): void {+ const candidates = root.querySelectorAll<HTMLElement>(+ 'button, a[href], input, [tabindex]:not([tabindex="-1"])',+ );+ for (const el of candidates) {+ if (el.closest('[data-swipe-panel]') == null) {+ el.focus();+ return;+ }+ }+ if (document.activeElement instanceof HTMLElement) {+ document.activeElement.blur();+ }+}++export function useSwipeAction({+ isEnabled,+ behavior,+ sides,+ measurePanel,+ fireOutermost,+ isReducedMotion = false,+ rootRef,+}: UseSwipeActionOptions): UseSwipeActionResult {+ const dragRef = useRef<DragState | null>(null);+ const travelRef = useRef(0);+ const inlineSignRef = useRef<1 | -1>(1);+ const suppressClickUntilRef = useRef(0);+ const settleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const frameRef = useRef<number | null>(null);+ const pendingRef = useRef<number | null>(null);+ const [state, setState] = useState<SwipeState>(IDLE_STATE);+ const stateRef = useRef(state);+ stateRef.current = state;++ // The latest callbacks, read by handlers and timers that outlive a render.+ const measurePanelRef = useRef(measurePanel);+ const fireOutermostRef = useRef(fireOutermost);+ const sidesRef = useRef(sides);+ const behaviorRef = useRef(behavior);+ const reducedMotionRef = useRef(isReducedMotion);+ useEffect(() => {+ measurePanelRef.current = measurePanel;+ fireOutermostRef.current = fireOutermost;+ sidesRef.current = sides;+ behaviorRef.current = behavior;+ reducedMotionRef.current = isReducedMotion;+ });++ useEffect(+ () => () => {+ if (settleTimerRef.current != null) {+ clearTimeout(settleTimerRef.current);+ }+ if (frameRef.current != null) {+ cancelAnimationFrame(frameRef.current);+ }+ },+ [],+ );++ /** Write the travel (physical px) the transforms read. */+ const writeTravel = useCallback(+ (travel: number) => {+ const root = rootRef.current;+ if (!root) {+ return;+ }+ travelRef.current = travel;+ root.style.setProperty(SWIPE_TRAVEL_PROPERTY, `${travel}px`);+ },+ [rootRef],+ );++ const writeDuration = useCallback(+ (ms: number) => {+ const root = rootRef.current;+ if (!root) {+ return;+ }+ if (ms > 0) {+ root.style.setProperty(SWIPE_DURATION_PROPERTY, `${ms}ms`);+ } else {+ root.style.setProperty(SWIPE_DURATION_PROPERTY, '0s');+ }+ },+ [rootRef],+ );++ const clearInlineProperties = useCallback(() => {+ const root = rootRef.current;+ if (!root) {+ return;+ }+ root.style.removeProperty(SWIPE_TRAVEL_PROPERTY);+ root.style.removeProperty(SWIPE_DIRECTION_PROPERTY);+ root.style.removeProperty(SWIPE_DURATION_PROPERTY);+ travelRef.current = 0;+ }, [rootRef]);++ const cancelPendingPaint = useCallback(() => {+ if (frameRef.current != null) {+ cancelAnimationFrame(frameRef.current);+ }+ frameRef.current = null;+ pendingRef.current = null;+ }, []);++ /** One write per frame while the finger drives the row. */+ const paintOnNextFrame = useCallback(+ (travel: number) => {+ pendingRef.current = travel;+ if (frameRef.current != null) {+ return;+ }+ frameRef.current = requestAnimationFrame(() => {+ frameRef.current = null;+ const next = pendingRef.current;+ pendingRef.current = null;+ if (next != null) {+ writeTravel(next);+ }+ });+ },+ [writeTravel],+ );++ /**+ * Move the row to `travel` on the settle clock, then land in `phase`. A+ * zero clock (reduced motion) lands at once.+ */+ const settle = useCallback(+ (+ side: SwipeSide,+ travel: number,+ phase: 'idle' | 'resting' | 'held',+ afterSlide?: () => boolean,+ ) => {+ cancelPendingPaint();+ const duration = reducedMotionRef.current ? 0 : SWIPE_SETTLE_MS;+ setState({isArmed: false, phase: 'settling', side});+ writeDuration(duration);+ writeTravel(travel);+ if (settleTimerRef.current != null) {+ clearTimeout(settleTimerRef.current);+ }+ settleTimerRef.current = setTimeout(() => {+ settleTimerRef.current = null;+ writeDuration(0);+ // A settle that fires an entry may start the spring back itself; the+ // landing below is then that settle's to make.+ if (afterSlide?.() === true) {+ return;+ }+ if (phase === 'idle') {+ clearInlineProperties();+ }+ setState(phase === 'idle' ? IDLE_STATE : {isArmed: false, phase, side});+ }, duration);+ },+ [cancelPendingPaint, clearInlineProperties, writeDuration, writeTravel],+ );++ /**+ * The outermost entry fires. Under both models the row first travels to+ * its slide-out, fires, then holds out (`hasRemoval`) or springs back.+ */+ const slideOutAndFire = useCallback(+ (side: SwipeSide, inlineSign: 1 | -1) => {+ const root = rootRef.current;+ const width = root?.clientWidth ?? 0;+ const out = signOf(side) * inlineSign * (width + SLIDE_OUT_OVERSHOOT_PX);+ settle(side, out, 'held', () => {+ const holdsOut = fireOutermostRef.current(side);+ if (holdsOut) {+ return false;+ }+ settle(side, 0, 'idle');+ return true;+ });+ },+ [rootRef, settle],+ );++ const close = useCallback(() => {+ const current = stateRef.current;+ if (current.phase !== 'resting') {+ return;+ }+ const root = rootRef.current;+ if (root != null && root.contains(document.activeElement)) {+ focusRowContent(root);+ }+ settle(current.side, 0, 'idle');+ }, [rootRef, settle]);++ // A resting row closes on a pointer landing anywhere outside it, which is+ // also how a drag on a neighbour closes it: one row rests open at a time+ // with no shared state.+ useEffect(() => {+ if (state.phase !== 'resting') {+ return undefined;+ }+ const onOutside = (event: PointerEvent) => {+ const root = rootRef.current;+ if (+ root != null &&+ event.target instanceof Node &&+ !root.contains(event.target)+ ) {+ close();+ }+ };+ document.addEventListener('pointerdown', onOutside, true);+ return () => {+ document.removeEventListener('pointerdown', onOutside, true);+ };+ }, [close, rootRef, state.phase]);++ // The browser's half of the claim (see the header). React's own touch+ // listeners are passive, so this one is attached by hand; it is removed+ // with the element.+ useEffect(() => {+ const root = rootRef.current;+ if (root == null || !isEnabled) {+ return undefined;+ }+ const onTouchMove = (event: TouchEvent) => {+ if (dragRef.current?.claimed === true && event.cancelable) {+ event.preventDefault();+ }+ };+ root.addEventListener('touchmove', onTouchMove, {passive: false});+ return () => {+ root.removeEventListener('touchmove', onTouchMove);+ };+ }, [isEnabled, rootRef]);++ const activateEntry = useCallback(+ (fire: () => boolean) => {+ const current = stateRef.current;+ if (current.phase !== 'resting') {+ return;+ }+ const root = rootRef.current;+ if (root != null && root.contains(document.activeElement)) {+ focusRowContent(root);+ }+ const holdsOut = fire();+ if (holdsOut) {+ const width = root?.clientWidth ?? 0;+ const out =+ signOf(current.side) *+ inlineSignRef.current *+ (width + SLIDE_OUT_OVERSHOOT_PX);+ settle(current.side, out, 'held');+ } else {+ settle(current.side, 0, 'idle');+ }+ },+ [rootRef, settle],+ );++ const onPointerDown = useCallback(+ (event: ReactPointerEvent) => {+ const current = stateRef.current;+ if (+ !isEnabled ||+ event.pointerType !== 'touch' ||+ dragRef.current != null ||+ current.phase === 'settling' ||+ current.phase === 'held'+ ) {+ return;+ }+ const root = rootRef.current;+ const inlineSign: 1 | -1 = isRtlElement(root) ? -1 : 1;+ inlineSignRef.current = inlineSign;+ const startTime = now();+ dragRef.current = {+ // Logical: the physical travel through the inline sign.+ baseTravel: travelRef.current * inlineSign,+ claimed: null,+ commitPx: 0,+ inlineSign,+ lastTime: startTime,+ lastX: event.clientX,+ panelWidth: 0,+ pointerId: event.pointerId,+ prevTime: startTime,+ prevX: event.clientX,+ side: current.phase === 'resting' ? current.side : 'leading',+ startX: event.clientX,+ startY: event.clientY,+ travel: 0,+ };+ },+ [isEnabled, rootRef],+ );++ const onPointerMove = useCallback(+ (event: ReactPointerEvent) => {+ const drag = dragRef.current;+ if (+ drag == null ||+ drag.pointerId !== event.pointerId ||+ drag.claimed === false+ ) {+ return;+ }+ // Logical travel: positive toward the inline end.+ const deltaX = (event.clientX - drag.startX) * drag.inlineSign;+ const deltaY = event.clientY - drag.startY;+ if (drag.claimed === null) {+ if (Math.max(Math.abs(deltaX), Math.abs(deltaY)) < AXIS_LOCK_PX) {+ return;+ }+ // More horizontal than vertical is the row's, the rest the scroller's.+ if (Math.abs(deltaX) <= Math.abs(deltaY)) {+ drag.claimed = false;+ return;+ }+ const resting = stateRef.current.phase === 'resting';+ // From rest, the drag continues the open side (closing it or going+ // further); from closed, the drag's direction names the side.+ const side: SwipeSide = resting+ ? drag.side+ : deltaX > 0+ ? 'leading'+ : 'trailing';+ if (!sidesRef.current[side]) {+ drag.claimed = false;+ return;+ }+ drag.claimed = true;+ drag.side = side;+ drag.panelWidth = measurePanelRef.current(side);+ const width = rootRef.current?.clientWidth ?? 0;+ drag.commitPx = Math.max(+ drag.panelWidth + COMMIT_PAST_PANEL_PX,+ width * COMMIT_FRACTION,+ );+ if (rootRef.current != null) {+ rootRef.current.style.setProperty(+ SWIPE_DIRECTION_PROPERTY,+ String(drag.inlineSign),+ );+ }+ writeDuration(0);+ setState({isArmed: false, phase: 'dragging', side});+ try {+ rootRef.current?.setPointerCapture(event.pointerId);+ } catch {+ // Pointer capture is a nicety (keeps the drag when the finger+ // leaves the row); a platform without it still drags.+ }+ }+ const sign = signOf(drag.side);+ // Travel toward the side, counted from where the row already was.+ const raw = Math.max(0, deltaX * sign + drag.baseTravel * sign);+ const offset =+ raw <= drag.commitPx+ ? raw+ : drag.commitPx + (raw - drag.commitPx) * OVERSHOOT_RESISTANCE;+ const isArmed = raw >= drag.commitPx;+ if (isArmed !== drag.travel >= drag.commitPx) {+ setState({isArmed, phase: 'dragging', side: drag.side});+ }+ drag.travel = raw;+ drag.prevX = drag.lastX;+ drag.prevTime = drag.lastTime;+ drag.lastX = event.clientX;+ drag.lastTime = now();+ paintOnNextFrame(sign * drag.inlineSign * offset);+ },+ [paintOnNextFrame, rootRef, writeDuration],+ );++ const endGesture = useCallback(+ (event: ReactPointerEvent, cancelled: boolean) => {+ const drag = dragRef.current;+ if (drag == null || drag.pointerId !== event.pointerId) {+ return;+ }+ dragRef.current = null;+ if (drag.claimed !== true) {+ return;+ }+ suppressClickUntilRef.current = now() + CLICK_SUPPRESS_MS;+ try {+ rootRef.current?.releasePointerCapture(event.pointerId);+ } catch {+ // See setPointerCapture above.+ }+ const {side, inlineSign} = drag;+ const restTravel = signOf(side) * inlineSign * drag.panelWidth;+ if (cancelled) {+ settle(side, 0, 'idle');+ return;+ }+ const elapsed = Math.max(1, drag.lastTime - drag.prevTime);+ const velocity =+ (signOf(side) * inlineSign * (drag.lastX - drag.prevX)) / elapsed;+ const flung =+ velocity >= FLING_VELOCITY_PX_PER_MS && drag.travel >= FLING_MIN_PX;+ if (drag.travel >= drag.commitPx || flung) {+ slideOutAndFire(side, inlineSign);+ return;+ }+ if (+ behaviorRef.current === 'reveal' &&+ drag.travel >= drag.panelWidth * REST_FRACTION+ ) {+ settle(side, restTravel, 'resting');+ return;+ }+ settle(side, 0, 'idle');+ },+ [rootRef, settle, slideOutAndFire],+ );++ const onPointerUp = useCallback(+ (event: ReactPointerEvent) => endGesture(event, false),+ [endGesture],+ );+ const onPointerCancel = useCallback(+ (event: ReactPointerEvent) => endGesture(event, true),+ [endGesture],+ );+ const shouldSuppressClick = useCallback(+ () => now() < suppressClickUntilRef.current,+ [],+ );+ const onClickCapture = useCallback(+ (event: ReactMouseEvent) => {+ // A tap on a resting panel's entry is a tap, however soon after the+ // drag that opened it; the synthesized click lands on the row's content.+ if (+ !shouldSuppressClick() ||+ (event.target instanceof Element &&+ event.target.closest('[data-swipe-panel]') != null)+ ) {+ return;+ }+ suppressClickUntilRef.current = 0;+ event.preventDefault();+ event.stopPropagation();+ },+ [shouldSuppressClick],+ );+ const onKeyDown = useCallback(+ (event: ReactKeyboardEvent) => {+ if (event.key === 'Escape' && stateRef.current.phase === 'resting') {+ event.stopPropagation();+ close();+ }+ },+ [close],+ );++ return {+ activateEntry,+ close,+ handlers: {+ onClickCapture,+ onKeyDown,+ onPointerCancel,+ onPointerDown,+ onPointerMove,+ onPointerUp,+ },+ shouldSuppressClick,+ state,+ };+}diff --git a/packages/core/src/List/List.spec.md b/packages/core/src/List/List.spec.mdindex 9f83500c25..d66175de56 100644--- a/packages/core/src/List/List.spec.md+++ b/packages/core/src/List/List.spec.md@@ -25,7 +25,7 @@ design_specs: []architecture:[architecture:container-padding, architecture:public-component-api]contributing: [contributing:api-conventions]-system_specs: [spec:AST-002/DEC-1, spec:AST-002/DEC-2]+system_specs: [spec:AST-002/DEC-1, spec:AST-002/DEC-2, spec:AST-057/FR9]---# List component contract@@ -94,6 +94,7 @@ Consumer migration instructions belong in consumer docs and release notes.| FR4 | The retained row inset MUST come from the same private density- and theme-derived source as Item's applied inline padding. A consumer override of row padding through `xstyle`, `className`, or `style` is outside the alignment guarantee; `edgeCompensation` MUST NOT mirror or infer that arbitrary CSS. | Shared two-owner geometry contract | Accepted contract; implementation pending || FR5 | Compensation MUST preserve Item's hover, press, selection, focus, content, semantics, and hit target. It MUST NOT make the row a full-bleed surface or pull it past either available host edge. | Owner direction | Accepted contract; implementation pending || FR6 | The opt-in is valid only under a host state whose published inline inset matches its applied padding and whose relevant boundary is visually neutral. Current automatic LayoutContent/LayoutPanel states with known publication mismatch are not eligible until that conformance gap is fixed. | `architecture:container-padding/INV8–INV11` | Accepted contract; implementation pending |+| FR7 | The list element containing the rows MUST clip in the inline axis with `overflow-inline: clip`, never `hidden`, so a row dragged aside for its swipe actions paints no further than the list's inline edge without the list becoming a scroll container. | `spec:AST-057/FR9` | Verified by `List.test.tsx` |### Allowed variation@@ -153,6 +154,10 @@ Consumer migration instructions belong in consumer docs and release notes.- `architecture:public-component-api` and `spec:AST-002` own public API admission.- Item remains the implementation owner of row padding and interaction paint;List owns only the collection-level opt-in and row application.+- `spec:AST-057` owns swipe actions on `Item` and the rule that the element+ containing swipe-capable rows clips in the inline axis; List carries that+ clip (FR7) and `ListItem` passes `swipeActions` and `swipeBehavior` through+ to `Item` unchanged.## Verification mapdiff --git a/packages/core/src/List/List.test.tsx b/packages/core/src/List/List.test.tsxindex fdee002012..485be80759 100644--- a/packages/core/src/List/List.test.tsx+++ b/packages/core/src/List/List.test.tsx@@ -12,6 +12,7 @@import {describe, it, expect, vi} from 'vitest';import {render, screen} from '@testing-library/react';import userEvent from '@testing-library/user-event';+import {rulesDeclaredFor} from '../__tests__/pressState';import {List} from './List';import {ListItem} from './ListItem';import {ListMarkerScope} from './ListContext';@@ -941,3 +942,38 @@ describe('List', () => {});});});++describe('List and swipe actions', () => {+ it('clips the rows in the inline axis with clip, never hidden, so a row dragged aside paints no further than the list', () => {+ render(+ <List>+ <ListItem label="A" />+ </List>,+ );+ const rules = rulesDeclaredFor(screen.getByRole('list'));+ // Declared as `overflow-inline`; StyleX emits the physical longhand of+ // the same axis in horizontal writing modes.+ expect(rules.some(r => /overflow-(inline|x): clip/.test(r))).toBe(true);+ expect(rules.some(r => /overflow[-a-z]*: hidden/.test(r))).toBe(false);+ });++ it('passes swipeActions and swipeBehavior through to the row unchanged', () => {+ render(+ <List>+ <ListItem+ label="A"+ data-testid="row"+ swipeBehavior="commit"+ swipeActions={{trailing: [{label: 'Archive', onActivate: () => {}}]}}+ />+ </List>,+ );+ const row = screen.getByTestId('row');+ expect(row.tagName).toBe('LI');+ expect(row.parentElement).toBe(screen.getByRole('list'));+ const panel = row.querySelector('[data-swipe-panel="trailing"]');+ expect(panel).not.toBeNull();+ // Commit: presentational.+ expect(panel).toHaveAttribute('aria-hidden', 'true');+ });+});diff --git a/packages/core/src/List/List.tsx b/packages/core/src/List/List.tsxindex 12b0422da9..315bf16a08 100644--- a/packages/core/src/List/List.tsx+++ b/packages/core/src/List/List.tsx@@ -115,6 +115,11 @@ const styles = stylex.create({display: 'flex',flexDirection: 'column',gap: spacingVars['--spacing-0-5'],+ // A row dragged aside for its swipe actions (Item.swipeActions) paints+ // past the list's inline edge unless the list clips. `clip`, never+ // `hidden`: hidden makes a scroll container, which fights the list's+ // vertical scroller. (StyleX emits the physical longhand of this axis.)+ overflowInline: 'clip',},withDividers: {gap: 0,diff --git a/packages/core/src/List/ListItem.doc.mjs b/packages/core/src/List/ListItem.doc.mjsindex 21ade534d9..d0a4d35da7 100644--- a/packages/core/src/List/ListItem.doc.mjs+++ b/packages/core/src/List/ListItem.doc.mjs@@ -7,7 +7,8 @@ export const docs = {subComponentOf: 'List',displayName: 'List Item',isHiddenFromOverview: true,- description: 'List item with label, description, start/end content slots, and interactive patterns.',+ description:+ 'List item with label, description, start/end content slots, and interactive patterns.',props: [{name: 'label',@@ -18,12 +19,14 @@ export const docs = {{name: 'description',type: 'ReactNode',- description: 'Secondary content below the label. A plain string gets single-line truncation automatically; a ReactNode lets child components control their own wrapping and line-clamp behavior.',+ description:+ 'Secondary content below the label. A plain string gets single-line truncation automatically; a ReactNode lets child components control their own wrapping and line-clamp behavior.',},{name: 'startContent',type: 'ReactNode',- description: 'Content rendered before the label area (e.g. icon, avatar).',+ description:+ 'Content rendered before the label area (e.g. icon, avatar).',slotElements: [{__element: 'Icon',@@ -37,7 +40,8 @@ export const docs = {{name: 'endContent',type: 'ReactNode',- description: 'Content rendered after the label area (e.g. badge, chevron).',+ description:+ 'Content rendered after the label area (e.g. badge, chevron).',slotElements: [{__element: 'Icon',@@ -62,22 +66,26 @@ export const docs = {{name: 'interactiveRef',type: 'RefObject<HTMLElement | null>',- description: 'Ref to a nested control (e.g. a checkbox in startContent) that owns the item\'s keyboard access and action. The row becomes an enlarged click/tap target that delegates surface clicks to it (useClickableContainer) and renders no invisible button/anchor, so the row adds no second tab stop (WCAG 4.1.2). Mutually exclusive with onClick/href; those are ignored when set.',+ description:+ "Ref to a nested control (e.g. a checkbox in startContent) that owns the item's keyboard access and action. The row becomes an enlarged click/tap target that delegates surface clicks to it (useClickableContainer) and renders no invisible button/anchor, so the row adds no second tab stop (WCAG 4.1.2). Mutually exclusive with onClick/href; those are ignored when set.",},{name: 'href',type: 'string',- description: 'Link URL; enables the invisible anchor pattern. The destination follows the shared navigation rule described on the Link `href` prop.',+ description:+ 'Link URL; enables the invisible anchor pattern. The destination follows the shared navigation rule described on the Link `href` prop.',},{name: 'target',type: 'string',- description: 'Link target attribute, only applicable when href is provided. target="_blank" automatically adds noopener noreferrer.',+ description:+ 'Link target attribute, only applicable when href is provided. target="_blank" automatically adds noopener noreferrer.',},{name: 'rel',type: 'string',- description: 'Link relationship tokens. noopener noreferrer are merged automatically for target="_blank".',+ description:+ 'Link relationship tokens. noopener noreferrer are merged automatically for target="_blank".',},{name: 'isDisabled',@@ -91,6 +99,19 @@ export const docs = {description: 'Selected state; sets aria-selected on the item.',default: 'false',},+ {+ name: 'swipeActions',+ type: '{leading?: ItemSwipeAction[]; trailing?: ItemSwipeAction[]}',+ description:+ "Swipe actions for touch, passed through to Item unchanged: the verbs a sideways drag uncovers on each side, each `{id?, label, icon?, onActivate, isDisabled?, variant?: 'neutral' | 'accent' | 'destructive', hasRemoval?}`. See Item.swipeActions; List clips its rows in the inline axis for them.",+ },+ {+ name: 'swipeBehavior',+ type: "'reveal' | 'commit'",+ description:+ 'What a swipe does, passed through to Item unchanged. See Item.swipeBehavior.',+ default: "'reveal'",+ },],};@@ -109,7 +130,8 @@ export const docsZh = {{name: 'description',type: 'ReactNode',- description: '标签下方的次要内容。纯字符串会自动应用单行截断;ReactNode 允许子组件自行控制换行和多行截断行为。',+ description:+ '标签下方的次要内容。纯字符串会自动应用单行截断;ReactNode 允许子组件自行控制换行和多行截断行为。',},{name: 'startContent',@@ -129,7 +151,8 @@ export const docsZh = {{name: 'interactiveRef',type: 'RefObject<HTMLElement | null>',- description: '指向嵌套控件(如 startContent 中的复选框)的 ref,该控件承载项目的键盘访问和操作。行成为更大的点击/触摸目标,将表面点击委托给该控件(useClickableContainer),且不渲染不可见按钮/锚点,因此行不会增加第二个 Tab 停留点(WCAG 4.1.2)。与 onClick/href 互斥——设置后二者将被忽略。',+ description:+ '指向嵌套控件(如 startContent 中的复选框)的 ref,该控件承载项目的键盘访问和操作。行成为更大的点击/触摸目标,将表面点击委托给该控件(useClickableContainer),且不渲染不可见按钮/锚点,因此行不会增加第二个 Tab 停留点(WCAG 4.1.2)。与 onClick/href 互斥——设置后二者将被忽略。',},{name: 'href',@@ -139,12 +162,14 @@ export const docsZh = {{name: 'target',type: 'string',- description: '链接 target 属性,仅在提供 href 时适用。target="_blank" 会自动添加 noopener noreferrer。',+ description:+ '链接 target 属性,仅在提供 href 时适用。target="_blank" 会自动添加 noopener noreferrer。',},{name: 'rel',type: 'string',- description: '链接关系标记。target="_blank" 会自动合并 noopener noreferrer。',+ description:+ '链接关系标记。target="_blank" 会自动合并 noopener noreferrer。',},{name: 'isDisabled',@@ -158,6 +183,18 @@ export const docsZh = {description: '选中状态;在项目上设置 aria-selected。',default: 'false',},+ {+ name: 'swipeActions',+ type: '{leading?: ItemSwipeAction[]; trailing?: ItemSwipeAction[]}',+ description:+ "触摸滑动操作,原样传递给 Item:横向拖动在每一侧揭示的操作,每项为 `{id?, label, icon?, onActivate, isDisabled?, variant?: 'neutral' | 'accent' | 'destructive', hasRemoval?}`。参见 Item.swipeActions;List 会在行内轴上裁剪行。",+ },+ {+ name: 'swipeBehavior',+ type: "'reveal' | 'commit'",+ description: '滑动的行为,原样传递给 Item。参见 Item.swipeBehavior。',+ default: "'reveal'",+ },],};@@ -165,7 +202,8 @@ export const docsDense = {name: 'ListItem',isHiddenFromOverview: true,displayName: 'List Item',- description: 'List item w/ label, description, start/end content slots, interactive patterns.',+ description:+ 'List item w/ label, description, start/end content slots, interactive patterns.',propDescriptions: {label: 'Primary text.',description: 'Secondary text below label.',@@ -173,9 +211,10 @@ export const docsDense = {endContent: 'Content after label area (e.g. badge, chevron).',onClick: 'Click handler; enables invisible button pattern.',interactiveRef:- 'Ref to a nested control that owns the item\'s keyboard access/action; row delegates surface clicks to it (useClickableContainer), no invisible button/anchor, no second tab stop (WCAG 4.1.2). Mutually exclusive with onClick/href.',+ "Ref to a nested control that owns the item's keyboard access/action; row delegates surface clicks to it (useClickableContainer), no invisible button/anchor, no second tab stop (WCAG 4.1.2). Mutually exclusive with onClick/href.",href: 'Link URL; enables invisible anchor pattern. Follows the shared navigation rule (see Link href).',- target: 'Link target attribute, only when href provided. target="_blank" auto-adds noopener noreferrer.',+ target:+ 'Link target attribute, only when href provided. target="_blank" auto-adds noopener noreferrer.',rel: 'Link relationship tokens. noopener noreferrer are merged for target="_blank".',isDisabled: 'Disabled state; sets aria-disabled.',isSelected: 'Selected state; sets aria-selected.',diff --git a/packages/core/src/List/ListItem.tsx b/packages/core/src/List/ListItem.tsxindex ebf56340c4..a2d7457695 100644--- a/packages/core/src/List/ListItem.tsx+++ b/packages/core/src/List/ListItem.tsx@@ -34,6 +34,7 @@ import {ListContext, type ListMarker} from './ListContext';import {CheckboxInput} from '../CheckboxInput';import {mergeProps} from '../utils';import {Item} from '../Item';+import type {ItemSwipeActions, ItemSwipeBehavior} from '../Item';import {themeProps} from '../utils/themeProps';// =============================================================================@@ -117,6 +118,20 @@ export interface ListItemProps extends BaseProps<HTMLLIElement> {* @default false*/isSelected?: boolean;++ /**+ * Swipe actions for touch, passed through to `Item` unchanged: the verbs a+ * sideways drag uncovers on each side. See `Item.swipeActions`; `List`+ * clips the rows in the inline axis for them.+ */+ swipeActions?: ItemSwipeActions;++ /**+ * What a swipe does, passed through to `Item` unchanged. See+ * `Item.swipeBehavior`.+ * @default 'reveal'+ */+ swipeBehavior?: ItemSwipeBehavior;}// =============================================================================