An open source design system that's fully customizable and agent ready
TypeScript
fix(BottomSheet, Tokenizer, PowerSearch): the scrim returns with a sheet whose swipe dismissal the owner refuses (#10141)
Xinzi Zhoudd5ca2957576
diff --git a/.changeset/bottom-sheet-refused-dismissal-scrim.md b/.changeset/bottom-sheet-refused-dismissal-scrim.mdnew file mode 100644index 0000000000..4c5ec8b539--- /dev/null+++ b/.changeset/bottom-sheet-refused-dismissal-scrim.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] BottomSheet, Tokenizer, PowerSearch: a swipe that asks to close a sheet whose owner keeps it open — the Tokenizer and PowerSearch sheets ask before a changed draft is discarded — no longer leaves the page behind the sheet undimmed. The scrim the drag thinned returns with the sheet to its resting detent, so the page stays dimmed while the confirmation is open and after Keep editing; Discard still closes the sheet with its exit.++@imdreamrunnerdiff --git a/packages/core/src/BottomSheet/__tests__/BottomSheetRefusedDismissal.a11y.browser.spec.ts b/packages/core/src/BottomSheet/__tests__/BottomSheetRefusedDismissal.a11y.browser.spec.tsnew file mode 100644index 0000000000..727544fb9c--- /dev/null+++ b/packages/core/src/BottomSheet/__tests__/BottomSheetRefusedDismissal.a11y.browser.spec.ts@@ -0,0 +1,249 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y scope core/Tokenizer core/PowerSearch ^packages/core/src/internal/SheetConfirmation ^apps/storybook/stories/(Tokenizer|PowerSearch)++/**+ * @file BottomSheetRefusedDismissal.a11y.browser.spec.ts+ * @input The Tokenizer and PowerSearch sheet stories in a built Storybook, on+ * a phone viewport with touch; the swipe is real touch input through the+ * interaction harness.+ * @output Real-engine proof that a sheet whose dismissal its host refuses — a+ * swipe, a scrim tap or Escape on a changed draft opens the discard+ * confirmation — keeps its scrim while the confirmation is open, keeps it+ * after Keep editing, and leaves with it on Discard.+ * @position Chromium and WebKit. The scrim is the sheet dialog's `::backdrop`,+ * whose opacity the drag thins on the compositor and the host restores; only+ * a shipping engine computes the pseudo-element's style.+ */++import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';+import {drag, touchDriver} from '@astryxdesign/interaction-harness';++let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => {+ await storybook?.close();+});++test.use({viewport: {width: 390, height: 844}, hasTouch: true});++interface SheetFixture {+ readonly name: string;+ readonly story: string;+ /** The sheet dialog's accessible name. */+ readonly sheetLabel: string;+ /** The control that reopens the sheet, and takes focus back after a close. */+ trigger(page: Page): ReturnType<Page['locator']>;+ /** One edit, so the draft differs from the selection at open. */+ dirty(page: Page): Promise<void>;+ /** Where Keep editing puts focus. */+ readonly focusAfterKeepEditing: string;+}++const FIXTURES: ReadonlyArray<SheetFixture> = [+ {+ name: 'Tokenizer',+ story: 'core-tokenizer--sheet-presentation',+ sheetLabel: 'Tags',+ trigger: page => page.getByRole('button', {name: 'Tags'}),+ dirty: async page => {+ await page.getByRole('checkbox', {name: 'Tag 03'}).tap();+ await expect(+ page.getByRole('checkbox', {name: 'Tag 03'}),+ ).toHaveAttribute('aria-checked', 'true');+ },+ focusAfterKeepEditing: 'Search Tags',+ },+ {+ name: 'PowerSearch',+ story: 'core-powersearch--sheet-presentation',+ sheetLabel: 'Filters',+ trigger: page => page.locator('button[aria-haspopup="dialog"]').first(),+ dirty: async page => {+ const remove = page+ .getByRole('button', {name: /^Remove .* filter$/})+ .first();+ const name = (await remove.getAttribute('aria-label')) ?? '';+ await remove.tap();+ await expect(page.getByRole('button', {name})).toHaveCount(0);+ },+ focusAfterKeepEditing: 'Add filter',+ },+];++type ClosePath = 'swipe' | 'scrim' | 'escape';+const CLOSE_PATHS: ReadonlyArray<ClosePath> = ['swipe', 'scrim', 'escape'];++interface ScrimReading {+ readonly open: boolean;+ readonly modal: boolean;+ /** The sheet dialog's `::backdrop` opacity, computed. */+ readonly opacity: number;+ /** The panel's transform at rest is the identity. */+ readonly panelAtRest: boolean;+}++function sheetDialog(page: Page, fixture: SheetFixture) {+ return page.locator(`dialog[aria-label="${fixture.sheetLabel}"]`);+}++async function readScrim(+ page: Page,+ fixture: SheetFixture,+): Promise<ScrimReading> {+ return sheetDialog(page, fixture).evaluate(node => {+ const dialog = node as HTMLDialogElement;+ const panel = dialog.querySelector<HTMLElement>('[tabindex="-1"]');+ const transform =+ panel == null ? 'none' : getComputedStyle(panel).transform;+ return {+ open: dialog.open,+ modal: dialog.matches(':modal'),+ opacity: Number(getComputedStyle(dialog, '::backdrop').opacity),+ panelAtRest:+ transform === 'none' || transform === 'matrix(1, 0, 0, 1, 0, 0)',+ };+ });+}++/** The sheet's own motion has ended: its entrance, or a return to rest. */+async function waitForSheetRest(page: Page, fixture: SheetFixture) {+ const dialog = sheetDialog(page, fixture);+ await expect+ .poll(async () =>+ dialog.evaluate(+ node =>+ node+ .getAnimations({subtree: true})+ .filter(animation => animation.playState === 'running').length,+ ),+ )+ .toBe(0);+}++async function openDirtySheet(page: Page, fixture: SheetFixture) {+ await page.goto(+ `${storybook.origin}/iframe.html?id=${fixture.story}&viewMode=story`,+ {waitUntil: 'load'},+ );+ await fixture.trigger(page).waitFor({state: 'visible'});+ await page.evaluate(async () => {+ await document.fonts.ready;+ });+ await fixture.trigger(page).tap();+ await expect(+ page.getByRole('dialog', {name: fixture.sheetLabel}),+ ).toBeVisible();+ await waitForSheetRest(page, fixture);+ await fixture.dirty(page);+ const before = await readScrim(page, fixture);+ expect(before).toEqual({+ open: true,+ modal: true,+ opacity: 1,+ panelAtRest: true,+ });+}++/** Asks to close the sheet by `path`; the changed draft then asks first. */+async function requestClose(+ page: Page,+ fixture: SheetFixture,+ path: ClosePath,+) {+ const panel = sheetDialog(page, fixture).locator('[tabindex="-1"]').first();+ const box = await panel.boundingBox();+ if (box == null) {+ throw new Error('The sheet panel has no box');+ }+ const x = Math.round(box.x + box.width / 2);+ if (path === 'swipe') {+ // A finger on the grabber, pulled past the dismiss line and lifted: the+ // live drag thins the scrim with the sheet's travel.+ const driver = await touchDriver(page);+ const from = {x, y: Math.round(box.y + 12)};+ const to = {x, y: Math.round(Math.min(box.y + box.height, 844 - 8))};+ await driver.play(drag(from, to, {durationMs: 320}), {pacing: 'spacing'});+ } else if (path === 'scrim') {+ // The dialog above the panel is the scrim.+ await page.touchscreen.tap(x, Math.max(12, Math.round(box.y - 40)));+ } else {+ // A tooltip a focused control shows would take the press first (the+ // dismissal stack's order), so the press starts from the sheet's panel,+ // once that tooltip has gone.+ await panel.focus();+ await expect(page.getByRole('tooltip')).toHaveCount(0);+ await page.keyboard.press('Escape');+ }+}++const confirmation = (page: Page) =>+ page.getByRole('alertdialog', {name: 'Discard changes?'});++for (const fixture of FIXTURES) {+ for (const path of CLOSE_PATHS) {+ test(`${fixture.name}: the scrim stays while the confirmation a ${path} opened is up, and after Keep editing`, async ({+ page,+ }) => {+ await openDirtySheet(page, fixture);+ await requestClose(page, fixture, path);+ await expect(confirmation(page)).toBeVisible();+ await expect(+ page.getByRole('button', {name: 'Keep editing'}),+ ).toBeFocused();++ // The sheet stayed presented and modal, with its backdrop painting.+ // After a swipe the panel returns to rest and the scrim with it, over+ // the sheet's own motion, so the reading waits for that rest.+ await waitForSheetRest(page, fixture);+ await expect+ .poll(async () => readScrim(page, fixture), {+ message: `the ${fixture.name} sheet's scrim while the confirmation is open`,+ })+ .toEqual({open: true, modal: true, opacity: 1, panelAtRest: true});++ await page.getByRole('button', {name: 'Keep editing'}).tap();+ await expect(confirmation(page)).toHaveCount(0);+ await expect(+ page.getByRole('dialog', {name: fixture.sheetLabel}),+ ).toBeVisible();+ await expect(+ page.getByRole(fixture.name === 'Tokenizer' ? 'textbox' : 'button', {+ name: fixture.focusAfterKeepEditing,+ }),+ ).toBeFocused();+ // Keep editing changes nothing of the sheet's own presentation.+ expect(await readScrim(page, fixture)).toEqual({+ open: true,+ modal: true,+ opacity: 1,+ panelAtRest: true,+ });+ });+ }++ test(`${fixture.name}: Discard after a swipe closes the sheet with its exit, and focus returns to the trigger`, async ({+ page,+ }) => {+ await openDirtySheet(page, fixture);+ await requestClose(page, fixture, 'swipe');+ await expect(confirmation(page)).toBeVisible();+ await waitForSheetRest(page, fixture);+ await page.getByRole('button', {name: 'Discard changes'}).tap();+ await expect(confirmation(page)).toHaveCount(0);+ // The exit runs: the dialog is still presented for a moment, then gone,+ // and the backdrop has faded with it.+ await expect(+ page.locator(`dialog[aria-label="${fixture.sheetLabel}"][open]`),+ ).toHaveCount(0, {timeout: 5000});+ await expect(fixture.trigger(page)).toBeFocused();+ });+}diff --git a/packages/core/src/BottomSheet/useSheetGestures.test.ts b/packages/core/src/BottomSheet/useSheetGestures.test.tsindex 14278143d2..b86150c2a9 100644--- a/packages/core/src/BottomSheet/useSheetGestures.test.ts+++ b/packages/core/src/BottomSheet/useSheetGestures.test.ts@@ -11,6 +11,7 @@import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';import {act, renderHook} from '@testing-library/react';+import {useState} from 'react';import {rubberBand} from '../motion/rubberBand';import {isInsideNestedLayer,@@ -814,6 +815,88 @@ describe('useSheetGestures', () => {expect(onDismiss).toHaveBeenCalledTimes(1);});+ describe('a dismissal the host refuses', () => {+ // The host answers a dismissal through `isOpenRequested`: it stays true+ // when a guarded `onOpenChange` keeps the sheet open (a confirmation+ // asks before a changed draft is discarded). The panel then rests on its+ // detent again, and the scrim the drag thinned toward the dismiss line+ // must rest with it.+ it('restores the full scrim of a sheet resting fully open', () => {+ const onScrimOpacity = vi.fn();+ const {hook, onDismiss} = setup({+ snapHeights: () => [200],+ onScrimOpacity,+ });+ const t = makeTarget();+ down(hook, 0, 0, t);+ move(hook, 160, 400, t);+ move(hook, 330, 900, t);+ // The live drag has thinned the scrim past the shortest detent.+ expect(onScrimOpacity.mock.lastCall?.[0]).toBeLessThan(1);+ // The release asks to close; `isOpen` stays true, so the host refused.+ up(hook, 330, 1400, t);+ expect(onDismiss).toHaveBeenCalledTimes(1);+ expect(hook.result.current.settledOffset).toBe(0);+ expect(hook.result.current.isDismissedByTouchDrag).toBe(false);+ expect(onScrimOpacity).toHaveBeenLastCalledWith(1);+ });++ it('restores the thinned scrim of a sheet resting at its peek', () => {+ const onScrimOpacity = vi.fn();+ // Sheet 400, stops at 300 and a 60px sliver -> offsets [0, 100, 340];+ // the sliver is a peek, which rests under the peek floor (0.3).+ const {hook, onDismiss} = setup({+ snapHeights: () => [60, 300],+ onScrimOpacity,+ });+ const t = makeTarget();+ down(hook, 0, 0, t);+ move(hook, 170, 400, t);+ move(hook, 340, 900, t);+ up(hook, 340, 1400, t);+ expect(hook.result.current.settledOffset).toBe(340);+ // From the peek, a slow pull past the dismiss line asks to close.+ down(hook, 340, 2000, t);+ move(hook, 380, 2400, t);+ move(hook, 420, 2900, t);+ up(hook, 420, 3400, t);+ expect(onDismiss).toHaveBeenCalledTimes(1);+ expect(hook.result.current.settledOffset).toBe(340);+ expect(Number(onScrimOpacity.mock.lastCall?.[0])).toBeCloseTo(0.3);+ });++ it('leaves the thinned scrim alone when the host takes the dismissal', () => {+ const onScrimOpacity = vi.fn();+ const onDismiss = vi.fn();+ // A host that takes the close: its controlled state answers in the+ // same update the release asked in.+ const hook = renderHook(() => {+ const [isOpenRequested, setIsOpenRequested] = useState(true);+ return useSheetGestures({+ isOpen: true,+ isOpenRequested,+ onDismiss: () => {+ onDismiss();+ setIsOpenRequested(false);+ },+ snapHeights: () => [200],+ onScrimOpacity,+ });+ });+ const t = makeTarget();+ down(hook, 0, 0, t);+ move(hook, 160, 400, t);+ move(hook, 330, 900, t);+ const thinned = onScrimOpacity.mock.lastCall?.[0];+ expect(thinned).toBeLessThan(1);+ up(hook, 330, 1400, t);+ expect(onDismiss).toHaveBeenCalledTimes(1);+ // The host's exit owns the scrim from here, so the hook writes nothing+ // more.+ expect(onScrimOpacity.mock.lastCall?.[0]).toBe(thinned);+ });+ });+describe('body overscroll', () => {// A scrollable body element nested inside the sheet, with a settable// scrollTop so we can simulate "at the top" vs "scrolled".diff --git a/packages/core/src/BottomSheet/useSheetGestures.ts b/packages/core/src/BottomSheet/useSheetGestures.tsindex b4608fc571..a484f85d2b 100644--- a/packages/core/src/BottomSheet/useSheetGestures.ts+++ b/packages/core/src/BottomSheet/useSheetGestures.ts@@ -560,22 +560,29 @@ export function useSheetGestures({// onDismiss() and sets `pending`; the host answers in the same update, so// the first render afterwards says whether it took the close (its// controlled state now says closed: the exit under way is the drag's) or- // refused it (a guarded onOpenChange left it open: the sheet snaps back and- // the request is spent). Either way the flag is settled during render, the- // prev-prop pattern, and derived back to false once the sheet is open- // again — so a later close from a control, Escape or code is never- // mistaken for a drag.+ // refused it (a guarded onOpenChange left it open: the sheet snaps back,+ // its scrim with it, and the request is spent). Either way the flag is+ // settled during render, the prev-prop pattern, and derived back to false+ // once the sheet is open again — so a later close from a control, Escape+ // or code is never mistaken for a drag.const [touchDragDismissal, setTouchDragDismissal] = useState<{isTouch: boolean;pending: boolean;} | null>(null);+ // The render that spends a refused request counts it. The layout effect+ // below answers each count.+ const [refusedDismissalCount, setRefusedDismissalCount] = useState(0);if (touchDragDismissal != null) {if (touchDragDismissal.pending) {- setTouchDragDismissal(- isOpenRequested- ? null- : {isTouch: touchDragDismissal.isTouch, pending: false},- );+ if (isOpenRequested) {+ setTouchDragDismissal(null);+ setRefusedDismissalCount(count => count + 1);+ } else {+ setTouchDragDismissal({+ isTouch: touchDragDismissal.isTouch,+ pending: false,+ });+ }} else if (isOpenRequested) {setTouchDragDismissal(null);}@@ -712,6 +719,24 @@ export function useSheetGestures({hasFixedHeightRef.current = hasFixedHeight;});+ // The release cannot know whether the host takes the close. The host+ // answers through `isOpenRequested` in the next render. Keep the left+ // detent's scrim until then.+ const restingScrimOpacityRef = useRef<number | null>(null);+ // Syncs the host's scrim (its backdrop, written through `onScrimOpacity`)+ // with the panel's return to rest after a refusal: the panel rests on that+ // detent again, so the scrim the drag thinned toward the dismiss line rests+ // with it. The refusal changes none of the host's own scrim inputs, so the+ // drag's last value would otherwise stand.+ useLayoutEffect(() => {+ const restingScrimOpacity = restingScrimOpacityRef.current;+ if (refusedDismissalCount === 0 || restingScrimOpacity == null) {+ return;+ }+ restingScrimOpacityRef.current = null;+ onScrimOpacityRef.current?.(restingScrimOpacity);+ }, [refusedDismissalCount]);+// Live drag bookkeeping (refs so pointermove doesn't churn renders).const dragStateRef = useRef<{// Whether the touch path drives this drag. Such a drag holds no pointer@@ -1169,6 +1194,12 @@ export function useSheetGestures({naturalEndGap,false,);+ restingScrimOpacityRef.current = scrimOpacityForOffset(+ baseOffset,+ offsets,+ dismissOffset,+ peekOffset,+ );setTouchDragDismissal({isTouch, pending: true});onDismissRef.current();} else {