An open source design system that's fully customizable and agent ready
TypeScript
fix(MobileNav): closing the drawer could leave the page unresponsive (#4388)
AK551a8de8d197
diff --git a/.changeset/mobilenav-close-stays-rendered.md b/.changeset/mobilenav-close-stays-rendered.mdnew file mode 100644index 0000000000..7564277442--- /dev/null+++ b/.changeset/mobilenav-close-stays-rendered.md@@ -0,0 +1,9 @@+---+'@astryxdesign/core': patch+---++[fix] MobileNav: keep the drawer rendered until the native dialog has actually closed (#4290)++`display` was driven by the `isOpen` prop, which flips during the commit, while `dialog.close()` only ran afterwards from an effect — so every close called `close()` on a dialog that was already `display: none` but still open and still in the top layer, and an open modal dialog blocks the whole document whether or not it is rendered. Safari 26.1 never un-blocked it, leaving the page inert with no JavaScript error. `display` now takes part in the transition with `transition-behavior: allow-discrete`, including when React's `<Activity mode="hidden">` hides the drawer inside AppShell, and the unmount close moves into its own effect so the deferred close is no longer cut off by its own cleanup. The close delay is derived from the hold in effect rather than assumed, because that hold is `--duration-medium` — a theme value, which the shipped y2k theme sets to exactly the 250ms the delay used to hard-code.++@AKnassadiff --git a/.github/scripts/modal-close-visibility.js b/.github/scripts/modal-close-visibility.jsnew file mode 100644index 0000000000..b0e3ce4b05--- /dev/null+++ b/.github/scripts/modal-close-visibility.js@@ -0,0 +1,178 @@+#!/usr/bin/env node+// Copyright (c) Meta Platforms, Inc. and affiliates.+++/**+ * @description Asserts a modal <dialog> is still rendered when close() runs+ * @input --storybook-dir <path> [--port <n>]+ * @output One line per target; exit 1 if any close() ran at display: none+ *+ * A modal <dialog> that is `display: none` while still `:modal` blocks every+ * pointer event on the document, and browsers are not required to release that+ * block when close() finally runs — Safari 26.1 did not, leaving a page that+ * looked normal and answered nothing (#4290). The drawer must therefore still+ * be rendered at the moment it is told to close.+ *+ * That ordering only exists in a browser: it is produced by a `display`+ * transition with `allow-discrete`, which jsdom neither runs nor exposes, so+ * the unit suite passes whether or not the invariant holds. Chromium is enough+ * to observe it — the ordering is the bug, and the Safari version it was+ * reported against is not needed to see it go wrong.+ */++const { chromium } = require('playwright');+const fs = require('node:fs');+const path = require('node:path');+const http = require('node:http');++const args = process.argv.slice(2);+const getArg = (name) => {+ const idx = args.indexOf(`--${name}`);+ return idx !== -1 ? args[idx + 1] : null;+};++const storybookDir = getArg('storybook-dir') || 'apps/storybook/dist';+const port = Number(getArg('port') || 6009);++const TARGETS = [+ {+ component: 'MobileNav',+ story: 'core-mobilenav--default',+ openButton: 'Open Navigation',+ },+];++const CONTENT_TYPES = {+ '.html': 'text/html',+ '.js': 'application/javascript',+ '.css': 'text/css',+ '.json': 'application/json',+ '.png': 'image/png',+ '.svg': 'image/svg+xml',+};++function createServer(dir, listenPort) {+ return new Promise((resolve) => {+ const server = http.createServer((req, res) => {+ const filePath = path+ .join(dir, req.url === '/' ? 'index.html' : req.url)+ .split('?')[0];++ const resolved = path.resolve(filePath);+ if (!resolved.startsWith(path.resolve(dir))) {+ res.writeHead(403);+ res.end('Forbidden');+ return;+ }++ fs.readFile(resolved, (err, data) => {+ if (err) {+ res.writeHead(404);+ res.end('Not found');+ return;+ }+ res.writeHead(200, {+ 'Content-Type':+ CONTENT_TYPES[path.extname(resolved)] || 'text/plain',+ });+ res.end(data);+ });+ });++ server.listen(listenPort, () => resolve(server));+ });+}++// Records the computed `display` of every dialog at the instant it is closed.+function recordCloseDisplay() {+ window.__closeDisplays = [];+ const close = HTMLDialogElement.prototype.close;+ HTMLDialogElement.prototype.close = function (...args) {+ window.__closeDisplays.push(getComputedStyle(this).display);+ return close.apply(this, args);+ };+}++async function probe(page, target) {+ await page.addInitScript(recordCloseDisplay);+ await page.goto(+ `http://localhost:${port}/iframe.html?id=${target.story}&viewMode=story`,+ { waitUntil: 'networkidle', timeout: 15000 }+ );++ await page.getByRole('button', { name: target.openButton }).click();+ await page.waitForFunction(+ () => document.querySelector('dialog')?.matches(':modal') === true,+ null,+ { timeout: 5000 }+ );++ await page.keyboard.press('Escape');+ await page.waitForFunction(() => window.__closeDisplays.length > 0, null, {+ timeout: 5000,+ });++ return page.evaluate(() => window.__closeDisplays);+}++async function run() {+ const dir = path.resolve(process.cwd(), storybookDir);+ if (!fs.existsSync(dir)) {+ console.error(`Storybook build not found at ${dir}`);+ return 1;+ }++ const server = await createServer(dir, port);+ const browser = await chromium.launch();+ let failures = 0;++ try {+ const context = await browser.newContext({+ viewport: { width: 430, height: 860 },+ });++ for (const target of TARGETS) {+ const page = await context.newPage();+ try {+ const displays = await probe(page, target);+ const hidden = displays.filter((d) => d === 'none');+ if (hidden.length > 0) {+ failures++;+ console.error(+ `✗ ${target.component}: close() ran at display: none (${displays.join(', ')})`+ );+ } else {+ console.log(+ `✓ ${target.component}: close() ran at display: ${displays.join(', ')}`+ );+ }+ } catch (e) {+ failures++;+ console.error(`✗ ${target.component}: probe failed — ${e.message}`);+ } finally {+ await page.close();+ }+ }+ } finally {+ await browser.close();+ server.close();+ }++ if (failures > 0) {+ console.error(+ `\nFailing: ${failures} modal(s) closed while not rendered — see #4290.`+ );+ return 1;+ }+ console.log('\nAll modals were still rendered when close() ran.');+ return 0;+}++run()+ .then((code) => {+ process.exitCode = code;+ })+ .catch((e) => {+ console.error('Modal close visibility guard failed:', e);+ process.exit(1);+ });diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 193c11fff6..f18225d0ad 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -443,6 +443,14 @@ jobs:path: a11y-report.jsonretention-days: 1+ # A modal <dialog> hidden before close() blocks the whole page in Safari+ # 26.1 and leaves no trace (#4290). The ordering is produced by a CSS+ # transition, which jsdom does not run — so the unit suite cannot see it+ # and this Chromium probe is the guard. Runs after the upload above so an+ # a11y failure still publishes its report.+ - name: Run modal close visibility guard+ run: node .github/scripts/modal-close-visibility.js --storybook-dir apps/storybook/dist+# RTL semantic audit. Sibling to pr-a11y: same build-storybook artifact, same# analysis.json scoping, so a PR only pays for the components it touched.# Unscoped this swept ~1400 stories and took ~26 min. The full sweep thatdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 1a97e87a9e..b0cf37b827 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -477,6 +477,20 @@ summary but don't block. Repro locally with `pnpm rtl:audit -- --filter Avatar`(the `--` matters: `pnpm -F` is itself `--filter`). See`apps/storybook/rtl-audit/README.md`.+### Modal close visibility guard++The same `pr-a11y` job runs one more Chromium probe+(`.github/scripts/modal-close-visibility.js`, or `pnpm guard:modal-close`+against a built Storybook). It opens each modal `<dialog>` surface in the+list at the top of that script, closes it, and fails if the dialog's computed+`display` was `none` at the moment `close()` ran.++A dialog hidden while still `:modal` swallows every click on the page, and a+browser is not obliged to release that when `close()` finally runs — Safari+26.1 did not (#4290). The ordering comes from a CSS transition, so jsdom+cannot see it and the unit suites pass either way. Add a target here when a+component closes a `<dialog>` on a delay.+## Versioning & ReleasesWe use [Changesets](https://github.com/changesets/changesets) for versioning, with a thin Astryx layer on top so changelogs stay categorized, contributor-attributed, and aligned with our pre-1.0 conventions.diff --git a/package.json b/package.jsonindex 25538437c8..3ae1670c50 100644--- a/package.json+++ b/package.json@@ -24,6 +24,7 @@"a11y:audit": "node .github/scripts/accessibility-audit.js --baseline .github/a11y-baseline.json --fail-on-new","a11y:baseline": "node .github/scripts/accessibility-audit.js --baseline .github/a11y-baseline.json --update-baseline","rtl:audit": "node apps/storybook/rtl-audit/rtl-audit.mjs",+ "guard:modal-close": "node .github/scripts/modal-close-visibility.js","storybook": "pnpm -F @astryxdesign/storybook dev","storybook:build": "pnpm -F @astryxdesign/storybook build","docsite": "pnpm -F @astryxdesign/docsite dev",diff --git a/packages/core/src/MobileNav/MobileNav.tsx b/packages/core/src/MobileNav/MobileNav.tsxindex 0509c980a7..9c2af78d41 100644--- a/packages/core/src/MobileNav/MobileNav.tsx+++ b/packages/core/src/MobileNav/MobileNav.tsx@@ -77,7 +77,19 @@ const styles = stylex.create({outline: 'none',// Native <dialog> uses display:none when closed.// Open state applied via isOpen prop to avoid :where([open]) specificity issues.+ // `display` participates in the transition with allow-discrete so it flips+ // to none only after the slide-out finishes. That also keeps the dialog+ // rendered until close() has actually run: an open modal dialog that isn't+ // rendered still blocks the whole document, and a browser that fails to+ // un-block it on close leaves the page inert with no error (#4290).+ // Deliberately not shortened under reduced motion: `display` is discrete,+ // so a long hold animates nothing — it is only the window the close has to+ // land inside. The visible transitions (the drawer's transform and the+ // backdrop's opacity) are the ones that respect the preference.display: 'none',+ transitionProperty: 'display',+ transitionDuration: durationVars['--duration-medium'],+ transitionBehavior: 'allow-discrete',},open: {display: 'flex',@@ -183,6 +195,75 @@ const dynamicStyles = stylex.create({}),});+// =============================================================================+// Close timing+// =============================================================================++/** Longest the drawer will wait before closing, however long the hold is. */+const MAX_CLOSE_DELAY_MS = 250;+/** Fraction of the hold to close at, so the close never lands on its boundary. */+const CLOSE_WITHIN_HOLD = 0.6;++/**+ * Shortest duration in a `transition-duration` list, in ms; null if unreadable.+ *+ * Browsers serialise computed `<time>` values in seconds — an authored `410ms`+ * reads back as `"0.41s"` and a list as `"0.41s, 0.12s"` — so the seconds branch+ * is the one that runs outside tests. jsdom echoes an inline `250ms` back as-is+ * and never resolves `var()`, so both units and the unreadable case are covered+ * directly in MobileNavCloseTiming.test.ts rather than through the component.+ *+ * @internal Exported for unit tests.+ */+export function parseShortestDurationMs(value: string): number | null {+ const durations = value+ .split(',')+ .map(part => {+ const trimmed = part.trim();+ const ms = Number.parseFloat(trimmed);+ if (!Number.isFinite(ms)) {+ return null;+ }+ return trimmed.endsWith('ms')+ ? ms+ : trimmed.endsWith('s')+ ? ms * 1000+ : null;+ })+ .filter((ms): ms is number => ms !== null);++ return durations.length ? Math.min(...durations) : null;+}++/**+ * How long to wait before closing the native dialog.+ *+ * The drawer is only rendered for as long as its `display` transition runs, and+ * closing an unrendered modal dialog is what leaves the page inert (#4290). So+ * the close has to land inside that hold. The hold is `--duration-medium`,+ * which themes rewrite — the shipped y2k theme sets it to exactly 250ms — so+ * read the hold in effect rather than assuming it.+ */+function resolveCloseDelay(dialog: HTMLDialogElement): number {+ // Reduced motion makes the close sooner; it must not make the hold shorter.+ // Shrinking both leaves no slack — one slow frame between the commit and this+ // macrotask and the drawer has already stopped being rendered.+ const cap = window.matchMedia('(prefers-reduced-motion: reduce)').matches+ ? 0+ : MAX_CLOSE_DELAY_MS;++ const hold = parseShortestDurationMs(+ window.getComputedStyle(dialog).transitionDuration,+ );++ // The hold is unreadable — an unresolved var() outside a real browser.+ if (hold === null) {+ return cap;+ }++ return hold <= 0 ? 0 : Math.min(cap, hold * CLOSE_WITHIN_HOLD);+}+// =============================================================================// Types// =============================================================================@@ -320,6 +401,34 @@ export function MobileNav({side === 'auto' ? 'end' : side,);+ // Resolve which edge the drawer slides from. Deliberately its own effect,+ // declared before the open/close effect below so the trigger is still the+ // active element when `side='auto'` reads it. Keeping it out of that effect+ // is what stops a `side` change during a close from re-arming the delay: the+ // CSS hold runs from the commit that started the slide-out and does not+ // restart, so a fresh full delay could land after the drawer had already+ // stopped being rendered — #4290 again.+ useEffect(() => {+ if (!isOpen) {+ return;+ }++ if (side === 'auto') {+ const trigger = document.activeElement as HTMLElement | null;+ if (trigger && trigger !== document.body) {+ const rect = trigger.getBoundingClientRect();+ const triggerCenter = rect.left + rect.width / 2;+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- side is resolved from trigger layout immediately before showModal()+ setResolvedSide(+ triggerCenter < window.innerWidth / 2 ? 'start' : 'end',+ );+ }+ } else {+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- side prop changes must update the open dialog placement+ setResolvedSide(side);+ }+ }, [isOpen, side]);+// Open/close the dialog via showModal()/close()// close() is delayed so the slide-out transition can play.useEffect(() => {@@ -328,28 +437,7 @@ export function MobileNav({return;}- if (closeTimeoutRef.current) {- clearTimeout(closeTimeoutRef.current);- closeTimeoutRef.current = null;- }-if (isOpen) {- // Determine drawer side from trigger position when auto- if (side === 'auto') {- const trigger = document.activeElement as HTMLElement | null;- if (trigger && trigger !== document.body) {- const rect = trigger.getBoundingClientRect();- const triggerCenter = rect.left + rect.width / 2;- // eslint-disable-next-line @eslint-react/set-state-in-effect -- side is resolved from trigger layout immediately before showModal()- setResolvedSide(- triggerCenter < window.innerWidth / 2 ? 'start' : 'end',- );- }- } else {- // eslint-disable-next-line @eslint-react/set-state-in-effect -- side prop changes must update the open dialog placement- setResolvedSide(side);- }-if (!dialog.open) {dialog.showModal();}@@ -360,13 +448,9 @@ export function MobileNav({} else if (dialog.open) {document.documentElement.style.overflow = '';- const duration = window.matchMedia('(prefers-reduced-motion: reduce)')- .matches- ? 10- : 250;closeTimeoutRef.current = setTimeout(() => {dialog.close();- }, duration);+ }, resolveCloseDelay(dialog));}return () => {@@ -375,20 +459,27 @@ export function MobileNav({closeTimeoutRef.current = null;}document.documentElement.style.overflow = '';- // Close the native dialog on teardown if it's still open. Inside AppShell- // the drawer is mounted in an <Activity> that switches to mode="hidden"- // when the drawer closes; React then runs this cleanup (with a stale- // isOpen) instead of re-running the effect with isOpen=false, so the- // close branch above never fires. If we leave the <dialog> `open` here,- // showModal() is skipped on the next open (the dialog is already open in- // the hidden tree) and the drawer can never be re-opened. Closing it- // unconditionally on teardown keeps the native dialog state in sync so a- // subsequent open cleanly calls showModal() again.- if (dialog.open) {+ };+ }, [isOpen]);++ // Close the native dialog on unmount if it's still open. Inside AppShell the+ // drawer is mounted in an <Activity> that switches to mode="hidden" when the+ // drawer closes; React then runs effect cleanups (with a stale isOpen)+ // instead of re-running the effect with isOpen=false, so the close branch+ // above never fires. If we leave the <dialog> `open` here, showModal() is+ // skipped on the next open (the dialog is already open in the hidden tree)+ // and the drawer can never be re-opened — see MobileNavReopen.test.tsx.+ // This must be a separate unmount-only effect: putting it in the open/close+ // effect above would close the dialog on every isOpen flip and cut off the+ // delayed slide-out close.+ useEffect(() => {+ const dialog = dialogRef.current;+ return () => {+ if (dialog?.open) {dialog.close();}};- }, [isOpen, side]);+ }, []);// Handle native cancel event (Escape key) — prevent default and route through onOpenChangeconst handleCancel = useCallback(diff --git a/packages/core/src/MobileNav/MobileNavCloseEdgeCases.test.tsx b/packages/core/src/MobileNav/MobileNavCloseEdgeCases.test.tsxnew file mode 100644index 0000000000..7e261cbeb0--- /dev/null+++ b/packages/core/src/MobileNav/MobileNavCloseEdgeCases.test.tsx@@ -0,0 +1,426 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file MobileNavCloseEdgeCases.test.tsx+ * @input Uses vitest, @testing-library/react, MobileNav + AppShell + SideNav+ * @output Edge-case coverage for the deferred close introduced for #4290+ * @position Testing; guards the close path of MobileNav.tsx+ *+ * #4290 moved the unmount close into its own effect so the deferred slide-out+ * close is no longer cut off by its own cleanup. That split is the risky part:+ * the close now depends on a timer surviving to fire, and on the unmount-only+ * effect catching every teardown the timer misses. These tests cover the paths+ * where the two could disagree and leave a modal dialog open — which blocks the+ * whole document, whether or not the drawer is rendered.+ *+ * The invariant behind all of them: the drawer must never be left open. Being+ * slow to close is a glitch; never closing is a wedged page.+ */++import {+ describe,+ it,+ expect,+ vi,+ beforeAll,+ beforeEach,+ afterEach,+} from 'vitest';+import {StrictMode} from 'react';+import {render, screen, fireEvent, act} from '@testing-library/react';+import {MobileNav} from './MobileNav';+import {AppShell} from '../AppShell/AppShell';+import {SideNav, SideNavItem, SideNavSection} from '../SideNav';+import {stubMatchMedia} from '../__tests__/stubMatchMedia';++// jsdom doesn't implement showModal/close on <dialog>, so we mock them+beforeAll(() => {+ HTMLDialogElement.prototype.showModal =+ HTMLDialogElement.prototype.showModal ||+ function (this: HTMLDialogElement) {+ this.setAttribute('open', '');+ };+ HTMLDialogElement.prototype.close =+ HTMLDialogElement.prototype.close ||+ function (this: HTMLDialogElement) {+ this.removeAttribute('open');+ };+});++class MockResizeObserver {+ observe() {}+ unobserve() {}+ disconnect() {}+}++// `matches` has to depend on the query: a blanket `matches: true` puts AppShell+// below its breakpoint, which these tests need, but it also matches+// `prefers-reduced-motion`, which caps the close delay at 0 — every test here+// would run against an immediate close while appearing to exercise the real+// delay. See the header of stubMatchMedia.ts.++beforeEach(() => {+ vi.stubGlobal('ResizeObserver', MockResizeObserver);+ stubMatchMedia({reduceMotion: false});+});++afterEach(() => {+ document.documentElement.style.overflow = '';+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++function Drawer({+ isOpen,+ side,+}: {+ isOpen: boolean;+ side?: 'start' | 'end' | 'auto';+}) {+ return (+ <MobileNav+ isOpen={isOpen}+ onOpenChange={() => {}}+ side={side}+ data-testid="mobile-nav">+ <span>Nav content</span>+ </MobileNav>+ );+}++function TestShell() {+ return (+ <AppShell+ sideNav={+ <SideNav>+ <SideNavSection title="Test" isHeaderHidden>+ <SideNavItem label="Home" />+ </SideNavSection>+ </SideNav>+ }+ mobileNav={{breakpoint: 'md'}}>+ <div>Content</div>+ </AppShell>+ );+}++describe('MobileNav close path edge cases', () => {+ it('survives StrictMode double-invoked effects', () => {+ vi.useFakeTimers();+ try {+ const {rerender} = render(+ <StrictMode>+ <Drawer isOpen />+ </StrictMode>,+ );+ const dialog = screen.getByTestId('mobile-nav');++ // StrictMode mounts effects, tears them down, and mounts them again. The+ // unmount-only effect closes the dialog during that teardown, so the+ // open/close effect has to re-open it on the second mount.+ expect(dialog).toHaveAttribute('open');++ act(() => {+ rerender(+ <StrictMode>+ <Drawer isOpen={false} />+ </StrictMode>,+ );+ });+ act(() => {+ vi.advanceTimersByTime(300);+ });+ expect(dialog).not.toHaveAttribute('open');+ } finally {+ vi.useRealTimers();+ }+ });++ it('closes the dialog when unmounted while fully open', () => {+ const {unmount} = render(<Drawer isOpen />);+ const dialog = screen.getByTestId('mobile-nav');+ expect(dialog).toHaveAttribute('open');++ unmount();++ // Left open, the next showModal() is skipped and the drawer can never be+ // re-opened (#3091) — and the document stays blocked meanwhile.+ expect(dialog).not.toHaveAttribute('open');+ });++ it('does not restart the pending close when the side prop changes', () => {+ vi.useFakeTimers();+ try {+ const {rerender} = render(<Drawer isOpen side="start" />);+ const dialog = screen.getByTestId('mobile-nav');++ act(() => {+ rerender(<Drawer isOpen={false} side="start" />);+ });+ expect(dialog).toHaveAttribute('open');++ // Most of the way through the pending close...+ act(() => {+ vi.advanceTimersByTime(200);+ });+ expect(dialog).toHaveAttribute('open');++ // ...then change the side. Side resolution lives in its own effect, so+ // this has to leave the close alone. Were `side` a dep of the open/close+ // effect, its cleanup would cancel the pending close and re-arm a fresh+ // full delay — while the CSS hold keeps running from the commit that+ // started the slide-out. The close would then land after the drawer had+ // stopped being rendered, which is the #4290 state again.+ //+ // The split advance is the whole point: the total must clear one delay+ // but not two.+ act(() => {+ rerender(<Drawer isOpen={false} side="end" />);+ });+ act(() => {+ vi.advanceTimersByTime(100);+ });++ expect(dialog).not.toHaveAttribute('open');+ } finally {+ vi.useRealTimers();+ }+ });++ it('settles closed after a rapid open/close/open/close burst', () => {+ vi.useFakeTimers();+ try {+ const {rerender} = render(<Drawer isOpen={false} />);+ const dialog = screen.getByTestId('mobile-nav');++ act(() => {+ rerender(<Drawer isOpen />);+ });+ act(() => {+ rerender(<Drawer isOpen={false} />);+ });+ act(() => {+ rerender(<Drawer isOpen />);+ });+ act(() => {+ rerender(<Drawer isOpen={false} />);+ });+ act(() => {+ vi.advanceTimersByTime(300);+ });++ expect(dialog).not.toHaveAttribute('open');+ } finally {+ vi.useRealTimers();+ }+ });++ it('restores documentElement overflow once the drawer has closed', () => {+ vi.useFakeTimers();+ try {+ const {rerender} = render(<Drawer isOpen />);+ const dialog = screen.getByTestId('mobile-nav');+ expect(document.documentElement.style.overflow).toBe('clip');++ // Two acts on purpose: the close timer is armed by the effect that runs+ // when the first act flushes, so advancing inside that same act would+ // advance past nothing and the drawer would never actually close.+ act(() => {+ rerender(<Drawer isOpen={false} />);+ });+ act(() => {+ vi.advanceTimersByTime(300);+ });+ // Pin the close itself. The effect cleanup resets overflow on every+ // isOpen flip, so the overflow assertion alone passes even with the whole+ // close path deleted — the test name would be the only thing left of it.+ expect(dialog).not.toHaveAttribute('open');+ // A drawer that closes but leaves the page scroll-locked is its own+ // flavour of "the page is broken and nothing says why".+ expect(document.documentElement.style.overflow).toBe('');+ } finally {+ vi.useRealTimers();+ }+ });++ it('restores documentElement overflow when unmounted while open', () => {+ const {unmount} = render(<Drawer isOpen />);+ expect(document.documentElement.style.overflow).toBe('clip');++ unmount();++ expect(document.documentElement.style.overflow).toBe('');+ });++ it('leaves no pending close timer behind after unmount', () => {+ vi.useFakeTimers();+ try {+ const {rerender, unmount} = render(<Drawer isOpen />);+ act(() => {+ rerender(<Drawer isOpen={false} />);+ });+ unmount();++ // The queued close must be cancelled, not left to fire against a+ // detached node.+ expect(vi.getTimerCount()).toBe(0);+ } finally {+ vi.useRealTimers();+ }+ });++ it('closes inside the display hold when a theme shortens it', () => {+ // The hold is `--duration-medium`, which themes rewrite: the shipped y2k+ // theme uses 250ms and the documented "Snappy" preset does too. A close+ // scheduled on the hold's boundary lands on the frame the drawer stops+ // being rendered — which is exactly the #4290 state. The delay has to be+ // derived from the hold actually in effect, not assumed.+ // Full motion (the file default) — under reduced motion the close is+ // immediate and the boundary is never exercised.+ vi.useFakeTimers();+ try {+ const hold = 250;+ const {rerender} = render(+ <MobileNav+ isOpen+ onOpenChange={() => {}}+ style={{transitionDuration: `${hold}ms`}}+ data-testid="mobile-nav">+ <span>Nav content</span>+ </MobileNav>,+ );+ const dialog = screen.getByTestId('mobile-nav');+ expect(getComputedStyle(dialog).transitionDuration).toBe(`${hold}ms`);++ act(() => {+ rerender(+ <MobileNav+ isOpen={false}+ onOpenChange={() => {}}+ style={{transitionDuration: `${hold}ms`}}+ data-testid="mobile-nav">+ <span>Nav content</span>+ </MobileNav>,+ );+ });+ act(() => {+ vi.advanceTimersByTime(hold - 1);+ });++ expect(dialog).not.toHaveAttribute('open');+ } finally {+ vi.useRealTimers();+ }+ });++ it('closes on the next macrotask when the hold is zero', () => {+ // A theme can set --duration-medium to 0 — nothing validates motion values+ // — and then `display` flips on the next style recalc with no hold at all.+ // No delay is safe at that point, so the close has to go out immediately+ // rather than fall back to the cap and land a quarter-second after the+ // drawer stopped being rendered, which is #4290 restored.+ vi.useFakeTimers();+ try {+ const style = {transitionDuration: '0ms'};+ const {rerender} = render(+ <MobileNav+ isOpen+ onOpenChange={() => {}}+ style={style}+ data-testid="mobile-nav">+ <span>Nav content</span>+ </MobileNav>,+ );+ const dialog = screen.getByTestId('mobile-nav');++ act(() => {+ rerender(+ <MobileNav+ isOpen={false}+ onOpenChange={() => {}}+ style={style}+ data-testid="mobile-nav">+ <span>Nav content</span>+ </MobileNav>,+ );+ });+ act(() => {+ vi.advanceTimersByTime(1);+ });++ expect(dialog).not.toHaveAttribute('open');+ } finally {+ vi.useRealTimers();+ }+ });++ it('closes on the next macrotask under reduced motion', () => {+ // Reduced motion should make the close *sooner*, not the safety margin+ // *smaller*. Shortening the hold to match leaves no slack: one slow frame+ // between the commit and the close macrotask and the drawer has already+ // stopped being rendered — #4290 again, on the accessibility setting.+ //+ // Only the delay is assertable here. That the hold itself stays long is a+ // CSS fact — styles.dialog carries no reduced-motion override, unlike+ // styles.drawer and ::backdrop — and jsdom does not evaluate media queries+ // inside stylesheets, so there is nothing to read back.+ stubMatchMedia({reduceMotion: true});+ vi.useFakeTimers();+ try {+ const style = {transitionDuration: '410ms'};+ const {rerender} = render(+ <MobileNav+ isOpen+ onOpenChange={() => {}}+ style={style}+ data-testid="mobile-nav">+ <span>Nav content</span>+ </MobileNav>,+ );+ const dialog = screen.getByTestId('mobile-nav');++ act(() => {+ rerender(+ <MobileNav+ isOpen={false}+ onOpenChange={() => {}}+ style={style}+ data-testid="mobile-nav">+ <span>Nav content</span>+ </MobileNav>,+ );+ });+ act(() => {+ vi.advanceTimersByTime(1);+ });++ expect(dialog).not.toHaveAttribute('open');+ } finally {+ vi.useRealTimers();+ }+ });++ it('closes the AppShell drawer when dismissed with Escape', () => {+ render(<TestShell />);+ fireEvent.click(screen.getByRole('button', {name: /open navigation/i}));+ const dialog = screen.getAllByRole('dialog', {hidden: true})[0];+ expect(dialog).toHaveAttribute('open');++ fireEvent(dialog, new Event('cancel', {cancelable: true, bubbles: false}));++ expect(dialog).not.toHaveAttribute('open');+ });++ it('closes the AppShell drawer when the backdrop is clicked', () => {+ render(<TestShell />);+ fireEvent.click(screen.getByRole('button', {name: /open navigation/i}));+ const dialog = screen.getAllByRole('dialog', {hidden: true})[0];+ expect(dialog).toHaveAttribute('open');++ // A click landing on the dialog itself, not the drawer panel, is a+ // backdrop dismiss.+ fireEvent.click(dialog);++ expect(dialog).not.toHaveAttribute('open');+ });+});diff --git a/packages/core/src/MobileNav/MobileNavCloseTiming.test.ts b/packages/core/src/MobileNav/MobileNavCloseTiming.test.tsnew file mode 100644index 0000000000..ae19b30a0f--- /dev/null+++ b/packages/core/src/MobileNav/MobileNavCloseTiming.test.ts@@ -0,0 +1,58 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file MobileNavCloseTiming.test.ts+ * @input Uses vitest, parseShortestDurationMs from MobileNav+ * @output Unit coverage for the close-delay duration parsing (#4290)+ * @position Testing; guards the timing helper behind MobileNav's deferred close+ *+ * Through the component this helper is only ever reachable via jsdom, which+ * echoes an inline `250ms` back verbatim and never resolves `var()`. Browsers do+ * neither: they serialise computed `<time>` values in seconds, so `"0.41s"` is+ * the only shape the helper sees in production and `"250ms"` is a shape it never+ * sees. Reading it directly is the only way the seconds branch, a list, and a+ * zero hold get covered at all.+ */++import {describe, it, expect} from 'vitest';+import {parseShortestDurationMs} from './MobileNav';++describe('parseShortestDurationMs', () => {+ it.each([+ // How browsers actually serialise a computed transition-duration.+ ['0.41s', 410],+ ['0.25s', 250],+ ['1s', 1000],+ // jsdom's shape: an inline declaration echoed back unchanged.+ ['250ms', 250],+ // Lists. The dialog transitions one property today, but a style or xstyle+ // prop can add more, and only the shortest entry is safe to close inside.+ ['0.41s, 0.12s', 120],+ ['120ms, 410ms', 120],+ // A zero hold is the #4290 state itself. It has to read as 0 — meaning+ // "close now" — rather than as unreadable, which would fall back to the cap+ // and schedule the close long after the drawer stopped being rendered.+ ['0s', 0],+ ['0ms', 0],+ ])('reads %j as %ims', (value, expected) => {+ expect(parseShortestDurationMs(value)).toBeCloseTo(expected, 6);+ });++ it.each([+ // An unresolved var() — jsdom, or any style read outside a browser.+ ['var(--duration-medium)'],+ // A CSS math function reads as unreadable too, so the caller falls back to+ // the cap rather than deriving a delay from a number it did not compute.+ ['max(150ms, var(--duration-medium))'],+ // A bare number is not a duration.+ ['250'],+ [''],+ [' '],+ ])('reports %j as unreadable', value => {+ expect(parseShortestDurationMs(value)).toBeNull();+ });++ it('skips unreadable entries rather than discarding the whole list', () => {+ expect(parseShortestDurationMs('var(--x), 0.3s')).toBeCloseTo(300, 6);+ });+});diff --git a/packages/core/src/MobileNav/MobileNavCloseVisibility.test.tsx b/packages/core/src/MobileNav/MobileNavCloseVisibility.test.tsxnew file mode 100644index 0000000000..ddf3611186--- /dev/null+++ b/packages/core/src/MobileNav/MobileNavCloseVisibility.test.tsx@@ -0,0 +1,172 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file MobileNavCloseVisibility.test.tsx+ * @input Uses vitest, @testing-library/react, MobileNav+ * @output Regression tests keeping the drawer rendered until the dialog closes+ * @position Testing; guards the close path of MobileNav.tsx+ *+ * Repro for #4290 (page unresponsive after closing the drawer in Safari 26.1).+ *+ * A `<dialog>` opened with `showModal()` blocks the rest of the document for as+ * long as it stays in the top layer — whether or not it is rendered. The drawer+ * hid itself the moment `isOpen` flipped, while the native `close()` only ran+ * afterwards from an effect, so `close()` was always called on a dialog that was+ * already `display: none`. A browser that fails to un-block the document when+ * such a dialog closes leaves the page inert with no JavaScript error.+ *+ * The fix keeps `display` in the transition with `allow-discrete`, so the drawer+ * stays rendered until the slide-out finishes, and moves the unmount close into+ * its own effect so the deferred close is no longer cut off by its own cleanup.+ *+ * Note on scope: jsdom has no top layer and no CSS transitions, so the inertness+ * itself is not observable here. These tests pin the two mechanisms that prevent+ * it — the declared transition, and the close actually being deferred.+ */++import {describe, it, expect, vi, beforeAll} from 'vitest';+import {render, screen, act} from '@testing-library/react';+import {MobileNav} from './MobileNav';+import {stubMatchMedia} from '../__tests__/stubMatchMedia';++// jsdom doesn't implement showModal/close on <dialog>, so we mock them+beforeAll(() => {+ HTMLDialogElement.prototype.showModal =+ HTMLDialogElement.prototype.showModal ||+ function (this: HTMLDialogElement) {+ this.setAttribute('open', '');+ };+ HTMLDialogElement.prototype.close =+ HTMLDialogElement.prototype.close ||+ function (this: HTMLDialogElement) {+ this.removeAttribute('open');+ };+});++function Drawer({isOpen}: {isOpen: boolean}) {+ return (+ <MobileNav isOpen={isOpen} onOpenChange={() => {}} data-testid="mobile-nav">+ <span>Nav content</span>+ </MobileNav>+ );+}++describe('MobileNav stays rendered while it closes', () => {+ it('transitions display with allow-discrete so it hides only once closed', () => {+ render(<Drawer isOpen />);+ const style = getComputedStyle(screen.getByTestId('mobile-nav'));++ // Without these two the drawer blanks out the instant `isOpen` flips,+ // leaving an open modal dialog that nothing renders — and nothing can+ // click past. See the file header.+ expect(style.transitionProperty).toContain('display');+ expect(style.transitionBehavior).toBe('allow-discrete');+ // A zero hold is the bug wearing the fix's clothes: the drawer stops being+ // rendered on the next style recalc, before any effect can close it.+ expect(style.transitionDuration.trim()).not.toBe('');+ // The hold must stay tied to the motion token rather than a literal: the+ // close delay is derived by reading this value back, so a hardcoded hold+ // and a themed slide-out would drift apart again. jsdom leaves var()+ // unresolved, which is exactly why this reads as a declaration.+ expect(style.transitionDuration).toContain('var(');+ });++ it('keeps the native dialog open until the slide-out has run', () => {+ vi.useFakeTimers();+ try {+ const {rerender} = render(<Drawer isOpen />);+ const dialog = screen.getByTestId('mobile-nav');+ expect(dialog).toHaveAttribute('open');++ act(() => {+ rerender(<Drawer isOpen={false} />);+ });++ // The drawer is on its way out but the dialog is still open, so it is+ // still rendered and still the thing holding the top layer.+ expect(dialog).toHaveAttribute('open');++ act(() => {+ vi.advanceTimersByTime(300);+ });+ expect(dialog).not.toHaveAttribute('open');+ } finally {+ vi.useRealTimers();+ }+ });++ it('still closes the dialog when unmounted mid-slide-out', () => {+ vi.useFakeTimers();+ try {+ const {rerender, unmount} = render(<Drawer isOpen />);+ const dialog = screen.getByTestId('mobile-nav');++ act(() => {+ rerender(<Drawer isOpen={false} />);+ });+ expect(dialog).toHaveAttribute('open');++ // Teardown before the timer fires — the unmount-only effect has to close+ // the dialog, or the next showModal() is skipped and the drawer can never+ // be re-opened (#3091).+ unmount();+ expect(dialog).not.toHaveAttribute('open');+ } finally {+ vi.useRealTimers();+ }+ });++ it('still defers the close under prefers-reduced-motion', () => {+ // Query-aware on purpose. A blanket `matches: true` is the stub shape that+ // once left 9 of 11 tests in the sibling edge-case file silently running+ // against a 0ms close delay — see the header of stubMatchMedia.ts. It is+ // inert for this file today (MobileNav renders standalone here, so+ // prefers-reduced-motion is the only query in play), but the shape is the+ // hazard, not the blast radius.+ stubMatchMedia({reduceMotion: true});+ vi.useFakeTimers();+ try {+ const {rerender} = render(<Drawer isOpen />);+ const dialog = screen.getByTestId('mobile-nav');++ act(() => {+ rerender(<Drawer isOpen={false} />);+ });+ // Reduced motion caps the delay at 0 — but 0 is still a macrotask. What+ // must not happen is the close landing synchronously in the commit, while+ // the dialog is mid-flip. This pins deferral, not duration.+ expect(dialog).toHaveAttribute('open');++ act(() => {+ vi.advanceTimersByTime(20);+ });+ expect(dialog).not.toHaveAttribute('open');+ } finally {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ }+ });++ it('re-opening mid-slide-out cancels the pending close', () => {+ vi.useFakeTimers();+ try {+ const {rerender} = render(<Drawer isOpen />);+ const dialog = screen.getByTestId('mobile-nav');++ act(() => {+ rerender(<Drawer isOpen={false} />);+ });+ act(() => {+ rerender(<Drawer isOpen />);+ });+ act(() => {+ vi.advanceTimersByTime(300);+ });++ // The queued close must not fire after the drawer has been re-opened.+ expect(dialog).toHaveAttribute('open');+ } finally {+ vi.useRealTimers();+ }+ });+});diff --git a/packages/core/src/__tests__/stubMatchMedia.test.ts b/packages/core/src/__tests__/stubMatchMedia.test.tsnew file mode 100644index 0000000000..01846d67f3--- /dev/null+++ b/packages/core/src/__tests__/stubMatchMedia.test.ts@@ -0,0 +1,79 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file stubMatchMedia.test.ts+ * @input Uses vitest, stubMatchMedia+ * @output Unit coverage for the shared query-aware matchMedia stub+ * @position Testing; guards the helper other suites trust to route queries+ *+ * The helper exists because a stub that ignores its query silently reroutes+ * code branching on a different one — the failure mode leaves every test+ * green. A helper sold on that promise has to be held to it, so these assert+ * the routing itself rather than any component behaviour.+ */++import {describe, it, expect, afterEach, vi} from 'vitest';+import {stubMatchMedia} from './stubMatchMedia';++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('stubMatchMedia', () => {+ it('routes prefers-reduced-motion independently of every other query', () => {+ // The exact combination the blanket stub could not express: below a+ // breakpoint (matches) while motion is NOT reduced.+ stubMatchMedia({reduceMotion: false, matches: true});++ expect(matchMedia('(prefers-reduced-motion: reduce)').matches).toBe(false);+ expect(matchMedia('(max-width: 768px)').matches).toBe(true);+ });++ it('answers no-preference as the opposite of reduce', () => {+ // Two spellings, opposite meanings. A substring test on+ // 'prefers-reduced-motion' alone would hand both the same answer.+ stubMatchMedia({reduceMotion: true});++ expect(matchMedia('(prefers-reduced-motion: reduce)').matches).toBe(true);+ expect(matchMedia('(prefers-reduced-motion: no-preference)').matches).toBe(+ false,+ );+ });++ it('treats the bare preference query as reduce', () => {+ stubMatchMedia({reduceMotion: true});+ expect(matchMedia('(prefers-reduced-motion)').matches).toBe(true);++ stubMatchMedia({reduceMotion: false});+ expect(matchMedia('(prefers-reduced-motion)').matches).toBe(false);+ });++ it('defaults to full motion and matching everything else', () => {+ stubMatchMedia();++ expect(matchMedia('(prefers-reduced-motion: reduce)').matches).toBe(false);+ expect(matchMedia('(max-width: 768px)').matches).toBe(true);+ });++ it('lets a non-motion query be answered false', () => {+ // Above the breakpoint, motion still reduced — the other axis of the+ // combination, so neither knob can be quietly driving both.+ stubMatchMedia({reduceMotion: true, matches: false});++ expect(matchMedia('(prefers-reduced-motion: reduce)').matches).toBe(true);+ expect(matchMedia('(max-width: 768px)').matches).toBe(false);+ });++ it('echoes the query and exposes the listener API components subscribe to', () => {+ stubMatchMedia();+ const mql = matchMedia('(max-width: 768px)');++ // useMediaQuery subscribes; a stub without these throws on mount rather+ // than failing an assertion, which reads as an unrelated crash.+ expect(mql.media).toBe('(max-width: 768px)');+ expect(typeof mql.addEventListener).toBe('function');+ expect(typeof mql.removeEventListener).toBe('function');+ expect(typeof mql.addListener).toBe('function');+ expect(typeof mql.removeListener).toBe('function');+ });+});diff --git a/packages/core/src/__tests__/stubMatchMedia.ts b/packages/core/src/__tests__/stubMatchMedia.tsnew file mode 100644index 0000000000..5fad7a2030--- /dev/null+++ b/packages/core/src/__tests__/stubMatchMedia.ts@@ -0,0 +1,95 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file stubMatchMedia.ts+ * @input Uses vitest+ * @output stubMatchMedia — a query-aware window.matchMedia stub+ * @position Shared test helper; imported by component tests that render below+ * a breakpoint while also exercising motion-sensitive behaviour+ *+ * jsdom has no matchMedia, so tests stub it. The usual stub answers every query+ * with one boolean:+ *+ * vi.stubGlobal('matchMedia', vi.fn().mockReturnValue({matches: true, ...}))+ *+ * That is enough to put AppShell below its breakpoint — and it silently also+ * matches `prefers-reduced-motion`, rerouting any code that branches on motion.+ * MobileNav's close delay is capped at 0 under reduced motion, so a suite using+ * the blanket stub runs against an immediate close while its test names claim+ * it is exercising the real delay. The failure mode is invisible: every test+ * still passes.+ *+ * So the two answers are separate knobs here. `reduceMotion` answers+ * `prefers-reduced-motion` only; `matches` answers everything else (breakpoint+ * width queries, which tests below a breakpoint want to be true).+ *+ * SYNC: When modified, update this header.+ */++import {vi} from 'vitest';++export interface StubMatchMediaOptions {+ /** Whether the user prefers reduced motion. */+ reduceMotion?: boolean;+ /** Answer for every other query — width breakpoints, hover, etc. */+ matches?: boolean;+}++/**+ * Answer a `prefers-reduced-motion` query, or null if it isn't one.+ *+ * The preference has two spellings and they are opposites, so a single+ * `includes('prefers-reduced-motion')` would answer `no-preference` with the+ * value meant for `reduce` — the same answer-without-reading mistake this+ * helper exists to prevent. Core only queries `reduce` today (MobileNav,+ * Carousel); handling both is what keeps that true if one changes.+ */+function answerReducedMotion(+ query: string,+ reduceMotion: boolean,+): boolean | null {+ if (query.includes('prefers-reduced-motion: reduce')) {+ return reduceMotion;+ }+ if (query.includes('prefers-reduced-motion: no-preference')) {+ return !reduceMotion;+ }+ // Bare `(prefers-reduced-motion)` is true for any value other than+ // no-preference, i.e. the same as `reduce`.+ if (query.includes('prefers-reduced-motion')) {+ return reduceMotion;+ }+ return null;+}++/**+ * Install a `window.matchMedia` stub whose answer depends on the query.+ *+ * Call from `beforeEach` (or inside a test that needs different motion+ * settings) and pair with `vi.unstubAllGlobals()` in `afterEach`.+ *+ * @example+ * ```+ * beforeEach(() => {+ * stubMatchMedia({reduceMotion: false});+ * });+ * ```+ */+export function stubMatchMedia({+ reduceMotion = false,+ matches = true,+}: StubMatchMediaOptions = {}): void {+ vi.stubGlobal(+ 'matchMedia',+ vi.fn((query: string) => ({+ matches: answerReducedMotion(query, reduceMotion) ?? matches,+ media: query,+ onchange: null,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),+ );+}