Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(BottomSheet): a render reads the stored viewport height (#10363)

Christopher Chedeau3c1f7b217033
diff --git a/.changeset/bottom-sheet-viewport-height-store.md b/.changeset/bottom-sheet-viewport-height-store.md
new file mode 100644
index 0000000000..466c02b0c1
--- /dev/null
+++ b/.changeset/bottom-sheet-viewport-height-store.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] BottomSheet: an open sheet that renders again no longer reads the viewport height. It keeps the viewport height that its `resize` listener reads, so a tap that renders the sheet again forces no style recalculation or layout in React's commit. The sheet's height, reserve and detents are unchanged.
+
+@vjeux
diff --git a/packages/core/src/BottomSheet/BottomSheetPanel.test.tsx b/packages/core/src/BottomSheet/BottomSheetPanel.test.tsx
index 78eb837dc4..d507f4e625 100644
--- a/packages/core/src/BottomSheet/BottomSheetPanel.test.tsx
+++ b/packages/core/src/BottomSheet/BottomSheetPanel.test.tsx
@@ -10,6 +10,8 @@
import * as stylex from '@stylexjs/stylex';
import {act, fireEvent, render, screen} from '@testing-library/react';
+import {Suspense, use, useLayoutEffect} from 'react';
+import {renderToString} from 'react-dom/server';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {
BottomSheetPanel,
@@ -82,6 +84,98 @@ function renderPanel(
);
}
+function renderNamedPanel(name: string) {
+ return render(
+ <BottomSheetPanel
+ label={name}
+ state={{kind: 'open', entering: false}}
+ height="hug"
+ style={panelTransitionStyle}
+ onDismiss={() => {}}
+ onScrimOpacity={() => {}}>
+ {name} content
+ </BottomSheetPanel>,
+ );
+}
+
+function getNamedPanel(name: string): HTMLElement {
+ const panel = screen
+ .getByText(`${name} content`)
+ .closest<HTMLElement>('.astryx-bottom-sheet');
+ if (panel == null) {
+ throw new Error(`${name} surface not found`);
+ }
+ return panel;
+}
+
+// Counts reads of `window.innerHeight` until `restore`. A read after a
+// commit's DOM writes forces a style recalculation and a layout.
+function countViewportHeightReads() {
+ const descriptor = Object.getOwnPropertyDescriptor(window, 'innerHeight');
+ let value = window.innerHeight;
+ const reads = {
+ count: 0,
+ restore: () => {
+ if (descriptor != null) {
+ Object.defineProperty(window, 'innerHeight', descriptor);
+ }
+ window.innerHeight = value;
+ },
+ };
+ Object.defineProperty(window, 'innerHeight', {
+ configurable: true,
+ get: () => {
+ reads.count += 1;
+ return value;
+ },
+ set: next => {
+ value = next;
+ },
+ });
+ return reads;
+}
+
+// Tracks the `resize` listeners on `window` until `restore`. `attached` is
+// the number added and not yet removed.
+function trackResizeListeners() {
+ const add = vi.spyOn(window, 'addEventListener');
+ const remove = vi.spyOn(window, 'removeEventListener');
+ return {
+ attached: () => {
+ const events = [
+ ...add.mock.calls.map((call, index) => ({
+ type: call[0],
+ listener: call[1],
+ order: add.mock.invocationCallOrder[index] ?? 0,
+ isAdd: true,
+ })),
+ ...remove.mock.calls.map((call, index) => ({
+ type: call[0],
+ listener: call[1],
+ order: remove.mock.invocationCallOrder[index] ?? 0,
+ isAdd: false,
+ })),
+ ].sort((a, b) => a.order - b.order);
+ const live = new Set<unknown>();
+ for (const event of events) {
+ if (event.type !== 'resize') {
+ continue;
+ }
+ if (event.isAdd) {
+ live.add(event.listener);
+ } else {
+ live.delete(event.listener);
+ }
+ }
+ return live.size;
+ },
+ restore: () => {
+ add.mockRestore();
+ remove.mockRestore();
+ },
+ };
+}
+
function getPanel(): HTMLElement {
const panel = screen
.getByText('Panel content')
@@ -237,6 +331,187 @@ describe('BottomSheetPanel', () => {
}
});
+ it('reads the viewport height from its resize listener, not from layout, when it renders again', () => {
+ stubTouchPointer();
+ const {rerender} = renderPanel({kind: 'open', entering: false});
+ const reads = countViewportHeightReads();
+ try {
+ rerender(
+ <BottomSheetPanel
+ label="Sheet details"
+ state={{kind: 'open', entering: false}}
+ height="hug"
+ style={panelTransitionStyle}
+ onDismiss={() => {}}
+ onScrimOpacity={() => {}}>
+ Panel content, changed
+ </BottomSheetPanel>,
+ );
+ expect(screen.getByText('Panel content, changed')).toBeTruthy();
+ expect(reads.count).toBe(0);
+ } finally {
+ reads.restore();
+ }
+ });
+
+ it('shares one viewport height among open sheets, and forgets it when the last one closes', () => {
+ const viewportHeight = window.innerHeight;
+ const listeners = trackResizeListeners();
+ stubTouchPointer();
+ try {
+ const first = renderNamedPanel('First sheet');
+ const second = renderNamedPanel('Second sheet');
+ act(() => {
+ window.innerHeight = 1000;
+ window.dispatchEvent(new Event('resize'));
+ });
+ expect(
+ getNamedPanel('First sheet').style.getPropertyValue('--_sheet-reserve'),
+ ).toBe('400px');
+ expect(
+ getNamedPanel('Second sheet').style.getPropertyValue(
+ '--_sheet-reserve',
+ ),
+ ).toBe('400px');
+
+ first.unmount();
+ act(() => {
+ window.innerHeight = 900;
+ window.dispatchEvent(new Event('resize'));
+ });
+ expect(
+ getNamedPanel('Second sheet').style.getPropertyValue(
+ '--_sheet-reserve',
+ ),
+ ).toBe('360px');
+
+ second.unmount();
+ expect(listeners.attached()).toBe(0);
+ // With no sheet open, a resize reads nothing.
+ const reads = countViewportHeightReads();
+ try {
+ act(() => {
+ window.innerHeight = 700;
+ window.dispatchEvent(new Event('resize'));
+ });
+ expect(reads.count).toBe(0);
+ } finally {
+ reads.restore();
+ }
+ // Nothing kept the height meanwhile, so the next sheet reads the
+ // viewport in its first commit.
+ let firstReserve = '';
+ function FirstCommit() {
+ useLayoutEffect(() => {
+ firstReserve =
+ getNamedPanel('Third sheet').style.getPropertyValue(
+ '--_sheet-reserve',
+ );
+ }, []);
+ return null;
+ }
+ render(
+ <>
+ <BottomSheetPanel
+ label="Third sheet"
+ state={{kind: 'open', entering: false}}
+ height="hug"
+ style={panelTransitionStyle}
+ onDismiss={() => {}}
+ onScrimOpacity={() => {}}>
+ Third sheet content
+ </BottomSheetPanel>
+ <FirstCommit />
+ </>,
+ );
+ expect(firstReserve).toBe('280px');
+ } finally {
+ listeners.restore();
+ window.innerHeight = viewportHeight;
+ }
+ });
+
+ it('reads the viewport again after a render that never commits', async () => {
+ const viewportHeight = window.innerHeight;
+ stubTouchPointer();
+ const never = new Promise<never>(() => {});
+ function Suspend(): null {
+ use(never);
+ return null;
+ }
+ try {
+ window.innerHeight = 900;
+ const suspended = await act(async () =>
+ render(
+ <Suspense fallback={null}>
+ <BottomSheetPanel
+ label="Hidden sheet"
+ state={{kind: 'open', entering: false}}
+ height="hug"
+ style={panelTransitionStyle}
+ onDismiss={() => {}}
+ onScrimOpacity={() => {}}>
+ Hidden sheet content
+ </BottomSheetPanel>
+ <Suspend />
+ </Suspense>,
+ ),
+ );
+ expect(screen.queryByText('Hidden sheet content')).toBeNull();
+ suspended.unmount();
+ // No listener watched the viewport since that render.
+ window.innerHeight = 650;
+ let firstReserve = '';
+ function FirstCommit() {
+ useLayoutEffect(() => {
+ firstReserve =
+ getNamedPanel('Next sheet').style.getPropertyValue(
+ '--_sheet-reserve',
+ );
+ }, []);
+ return null;
+ }
+ render(
+ <>
+ <BottomSheetPanel
+ label="Next sheet"
+ state={{kind: 'open', entering: false}}
+ height="hug"
+ style={panelTransitionStyle}
+ onDismiss={() => {}}
+ onScrimOpacity={() => {}}>
+ Next sheet content
+ </BottomSheetPanel>
+ <FirstCommit />
+ </>,
+ );
+ expect(firstReserve).toBe('260px');
+ } finally {
+ window.innerHeight = viewportHeight;
+ }
+ });
+
+ it('renders on the server without reading the viewport', () => {
+ stubTouchPointer();
+ const reads = countViewportHeightReads();
+ try {
+ const html = renderToString(
+ <BottomSheetPanel
+ label="Sheet details"
+ state={{kind: 'open', entering: false}}
+ height="hug"
+ onDismiss={() => {}}
+ onScrimOpacity={() => {}}>
+ Panel content
+ </BottomSheetPanel>,
+ );
+ expect(html).toContain('Panel content');
+ expect(reads.count).toBe(0);
+ } finally {
+ reads.restore();
+ }
+ });
+
it('reports entrance completion only for the surface transform', () => {
const onMotionStart = vi.fn();
const onMotionComplete = vi.fn();
diff --git a/packages/core/src/BottomSheet/BottomSheetPanel.tsx b/packages/core/src/BottomSheet/BottomSheetPanel.tsx
index 5b150fbfbe..eb61ef7f3e 100644
--- a/packages/core/src/BottomSheet/BottomSheetPanel.tsx
+++ b/packages/core/src/BottomSheet/BottomSheetPanel.tsx
@@ -185,8 +185,53 @@ function layoutViewportHeight(): number {
return typeof window === 'undefined' ? 0 : window.innerHeight;
}
-function subscribeToResize(onChange: () => void): () => void {
- return subscribeInput(window, 'resize', onChange);
+// The layout viewport's height, as the `resize` listener last read it. While
+// the listener runs, a render reads this value, never `innerHeight`. After a
+// commit's DOM writes, a read of `innerHeight` forces a style recalculation
+// and a layout. Open sheets share one listener. With no sheet open, the value
+// is null, because nothing keeps it current.
+let viewportHeight: number | null = null;
+const viewportHeightListeners = new Set<() => void>();
+let stopViewportResize: (() => void) | null = null;
+
+function handleViewportResize(): void {
+ viewportHeight = layoutViewportHeight();
+ for (const listener of viewportHeightListeners) {
+ listener();
+ }
+}
+
+function subscribeToViewportHeight(onChange: () => void): () => void {
+ viewportHeightListeners.add(onChange);
+ if (stopViewportResize == null) {
+ stopViewportResize = subscribeInput(window, 'resize', handleViewportResize);
+ // A resize between the first render and this listener has no event left
+ // to deliver. So read the height now, and let React compare it with the
+ // height it rendered.
+ viewportHeight = layoutViewportHeight();
+ onChange();
+ }
+ return () => {
+ viewportHeightListeners.delete(onChange);
+ if (viewportHeightListeners.size === 0) {
+ stopViewportResize?.();
+ stopViewportResize = null;
+ viewportHeight = null;
+ }
+ };
+}
+
+function readViewportHeight(): number {
+ // Without a listener, nothing keeps a stored height current.
+ if (stopViewportResize == null) {
+ return layoutViewportHeight();
+ }
+ viewportHeight ??= layoutViewportHeight();
+ return viewportHeight;
+}
+
+function readNoViewportHeight(): number {
+ return 0;
}
function subscribeToNothing(): () => void {
@@ -769,13 +814,17 @@ export function BottomSheetPanel({
// sizes, which nothing extends by the reserve; the stretch stops at it.
const hasTouchPointer = useMediaQuery('(any-pointer: coarse)');
const tracksViewport = isPresented && hasTouchPointer && !isSizedByCaller;
- const viewportHeight = useSyncExternalStore(
- tracksViewport ? subscribeToResize : subscribeToNothing,
- () => (tracksViewport ? layoutViewportHeight() : 0),
- () => 0,
+ // Each argument is a module function, so React keeps one snapshot function
+ // across renders and does not re-read it in the commit.
+ const trackedViewportHeight = useSyncExternalStore(
+ tracksViewport ? subscribeToViewportHeight : subscribeToNothing,
+ tracksViewport ? readViewportHeight : readNoViewportHeight,
+ readNoViewportHeight,
);
const reserve =
- viewportHeight > 0 ? sheetReserve(viewportHeight) : MIN_RESERVE;
+ trackedViewportHeight > 0
+ ? sheetReserve(trackedViewportHeight)
+ : MIN_RESERVE;
const {
contentProps,
handleProps,
diff --git a/packages/core/src/BottomSheet/__tests__/BottomSheetCommitLayout.a11y.chromium.spec.ts b/packages/core/src/BottomSheet/__tests__/BottomSheetCommitLayout.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..836f0f62d9
--- /dev/null
+++ b/packages/core/src/BottomSheet/__tests__/BottomSheetCommitLayout.a11y.chromium.spec.ts
@@ -0,0 +1,177 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y scope core/DateInput
+
+/**
+ * @file BottomSheetCommitLayout.a11y.chromium.spec.ts
+ * @input Built stories, real Chromium touch input, and a count of the page's
+ * reads of `window.innerHeight`
+ * @output Browser evidence that a tap that renders an open sheet again reads
+ * no `innerHeight`, so its commit forces no style recalculation or layout
+ * for it. That holds for the month and year toggle in DateInput's sheet and
+ * for a checkbox in a BottomSheet. A control proves that the count sees a
+ * read in a tap.
+ * @position Chromium proof for BottomSheetPanel's viewport height. The sheet
+ * renders from the height its resize listener keeps.
+ */
+
+import {
+ expect,
+ test,
+ type Locator,
+ type Page,
+} from '@astryxdesign/a11y-spec/playwright';
+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();
+});
+
+test.use({hasTouch: true, isMobile: true, viewport: {width: 390, height: 844}});
+
+interface ReadCounter {
+ isCounting: boolean;
+ reads: number;
+}
+
+test.beforeEach(async ({page}) => {
+ // Counts reads of `innerHeight` while `isCounting` is set. After a commit's
+ // DOM writes, such a read forces a style recalculation and a layout.
+ await page.addInitScript(() => {
+ const counter = {isCounting: false, reads: 0};
+ Object.assign(window, {innerHeightReads: counter});
+ const descriptor = Object.getOwnPropertyDescriptor(window, 'innerHeight');
+ const read = descriptor?.get;
+ if (read == null) {
+ throw new Error('innerHeight has no getter');
+ }
+ Object.defineProperty(window, 'innerHeight', {
+ ...descriptor,
+ get(this: Window): number {
+ if (counter.isCounting) {
+ counter.reads += 1;
+ }
+ return read.call(this) as number;
+ },
+ });
+ });
+});
+
+/**
+ * Taps `target` with a real touch and returns the reads of `innerHeight` from
+ * the tap to two frames after it.
+ */
+async function innerHeightReadsInTap(
+ page: Page,
+ target: Locator,
+): Promise<number> {
+ const box = await target.boundingBox();
+ if (box == null) {
+ throw new Error('no target box');
+ }
+ const x = box.x + box.width / 2;
+ const y = box.y + box.height / 2;
+ await page.evaluate(() => {
+ const counter = (window as unknown as {innerHeightReads: ReadCounter})
+ .innerHeightReads;
+ counter.reads = 0;
+ counter.isCounting = true;
+ });
+ const cdp = await page.context().newCDPSession(page);
+ await cdp.send('Input.dispatchTouchEvent', {
+ type: 'touchStart',
+ touchPoints: [{x, y}],
+ });
+ await cdp.send('Input.dispatchTouchEvent', {
+ type: 'touchEnd',
+ touchPoints: [],
+ });
+ await cdp.detach();
+ return page.evaluate(async () => {
+ await new Promise(resolve => {
+ requestAnimationFrame(() => requestAnimationFrame(resolve));
+ });
+ const counter = (window as unknown as {innerHeightReads: ReadCounter})
+ .innerHeightReads;
+ counter.isCounting = false;
+ return counter.reads;
+ });
+}
+
+/** Waits until nothing animates on the page. */
+async function waitForStill(page: Page): Promise<void> {
+ await expect
+ .poll(async () =>
+ page.evaluate(
+ () =>
+ document
+ .getAnimations()
+ .filter(animation => animation.playState === 'running').length,
+ ),
+ )
+ .toBe(0);
+}
+
+async function openDateSheet(page: Page): Promise<Locator> {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-dateinput--bottom-sheet-wide-range&viewMode=story`,
+ );
+ await page.getByRole('combobox', {name: 'Date of birth'}).tap();
+ const dialog = page.getByRole('dialog');
+ await expect(dialog).toBeVisible();
+ const toggle = dialog.locator('button[data-title="month-year"]');
+ await expect(toggle).toHaveAttribute('aria-expanded', 'false');
+ await waitForStill(page);
+ return toggle;
+}
+
+test("the month and year toggle in DateInput's sheet reads no innerHeight in its tap", async ({
+ page,
+}) => {
+ const toggle = await openDateSheet(page);
+ const reads = await innerHeightReadsInTap(page, toggle);
+ await expect(toggle).toHaveAttribute('aria-expanded', 'true');
+ expect(reads).toBe(0);
+});
+
+test("a checkbox in a BottomSheet's content reads no innerHeight in its tap", async ({
+ page,
+}) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-bottomsheet--showcase&viewMode=story`,
+ );
+ await page.getByRole('button', {name: 'Open sheet'}).tap();
+ const dialog = page.getByRole('dialog', {name: 'Filters'});
+ await expect(dialog).toBeVisible();
+ await waitForStill(page);
+ const checkbox = dialog.getByRole('checkbox', {name: 'In stock'});
+ await expect(checkbox).not.toBeChecked();
+ const reads = await innerHeightReadsInTap(page, checkbox);
+ await expect(checkbox).toBeChecked();
+ expect(reads).toBe(0);
+});
+
+test('the count sees a read of innerHeight in a tap', async ({page}) => {
+ const toggle = await openDateSheet(page);
+ // The control: the tap's own click reads the height once.
+ await page.evaluate(() => {
+ document.addEventListener(
+ 'click',
+ () => {
+ void window.innerHeight;
+ },
+ {capture: true, once: true},
+ );
+ });
+ const reads = await innerHeightReadsInTap(page, toggle);
+ expect(reads).toBeGreaterThanOrEqual(1);
+});