An open source design system that's fully customizable and agent ready
TypeScript
test(core): BottomSheet detents, proven with the interaction harness (#10055)
Cindy Zhang0200dfe0f6ef
diff --git a/docs/specs/components/BottomSheet/BottomSheet.spec.md b/docs/specs/components/BottomSheet/BottomSheet.spec.mdindex 964e302071..d0d471d0e0 100644--- a/docs/specs/components/BottomSheet/BottomSheet.spec.md+++ b/docs/specs/components/BottomSheet/BottomSheet.spec.md@@ -22,6 +22,7 @@ verified_by:packages/core/src/BottomSheet/__tests__/BottomSheetNativeModal.a11y.browser.spec.ts,packages/core/src/BottomSheet/__tests__/BottomSheetKeyboard.a11y.browser.spec.ts,packages/core/src/BottomSheet/__tests__/BottomSheetDrag.a11y.chromium.spec.ts,+ packages/core/src/BottomSheet/__tests__/BottomSheetDetent.interaction.browser.spec.ts,apps/storybook/stories/BottomSheet.stories.tsx,scripts/check-knowledge.mjs,]@@ -167,6 +168,7 @@ remain documented in `BottomSheet.doc.mjs`.| FR16 | An open modal sheet is a focus region through Core's shared focus-region module (`component:Dialog/DEC-2`): in the top sheet, Tab from the last tabbable control moves focus to the first and Shift+Tab from the first moves focus to the last, so focus never leaves the sheet for the browser's own interface. A covered or closing sheet does not answer Tab, and a non-modal sheet contains nothing (FR11). A switcher step (the deprecated BottomSheetSwitcher) is the exception to DEC-2, as `component:Dialog` DEC-2 states. | `component:Dialog/DEC-2` || FR17 | A BottomSheet open on the server, by its own `isOpen` or as a `BottomSheetSwitcher`'s active sheet, renders closed until hydration (no open styles, no `aria-modal`, the markup of a closed sheet) and opens in the render after hydration, the first that can enter its native host; it never claims a modality it does not have (`spec:AST-020` FR1, WCAG 2.2 SC 4.1.2). The server and hydrating renders produce the same markup (`spec:AST-013` FR9), and the open after hydration is settled, with no entry motion; later opens and closes animate as usual (`spec:AST-013` FR13). | `spec:AST-020` FR1 || FR18 | A finger's pull up past the tallest detent stretches the sheet on `spec:AST-094` FR3's rubber band, the same on every pull, with no hold. The sheet's surface reaches below the screen far enough for the whole stretch and the release, so the page under it never shows. A pull on the sheet's body stretches it as a pull on the grabber does, once the content has no room left to scroll that way: content that fits stretches at once, and a long list scrolls to its end first, then holds still while the sheet stretches. At every detent, a list that reaches its end mid-pull holds still while the sheet takes the rest of the pull. A sheet the caller sizes or styles keeps 48 px below the screen, and its stretch stops there. An inline block size, any `xstyle` and any class name count, because the sheet cannot read their rules. A mouse or a pen keeps its own resisted stretch, at most 48 px (`spec:AST-017` FR59). | DEC-3; `spec:AST-094` FR3 |+| FR19 | A release settles on the detent nearest its projected position (`spec:AST-094` FR36); a release whose velocity points back toward its start returns to its starting detent (`spec:AST-094` FR37). An `info` sheet whose projection passes the dismiss point closes; a `form` or `required` sheet settles on its shortest detent (FR7). Implementation gap: the settle plays `--ease-standard` over the theme's `--duration-medium`, at a speed set by the distance left rather than the finger's (`spec:AST-094` FR38). Implementation gap: in WebKit, the settle stops advancing while the main thread is blocked (`spec:AST-094` FR5). Implementation gap: a release whose velocity points back toward its start still commits when it follows a net downward drag and its projection passes the dismiss point, or when its projection lies nearer the next detent in the drag's direction (`spec:AST-094` FR37). Implementation gap: a release after 48 px of travel or less projects nothing: it is judged where the finger lifted, so a short fast flick closes an `info` sheet only when the finger itself lifts past the dismiss point (`spec:AST-094` FR36). | `spec:AST-094` FR5, FR36, FR37, FR38; FR7 || FR20 | A standalone sheet (not a switcher step) removed while open is closed for focus: when it was the standalone or top sheet and focus was inside it, or fell to the body with its removal, focus returns as FR9 (modal) or FR11 (non-modal) state, to `finalFocusRef`, else the opener while it is still connected; with a sheet open beneath, focus goes into that revealed sheet by FR9. An FR10 replace keeps its handoff to the entering sheet, and a switcher step's change keeps FR12's handoff. Removing a whole stack in one update returns focus once, as FR9 closes it: to the bottom sheet's `finalFocusRef` or opener. Removing a covered sheet under a top sheet that stays moves no focus, because focus is in the top sheet. A removed opener moves no focus and raises no error. Implementation gap: a `BottomSheetSwitcher` flow removed while open, alone or as the bottom level of a stack, returns no focus. | `spec:AST-020/FR1` (WCAG 2.2 SC 2.4.3); FR9; FR11 |### Allowed variation@@ -390,6 +392,7 @@ a decision that they must remain unthemeable.| FR16 | `BottomSheet.test.tsx` focus-region suite | Modal and non-modal sheets; Tab and Shift+Tab at the sheet's edge | Tab from the last control leaves a modal sheet, or a non-modal sheet captures Tab | `audit:BottomSheet/accessibility` || FR17 | `BottomSheet.ssr.test.tsx`; `BottomSheetSwitcher.test.tsx` flow that mounts open | Open on the server; hydration; a closed sheet's markup | An open server render with `aria-modal`, open styles, or markup unlike a closed one, a hydration error, no `showModal()` after hydration, an entry motion on the open right after hydration, or none on a later open fails. | `audit:BottomSheet/accessibility` || FR18 | `useSheetGestures.test.ts` stretch suites; `BottomSheetPanel.test.tsx` reserve cases; `BottomSheetDrag.a11y.chromium.spec.ts` | Three finger pulls past the top; short content pulled up on its body at five points, the first pull and every one after it; a long list pulled past its end; a mouse pull and a pen pull | A capped or held stretch, a pull that stretches less than the one before it, a body pull on short content that moves nothing, a long list that never stretches the sheet once at its end or rubber-bands itself while the sheet stretches, or a reserve under 40% of the viewport on a device with a touch pointer fails, unless the caller sizes or styles the sheet (48 px). | `audit:BottomSheet/behavior` |+| FR19 | `BottomSheetDetent.interaction.browser.spec.ts`; `useSheetGestures.test.ts`; `snapOffsets.test.ts` | On the Snap points story under real touch input: a slow release between detents, a 2,000 px/s downward flick, the settle to a detent with its curve recorded (FR19's FR38 gap), in Chromium the settle through a 700 ms main-thread block (`spec:AST-094` FR5; WebKit's gap is skipped), and a rendering trace of the settle in Chromium | A slow release that lands off the nearest detent, a flick past the dismiss point that leaves the sheet open, a settle that ends off the detent, or a settle that stalls while the main thread is blocked, or lays out or paints during the settle, fails | `audit:BottomSheet/behavior` || FR20 | `BottomSheetCloseFocus.test.tsx` "BottomSheet removed while open" suite; real-browser focus check in Chromium | A modal and a non-modal sheet removed from inside; `finalFocusRef`; the top sheet of a stack removed; a covered sheet removed under a top sheet that stays; a whole stack removed in one update; a sheet removed in the update that opens another; an opener removed with the sheet | Focus on `body` after a removal from inside, focus on `body` after a whole stack is removed, focus moved out of the top sheet when a covered sheet is removed, focus pulled out of a sheet that opened in the same update, or an error when the opener is gone, fails. | `audit:BottomSheet/behavior` |Existing tests directly assert the Sheet panel target, Content area placement,diff --git a/internal/interaction-harness/README.md b/internal/interaction-harness/README.mdindex aae238bf65..7febeacde6 100644--- a/internal/interaction-harness/README.md+++ b/internal/interaction-harness/README.md@@ -11,6 +11,8 @@ An accessibility spec (`*.a11y.browser.spec.ts`, under[`playwright.config.ts`](../../playwright.config.ts)) may use the animationholds and the timer gate too, to check a state an animation passes through.+The exemplar to copy is+[`BottomSheetDetent.interaction.browser.spec.ts`](../../packages/core/src/BottomSheet/__tests__/BottomSheetDetent.interaction.browser.spec.ts).The harness proves its own instruments in[`src/harness.interaction.browser.spec.ts`](src/harness.interaction.browser.spec.ts).The busy-main-thread proof and the rendering-trace counts have a negative@@ -24,7 +26,7 @@ self-tests check an instrument against a known answer.pnpm storybook:build # the specs read stories from the built Storybookpnpm exec playwright install chromium webkitpnpm test:interaction --project chromium # everything, Chromium-pnpm test:interaction <spec file> # one spec, both engines+pnpm test:interaction BottomSheetDetent # one spec, both enginespnpm storyboards # only the tests tagged @storyboard```diff --git a/packages/core/src/BottomSheet/__tests__/BottomSheetDetent.interaction.browser.spec.ts b/packages/core/src/BottomSheet/__tests__/BottomSheetDetent.interaction.browser.spec.tsnew file mode 100644index 0000000000..5b5b023a8d--- /dev/null+++ b/packages/core/src/BottomSheet/__tests__/BottomSheetDetent.interaction.browser.spec.ts@@ -0,0 +1,406 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file BottomSheetDetent.interaction.browser.spec.ts+ * @input The built "Snap points" BottomSheet story, real touch input+ * (Chromium CDP / WebKit's input command) and the interaction harness+ * @output Interaction and animation proofs for dragging the sheet to a+ * detent: the drag follows the finger and a slow release settles on the+ * nearest detent; a flick dismisses; the settle lands on the detent, its+ * sampled curve recorded; the settle keeps advancing every frame through a blocked+ * main thread; the settle does no Layout or Paint per frame; a storyboard of+ * the drag and the settle.+ * @position The exemplar for `*.interaction.browser.spec.ts`: component lanes+ * copy this shape. Each test names the instrument it uses from+ * @astryxdesign/interaction-harness, so the evidence layer is explicit.+ *+ * The settle's curve is recorded, not asserted: today it is the panel's+ * `--ease-standard` CSS transition over `--duration-medium` (SETTLE_EASING and+ * SETTLE_MS below), which starts a release at rest at a speed of its own. The+ * touch model starts it at the finger's speed. When the settle moves to the+ * UIKit spring, `expectedSettle` becomes the spring from the motion constants,+ * and the curve and the velocity hand-off reported below become assertions.+ */++import {+ expect,+ test,+ type Locator,+ type Page,+} from '@astryxdesign/a11y-spec/playwright';+import {+ animationStoryboard,+ blockMainThread,+ busyWindowProof,+ castStoryboard,+ compareCurve,+ countBetween,+ curveOf,+ drag,+ flick,+ frames,+ freezeTimers,+ holdAnimations,+ installLongTaskLog,+ installTimerGate,+ markElement,+ openStory,+ readLongTasks,+ releaseAnimations,+ releaseVelocity,+ sampleCurve,+ startScreencast,+ thawTimers,+ timeline,+ timingFunction,+ touchDriver,+ toTouchEvents,+ touchStoryboard,+ traceRendering,+ trackMarker,+ withStorybook,+ waitForAnimation,+ waitForRest,+ writeEvidence,+ type TouchDriver,+} from '@astryxdesign/interaction-harness';++const storybook = withStorybook(test);++// The settle's timing, from the theme the story renders in: `--ease-standard`+// is the default cubic-bezier(0.24, 1, 0.4, 1), and `--duration-medium` is the+// neutral theme's motion `medium` (300 ms; the base theme's is 410 ms).+const SETTLE_EASING = 'cubic-bezier(0.24, 1, 0.4, 1)';+const SETTLE_MS = 300;++interface OpenSheet {+ driver: TouchDriver;+ sheet: Locator;+ /** Top of the sheet at its tall detent and at the half-viewport detent, CSS px. */+ tallTop: number;+ halfTop: number;+ handle: {x: number; y: number};+}++async function openSheet(page: Page): Promise<OpenSheet> {+ await installLongTaskLog(page);+ await openStory(page, storybook(), 'core-bottomsheet--snap-points');+ const driver = await touchDriver(page);+ const trigger = page.getByRole('button', {name: 'Open nearby places'});+ const box = await trigger.boundingBox();+ if (box == null) {+ throw new Error('no trigger');+ }+ await driver.tap({x: box.x + box.width / 2, y: box.y + box.height / 2});+ const sheet = page+ .getByRole('dialog', {name: 'Nearby places'})+ .locator('.astryx-bottom-sheet')+ .first();+ await expect(sheet).toBeVisible();+ await waitForRest(sheet);+ const rect = await sheet.boundingBox();+ if (rect == null) {+ throw new Error('no sheet');+ }+ const viewport = page.viewportSize();+ if (viewport == null) {+ throw new Error('no viewport');+ }+ return {+ driver,+ sheet,+ tallTop: rect.y,+ // snapPoints={[0.5]}: the extra stop shows half the viewport.+ halfTop: viewport.height * 0.5,+ handle: {x: rect.x + rect.width / 2, y: rect.y + 12},+ };+}++// A plain evaluate, not boundingBox(): it must also work while the page's timers are frozen.+const sheetTop = async (sheet: Locator) =>+ sheet.evaluate(el => el.getBoundingClientRect().y);++/** A slow drag that rests before the lift: release velocity 0, so the release projects onto itself. */+function slowDragTo(from: {x: number; y: number}, dy: number) {+ return drag(+ from,+ {x: from.x, y: from.y + dy},+ {durationMs: 400, hz: 60, restMs: 150},+ );+}++test('a slow drag follows the finger and settles on the nearest detent', async ({+ page,+ browserName,+}) => {+ const {driver, sheet, tallTop, halfTop, handle} = await openSheet(page);+ // Two thirds of the way to the half detent: nearer to it than to tall.+ const dy = Math.round((halfTop - tallTop) * 0.66);+ const script = slowDragTo(handle, dy);+ const lastMove =+ toTouchEvents(script).filter(e => e.type === 'touchMove').length - 1;+ const tops: number[] = [];+ let moves = 0;+ let restingTop = NaN;+ const started = Date.now();+ await driver.play(script, {+ onEvent: async step => {+ if (step.type !== 'touchMove') {+ return;+ }+ // Read right away (moves are paced at 60 Hz), and once more after the+ // last move has been presented: the finger rests 150 ms before lifting.+ tops.push(await sheetTop(sheet));+ if (moves++ === lastMove) {+ await frames(page, 1);+ restingTop = await sheetTop(sheet);+ }+ },+ });+ // The sheet tracked the finger: monotonic, and 1:1 once out of the+ // starting detent's 40 px magnet.+ expect(tops.every((top, i) => i === 0 || top >= tops[i - 1] - 0.5)).toBe(+ true,+ );+ expect(restingTop).toBeCloseTo(tallTop + dy, 0);+ await waitForRest(sheet);+ expect(await sheetTop(sheet)).toBeCloseTo(halfTop, 0);+ // No long task from the gesture or the settle (the story's own load is+ // excluded). Only Chromium has the Long Tasks API, so only Chromium can+ // check this; the drag and the settle above hold in both engines.+ if (browserName === 'chromium') {+ expect(await readLongTasks(page, {from: started, to: Date.now()})).toEqual(+ [],+ );+ }+});++test('a downward flick dismisses the sheet', async ({page}) => {+ const {driver, handle} = await openSheet(page);+ const script = flick(handle, {+ velocity: {x: 0, y: 2000},+ durationMs: 80,+ hz: 120,+ });+ expect(releaseVelocity(script).y).toBeCloseTo(2000, -1);+ await driver.play(script);+ await expect(page.getByRole('dialog', {name: 'Nearby places'})).toBeHidden();+});++test('the settle lands on the detent, its curve recorded frame by frame', async ({+ page,+}, testInfo) => {+ const {driver, sheet, tallTop, halfTop, handle} = await openSheet(page);+ const dy = Math.round((halfTop - tallTop) * 0.66);+ await driver.play(slowDragTo(handle, dy));+ const [settle] = await waitForAnimation(sheet);+ const held = await holdAnimations(page, sheet);+ const transition = held.find(a => a.name === 'transform');+ if (transition == null) {+ throw new Error(`no transform transition held: ${JSON.stringify(held)}`);+ }+ // The curve is recorded, not asserted: today's settle is the theme's+ // transition, which starts a release at rest at a speed of its own, where+ // the touch model starts it at the finger's; this records what it plays.+ // Seek the held settle to every frame time and read the presented transform.+ const samples = curveOf(+ await sampleCurve(sheet, timeline(SETTLE_MS)),+ 'translateY',+ );+ const from = samples[0].value;+ const to = samples[samples.length - 1].value;+ const ease = timingFunction(SETTLE_EASING);+ const expectedSettle = (t: number) =>+ from + (to - from) * ease(Math.min(1, t / SETTLE_MS));+ const result = compareCurve(samples, expectedSettle, 0.5);+ await releaseAnimations(page);+ testInfo.annotations.push({+ type: 'settle-curve',+ description: `settle: ${transition.easing}, ${transition.durationMs} ms; frame-by-frame max error ${result.maxError.toFixed(2)} px against ${SETTLE_EASING} over ${SETTLE_MS} ms`,+ });+ // UIKit parity metric, reported rather than asserted until the spring lands:+ // the settle's initial velocity, read from its first two frames, vs the+ // finger's at release (here 0).+ const initialVelocity =+ ((samples[1].value - samples[0].value) / (samples[1].t - samples[0].t)) *+ 1000;+ testInfo.annotations.push({+ type: 'uikit-parity',+ description: `settle starts at ${initialVelocity.toFixed(0)} px/s for a release at 0 px/s (UIKit hands the release velocity to the spring)`,+ });+ await writeEvidence(+ 'curves/bottomsheet-settle',+ {+ [`${testInfo.project.name}.json`]: JSON.stringify(+ {settle, transition, comparison: result},+ null,+ 2,+ ),+ },+ testInfo,+ );+ // Where it lands is asserted: the half detent.+ expect(samples.at(-1)?.value).toBeCloseTo(halfTop - tallTop, 0);+});++test('the settle keeps advancing every frame while the main thread is blocked', async ({+ page,+ browserName,+}, testInfo) => {+ test.skip(+ browserName === 'webkit',+ 'WebKit holds the settle short of its detent until a blocked main thread resumes',+ );+ const {driver, sheet, tallTop, halfTop, handle} = await openSheet(page);+ await markElement(sheet);+ const cast = await startScreencast(page);+ // The settle must be running (and composited) before the block: an+ // animation cannot start while the main thread is held. Armed before the+ // release, the page waits for the settle itself (the sheet runs no other+ // animation during the drag) and blocks once it has run 16 ms, however busy+ // the machine; armed after, the round trip would leave little of the settle+ // to judge.+ const blocking = blockMainThread(page, 700, {+ during: sheet,+ minProgressMs: 16,+ });+ await driver.play(slowDragTo(handle, Math.round((halfTop - tallTop) * 0.66)));+ const block = await blocking;+ // Where the settle ends, from the page: a frame after the block can still+ // show a stale position (see `settledAt`). The frames track the marker+ // chip, which sits inset in the sheet, so it is the chip's rest: the sheet's+ // own top would end the judged window about 9 px before the settle does.+ await waitForRest(sheet);+ const settledAt = await sheet.evaluate(el => {+ const chip = el.querySelector('[data-harness-marker-chip]');+ if (chip == null) {+ throw new Error('the sheet lost its marker chip');+ }+ return chip.getBoundingClientRect().y;+ });+ const castFrames = await cast.stop();+ const tracked = await trackMarker(page, castFrames);+ // Judge the part of the block during which the settle was still moving:+ // until it is within 2 px of rest (the screencast rounds to whole pixels,+ // so the easing tail shows plateaus there).+ const proof = busyWindowProof(tracked, block, {settledWithin: 2, settledAt});+ await writeEvidence(+ 'busy-main-thread/bottomsheet-settle',+ {+ [`${testInfo.project.name}.json`]: JSON.stringify(+ {+ block,+ settledAt,+ proof,+ frames: tracked.map(f => ({+ t: +(f.t - block.from).toFixed(1),+ y: f.box?.y ?? null,+ h: f.box?.height ?? null,+ })),+ },+ null,+ 1,+ ),+ },+ testInfo,+ );+ const film = await castStoryboard(page, castFrames, {+ name: 'bottomsheet-settle-busy-main-thread',+ zero: block.from,+ from: block.from - 40,+ to: proof.judged.to + 40,+ columns: 8,+ cellScale: 0.35,+ data: t => ({y: tracked.find(f => f.t === t)?.box?.y ?? -1}),+ });+ await film.write(testInfo, {block, judged: proof.judged});+ testInfo.annotations.push({+ type: 'busy-main-thread',+ description: proof.summary,+ });+ expect(proof.verdict.failures, proof.summary).toEqual([]);+ expect(proof.monotonic).toBe(true);+ // The judged window runs until the marker is within 2 px of where it rests.+ const lastJudged = tracked+ .filter(f => f.box != null && f.t <= proof.judged.to)+ .at(-1);+ expect(+ Math.abs((lastJudged?.box?.y ?? Number.NaN) - settledAt),+ ).toBeLessThanOrEqual(2);+});++test('the settle does no Layout or Paint per frame', async ({+ page,+ browserName,+}) => {+ test.skip(browserName !== 'chromium', 'rendering traces are Chromium-only');+ const {driver, sheet, tallTop, halfTop, handle} = await openSheet(page);+ let settle = {from: 0, to: 0};+ const trace = await traceRendering(page, async () => {+ await driver.play(+ slowDragTo(handle, Math.round((halfTop - tallTop) * 0.66)),+ );+ [settle] = await waitForAnimation(sheet);+ await waitForRest(sheet);+ });+ // The steady part of the settle: its first and last frames may commit.+ const during = countBetween(trace, settle.from + 50, settle.to - 50);+ expect(during.Layout ?? 0, JSON.stringify(during)).toBe(0);+ expect(during.Paint ?? 0, JSON.stringify(during)).toBe(0);+ expect(trace.longTasks).toEqual([]);+});++test(+ 'storyboard: drag to the half detent and settle',+ {tag: '@storyboard'},+ async ({page}, testInfo) => {+ const {driver, sheet, tallTop, halfTop, handle} = await openSheet(page);+ // Gate the page's timers from here on, so the settle's completion timer can+ // be held with its animation while the filmstrip is photographed.+ await installTimerGate(page);+ const viewport = page.viewportSize() ?? {width: 402, height: 714};+ const clip = {x: 0, y: 0, width: viewport.width, height: viewport.height};+ const dy = Math.round((halfTop - tallTop) * 0.66);+ const measure = async () => ({top: await sheetTop(sheet)});+ const dragBoard = await touchStoryboard(+ page,+ driver,+ drag(+ handle,+ {x: handle.x, y: handle.y + dy},+ {durationMs: 200, hz: 30, restMs: 150},+ ),+ {+ name: 'bottomsheet-drag-to-detent',+ clip,+ measure,+ columns: 5,+ cellScale: 0.4,+ },+ );+ await waitForAnimation(sheet);+ await freezeTimers(page);+ const {storyboard: settleBoard} = await animationStoryboard(page, {+ name: 'bottomsheet-settle',+ clip,+ scope: sheet,+ measure,+ columns: 7,+ cellScale: 0.4,+ });+ await releaseAnimations(page, {finish: true});+ await thawTimers(page);+ await dragBoard.write(testInfo);+ await settleBoard.write(testInfo);+ // The trace is the assertion; the sheets are the evidence.+ const dragTops = dragBoard.frames.map(f => f.data.top as number);+ expect(+ dragTops.every((top, i) => i === 0 || top >= dragTops[i - 1] - 0.5),+ ).toBe(true);+ const settleTops = settleBoard.frames.map(f => f.data.top as number);+ expect(+ settleTops.every((top, i) => i === 0 || top >= settleTops[i - 1] - 0.5),+ ).toBe(true);+ expect(settleTops.at(-1)).toBeCloseTo(halfTop, 0);+ },+);diff --git a/playwright.interaction.config.ts b/playwright.interaction.config.tsindex 370c157f78..6bc65076e1 100644--- a/playwright.interaction.config.ts+++ b/playwright.interaction.config.ts@@ -15,7 +15,7 @@* pnpm storybook:build* pnpm exec playwright install chromium webkit* pnpm test:interaction --project chromium- * pnpm test:interaction harness.interaction.browser.spec.ts+ * pnpm test:interaction BottomSheetDetent.interaction.browser.spec.ts** Specs import `test` from `@astryxdesign/a11y-spec/playwright`, the base test* shared with playwright.config.ts: no context reaches a remote host. The