An open source design system that's fully customizable and agent ready
TypeScript
fix(BottomSheet): leave pinch-zoom to the browser (#7192)
Cindy Zhang1eb16a0d5a67
diff --git a/.changeset/bottom-sheet-pinch-zoom.md b/.changeset/bottom-sheet-pinch-zoom.mdnew file mode 100644index 0000000000..d8ede668a6--- /dev/null+++ b/.changeset/bottom-sheet-pinch-zoom.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] BottomSheet no longer blocks pinch-zoom. A pinch that started on an open sheet (its handle, its content, or across both) did nothing, because the sheet claimed every touch gesture: `touch-action: none` on the sheet and handle, `pan-y` on the content. The sheet now leaves pinch to the browser (`pinch-zoom`, and `pan-y pinch-zoom` on the content), and a second finger ends any sheet drag in flight, so the page zooms and the sheet stays at its detent. One-finger drag and scroll are unchanged.++@cixzhangdiff --git a/docs/pr-assets/7192/pinch-before-after.png b/docs/pr-assets/7192/pinch-before-after.pngnew file mode 100644index 0000000000..77aff942e0Binary files /dev/null and b/docs/pr-assets/7192/pinch-before-after.png differdiff --git a/packages/core/src/BottomSheet/BottomSheetPanel.tsx b/packages/core/src/BottomSheet/BottomSheetPanel.tsxindex 74f862c20c..201fee5e0d 100644--- a/packages/core/src/BottomSheet/BottomSheetPanel.tsx+++ b/packages/core/src/BottomSheet/BottomSheetPanel.tsx@@ -212,7 +212,8 @@ const styles = stylex.create({// surface behind the pill itself, fading out across the lower half so the// content emerging below has no visible cut line.backgroundImage: `linear-gradient(to bottom, ${colorVars['--color-background-surface']} 60%, transparent)`,- touchAction: 'none',+ // Drags are the handle's; a pinch still zooms the page (WCAG 1.4.4).+ touchAction: 'pinch-zoom',cursor: {default: 'grab',':is(:disabled,[aria-disabled="true"])': 'default',@@ -228,7 +229,7 @@ const styles = stylex.create({flexGrow: 1,minHeight: 0,boxSizing: 'border-box',- touchAction: 'pan-y',+ touchAction: 'pan-y pinch-zoom',outlineOffset: {default: 0,':focus-visible': `calc(-1 * ${focusVars['--focus-outline-width']})`,diff --git a/packages/core/src/BottomSheet/__tests__/BottomSheetPinchZoom.a11y.chromium.spec.ts b/packages/core/src/BottomSheet/__tests__/BottomSheetPinchZoom.a11y.chromium.spec.tsnew file mode 100644index 0000000000..bb33b68d34--- /dev/null+++ b/packages/core/src/BottomSheet/__tests__/BottomSheetPinchZoom.a11y.chromium.spec.ts@@ -0,0 +1,214 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file BottomSheetPinchZoom.a11y.chromium.spec.ts+ * @input Built BottomSheet stories and real Chromium touch input (CDP)+ * @output Browser evidence that a two-finger pinch on an open sheet zooms the+ * page and leaves the sheet where it rests, while one-finger drag and scroll+ * keep working (WCAG 1.4.4)+ * @position Chromium proof for the sheet's touch-action and pinch hand-off+ */++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));++async function openSheet(page: Page) {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-bottomsheet--text-only&viewMode=story`,+ );+ const dialog = page.getByRole('dialog', {name: 'Reading details'});+ await expect(dialog).toBeVisible();+ const sheet = dialog.locator('.astryx-bottom-sheet').first();+ await expect(sheet).toBeVisible();+ await page.waitForTimeout(800); // the entrance+ const box = await sheet.boundingBox();+ if (box == null) {+ throw new Error('no sheet box');+ }+ expect(await page.evaluate(() => window.visualViewport?.scale)).toBe(1);+ return {dialog, sheet, box};+}++type Point = {x: number; y: number};++// 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);+}++// Record the furthest the sheet travelled while the fingers were down.+async function trackSheetTravel(page: Page) {+ await page.evaluate(() => {+ const sheet = document.querySelector('.astryx-bottom-sheet')!;+ const top = () => sheet.getBoundingClientRect().top;+ const start = top();+ const w = window as unknown as {__travel: number};+ w.__travel = 0;+ const sample = () => {+ w.__travel = Math.max(w.__travel, Math.abs(top() - start));+ requestAnimationFrame(sample);+ };+ requestAnimationFrame(sample);+ });+}++const PINCHES: {name: string; fingers: (box: Box) => [Point, Point]}[] = [+ {+ name: 'across the handle and the body',+ fingers: box => [+ {x: box.x + box.width / 2, y: box.y + 12},+ {x: box.x + box.width / 2 + 10, y: box.y + 90},+ ],+ },+ {+ name: 'at the top of the body, spreading vertically',+ fingers: box => [+ {x: box.x + box.width / 2, y: box.y + 160},+ {x: box.x + box.width / 2 + 10, y: box.y + 220},+ ],+ },+ {+ name: 'in the body, spreading sideways',+ fingers: box => [+ {x: box.x + box.width / 2 - 30, y: box.y + 280},+ {x: box.x + box.width / 2 + 30, y: box.y + 280},+ ],+ },+];+type Box = {x: number; y: number; width: number; height: number};++for (const {name, fingers} of PINCHES) {+ test(`a pinch ${name} zooms the page and leaves the sheet at rest`, async ({+ page,+ }) => {+ const {dialog, sheet, box} = await openSheet(page);+ await trackSheetTravel(page);+ const cdp = await page.context().newCDPSession(page);+ const [first, second] = fingers(box);+ await pinch(cdp, first, second);++ expect(+ await page.evaluate(() => window.visualViewport?.scale ?? 1),+ ).toBeGreaterThan(1.2);+ // A pinch is not a drag: the sheet never left its detent.+ expect(+ await page.evaluate(+ () => (window as unknown as {__travel: number}).__travel,+ ),+ ).toBeLessThan(2);+ await expect(dialog).toBeVisible();+ // Layout-viewport coordinates: the zoom itself does not move them.+ expect(+ await sheet.evaluate(el => el.getBoundingClientRect().top),+ ).toBeCloseTo(box.y, 0);+ });+}++test('one finger still drags the handle and scrolls the body, without zooming', async ({+ page,+}) => {+ const {sheet, box} = await openSheet(page);+ const cdp = await page.context().newCDPSession(page);+ const x = box.x + box.width / 2;++ // Handle: the sheet follows the finger.+ const handleY = box.y + 12;+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchStart',+ touchPoints: [{x, y: handleY}],+ });+ for (let i = 1; i <= 10; i++) {+ await sleep(16);+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchMove',+ touchPoints: [{x, y: handleY + i * 12}],+ });+ }+ await sleep(50);+ const dragged = await sheet.boundingBox();+ expect((dragged?.y ?? box.y) - box.y).toBeGreaterThan(80);+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchCancel',+ touchPoints: [],+ });++ // Body, on a fresh sheet (that drag may have thrown the first one away): a+ // swipe up scrolls the content.+ await openSheet(page);+ const body = sheet.locator('[role="group"]').first();+ const before = await body.evaluate(el => el.scrollTop);+ const startY = box.y + box.height - 100;+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchStart',+ touchPoints: [{x, y: startY}],+ });+ for (let i = 1; i <= 10; i++) {+ await sleep(16);+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchMove',+ touchPoints: [{x, y: startY - i * 25}],+ });+ }+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchEnd',+ touchPoints: [],+ });+ await page.waitForTimeout(600);+ expect(await body.evaluate(el => el.scrollTop)).toBeGreaterThan(before + 100);+ expect(await page.evaluate(() => window.visualViewport?.scale)).toBe(1);+});diff --git a/packages/core/src/BottomSheet/useSheetGestures.test.ts b/packages/core/src/BottomSheet/useSheetGestures.test.tsindex 262845909d..ba4ef609d4 100644--- a/packages/core/src/BottomSheet/useSheetGestures.test.ts+++ b/packages/core/src/BottomSheet/useSheetGestures.test.ts@@ -586,6 +586,39 @@ describe('useSheetGestures', () => {expect(onDismiss).not.toHaveBeenCalled();});+ describe('pinch', () => {+ // A second finger is a pinch, and pinch-zoom belongs to the browser.+ it('declares pinch-zoom on the sliding surface and the handle', () => {+ const {hook} = setup();+ expect(hook.result.current.contentProps.style.touchAction).toBe(+ 'pinch-zoom',+ );+ expect(hook.result.current.handleProps.style.touchAction).toBe(+ 'pinch-zoom',+ );+ });++ it('returns to the settled detent when a second finger lands on the handle', () => {+ const {hook, onDismiss} = setup({snapHeights: () => [200]});+ const target = makeTarget();+ down(hook, 0, 0, target);+ move(hook, 120, 200, target);+ expect(hook.result.current.isDragging).toBe(true);++ act(() =>+ hook.result.current.handleProps.onPointerDown(+ pointerEvent(160, 220, target, 2, 0, false),+ ),+ );++ expect(hook.result.current.isDragging).toBe(false);+ expect(hook.result.current.contentProps.style.transform).toBeUndefined();+ // The first finger's later release is not a drag either.+ up(hook, 300, 400, target);+ expect(onDismiss).not.toHaveBeenCalled();+ });+ });+it('does not start a drag from a secondary pointer button', () => {const {hook} = setup();const target = makeTarget();@@ -863,6 +896,68 @@ describe('useSheetGestures', () => {expect(hook.result.current.isDragging).toBe(false);});+ function secondFinger(el: HTMLElement, y: number, firstY: number) {+ const ev = new Event('touchstart', {bubbles: true, cancelable: true});+ Object.defineProperty(ev, 'changedTouches', {+ value: [{identifier: 2, clientY: y}],+ });+ Object.defineProperty(ev, 'touches', {+ value: [+ {identifier: 1, clientY: firstY},+ {identifier: 2, clientY: y},+ ],+ });+ Object.defineProperty(ev, 'currentTarget', {value: el});+ el.dispatchEvent(ev);+ }++ it('leaves a pinch at the top to the browser', () => {+ const {hook} = setup({snapHeights: () => [200]});+ const el = makeScroller({+ scrollTop: 0,+ clientHeight: 200,+ scrollHeight: 800,+ });+ act(() => hook.result.current.sheetRef(el));+ act(() => hook.result.current.bodyProps.ref(el));+ let pull: Event | undefined;+ act(() => {+ touch(el, 'touchstart', 100);+ secondFinger(el, 140, 100);+ // The spread carries the second finger down past the promotion slop.+ pull = touch(el, 'touchmove', 160, 2);+ });+ expect(pull?.defaultPrevented).toBe(false);+ expect(hook.result.current.isDragging).toBe(false);+ });++ it('returns a pull in flight to its detent when a second finger lands', () => {+ const {hook, onDismiss} = setup({snapHeights: () => [200]});+ const el = makeScroller({+ scrollTop: 0,+ clientHeight: 200,+ scrollHeight: 800,+ });+ act(() => hook.result.current.sheetRef(el));+ act(() => hook.result.current.bodyProps.ref(el));+ act(() => {+ touch(el, 'touchstart', 0);+ touch(el, 'touchmove', 50);+ });+ expect(hook.result.current.isDragging).toBe(true);++ let after: Event | undefined;+ act(() => {+ secondFinger(el, 120, 50);+ after = touch(el, 'touchmove', 90);+ touch(el, 'touchend', 90);+ });+ expect(after?.defaultPrevented).toBe(false);+ expect(hook.result.current.isDragging).toBe(false);+ expect(hook.result.current.contentProps.style.transform).toBeUndefined();+ expect(onDismiss).not.toHaveBeenCalled();+ });+it('leaves native scrolling alone in the middle of the content', () => {const {hook} = setup({snapHeights: () => [200]});const el = makeScroller({diff --git a/packages/core/src/BottomSheet/useSheetGestures.ts b/packages/core/src/BottomSheet/useSheetGestures.tsindex a04879a8a1..9444ad534a 100644--- a/packages/core/src/BottomSheet/useSheetGestures.ts+++ b/packages/core/src/BottomSheet/useSheetGestures.ts@@ -52,6 +52,11 @@* nothing left to scroll — and instead anchors at the point where the content* ran out and drives the sheet from the travel beyond it.*+ * Every gesture here is one finger. A second finger is a pinch, and pinch-zoom+ * belongs to the browser (WCAG 1.4.4): the surfaces declare `pinch-zoom` in+ * their `touch-action`, and a second finger landing ends any drag in flight+ * or armed — the sheet returns to its detent and the pinch zooms the page.+ ** Kept private to BottomSheet: a dismiss edge + detents on a bottom-anchored* surface are inherently sheet concepts. It is not a general primitive and is* intentionally not exported.@@ -361,7 +366,7 @@ export interface UseSheetGesturesResult {* rotation / viewport changes without re-measuring mid-drag.*/sheetRef: (node: HTMLElement | null) => void;- /** Spread on the sliding surface: live translate + touch-action guard. */+ /** Spread on the sliding surface: live translate + touch-action guard (pans are the sheet's, pinch-zoom is the browser's). */contentProps: SheetContentProps;/** Spread on the grab-handle element: pointer drag handlers. */handleProps: SheetHandleProps;@@ -1077,7 +1082,12 @@ export function useSheetGestures({const handlePointerDown = useCallback((event: ReactPointerEvent) => {- if (event.button !== 0 || !event.isPrimary) {+ if (!event.isPrimary) {+ // A second finger is a pinch: give it to the browser.+ cancelDrag(event.currentTarget as HTMLElement);+ return;+ }+ if (event.button !== 0) {return;}// The handle has no native focus action. Prevent pointer-down from@@ -1086,7 +1096,7 @@ export function useSheetGestures({event.preventDefault();beginDrag(event, measureHeight());},- [beginDrag, measureHeight],+ [beginDrag, cancelDrag, measureHeight],);const handleContextMenu = useCallback(@@ -1375,6 +1385,13 @@ export function useSheetGestures({const onTouchStart = (event: TouchEvent) => {const body = event.currentTarget as HTMLElement;+ if (event.touches.length > 1) {+ // A second finger is a pinch. Disarm, and drop a drag already in+ // flight, so no later touchmove is cancelled out from under the zoom.+ touchDragRef.current = null;+ cancelDragRef.current(body);+ return;+ }const touch = event.changedTouches[0];// Record where the gesture began and whether it began at a scroll edge.// At the top, a pull DOWN hands off (collapse); at the bottom, a pull UP@@ -1596,7 +1613,8 @@ export function useSheetGestures({isOpen && (isDragging || isScrollAreaReconciling || reducedMotion)? 'none': undefined,- touchAction: 'none',+ // One-finger drags are the sheet's; a pinch stays the browser's.+ touchAction: 'pinch-zoom',overscrollBehavior: 'contain',},}),@@ -1605,7 +1623,7 @@ export function useSheetGestures({const handleProps = useMemo<SheetHandleProps>(() => ({- style: {touchAction: 'none', cursor: 'grab'},+ style: {touchAction: 'pinch-zoom', cursor: 'grab'},onContextMenu: handleContextMenu,onLostPointerCapture: handleLostPointerCapture,onPointerDown: handlePointerDown,