An open source design system that's fully customizable and agent ready
TypeScript
fix(Item): swipe rows leave pinch-zoom to the browser (#8042)
Christopher Chedeau5b87452eee33
diff --git a/.changeset/item-swipe-pinch-zoom.md b/.changeset/item-swipe-pinch-zoom.mdnew file mode 100644index 0000000000..e0ee7772be--- /dev/null+++ b/.changeset/item-swipe-pinch-zoom.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A row with `swipeActions` no longer blocks pinch-zoom. A pinch that started on a swipeable `Item` or `ListItem` did nothing, because the row declared `touch-action: pan-y`, and a sideways pinch could also be taken as a swipe. The row now leaves pinch to the browser (`pan-y pinch-zoom`), and a second finger that lands before the swipe has begun, on the row or anywhere else, hands the touch to the browser, so the page zooms and the row stays where it is. One-finger swipes and vertical scrolling are unchanged.++@vjeuxdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex a5d12cc813..dfd0139b31 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1682,6 +1682,17 @@ jobs:--project chromium \--output top-nav-mobile-long-heading-output+ # A pinch that starts on a row with swipe actions must zoom the page+ # (WCAG 1.4.4) and leave the row where it is, whichever finger lands+ # first, while a one-finger sideways drag still swipes. Pinch-zoom and+ # touch-action only exist in a real engine with two-finger touch input.+ - name: Run Item swipe pinch-zoom contract+ run: |+ pnpm exec playwright test \+ packages/core/src/Item/__tests__/ItemSwipePinchZoom.a11y.chromium.spec.ts \+ --project chromium \+ --output item-swipe-pinch-zoom-output+# The RichTextEditor "Markdown parity" stories render one Markdown# document with core Markdown and RichTextEditor and measure where each# block lands; geometry, the read/edit switch and the scroll anchor onlydiff --git a/packages/core/src/Item/Item.test.tsx b/packages/core/src/Item/Item.test.tsxindex 760c48f3ab..8358b096fb 100644--- a/packages/core/src/Item/Item.test.tsx+++ b/packages/core/src/Item/Item.test.tsx@@ -721,6 +721,7 @@ describe('swipeActions', () => {vi.useRealTimers();});+ /** The first finger down: the primary touch pointer. */function touch(element: Element,type: 'pointerDown' | 'pointerMove' | 'pointerUp' | 'pointerCancel',@@ -731,11 +732,29 @@ describe('swipeActions', () => {fireEvent[type](element, {clientX: x,clientY: y,+ isPrimary: true,pointerId: 7,pointerType: 'touch',});}+ /** A second finger: a touch pointer that is not the primary one. */+ function secondFinger(+ element: Element,+ type: 'pointerDown' | 'pointerMove' | 'pointerUp' | 'pointerCancel',+ x: number,+ y = 10,+ ) {+ vi.advanceTimersByTime(10);+ fireEvent[type](element, {+ clientX: x,+ clientY: y,+ isPrimary: false,+ pointerId: 8,+ pointerType: 'touch',+ });+ }+/** The time a settle takes, plus the frame before it. */const settled = () => void act(() => vi.advanceTimersByTime(250));@@ -958,6 +977,105 @@ describe('swipeActions', () => {});});+ describe('a pinch', () => {+ /** A touchmove listing both fingers; true when the row cancelled it. */+ const pinchMoveCancelled = (row: Element, x: number) =>+ !fireEvent.touchMove(row, {+ cancelable: true,+ touches: [+ {clientX: x, clientY: 10},+ {clientX: 300 - x, clientY: 10},+ ],+ });++ it('lets the touch go when a second finger lands on the row before the axis is decided, and cancels nothing', () => {+ const {row} = renderRow();+ touch(row, 'pointerDown', 100);+ secondFinger(row, 'pointerDown', 60);+ // The fingers spread apart; the first one travels toward the leading+ // side far past the axis lock.+ touch(row, 'pointerMove', 130);+ secondFinger(row, 'pointerMove', 30);+ touch(row, 'pointerMove', 160);+ expect(pinchMoveCancelled(row, 160)).toBe(false);+ void act(() => vi.advanceTimersByTime(20));+ expect(travelOf(row)).toBe('');+ // The browser takes the pinch.+ touch(row, 'pointerCancel', 160);+ secondFinger(row, 'pointerCancel', 0);+ settled();+ expect(travelOf(row)).toBe('');+ });++ it('lets the touch go when the second finger lands off the row', () => {+ const {row} = renderRow();+ touch(row, 'pointerDown', 100);+ secondFinger(document.body, 'pointerDown', 60, 200);+ touch(row, 'pointerMove', 130);+ touch(row, 'pointerMove', 160);+ expect(pinchMoveCancelled(row, 160)).toBe(false);+ void act(() => vi.advanceTimersByTime(20));+ expect(travelOf(row)).toBe('');+ touch(row, 'pointerCancel', 160);+ });++ it('never starts a drag from a finger that is not the first one down', () => {+ const {row} = renderRow();+ // The first finger is somewhere else on the page; this one lands on+ // the row and travels sideways.+ secondFinger(row, 'pointerDown', 100);+ secondFinger(row, 'pointerMove', 130);+ secondFinger(row, 'pointerMove', 160);+ expect(pinchMoveCancelled(row, 160)).toBe(false);+ void act(() => vi.advanceTimersByTime(20));+ expect(travelOf(row)).toBe('');+ secondFinger(row, 'pointerUp', 160);+ });++ it('keeps a drag the row already owns when a second finger lands', () => {+ const {row} = renderRow();+ touch(row, 'pointerDown', 10);+ touch(row, 'pointerMove', 30);+ touch(row, 'pointerMove', 45);+ void act(() => vi.advanceTimersByTime(20));+ expect(travelOf(row)).toBe('35px');+ secondFinger(row, 'pointerDown', 200);+ touch(row, 'pointerMove', 60);+ expect(pinchMoveCancelled(row, 60)).toBe(true);+ void act(() => vi.advanceTimersByTime(20));+ expect(travelOf(row)).toBe('50px');+ touch(row, 'pointerUp', 60);+ secondFinger(row, 'pointerUp', 200);+ settled();+ expect(travelOf(row)).toBe('72px');+ });++ it('stops listening to the document once the axis is decided or the touch ends', () => {+ const add = vi.spyOn(document, 'addEventListener');+ const remove = vi.spyOn(document, 'removeEventListener');+ try {+ const {row} = renderRow();+ const watching = () =>+ add.mock.calls.filter(([type]) => type === 'pointerdown').length -+ remove.mock.calls.filter(([type]) => type === 'pointerdown').length;+ const before = watching();+ touch(row, 'pointerDown', 10);+ expect(watching()).toBe(before + 1);+ touch(row, 'pointerMove', 40);+ expect(watching()).toBe(before);+ touch(row, 'pointerUp', 40);+ settled();+ touch(row, 'pointerDown', 10);+ expect(watching()).toBe(before + 1);+ touch(row, 'pointerUp', 12);+ expect(watching()).toBe(before);+ } finally {+ add.mockRestore();+ remove.mockRestore();+ }+ });+ });+it('does not move toward a side without entries', () => {const {row} = renderRow({leading: [{label: 'Unread', onActivate: vi.fn()}],diff --git a/packages/core/src/Item/Item.tsx b/packages/core/src/Item/Item.tsxindex 40501799c6..34b264d001 100644--- a/packages/core/src/Item/Item.tsx+++ b/packages/core/src/Item/Item.tsx@@ -503,11 +503,13 @@ const styles = stylex.create({},// 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.+ // list while the row owns horizontal movement, and `pinch-zoom` leaves a+ // two-finger pinch that starts on the row to the browser, so the page stays+ // zoomable (WCAG 1.4.4). The hover transition keeps its own clock beside+ // the transform's.swipeRoot: {isolation: 'isolate',- touchAction: 'pan-y',+ touchAction: 'pan-y pinch-zoom',transform: `translate3d(${SWIPE_TRAVEL}, 0, 0)`,transitionProperty: 'background-color, transform',transitionDuration: `${durationVars['--duration-fast-min']}, ${SWIPE_DURATION}`,diff --git a/packages/core/src/Item/__tests__/ItemSwipePinchZoom.a11y.chromium.spec.ts b/packages/core/src/Item/__tests__/ItemSwipePinchZoom.a11y.chromium.spec.tsnew file mode 100644index 0000000000..d3df5e667b--- /dev/null+++ b/packages/core/src/Item/__tests__/ItemSwipePinchZoom.a11y.chromium.spec.ts@@ -0,0 +1,185 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ItemSwipePinchZoom.a11y.chromium.spec.ts+ * @input The checked-in Core/Item › Swipe Actions story, a built Storybook and+ * real Chromium two-finger touch input (CDP) on a phone viewport+ * @output Browser evidence that a pinch which starts on a swipeable row zooms+ * the page and leaves the row where it is, whichever finger lands first and+ * wherever the second one lands, while a one-finger sideways drag still+ * swipes (WCAG 1.4.4)+ * @position Chromium proof for Item's swipe-row `touch-action` and the+ * gesture's hand-off of a second finger+ */++import {expect, test, type CDPSession, type Page} from '@playwright/test';+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();+});++// A phone: the viewport meta applies and the page can pinch-zoom.+test.use({+ hasTouch: true,+ isMobile: true,+ viewport: {width: 390, height: 844},+ deviceScaleFactor: 3,+});++const sleep = async (ms: number) =>+ new Promise(resolve => setTimeout(resolve, ms));++type Point = {x: number; y: number};+type Box = {x: number; y: number; width: number; height: number};++async function openStory(page: Page) {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-item--swipe-actions&viewMode=story`,+ );+ const rows = page.locator('.astryx-item');+ const row = rows.first();+ await expect(row.getByText('Message 1')).toBeVisible();+ // The gesture arrives with the lazily loaded swipe layer; its panel is the+ // sign the row can be dragged.+ await expect(row.locator('[data-swipe-panel="leading"]')).toBeAttached();+ const box = (await row.boundingBox()) as Box;+ const next = (await rows.nth(1).boundingBox()) as Box;+ expect(await page.evaluate(() => window.visualViewport?.scale)).toBe(1);+ // Record how far the first row ever moves sideways while fingers are down.+ await page.evaluate(() => {+ const el = document.querySelector('.astryx-item') as HTMLElement;+ const w = window as unknown as {__maxTravel: number};+ w.__maxTravel = 0;+ const tick = () => {+ const travel = Math.abs(new DOMMatrix(getComputedStyle(el).transform).e);+ w.__maxTravel = Math.max(w.__maxTravel, travel);+ requestAnimationFrame(tick);+ };+ requestAnimationFrame(tick);+ });+ const cdp = await page.context().newCDPSession(page);+ return {box, next, cdp};+}++const zoom = async (page: Page) =>+ page.evaluate(() => window.visualViewport?.scale ?? 1);+const maxTravel = async (page: Page) =>+ page.evaluate(() => (window as unknown as {__maxTravel: number}).__maxTravel);++// Two fingers land one after the other and spread apart, as a person pinches.+// The spread is wide enough to clear the browser's minimum pinch span.+async function pinch(cdp: CDPSession, first: Point, second: Point) {+ const steps = 12;+ const spread = 3;+ const mid = {x: (first.x + second.x) / 2, y: (first.y + second.y) / 2};+ const at = (p: Point, k: number, id: number) => ({+ x: mid.x + (p.x - mid.x) * k,+ y: mid.y + (p.y - mid.y) * k,+ id,+ });+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchStart',+ touchPoints: [at(first, 1, 1)],+ });+ await sleep(30);+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchStart',+ touchPoints: [at(first, 1, 1), at(second, 1, 2)],+ });+ for (let i = 1; i <= steps; i++) {+ await sleep(16);+ const k = 1 + ((spread - 1) * i) / steps;+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchMove',+ touchPoints: [at(first, k, 1), at(second, k, 2)],+ });+ }+ await sleep(16);+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchEnd',+ touchPoints: [],+ });+ await sleep(600);+}++test('a sideways pinch on a swipeable row zooms the page and the row stays put', async ({+ page,+}) => {+ const {box, cdp} = await openStory(page);+ const y = box.y + box.height / 2;+ const x = box.x + box.width / 2;+ await pinch(cdp, {x: x - 30, y}, {x: x + 30, y});+ expect(await zoom(page)).toBeGreaterThan(1.2);+ expect(await maxTravel(page)).toBeLessThan(1);+});++test('a vertical pinch starting on a swipeable row zooms the page', async ({+ page,+}) => {+ const {box, next, cdp} = await openStory(page);+ const x = box.x + box.width / 2;+ await pinch(+ cdp,+ {x, y: box.y + box.height / 2},+ {x, y: next.y + next.height / 2},+ );+ expect(await zoom(page)).toBeGreaterThan(1.2);+ expect(await maxTravel(page)).toBeLessThan(1);+});++test('a pinch with the first finger on the row and the second off it zooms the page', async ({+ page,+}) => {+ const {box, cdp} = await openStory(page);+ const y = box.y + box.height / 2;+ // The page below the list: no row, no swipe.+ await pinch(cdp, {x: box.x + 120, y}, {x: box.x + 220, y: 700});+ expect(await zoom(page)).toBeGreaterThan(1.2);+ expect(await maxTravel(page)).toBeLessThan(1);+});++test('a pinch with the first finger off the row and the second on it zooms the page', async ({+ page,+}) => {+ const {box, cdp} = await openStory(page);+ const y = box.y + box.height / 2;+ await pinch(cdp, {x: box.x + 220, y: 700}, {x: box.x + 120, y});+ expect(await zoom(page)).toBeGreaterThan(1.2);+ expect(await maxTravel(page)).toBeLessThan(1);+});++test('a one-finger sideways drag still swipes the row and leaves the zoom alone', async ({+ page,+}) => {+ const {box, cdp} = await openStory(page);+ const y = box.y + box.height / 2;+ const startX = box.x + 24;+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchStart',+ touchPoints: [{x: startX, y}],+ });+ for (const dx of [6, 14, 28, 44, 60]) {+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchMove',+ touchPoints: [{x: startX + dx, y}],+ });+ await sleep(40);+ }+ await expect.poll(async () => maxTravel(page)).toBeGreaterThan(50);+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchEnd',+ touchPoints: [],+ });+ expect(await zoom(page)).toBe(1);+});diff --git a/packages/core/src/Item/useSwipeAction.ts b/packages/core/src/Item/useSwipeAction.tsindex d8e97ce05e..7234a2e9e2 100644--- a/packages/core/src/Item/useSwipeAction.ts+++ b/packages/core/src/Item/useSwipeAction.ts@@ -32,6 +32,12 @@* signal WebKit honours. Before the axis is decided, and for a drag the* scroller got, nothing is cancelled.*+ * A pinch is the browser's: the root's `touch-action` keeps `pinch-zoom`, and+ * a second finger that lands anywhere before the axis is decided turns the+ * touch into a pinch, so the row lets it go and cancels nothing. A finger+ * that is not the first one down never starts a drag. Once the row owns a+ * drag, a second finger does not break it.+ ** 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@@ -211,6 +217,8 @@ export function useSwipeAction({const settleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);const frameRef = useRef<number | null>(null);const pendingRef = useRef<number | null>(null);+ /** Removes the document listener that watches for a pinch's second finger. */+ const stopPinchWatchRef = useRef<(() => void) | null>(null);const [state, setState] = useState<SwipeState>(IDLE_STATE);const stateRef = useRef(state);stateRef.current = state;@@ -237,10 +245,48 @@ export function useSwipeAction({if (frameRef.current != null) {cancelAnimationFrame(frameRef.current);}+ stopPinchWatchRef.current?.();+ stopPinchWatchRef.current = null;},[],);+ const stopWatchingForPinch = useCallback(() => {+ stopPinchWatchRef.current?.();+ stopPinchWatchRef.current = null;+ }, []);++ /**+ * Until the axis is decided, a second finger anywhere on the page makes+ * the touch a pinch: the row gives it up and cancels nothing, so the+ * browser zooms. The finger can land off the row, so the document listens.+ */+ const watchForPinch = useCallback(+ (drag: DragState) => {+ stopWatchingForPinch();+ const onAnyPointerDown = (event: PointerEvent) => {+ if (+ event.pointerType === 'touch' &&+ event.pointerId !== drag.pointerId &&+ drag.claimed === null+ ) {+ drag.claimed = false;+ stopWatchingForPinch();+ }+ };+ document.addEventListener('pointerdown', onAnyPointerDown, {+ capture: true,+ passive: true,+ });+ stopPinchWatchRef.current = () => {+ document.removeEventListener('pointerdown', onAnyPointerDown, {+ capture: true,+ });+ };+ },+ [stopWatchingForPinch],+ );+/** Write the travel (physical px) the transforms read. */const writeTravel = useCallback((travel: number) => {@@ -446,10 +492,24 @@ export function useSwipeAction({const onPointerDown = useCallback((event: ReactPointerEvent) => {const current = stateRef.current;+ const inFlight = dragRef.current;+ if (inFlight != null) {+ // A second finger before the axis is decided: a pinch, not a swipe.+ if (+ event.pointerType === 'touch' &&+ event.pointerId !== inFlight.pointerId &&+ inFlight.claimed === null+ ) {+ inFlight.claimed = false;+ stopWatchingForPinch();+ }+ return;+ }if (!isEnabled ||event.pointerType !== 'touch' ||- dragRef.current != null ||+ // Another finger is already down: this one is part of a pinch.+ event.isPrimary === false ||current.phase === 'settling' ||current.phase === 'held') {@@ -459,7 +519,7 @@ export function useSwipeAction({const inlineSign: 1 | -1 = isRtlElement(root) ? -1 : 1;inlineSignRef.current = inlineSign;const startTime = now();- dragRef.current = {+ const drag: DragState = {// Logical: the physical travel through the inline sign.baseTravel: travelRef.current * inlineSign,claimed: null,@@ -476,8 +536,10 @@ export function useSwipeAction({startY: event.clientY,travel: 0,};+ dragRef.current = drag;+ watchForPinch(drag);},- [isEnabled, rootRef],+ [isEnabled, rootRef, stopWatchingForPinch, watchForPinch],);const onPointerMove = useCallback(@@ -497,6 +559,9 @@ export function useSwipeAction({if (Math.max(Math.abs(deltaX), Math.abs(deltaY)) < AXIS_LOCK_PX) {return;}+ // The axis is decided now, whichever way: a later finger is the+ // swipe's to ignore or the scroller's to use.+ stopWatchingForPinch();// More horizontal than vertical is the row's, the rest the scroller's.if (Math.abs(deltaX) <= Math.abs(deltaY)) {drag.claimed = false;@@ -555,7 +620,7 @@ export function useSwipeAction({drag.lastTime = now();paintOnNextFrame(sign * drag.inlineSign * offset);},- [paintOnNextFrame, rootRef, writeDuration],+ [paintOnNextFrame, rootRef, stopWatchingForPinch, writeDuration],);const endGesture = useCallback(@@ -565,6 +630,7 @@ export function useSwipeAction({return;}dragRef.current = null;+ stopWatchingForPinch();if (drag.claimed !== true) {return;}@@ -598,7 +664,7 @@ export function useSwipeAction({}settle(side, 0, 'idle');},- [rootRef, settle, slideOutAndFire],+ [rootRef, settle, slideOutAndFire, stopWatchingForPinch],);const onPointerUp = useCallback(