diff --git a/.changeset/modal-backdrop-blur.md b/.changeset/modal-backdrop-blur.md new file mode 100644 index 0000000000000..8c1c0d7b7aee6 --- /dev/null +++ b/.changeset/modal-backdrop-blur.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[feat] Dialog (and so AlertDialog and CommandPalette), Drawer and MobileNav no longer blur the page behind the modal, under every pointer: the 2px full-viewport backdrop blur is costly to repaint. The dim keeps the theme's `--color-overlay`, and in forced colors the modal keeps an edge so it still stands apart from the page. BottomSheet never blurred. A theme keeps the blur by setting `backdropFilter: 'blur(2px)'` on the component's modal backdrop: `components.dialog.base['::backdrop']`, `components['mobile-nav'].base['::backdrop']`, and for Drawer `components.drawer.base[':modal::backdrop']`, which leaves a non-modal drawer (`hasScrim={false}`) unblurred. + +@vjeux diff --git a/docs/specs/components/AlertDialog/AlertDialog.spec.md b/docs/specs/components/AlertDialog/AlertDialog.spec.md index 4d2e3646a011a..7a35b27e55f1c 100644 --- a/docs/specs/components/AlertDialog/AlertDialog.spec.md +++ b/docs/specs/components/AlertDialog/AlertDialog.spec.md @@ -108,7 +108,8 @@ Consumer migration instructions belong in consumer docs and release notes. - A press that slides across the actions acts on the lifted one, as `family:action-groups` owns (FR8). - Modal presentation, focus return, backdrop, and dismissal mechanics — owned by - `component:Dialog` and `architecture:layer-runtime`. + `component:Dialog` and `architecture:layer-runtime`; AlertDialog inherits + Dialog's backdrop (`component:Dialog` FR9). - Button variants and loading — owned by `component:Button`. ## Public concepts diff --git a/docs/specs/components/Dialog/Dialog.spec.md b/docs/specs/components/Dialog/Dialog.spec.md index 46e16f6cd2f3a..009503d0c6eea 100644 --- a/docs/specs/components/Dialog/Dialog.spec.md +++ b/docs/specs/components/Dialog/Dialog.spec.md @@ -17,6 +17,8 @@ verified_by: packages/core/src/Dialog/__tests__/Dialog.a11y.test.tsx, packages/core/src/Dialog/__tests__/Dialog.a11y.chromium.spec.ts, packages/core/src/Dialog/__tests__/Dialog.a11y.browser.spec.ts, + packages/core/src/__tests__/modalBackdrop.test.tsx, + packages/core/src/__tests__/ModalBackdrop.a11y.browser.spec.ts, ] modules: [module:Dialog/DialogHeader] families: [family:overlay-dismissal] @@ -81,16 +83,17 @@ current family and architecture owners. ## Behavioral and layout contract -| ID | Candidate invariant | Basis | Draft review state | -| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------ | ------------------ | -| FR1 | A native Dialog MUST become visibly modal before Dialog applies its component-owned initial-focus request. | shipped `showModal()` ordering and descendant-focus behavior | settled | -| FR2 | Dialog MUST honor an eligible descendant initial-focus request. A request is eligible only when its rendered target is inside the active Dialog, is neither hidden nor inert, and can receive programmatic focus when selection runs. DialogHeader supplies its title as the default when no non-default eligible request is rendered. Ordering among multiple non-default requests is unspecified (AV3). | shipped DialogHeader and descendant autofocus behavior | settled | -| FR3 | When no eligible descendant request exists, Dialog MUST preserve the native dialog's valid initial-focus behavior rather than move focus outside the modal. | native modal semantics and shipped fallback | settled | -| FR4 | Closing a native Dialog MUST return focus to the still-connected external element that invoked the modal when that element can receive focus. Descendant mount focus MUST NOT replace that return owner. | shipped trigger-return intent and regression history | settled | -| FR5 | Inline rendering MUST NOT open a modal, apply modal initial focus, trap focus, or return focus as if a modal had closed. | documented `isInline` preview behavior | settled | -| FR6 | Initial-focus selection MUST follow the rendered eligible descendants, not a private component type or source-only assumption. | composable descendant contract | settled | -| FR7 | A native modal Dialog MUST be a focus region through Core's shared focus-region module: Tab from its last tabbable control moves focus to its first, and Shift+Tab from its first moves focus to its last, so focus never leaves the modal for the browser's own interface. When a Dialog opens from a Dialog, the innermost one holding focus answers Tab. | owner decision DEC-2 | settled | -| FR8 | A modal Dialog open on the server renders closed until hydration (no open styles, no `aria-modal`, the markup of a closed Dialog) and opens in the render after hydration, the first that can make it modal; it never claims a modality it does not have (`spec:AST-020` FR1, WCAG 2.2 SC 4.1.2). An inline Dialog is not modal and renders as it is. 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 | settled | +| ID | Candidate invariant | Basis | Draft review state | +| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------- | ------------------ | +| FR1 | A native Dialog MUST become visibly modal before Dialog applies its component-owned initial-focus request. | shipped `showModal()` ordering and descendant-focus behavior | settled | +| FR2 | Dialog MUST honor an eligible descendant initial-focus request. A request is eligible only when its rendered target is inside the active Dialog, is neither hidden nor inert, and can receive programmatic focus when selection runs. DialogHeader supplies its title as the default when no non-default eligible request is rendered. Ordering among multiple non-default requests is unspecified (AV3). | shipped DialogHeader and descendant autofocus behavior | settled | +| FR3 | When no eligible descendant request exists, Dialog MUST preserve the native dialog's valid initial-focus behavior rather than move focus outside the modal. | native modal semantics and shipped fallback | settled | +| FR4 | Closing a native Dialog MUST return focus to the still-connected external element that invoked the modal when that element can receive focus. Descendant mount focus MUST NOT replace that return owner. | shipped trigger-return intent and regression history | settled | +| FR5 | Inline rendering MUST NOT open a modal, apply modal initial focus, trap focus, or return focus as if a modal had closed. | documented `isInline` preview behavior | settled | +| FR6 | Initial-focus selection MUST follow the rendered eligible descendants, not a private component type or source-only assumption. | composable descendant contract | settled | +| FR7 | A native modal Dialog MUST be a focus region through Core's shared focus-region module: Tab from its last tabbable control moves focus to its first, and Shift+Tab from its first moves focus to its last, so focus never leaves the modal for the browser's own interface. When a Dialog opens from a Dialog, the innermost one holding focus answers Tab. | owner decision DEC-2 | settled | +| FR8 | A modal Dialog open on the server renders closed until hydration (no open styles, no `aria-modal`, the markup of a closed Dialog) and opens in the render after hydration, the first that can make it modal; it never claims a modality it does not have (`spec:AST-020` FR1, WCAG 2.2 SC 4.1.2). An inline Dialog is not modal and renders as it is. 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 | settled | +| FR9 | On every pointer, the modal backdrop is the theme's `--color-overlay` dim with no blur (no `backdrop-filter`); under forced colors the dialog keeps a visible edge (a system-colour border) so it stays apart from the page. A full-screen Dialog (`variant="fullscreen"`) covers the page and draws none. | Owner decision, 2026-10-25: the overlay stays theme-controlled and unblurred on every pointer. | settled | ### Allowed variation @@ -127,8 +130,8 @@ current family and architecture owners. ## Design relationships Dialog focus timing and destination do not prescribe title styling, modal size, -motion, backdrop appearance, or visual hierarchy. Those remain with Dialog's -component design and theming owners. +motion, or visual hierarchy. Those remain with Dialog's component design and +theming owners. FR9 sets the backdrop's appearance. ## Family and system relationships @@ -153,6 +156,7 @@ component design and theming owners. | FR6, AR3 | shared modal-dialog binding plus the local composed-action focus fixture | DialogHeader heading, TextInput, action button | focus depends on a private React child type or strips semantics from the target | audit:Dialog/public-api | | FR7 | `Dialog.test.tsx`, `AlertDialog.test.tsx` and `CommandPalette.test.tsx` focus-region suites | last and first tabbable control, Dialog in Dialog, inline | Tab from the last control leaves the modal, or an outer Dialog answers an inner one's Tab | audit:Dialog/accessibility | | FR8 | `Dialog.ssr.test.tsx` | Open on the server; hydration; a closed Dialog'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:Dialog/accessibility | +| FR9 | `modalBackdrop.test.tsx`; `ModalBackdrop.a11y.browser.spec.ts` in Chromium and WebKit | A finger at phone width; a mouse at desktop width; forced colors under either pointer; a full-screen Dialog in forced colors | A `backdrop-filter` on the backdrop at either width, no visible edge in forced colors, or an edge on a full-screen Dialog, fails. | audit:Dialog/accessibility | ## Decision log diff --git a/docs/specs/components/Drawer/Drawer.spec.md b/docs/specs/components/Drawer/Drawer.spec.md index 6ba13cce28f2f..7effabb54c2fb 100644 --- a/docs/specs/components/Drawer/Drawer.spec.md +++ b/docs/specs/components/Drawer/Drawer.spec.md @@ -18,6 +18,8 @@ verified_by: .github/scripts/modal-close-visibility.js, apps/storybook/rtl-audit/rtl-audit.mjs, scripts/check-knowledge.mjs, + packages/core/src/__tests__/modalBackdrop.test.tsx, + packages/core/src/__tests__/ModalBackdrop.a11y.browser.spec.ts, ] modules: [] families: [family:overlay-dismissal] @@ -111,6 +113,7 @@ Consumer migration instructions belong in consumer docs and release notes. - The viewport-relative side-panel surface, logical edge, inline-size budget, and entry/exit motion. +- The modal scrim's appearance (FR20). - The current presentation input: its value at native open selects `showModal()` or the manual Popover API host. Changing it while open is unsupported. - Drawer-local focus entry/return, the `purpose` dismissal policy, uncanceled @@ -154,27 +157,28 @@ Consumer prop syntax and examples remain in `Drawer.doc.mjs`. ## Behavioral and layout contract -| ID | Invariant | Basis | -| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | -| FR1 | Drawer MUST remain a viewport-relative, full-block-size overlay on the logical inline-start or inline-end edge and MUST NOT reserve layout space or reflow the page beneath it. | Current source, docs, stories, and tests | -| FR2 | The logical edge selected for an open Drawer MUST remain latched through its exit even when caller state changes the live edge prop during close. | Current exit-side test and implementation | -| FR3 | The desktop inline-size budget MUST accept pixel numbers or CSS lengths and remain bounded by the viewport. At or below 640px, page-reveal mode MUST preserve 56px and use `width` as a cap; full-mobile mode MUST override `width` with `100dvw`. | Current docs, styles, and width tests | -| FR4 | Visibility through Drawer-owned behavior MUST follow `isOpen`, from the render after hydration on (FR17). Uncanceled Escape routed by the shared stack and uncanceled modal-backdrop activation request `false` when `purpose` allows (FR15), and a `DrawerHeader` close action requests `false` through the callback it is given; Drawer prevents its handled native `cancel` event from closing the dialog directly. During controlled exit, Drawer keeps its host and content region mounted while rendering the caller's current `children`. | Current prop contract and lifecycle tests | -| FR5 | At open time, `hasScrim={true}` MUST select native `showModal()` with `aria-modal`, a focus trap, body scroll locking, and a visible backdrop; `hasScrim={false}` MUST select a manual Popover API host that leaves the page behind interactive. Changing `hasScrim` while open is not a supported native-mode transition. | Current source, docs, and initial-mode tests | -| FR6 | An uncanceled press on the modal backdrop that starts and ends there (`target === currentTarget` for the pointer-down, the pointer-up, and the click, while live `hasScrim` is true; `family:overlay-dismissal` FR10) MUST request close when `purpose` is `info`, and MUST NOT for `form` or `required`; a press that crosses the drawer's edge either way MUST NOT request close. Descendant clicks and dialog-root clicks while live `hasScrim` is false MUST NOT request close, and non-modal presentation MUST NOT install an invisible outside-pointer dismissal plane. | Current click tests; `useBackdropPress.test.tsx` | -| FR7 | Drawer MUST NOT render a close control of its own. A visible close action is caller composition, normally `DrawerHeader` with `onOpenChange` (`component:DrawerHeader` FR3), which requests `false` through that callback without taking open-state ownership. | DEC-1; close-control suite | -| FR8 | Opening MUST present the native host, capture the element focused before opening, and attempt to focus the first rendered `[data-autofocus]` descendant, if any. After a completed controlled close releases the native host, Drawer MUST attempt to restore focus to the captured element. The non-modal host's synthetic `close` event MUST dispatch after that restore attempt — matching the task-queued native `dialog.close()` event — so a consumer close listener keeps the last word on final focus. | Current presence hook and focus tests | -| FR9 | Closing MUST retain the panel host, content region, edge, and native presentation while the exit remains visible and continue rendering the caller's current `children`. The transform transition is authoritative, a computed-duration backstop prevents a lost event from stranding the host, and native release and React hiding land together so no frame paints outside the top layer. | Current lifecycle tests and browser close-visibility guard | -| FR10 | Sibling Drawers MUST be composed as siblings. The last-opened present sibling owns the first Escape request through the shared stack; a closing sibling retains that ownership through its visible exit, and reopening registers a new active cycle so one request never closes two surfaces. Paint order in both presentations follows the browser top layer's chronological order. | Current docs, shared stack, and tests | -| FR11 | `DrawerProps` extends `BaseProps` and separately declares `ref`. The root filters `open`, merges `xstyle`, `className`, and `style`, forwards remaining unclaimed props, composes consumer `onClick`, forwards consumer `onKeyDown` ahead of the shared document-level Escape owner, and owns `aria-label`, `aria-modal`, and, for a modal `required` drawer, `role="alertdialog"`. Implementation gap: a consumer `onCancel` is dropped (Current-state impact). A consumer `onKeyDown` that prevents default cancels shared-stack Escape dismissal for the press. | Current source and focused keyboard tests | -| FR12 | The painted root dialog emits the documented `drawer` target and `side` selector axis and applies the container-padding reset. `DrawerHeader`'s targets are owned by `component:DrawerHeader` FR5. No separate Drawer target is currently emitted for content or scrim; future target qualification remains owned by `architecture:component-theming-surface`. | Current source, docs, and structural target metadata | -| FR13 | Drawer MUST join the shared dismissal stack for its full rendered lifetime, provide logical depth to descendant layers, route platform close through the same topmost/IME decision, and preserve consumer `preventDefault()` ownership. | Shared family contract and focused tests | -| FR14 | Non-modal Drawer MUST use a manual Popover API host so cross-surface order comes from the browser top layer rather than a page-level z-index band. The reduced fallback may use `dialog.show()` only below the Popover API support floor. | Current source, browser guard, and `spec:AST-027` | -| FR15 | `purpose` takes the same values and default as Dialog's prop. `info` (default) lets Escape, platform close, and a modal scrim click request close; `form` lets Escape and platform close request close and ignores scrim clicks; `required` lets none request close, registers with the shared stack as `block` so the request does not reach a lower layer, and exposes a modal drawer as `role="alertdialog"`. Without a scrim, `form` and `info` behave the same. | DEC-1; purpose suite; `family:overlay-dismissal` Escape behavior | -| FR16 | The Content area pads caller content by the drawer's container inset, `--spacing-4` by default as in Dialog, and publishes the applied inset to descendants as a container publisher would; `architecture:container-padding` does not yet admit Drawer as one (Current-state impact). Its block-end edge applies the container inset plus the home-indicator safe area while publishing the inset alone, so a bleed child subtracts only the inset and the safe area survives below it. The root dialog keeps the container-padding reset (FR12). | `architecture:container-padding`; container padding suite | -| FR17 | A Drawer open on the server renders closed until hydration (no open styles, no `aria-modal`, the markup of a closed Drawer) 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 | While a modal Drawer (`hasScrim`) is open it supplies its `` as the passive global outlet, so app-global surfaces such as toasts render inside it, paint above it, and stay operable and reachable by keyboard; it stops supplying when it starts to close, so they return to their place and are not carried out with the exit. Moving them keeps toast entries, timers, and focus handoff (`spec:AST-003` FR18, FR19). A non-modal Drawer supplies no outlet (`architecture:layer-runtime`). | `spec:AST-003` FR18 | -| FR19 | When a non-modal Drawer (`hasScrim={false}`) enters the top layer through `showPopover()`, a top-layer toast viewport shown before it leaves and re-enters the top layer in place, keeping focus inside it, so toasts paint above the drawer; the drawer supplies no outlet, and its close moves and re-enters nothing (`architecture:layer-runtime`). | `architecture:layer-runtime` | +| ID | Invariant | Basis | +| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| FR1 | Drawer MUST remain a viewport-relative, full-block-size overlay on the logical inline-start or inline-end edge and MUST NOT reserve layout space or reflow the page beneath it. | Current source, docs, stories, and tests | +| FR2 | The logical edge selected for an open Drawer MUST remain latched through its exit even when caller state changes the live edge prop during close. | Current exit-side test and implementation | +| FR3 | The desktop inline-size budget MUST accept pixel numbers or CSS lengths and remain bounded by the viewport. At or below 640px, page-reveal mode MUST preserve 56px and use `width` as a cap; full-mobile mode MUST override `width` with `100dvw`. | Current docs, styles, and width tests | +| FR4 | Visibility through Drawer-owned behavior MUST follow `isOpen`, from the render after hydration on (FR17). Uncanceled Escape routed by the shared stack and uncanceled modal-backdrop activation request `false` when `purpose` allows (FR15), and a `DrawerHeader` close action requests `false` through the callback it is given; Drawer prevents its handled native `cancel` event from closing the dialog directly. During controlled exit, Drawer keeps its host and content region mounted while rendering the caller's current `children`. | Current prop contract and lifecycle tests | +| FR5 | At open time, `hasScrim={true}` MUST select native `showModal()` with `aria-modal`, a focus trap, body scroll locking, and a visible backdrop; `hasScrim={false}` MUST select a manual Popover API host that leaves the page behind interactive. Changing `hasScrim` while open is not a supported native-mode transition. | Current source, docs, and initial-mode tests | +| FR6 | An uncanceled press on the modal backdrop that starts and ends there (`target === currentTarget` for the pointer-down, the pointer-up, and the click, while live `hasScrim` is true; `family:overlay-dismissal` FR10) MUST request close when `purpose` is `info`, and MUST NOT for `form` or `required`; a press that crosses the drawer's edge either way MUST NOT request close. Descendant clicks and dialog-root clicks while live `hasScrim` is false MUST NOT request close, and non-modal presentation MUST NOT install an invisible outside-pointer dismissal plane. | Current click tests; `useBackdropPress.test.tsx` | +| FR7 | Drawer MUST NOT render a close control of its own. A visible close action is caller composition, normally `DrawerHeader` with `onOpenChange` (`component:DrawerHeader` FR3), which requests `false` through that callback without taking open-state ownership. | DEC-1; close-control suite | +| FR8 | Opening MUST present the native host, capture the element focused before opening, and attempt to focus the first rendered `[data-autofocus]` descendant, if any. After a completed controlled close releases the native host, Drawer MUST attempt to restore focus to the captured element. The non-modal host's synthetic `close` event MUST dispatch after that restore attempt — matching the task-queued native `dialog.close()` event — so a consumer close listener keeps the last word on final focus. | Current presence hook and focus tests | +| FR9 | Closing MUST retain the panel host, content region, edge, and native presentation while the exit remains visible and continue rendering the caller's current `children`. The transform transition is authoritative, a computed-duration backstop prevents a lost event from stranding the host, and native release and React hiding land together so no frame paints outside the top layer. | Current lifecycle tests and browser close-visibility guard | +| FR10 | Sibling Drawers MUST be composed as siblings. The last-opened present sibling owns the first Escape request through the shared stack; a closing sibling retains that ownership through its visible exit, and reopening registers a new active cycle so one request never closes two surfaces. Paint order in both presentations follows the browser top layer's chronological order. | Current docs, shared stack, and tests | +| FR11 | `DrawerProps` extends `BaseProps` and separately declares `ref`. The root filters `open`, merges `xstyle`, `className`, and `style`, forwards remaining unclaimed props, composes consumer `onClick`, forwards consumer `onKeyDown` ahead of the shared document-level Escape owner, and owns `aria-label`, `aria-modal`, and, for a modal `required` drawer, `role="alertdialog"`. Implementation gap: a consumer `onCancel` is dropped (Current-state impact). A consumer `onKeyDown` that prevents default cancels shared-stack Escape dismissal for the press. | Current source and focused keyboard tests | +| FR12 | The painted root dialog emits the documented `drawer` target and `side` selector axis and applies the container-padding reset. `DrawerHeader`'s targets are owned by `component:DrawerHeader` FR5. No separate Drawer target is currently emitted for content or scrim; future target qualification remains owned by `architecture:component-theming-surface`. | Current source, docs, and structural target metadata | +| FR13 | Drawer MUST join the shared dismissal stack for its full rendered lifetime, provide logical depth to descendant layers, route platform close through the same topmost/IME decision, and preserve consumer `preventDefault()` ownership. | Shared family contract and focused tests | +| FR14 | Non-modal Drawer MUST use a manual Popover API host so cross-surface order comes from the browser top layer rather than a page-level z-index band. The reduced fallback may use `dialog.show()` only below the Popover API support floor. | Current source, browser guard, and `spec:AST-027` | +| FR15 | `purpose` takes the same values and default as Dialog's prop. `info` (default) lets Escape, platform close, and a modal scrim click request close; `form` lets Escape and platform close request close and ignores scrim clicks; `required` lets none request close, registers with the shared stack as `block` so the request does not reach a lower layer, and exposes a modal drawer as `role="alertdialog"`. Without a scrim, `form` and `info` behave the same. | DEC-1; purpose suite; `family:overlay-dismissal` Escape behavior | +| FR16 | The Content area pads caller content by the drawer's container inset, `--spacing-4` by default as in Dialog, and publishes the applied inset to descendants as a container publisher would; `architecture:container-padding` does not yet admit Drawer as one (Current-state impact). Its block-end edge applies the container inset plus the home-indicator safe area while publishing the inset alone, so a bleed child subtracts only the inset and the safe area survives below it. The root dialog keeps the container-padding reset (FR12). | `architecture:container-padding`; container padding suite | +| FR17 | A Drawer open on the server renders closed until hydration (no open styles, no `aria-modal`, the markup of a closed Drawer) 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 | While a modal Drawer (`hasScrim`) is open it supplies its `` as the passive global outlet, so app-global surfaces such as toasts render inside it, paint above it, and stay operable and reachable by keyboard; it stops supplying when it starts to close, so they return to their place and are not carried out with the exit. Moving them keeps toast entries, timers, and focus handoff (`spec:AST-003` FR18, FR19). A non-modal Drawer supplies no outlet (`architecture:layer-runtime`). | `spec:AST-003` FR18 | +| FR19 | When a non-modal Drawer (`hasScrim={false}`) enters the top layer through `showPopover()`, a top-layer toast viewport shown before it leaves and re-enters the top layer in place, keeping focus inside it, so toasts paint above the drawer; the drawer supplies no outlet, and its close moves and re-enters nothing (`architecture:layer-runtime`). | `architecture:layer-runtime` | +| FR20 | Drawer's scrim is the theme's `--color-overlay` dim with no blur, on every pointer; under forced colors the drawer keeps a visible edge. | Owner decision, 2026-10-25: the overlay stays theme-controlled and unblurred on every pointer. | ### Allowed variation @@ -271,13 +275,13 @@ Consumer prop syntax and examples remain in `Drawer.doc.mjs`. ## Design relationships -| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract | -| ---------------- | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------ | -------------- | ------------------ | -| Panel | Paints the full-height side surface and owns edge, width, border, shadow, and motion. | Current source and public docs | Prominent | FR1–FR3, FR9, FR12 | -| Content region | Provides full-height scrolling and the container inset for caller-owned inspector content. | Current source and public docs | Prominent | FR4, FR16, AV1 | -| Header | `DrawerHeader` supplies the title row and, when given `onOpenChange`, the close action. | `component:DrawerHeader` | Supporting | FR7, AR5 | -| Modal scrim | At initial modal open, communicates the scrim-backed presentation and provides root-click activation behind the panel. | Current source and public docs | Supporting | FR5, FR6, AR2 | -| Page reveal | Preserves overlay context on narrow viewports unless full coverage is requested. | Current public docs | Supporting | FR3 | +| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract | +| ---------------- | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------ | -------------- | ------------------- | +| Panel | Paints the full-height side surface and owns edge, width, border, shadow, and motion. | Current source and public docs | Prominent | FR1–FR3, FR9, FR12 | +| Content region | Provides full-height scrolling and the container inset for caller-owned inspector content. | Current source and public docs | Prominent | FR4, FR16, AV1 | +| Header | `DrawerHeader` supplies the title row and, when given `onOpenChange`, the close action. | `component:DrawerHeader` | Supporting | FR7, AR5 | +| Modal scrim | At initial modal open, communicates the scrim-backed presentation and provides root-click activation behind the panel. | Current source and public docs | Supporting | FR5, FR6, FR20, AR2 | +| Page reveal | Preserves overlay context on narrow viewports unless full coverage is requested. | Current public docs | Supporting | FR3 | The root Panel carries the current `drawer` target and reflects `side`; `DrawerHeader`'s targets are owned by `component:DrawerHeader`. No separate @@ -327,6 +331,7 @@ block is optional during migration, so the map is deferred. | FR17 | `Drawer.ssr.test.tsx` | Open on the server; hydration; a closed Drawer'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:Drawer/accessibility` | | FR18 | `ToastViewport.modalHost.test.tsx` "ToastViewport above a Drawer" suite; `DrawerToastOutlet.a11y.chromium.spec.ts` (hit testing, click and Tab at desktop and phone widths) | modal drawer opened over a page toast; toast raised from inside the drawer; drawer closing; drawer without a scrim | A toast viewport left outside an open modal drawer, a toast carried out with the closing drawer, a remounted toast row, or a non-modal drawer that takes the viewport fails. | `audit:Drawer/accessibility` | | FR19 | `ToastViewport.modalHost.test.tsx` "ToastViewport above a Drawer" non-modal case; `DrawerToastOutlet.a11y.chromium.spec.ts` non-modal case | a toast shown before a scrimless drawer opens over its corner; the drawer closing | A toast the scrimless drawer covers, a viewport moved into the drawer, or a re-entry on close fails. | `audit:Drawer/accessibility` | +| FR20 | `modalBackdrop.test.tsx`; `ModalBackdrop.a11y.browser.spec.ts` in Chromium and WebKit | A finger at phone width; a mouse at desktop width; forced colors under either pointer | A `backdrop-filter` on the scrim at either width, or no visible edge in forced colors, fails. | `audit:Drawer/theming` | Read from source, with no focused test yet: diff --git a/docs/specs/components/MobileNav/MobileNav.spec.md b/docs/specs/components/MobileNav/MobileNav.spec.md index d42cb5bd2f55d..3041eb1f187b6 100644 --- a/docs/specs/components/MobileNav/MobileNav.spec.md +++ b/docs/specs/components/MobileNav/MobileNav.spec.md @@ -27,6 +27,8 @@ verified_by: packages/core/src/theme/themingTargets.test.ts, scripts/check-knowledge.mjs, apps/storybook/rtl-audit/targets.json, + packages/core/src/__tests__/modalBackdrop.test.tsx, + packages/core/src/__tests__/ModalBackdrop.a11y.browser.spec.ts, ] modules: [] families: [family:overlay-dismissal] @@ -111,6 +113,7 @@ Consumer migration instructions belong in consumer docs and release notes. - The Navigation overlay and its current `mobile-nav` target. - Drawer placement and motion, the stable Header and Content regions, and the connection between AppShell state, MobileNav, and MobileNavToggle (FR1–FR12). +- The backdrop's appearance (FR13). - Canonical anatomy for both exported components. `component:MobileNav` is the parent owner; MobileNavToggle has no consumer doc of its own and no separate component contract. @@ -133,20 +136,21 @@ Consumer migration instructions belong in consumer docs and release notes. ## Behavioral and layout contract -| ID | Invariant | Basis | -| ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | -| FR1 | MobileNav renders one native `` Navigation overlay containing a Drawer with a stable Header, Close button, and scrollable Content region. The overlay carries `mobile-nav` with the resolved `side`; Drawer, Header, and Content carry no MobileNav public target. | Current source, docs, and tests | -| FR2 | `isOpen` and `onOpenChange` win when given; otherwise the drawer reads and changes the enclosing AppShell's drawer state. The dialog uses AppShell's drawer id when there is one, else its own; a caller `id` replaces either (Current-state impact). | Current source and tests | -| FR3 | Opening calls `showModal()`, and records the focused element as the opener; where focus lands inside the open drawer is uncontracted here. While open, the page's root clips its overflow and keeps its scrollbar gutter; closing releases both. | Current source and tests | -| FR4 | The native cancel request (Escape) is routed through the shared dismissal stack and requests close only when this drawer is topmost. A click on the overlay outside the Drawer requests close; a click inside does not. The Close button, named by `@astryx.mobileNav.closeNavigation`, requests close. A caller `onClick` on the dialog runs before the backdrop check; one that calls `preventDefault()` cancels that backdrop close. | Current source and tests | -| FR5 | After a close request the drawer slides out while the dialog stays open, and the dialog closes within its slide-out transition and no later than 250 ms after the request (on the next task, never in the commit that requests it, under reduced motion or a zero-length transition). Reopening before then cancels the close. Unmounting closes the dialog. | Current source and tests | -| FR6 | When the dialog closes, focus returns to the recorded opener if it is still connected and was not the document body; otherwise focus is left alone. A reopen that interrupted a close keeps the original opener. | Current source and tests | -| FR7 | The Drawer enters from its resolved inline edge, from off-screen to on-screen, and the backdrop fades in from transparent, without a reduced-motion preference. Under reduced motion, motion follows `design:reduced-motion` DR1–DR3 (Current-state impact records today's shortfall). The overlay clips the off-screen drawer without becoming a scroll container and allows pinch zoom. | Current source and tests | -| FR8 | `side="start"` or `"end"` sets the edge. `side="auto"` MUST keep the drawer's start and end relationship to the element that opened it (`design:bidirectionality` DR7). Implementation gap: it resolves on each open from the focused element's physical half of the viewport (left half picks `start`, otherwise `end`); when nothing is focused at open it keeps its last value, and before any open it is `end`. | Current source | -| FR9 | The Drawer is `width` px wide (default 320), never wider than 85% of the viewport, so a strip of the page stays beside it. | Current source and tests | -| FR10 | The dialog is named by `label`, else a string `header`, else `@astryx.mobileNav.navigation`; a caller `aria-labelledby` outranks all three. A string `header` renders as a level-2 heading; other header content renders as given. | Current source and tests | -| FR11 | MobileNavToggle renders only while AppShell reports its mobile layout with mobile navigation enabled. It is an icon-only ghost Button named by default by `@astryx.mobileNav.toggle.open`, with a menu icon unless `children` replace it; it toggles the drawer, exposes `aria-expanded`, and its `aria-controls` carries AppShell's drawer id, which a MobileNav inside that AppShell applies to its dialog unless a caller `id` replaces it. | Current source, docs, and tests | -| FR12 | MobileNav forwards its `ref`, `data-testid`, other DOM props, `className`, `style`, and `xstyle` to the dialog, except that its own `aria-label` (FR10) replaces a caller's (Current-state impact), a caller `onCancel` never runs (Current-state impact), and a caller `id` replaces its id (FR2). | Current source and tests | +| ID | Invariant | Basis | +| ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| FR1 | MobileNav renders one native `` Navigation overlay containing a Drawer with a stable Header, Close button, and scrollable Content region. The overlay carries `mobile-nav` with the resolved `side`; Drawer, Header, and Content carry no MobileNav public target. | Current source, docs, and tests | +| FR2 | `isOpen` and `onOpenChange` win when given; otherwise the drawer reads and changes the enclosing AppShell's drawer state. The dialog uses AppShell's drawer id when there is one, else its own; a caller `id` replaces either (Current-state impact). | Current source and tests | +| FR3 | Opening calls `showModal()`, and records the focused element as the opener; where focus lands inside the open drawer is uncontracted here. While open, the page's root clips its overflow and keeps its scrollbar gutter; closing releases both. | Current source and tests | +| FR4 | The native cancel request (Escape) is routed through the shared dismissal stack and requests close only when this drawer is topmost. A click on the overlay outside the Drawer requests close; a click inside does not. The Close button, named by `@astryx.mobileNav.closeNavigation`, requests close. A caller `onClick` on the dialog runs before the backdrop check; one that calls `preventDefault()` cancels that backdrop close. | Current source and tests | +| FR5 | After a close request the drawer slides out while the dialog stays open, and the dialog closes within its slide-out transition and no later than 250 ms after the request (on the next task, never in the commit that requests it, under reduced motion or a zero-length transition). Reopening before then cancels the close. Unmounting closes the dialog. | Current source and tests | +| FR6 | When the dialog closes, focus returns to the recorded opener if it is still connected and was not the document body; otherwise focus is left alone. A reopen that interrupted a close keeps the original opener. | Current source and tests | +| FR7 | The Drawer enters from its resolved inline edge, from off-screen to on-screen, and the backdrop fades in from transparent, without a reduced-motion preference. Under reduced motion, motion follows `design:reduced-motion` DR1–DR3 (Current-state impact records today's shortfall). The overlay clips the off-screen drawer without becoming a scroll container and allows pinch zoom. | Current source and tests | +| FR8 | `side="start"` or `"end"` sets the edge. `side="auto"` MUST keep the drawer's start and end relationship to the element that opened it (`design:bidirectionality` DR7). Implementation gap: it resolves on each open from the focused element's physical half of the viewport (left half picks `start`, otherwise `end`); when nothing is focused at open it keeps its last value, and before any open it is `end`. | Current source | +| FR9 | The Drawer is `width` px wide (default 320), never wider than 85% of the viewport, so a strip of the page stays beside it. | Current source and tests | +| FR10 | The dialog is named by `label`, else a string `header`, else `@astryx.mobileNav.navigation`; a caller `aria-labelledby` outranks all three. A string `header` renders as a level-2 heading; other header content renders as given. | Current source and tests | +| FR11 | MobileNavToggle renders only while AppShell reports its mobile layout with mobile navigation enabled. It is an icon-only ghost Button named by default by `@astryx.mobileNav.toggle.open`, with a menu icon unless `children` replace it; it toggles the drawer, exposes `aria-expanded`, and its `aria-controls` carries AppShell's drawer id, which a MobileNav inside that AppShell applies to its dialog unless a caller `id` replaces it. | Current source, docs, and tests | +| FR12 | MobileNav forwards its `ref`, `data-testid`, other DOM props, `className`, `style`, and `xstyle` to the dialog, except that its own `aria-label` (FR10) replaces a caller's (Current-state impact), a caller `onCancel` never runs (Current-state impact), and a caller `id` replaces its id (FR2). | Current source and tests | +| FR13 | MobileNav's backdrop is the theme's `--color-overlay` dim with no blur, on every pointer; under forced colors the drawer keeps a visible edge. | Owner decision, 2026-10-25: the overlay stays theme-controlled and unblurred on every pointer. | ### Allowed variation @@ -195,7 +199,7 @@ Consumer migration instructions belong in consumer docs and release notes. | Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract | | ------------------ | --------------------------------------------------------------------- | ------------------------------ | -------------- | ------------------ | -| Navigation overlay | Hosts the modal navigation layer and its backdrop. | Current source and public docs | Supporting | FR1, FR4 | +| Navigation overlay | Hosts the modal navigation layer and its backdrop. | Current source and public docs | Supporting | FR1, FR4, FR13 | | Drawer | Paints the sliding mobile navigation surface. | Current source and public docs | Prominent | FR1, FR7–FR9 | | Header | Arranges optional header content with the persistent Close button. | Current source and public docs | Supporting | FR1, FR10 | | Content | Provides the scrolling region for caller-supplied navigation content. | Current source and public docs | Prominent | FR1 | @@ -259,19 +263,20 @@ ownership. ## Verification map -| Contract | Verification | Representative states | Mutation or failure expectation | Audit section | -| -------------------- | -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | -| FR1, FR2, FR10, FR12 | `MobileNav.test.tsx` | Open and closed; string and no header; caller `id` on a standalone drawer | Losing the dialog, name, Close, or forwarded props fails. | `audit:MobileNav/anatomy` | -| FR2, FR3, FR4 | `MobileNav.test.tsx`; `MobileNavCloseEdgeCases.test.tsx`; `MobileNavScrollbarGutter.test.tsx` | Escape, backdrop, content click, Close | A wrong close source or a lingering scroll lock fails. | `audit:MobileNav/behavior` | -| FR4 | `layerDismissalFamilies.test.tsx` MobileNav cases | Escape over a required Dialog; cancel while topmost and while not | Closing when not topmost, or not closing when topmost, fails. | `audit:MobileNav/behavior` | -| FR5, ORD3 | `MobileNavCloseVisibility.test.tsx`; `MobileNavCloseEdgeCases.test.tsx`; `MobileNavCloseTiming.test.ts` | Close, reduced motion, reopen, unmount, the 250 ms bound | Closing before the slide-out or a stuck dialog fails. | `audit:MobileNav/behavior` | -| FR6, AR2 | `MobileNavFocus.test.tsx` | Standalone, AppShell, Escape, removed opener | Focus not returned, or returned too early, fails. | `audit:MobileNav/accessibility` | -| FR7 | `MobileNavEntryAnimation.test.tsx` | Start and end edges | Missing starting style or a scroll-container overlay fails. | `audit:MobileNav/behavior` | -| FR11, AR3 | `MobileNavToggle.test.tsx`; `MobileNavReopen.test.tsx` | Closed, open, reopen | Broken expanded state or id link fails. | `audit:MobileNav/accessibility` | -| AR4 | `MobileNavPinchZoom.a11y.chromium.spec.ts` | Open drawer on a touch viewport | Pinch zoom blocked fails. | `audit:MobileNav/accessibility` | -| FR9 | `MobileNav.test.tsx` drawer cap test; `MobileNavWidth.a11y.chromium.spec.ts` | Default and wide `width` on a narrow viewport | A drawer wider than 85% of the viewport fails. | `audit:MobileNav/behavior` | -| Theming anatomy map | `scripts/check-knowledge.mjs`; `themingTargets.test.ts` | Canonical parent anatomy and current target | Missing, extra, prefixed, stale, or multiply assigned mappings fail repository validation. | `audit:MobileNav/theming` | -| RTL relation | RTL audit curated D4 target (`apps/storybook/rtl-audit/targets.json`) on `MobileNav / Default` (drawer opened) | The open drawer; LTR and RTL | A drawer that does not move to the mirrored side of the page in RTL fails D4. Evidence gap: the story centres its opener, so the documented `side="auto"` far-side RTL drawer (FR8) is not observed. | `audit:MobileNav/i18n-rtl` | +| Contract | Verification | Representative states | Mutation or failure expectation | Audit section | +| -------------------- | -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | +| FR1, FR2, FR10, FR12 | `MobileNav.test.tsx` | Open and closed; string and no header; caller `id` on a standalone drawer | Losing the dialog, name, Close, or forwarded props fails. | `audit:MobileNav/anatomy` | +| FR2, FR3, FR4 | `MobileNav.test.tsx`; `MobileNavCloseEdgeCases.test.tsx`; `MobileNavScrollbarGutter.test.tsx` | Escape, backdrop, content click, Close | A wrong close source or a lingering scroll lock fails. | `audit:MobileNav/behavior` | +| FR4 | `layerDismissalFamilies.test.tsx` MobileNav cases | Escape over a required Dialog; cancel while topmost and while not | Closing when not topmost, or not closing when topmost, fails. | `audit:MobileNav/behavior` | +| FR5, ORD3 | `MobileNavCloseVisibility.test.tsx`; `MobileNavCloseEdgeCases.test.tsx`; `MobileNavCloseTiming.test.ts` | Close, reduced motion, reopen, unmount, the 250 ms bound | Closing before the slide-out or a stuck dialog fails. | `audit:MobileNav/behavior` | +| FR6, AR2 | `MobileNavFocus.test.tsx` | Standalone, AppShell, Escape, removed opener | Focus not returned, or returned too early, fails. | `audit:MobileNav/accessibility` | +| FR7 | `MobileNavEntryAnimation.test.tsx` | Start and end edges | Missing starting style or a scroll-container overlay fails. | `audit:MobileNav/behavior` | +| FR11, AR3 | `MobileNavToggle.test.tsx`; `MobileNavReopen.test.tsx` | Closed, open, reopen | Broken expanded state or id link fails. | `audit:MobileNav/accessibility` | +| AR4 | `MobileNavPinchZoom.a11y.chromium.spec.ts` | Open drawer on a touch viewport | Pinch zoom blocked fails. | `audit:MobileNav/accessibility` | +| FR9 | `MobileNav.test.tsx` drawer cap test; `MobileNavWidth.a11y.chromium.spec.ts` | Default and wide `width` on a narrow viewport | A drawer wider than 85% of the viewport fails. | `audit:MobileNav/behavior` | +| Theming anatomy map | `scripts/check-knowledge.mjs`; `themingTargets.test.ts` | Canonical parent anatomy and current target | Missing, extra, prefixed, stale, or multiply assigned mappings fail repository validation. | `audit:MobileNav/theming` | +| RTL relation | RTL audit curated D4 target (`apps/storybook/rtl-audit/targets.json`) on `MobileNav / Default` (drawer opened) | The open drawer; LTR and RTL | A drawer that does not move to the mirrored side of the page in RTL fails D4. Evidence gap: the story centres its opener, so the documented `side="auto"` far-side RTL drawer (FR8) is not observed. | `audit:MobileNav/i18n-rtl` | +| FR13 | `modalBackdrop.test.tsx`; `ModalBackdrop.a11y.browser.spec.ts` in Chromium and WebKit | A finger at phone width; a mouse at desktop width; forced colors under either pointer | A `backdrop-filter` on the backdrop at either width, or no visible edge in forced colors, fails. | `audit:MobileNav/theming` | Read from source, with no focused test yet: diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsx index d9b6965a007a7..03b409480e4d1 100644 --- a/packages/core/src/Dialog/Dialog.tsx +++ b/packages/core/src/Dialog/Dialog.tsx @@ -189,8 +189,22 @@ const styles = stylex.create({ position: 'fixed', margin: 'auto', padding: 0, - borderWidth: 0, - borderStyle: 'none', + // The backdrop does not blur the page. Forced colors override the + // backdrop's colour, so a 1px border keeps the modal separate from the + // page. It is a border, not an outline: the focus ring + // (focusOutlineProps) owns the outline longhands on this element. + borderWidth: { + default: 0, + '@media (forced-colors: active)': 1, + }, + borderStyle: { + default: 'none', + '@media (forced-colors: active)': 'solid', + }, + borderColor: { + default: null, + '@media (forced-colors: active)': 'CanvasText', + }, backgroundColor: colorVars['--color-background-surface'], '--_dialog-radius': radiusVars['--radius-container'], borderRadius: 'var(--_dialog-radius)', @@ -236,11 +250,10 @@ const styles = stylex.create({ openSettled: { animationName: 'none', }, - // Backdrop using ::backdrop pseudo-element + // No backdrop-filter: a full-viewport blur is costly to repaint. backdrop: { '::backdrop': { backgroundColor: colorVars['--color-overlay'], - backdropFilter: 'blur(2px)', }, }, fullscreen: { @@ -249,6 +262,8 @@ const styles = stylex.create({ maxWidth: '100dvw', maxHeight: '100dvh', borderRadius: 0, + // Nothing of the page shows around a full-screen dialog: no edge. + borderWidth: 0, margin: 0, inset: 0, }, diff --git a/packages/core/src/Drawer/Drawer.tsx b/packages/core/src/Drawer/Drawer.tsx index 84d110cb7088c..7607542b045f4 100644 --- a/packages/core/src/Drawer/Drawer.tsx +++ b/packages/core/src/Drawer/Drawer.tsx @@ -222,8 +222,8 @@ const styles = stylex.create({ // Scrim via the browser's ::backdrop pseudo-element (top layer). scrim: { '::backdrop': { + // No backdrop-filter: a full-viewport blur is costly to repaint. backgroundColor: colorVars['--color-overlay'], - backdropFilter: 'blur(2px)', opacity: 0, transitionProperty: 'opacity', transitionDuration: durationVars['--duration-medium'], diff --git a/packages/core/src/MobileNav/MobileNav.tsx b/packages/core/src/MobileNav/MobileNav.tsx index 75bbdedf01630..6b3d53896930d 100644 --- a/packages/core/src/MobileNav/MobileNav.tsx +++ b/packages/core/src/MobileNav/MobileNav.tsx @@ -143,8 +143,8 @@ const styles = stylex.create({ // ::backdrop is provided by the browser's top layer backdrop: { '::backdrop': { + // No backdrop-filter: a full-viewport blur is costly to repaint. backgroundColor: colorVars['--color-overlay'], - backdropFilter: 'blur(2px)', opacity: 0, transitionProperty: 'opacity', transitionDuration: durationVars['--duration-medium'], diff --git a/packages/core/src/__tests__/ModalBackdrop.a11y.browser.spec.ts b/packages/core/src/__tests__/ModalBackdrop.a11y.browser.spec.ts new file mode 100644 index 0000000000000..34c36d2817719 --- /dev/null +++ b/packages/core/src/__tests__/ModalBackdrop.a11y.browser.spec.ts @@ -0,0 +1,285 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +// @pr-a11y scope ^(packages/core/src/(Dialog|AlertDialog|Drawer|MobileNav|BottomSheet)/|apps/storybook/stories/(Dialog|AlertDialog|Drawer|MobileNav|BottomSheet)\.stories) + +/** + * @file ModalBackdrop.a11y.browser.spec.ts + * @input The Dialog, AlertDialog, Drawer, MobileNav and BottomSheet stories in + * a built Storybook, under a finger at phone width and with a mouse at + * desktop width, in light and dark mode + * @output Browser evidence that no modal blurs the page and that each + * `::backdrop` keeps the theme's overlay colour. In forced colors, each modal + * has one 1px edge and the focus ring keeps the outline. A screenshot of an + * open Dialog in each mode. + * @position Cross-browser proof for the shared modal backdrop. jsdom paints + * nothing, so modalBackdrop.test.tsx pins only the declarations. WebKit here + * is desktop WebKit under Playwright, not iOS Safari. + * SYNC: When a component gains a modal ::backdrop, add it to MODALS. + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import {expect, test, type Page} from '@playwright/test'; +import { + DEFAULT_STORYBOOK_DIR, + serveStorybook, + type StaticServer, +} from '@astryxdesign/a11y-spec/storybook'; + +let storybook: StaticServer; +test.beforeAll(async () => { + storybook = await serveStorybook( + process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR, + ); +}); +test.afterAll(async () => { + await storybook?.close(); +}); + +test.use({viewport: {width: 390, height: 844}, hasTouch: true, isMobile: true}); + +/** Each modal surface that dims the page, and the tap that opens it. */ +const MODALS = [ + {name: 'Dialog', story: 'core-dialog--default', opener: 'Open Modal'}, + { + name: 'AlertDialog', + story: 'core-alertdialog--delete', + opener: 'Delete item', + }, + {name: 'Drawer', story: 'core-drawer--scrim', opener: 'With scrim'}, + { + name: 'MobileNav', + story: 'core-mobilenav--default', + opener: 'Open Navigation', + }, + { + name: 'BottomSheet', + story: 'core-bottomsheet--showcase', + opener: 'Open sheet', + }, +] as const; + +type Mode = 'light' | 'dark'; + +/** The dim with the base tokens, under every pointer: `--color-overlay`. */ +const OVERLAY_DIM: Record = { + light: 'rgba(1, 18, 40, 0.4)', + dark: 'rgba(17, 17, 18, 0.6)', +}; + +async function openModal( + page: Page, + modal: (typeof MODALS)[number], + mode: Mode, + theme: 'none' | 'neutral', +): Promise { + await page.goto( + `${storybook.origin}/iframe.html?id=${modal.story}&viewMode=story&globals=colorMode:${mode};astryxTheme:${theme}`, + ); + const opener = page.getByRole('button', {name: modal.opener}).first(); + if (await page.evaluate(() => matchMedia('(pointer: coarse)').matches)) { + await opener.tap(); + } else { + await opener.click(); + } + await expect(page.locator('dialog[open]').last()).toBeVisible(); +} + +/** The open modal's ::backdrop as the browser computes it. */ +async function readBackdrop( + page: Page, +): Promise<{color: string; filter: string}> { + return page + .locator('dialog[open]') + .last() + .evaluate(dialog => { + const style = getComputedStyle(dialog, '::backdrop'); + return { + color: style.backgroundColor, + filter: + style.backdropFilter ?? + (style as unknown as {webkitBackdropFilter?: string}) + .webkitBackdropFilter ?? + 'none', + }; + }); +} + +/** + * The open modal's visible surface (the dialog, or MobileNav's drawer): its + * outline, and its drawn side borders (solid and wider than 0), as + * `side width`. + */ +async function readSurfaceEdge( + page: Page, + name: string, +): Promise<{outline: string; sides: string[]}> { + return page + .locator('dialog[open]') + .last() + .evaluate((dialog, isMobileNav) => { + // MobileNav's dialog is a transparent full-viewport container; its + // drawer panel (the focus target) is what the person sees. + const surface = isMobileNav + ? (dialog.querySelector('[tabindex="-1"]') ?? dialog) + : dialog; + const style = getComputedStyle(surface); + return { + outline: `${style.outlineStyle} ${style.outlineWidth}`, + sides: (['left', 'right'] as const) + .filter( + side => + style.getPropertyValue(`border-${side}-style`) === 'solid' && + Number.parseFloat( + style.getPropertyValue(`border-${side}-width`), + ) > 0, + ) + .map( + side => `${side} ${style.getPropertyValue(`border-${side}-width`)}`, + ), + }; + }, name === 'MobileNav'); +} + +for (const modal of MODALS) { + for (const mode of ['light', 'dark'] as const) { + test(`${modal.name} keeps the overlay colour under a finger in ${mode} mode, unblurred`, async ({ + page, + }) => { + await openModal(page, modal, mode, 'none'); + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(true); + const backdrop = await readBackdrop(page); + expect(backdrop.color).toBe(OVERLAY_DIM[mode]); + expect(backdrop.filter).toBe('none'); + }); + } + + test(`${modal.name} keeps the neutral theme's own dim under a finger, unblurred`, async ({ + page, + }) => { + await openModal(page, modal, 'light', 'neutral'); + const backdrop = await readBackdrop(page); + // neutral's overlay: black at 50 %. + expect(backdrop.color).toBe('rgba(0, 0, 0, 0.5)'); + expect(backdrop.filter).toBe('none'); + }); +} + +test.describe('with a mouse', () => { + test.use({ + hasTouch: false, + isMobile: false, + viewport: {width: 1280, height: 800}, + }); + + for (const modal of MODALS) { + test(`${modal.name} keeps the overlay colour, unblurred`, async ({ + page, + }) => { + await openModal(page, modal, 'dark', 'none'); + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + const backdrop = await readBackdrop(page); + expect(backdrop.color).toBe(OVERLAY_DIM.dark); + expect(backdrop.filter).toBe('none'); + }); + } +}); + +test.describe('forced colors', () => { + test.use({colorScheme: 'light'}); + + for (const modal of MODALS.filter(m => m.name !== 'BottomSheet')) { + test(`${modal.name} has one 1px edge under a finger, where no blur sets it apart`, async ({ + page, + browserName, + }) => { + test.skip( + browserName !== 'chromium', + 'forced-colors emulation is Chromium-only in Playwright', + ); + await page.emulateMedia({forcedColors: 'active'}); + await openModal(page, modal, 'light', 'none'); + const edge = await readSurfaceEdge(page, modal.name); + if (modal.name === 'Drawer' || modal.name === 'MobileNav') { + // The side panel's border facing the page is its edge; no outline + // doubles it. + expect(edge.outline, JSON.stringify(edge)).toMatch(/^none /); + expect(edge.sides, JSON.stringify(edge)).toHaveLength(1); + expect(edge.sides[0], JSON.stringify(edge)).toMatch(/ 1px$/); + } else { + // Dialog's border is its edge, on every side; its outline stays the + // focus ring's (none until keyboard focus). + expect(edge, JSON.stringify(edge)).toEqual({ + outline: 'none 0px', + sides: ['left 1px', 'right 1px'], + }); + } + }); + } + + test.describe('with a mouse', () => { + test.use({ + hasTouch: false, + isMobile: false, + viewport: {width: 1280, height: 800}, + }); + + for (const modal of MODALS.filter(m => m.name !== 'BottomSheet')) { + test(`${modal.name} has the same one 1px edge`, async ({ + page, + browserName, + }) => { + test.skip( + browserName !== 'chromium', + 'forced-colors emulation is Chromium-only in Playwright', + ); + await page.emulateMedia({forcedColors: 'active'}); + await openModal(page, modal, 'light', 'none'); + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + const edge = await readSurfaceEdge(page, modal.name); + expect(edge, JSON.stringify(edge)).toEqual( + modal.name === 'Drawer' || modal.name === 'MobileNav' + ? { + outline: expect.stringMatching(/^none /), + sides: [expect.stringMatching(/ 1px$/)], + } + : {outline: 'none 0px', sides: ['left 1px', 'right 1px']}, + ); + }); + } + }); +}); + +test('the media scrim keeps --color-overlay', async ({page}) => { + // Overlay's dark scrim keeps text legible over media; it is not a modal + // dim and keeps the overlay colour. + await page.goto( + `${storybook.origin}/iframe.html?id=core-overlay--bottom-strip&viewMode=story&globals=colorMode:light;astryxTheme:none`, + ); + const scrim = page.locator('.astryx-overlay-scrim').first(); + await expect(scrim).toBeAttached(); + expect( + await scrim.evaluate(element => getComputedStyle(element).backgroundColor), + ).toBe('rgba(1, 18, 40, 0.4)'); +}); + +const EVIDENCE = process.env.MODAL_BACKDROP_EVIDENCE_DIR ?? ''; +test('evidence: an open Dialog over a page under a finger, per mode', async ({ + page, +}, testInfo) => { + test.skip(EVIDENCE === '', 'evidence capture runs on request'); + fs.mkdirSync(EVIDENCE, {recursive: true}); + for (const mode of ['light', 'dark'] as const) { + await openModal(page, MODALS[0], mode, 'none'); + // The page under the dim, with the open dialog: the viewport, no chrome. + await page.screenshot({ + path: path.join(EVIDENCE, `${testInfo.project.name}-dialog-${mode}.png`), + animations: 'disabled', + }); + } +}); diff --git a/packages/core/src/__tests__/modalBackdrop.test.tsx b/packages/core/src/__tests__/modalBackdrop.test.tsx new file mode 100644 index 0000000000000..18ec52de718c0 --- /dev/null +++ b/packages/core/src/__tests__/modalBackdrop.test.tsx @@ -0,0 +1,261 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file modalBackdrop.test.tsx + * @input Dialog, Drawer, MobileNav and BottomSheet rendered open, and the + * StyleX rules vitest injects into the document (`runtimeInjection`) + * @output Every modal `::backdrop` paints the theme's `--color-overlay` and + * none blurs the page, under any pointer. In forced colors, Dialog draws an + * edge, and Drawer and MobileNav keep their anchored-side border. + * @position Cross-component regression test for the shared modal backdrop. + * jsdom has no top layer and drops `backdrop-filter`, so this test pins the + * declarations as StyleX hands them to the style sheet. Real browsers prove + * the computed colours in ModalBackdrop.a11y.browser.spec.ts. + * SYNC: When a component gains a modal ::backdrop, add it here. + */ + +import {render} from '@testing-library/react'; +import type {ReactElement} from 'react'; +import {beforeAll, describe, expect, it} from 'vitest'; +import type {BottomSheet as BottomSheetComponent} from '../BottomSheet/BottomSheet'; +import type {Dialog as DialogComponent} from '../Dialog/Dialog'; +import type {Drawer as DrawerComponent} from '../Drawer/Drawer'; +import type {MobileNav as MobileNavComponent} from '../MobileNav/MobileNav'; + +let BottomSheet: typeof BottomSheetComponent; +let Dialog: typeof DialogComponent; +let Drawer: typeof DrawerComponent; +let MobileNav: typeof MobileNavComponent; + +// StyleX injects a component's rules when its module loads: record them +// first, then load the modals. +beforeAll(async () => { + const insertRule = CSSStyleSheet.prototype.insertRule; + CSSStyleSheet.prototype.insertRule = function ( + this: CSSStyleSheet, + rule: string, + index?: number, + ) { + rawRules.push(rule); + return insertRule.call(this, rule, index); + }; + ({BottomSheet} = await import('../BottomSheet/BottomSheet')); + ({Dialog} = await import('../Dialog/Dialog')); + ({Drawer} = await import('../Drawer/Drawer')); + ({MobileNav} = await import('../MobileNav/MobileNav')); +}); + +// jsdom does not implement showModal/close on . +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'); + }; +}); + +/** Every rule StyleX inserted, as the raw text it handed to `insertRule`. */ +const rawRules: string[] = []; + +/** + * The declarations that the element's StyleX classes make on its `::backdrop`, + * by property. With `pseudo: ''`, they are the declarations on the element. + * `where` selects the rules outside any at-rule, or inside one media query + * alone: `(pointer: coarse)` or `(forced-colors: active)`. StyleX minifies + * values, so the test compares them without spaces. + */ +function backdropDeclarations( + el: Element, + where: 'default' | 'touch' | 'forcedColors', + pseudo = '::backdrop', +): Map { + const declarations = new Map(); + for (const className of el.className.split(/\s+/).filter(Boolean)) { + for (const raw of rawRules) { + let rule = raw; + const atRules: string[] = []; + for (let match; (match = /^(@[^{]+)\{(.*)\}$/s.exec(rule));) { + atRules.push(match[1].trim()); + rule = match[2]; + } + const isTouch = + atRules.length === 1 && atRules[0] === '@media (pointer: coarse)'; + const isForcedColors = + atRules.length === 1 && atRules[0] === '@media (forced-colors: active)'; + const matchesWhere = + where === 'default' + ? atRules.length === 0 + : where === 'touch' + ? isTouch + : isForcedColors; + if (!matchesWhere) { + continue; + } + // StyleX raises a pseudo-element rule's specificity with repeated + // classes and `:not(#\#)`: `.x1abc.x1abc:not(#\#)…::backdrop{…}`. + const match = new RegExp( + `^(?:\\.${className})+(?::not\\(#\\\\#\\))*${pseudo}\\{([^}]*)\\}$`, + ).exec(rule); + if (match == null) { + continue; + } + for (const declaration of match[1].split(';')) { + const colon = declaration.indexOf(':'); + if (colon > 0) { + declarations.set( + declaration.slice(0, colon).trim(), + declaration.slice(colon + 1).replace(/\s+/g, ''), + ); + } + } + } + } + return declarations; +} + +const modals: ReadonlyArray<[string, () => ReactElement]> = [ + [ + 'Dialog', + () => ( + {}} aria-label="Title"> + Content + + ), + ], + [ + 'Drawer', + () => ( + {}} label="Details"> + Content + + ), + ], + [ + 'MobileNav', + () => ( + {}}> + Navigation + + ), + ], + [ + 'BottomSheet', + () => ( + {}} label="Filters"> + Content + + ), + ], +]; + +/** The modal's visible surface: the dialog, or MobileNav's drawer panel. */ +function surfaceOf(name: string, dialog: Element): Element { + // MobileNav's dialog is a transparent full-viewport container; its drawer + // panel (the focus target, tabIndex -1) is what the person sees. + return name === 'MobileNav' + ? (dialog.querySelector('[tabindex="-1"]') ?? dialog) + : dialog; +} + +describe('modal backdrop', () => { + it.each(modals)( + '%s keeps the theme’s overlay colour under every pointer', + (_name, element) => { + render(element()); + const dialog = document.querySelector('dialog'); + expect(dialog).not.toBeNull(); + expect( + backdropDeclarations(dialog!, 'default').get('background-color'), + ).toBe('var(--color-overlay)'); + // No colour change under a finger. + expect( + backdropDeclarations(dialog!, 'touch').has('background-color'), + ).toBe(false); + }, + ); + + it.each(modals)( + '%s does not blur the page under any pointer', + (_name, element) => { + render(element()); + const dialog = document.querySelector('dialog'); + expect(dialog).not.toBeNull(); + expect( + backdropDeclarations(dialog!, 'default').has('backdrop-filter'), + ).toBe(false); + expect( + backdropDeclarations(dialog!, 'touch').has('backdrop-filter'), + ).toBe(false); + }, + ); + + it('Dialog draws a border in forced colors, where no blur sets it apart', () => { + const [, element] = modals.find(([name]) => name === 'Dialog')!; + render(element()); + const dialog = document.querySelector('dialog'); + expect(dialog).not.toBeNull(); + const edge = backdropDeclarations(dialog!, 'forcedColors', ''); + expect(edge.get('border-width')).toBe('1px'); + expect(edge.get('border-style')).toBe('solid'); + expect(edge.get('border-color')).toBe('CanvasText'); + // Not an outline: the focus ring owns the outline longhands. An `outline` + // shorthand loses to them in the prebuilt style sheet. Where StyleX + // applies styles in order, the shorthand erases the ring. + for (const where of ['default', 'touch', 'forcedColors'] as const) { + expect(backdropDeclarations(dialog!, where, '').has('outline')).toBe( + false, + ); + } + }); + + it('a full-screen Dialog covers the page and draws no edge in forced colors', () => { + render( + {}} + aria-label="Title" + variant="fullscreen"> + Body + , + ); + const dialog = document.querySelector('dialog'); + expect(dialog).not.toBeNull(); + expect( + backdropDeclarations(dialog!, 'forcedColors', '').has('border-width'), + ).toBe(false); + expect( + backdropDeclarations(dialog!, 'default', '').get('border-width'), + ).toMatch(/^0(px)?$/); + }); + + it.each(modals.filter(([name]) => name === 'Drawer' || name === 'MobileNav'))( + '%s keeps its anchored-side border as the forced-colors edge, with no outline added', + (name, element) => { + render(element()); + const dialog = document.querySelector('dialog'); + expect(dialog).not.toBeNull(); + const surface = surfaceOf(name, dialog!); + // The panel's side facing the page has a solid border, which forced + // colors paint CanvasText: one 1px edge already, so no outline. + const declarations = [ + ...backdropDeclarations(surface, 'default', '').entries(), + ]; + expect( + declarations.some( + ([property, value]) => + /^border-inline-(start|end)-style$/.test(property) && + value === 'solid', + ), + JSON.stringify(declarations), + ).toBe(true); + expect( + backdropDeclarations(surface, 'forcedColors', '').has('outline'), + ).toBe(false); + }, + ); +});