An open source design system that's fully customizable and agent ready
TypeScript
fix(Dialog, Drawer, BottomSheet): an overlay open on the server renders closed until hydration (#9360)
Cindy Zhang16b95934f97c
diff --git a/.changeset/overlays-open-on-server-render-closed.md b/.changeset/overlays-open-on-server-render-closed.mdnew file mode 100644index 0000000000..17a7c81f64--- /dev/null+++ b/.changeset/overlays-open-on-server-render-closed.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A `Dialog`, `Drawer` or `BottomSheet` that is open on the server now renders closed until hydration, and opens right after it where it rests, with no entry motion, as anything present on page load does; its later opens and closes animate as before. Before, it painted open over a live page with `aria-modal="true"` but no modal state: the page under it stayed interactive, a sheet's invisible host could swallow clicks, and assistive technology was told a modality that didn't exist (WCAG 2.2 SC 4.1.2). A `BottomSheetSwitcher` whose active sheet is set on the server is covered too. Client-rendered overlays are unchanged.++@cixzhang @duytbpdiff --git a/docs/specs/AST-013/spec.md b/docs/specs/AST-013/spec.mdindex e202d31593..2b3bcbb42b 100644--- a/docs/specs/AST-013/spec.md+++ b/docs/specs/AST-013/spec.md@@ -175,8 +175,7 @@ page paints, the hydrating render produces entry-animation classes the server dinot send, and the hook's consumer documentation says it does not support serverrendering.-Other known FR9 and FR13 gaps: a Dialog rendered open in server markup plays its-entry animation on page load; CodeBlock's collapse chevron plays its reveal+Other known FR9 and FR13 gaps: CodeBlock's collapse chevron plays its revealanimation on page load; and CodeBlock chooses between token-span and HighlightAPI markup from browser capability and user-agent checks during render, so thehydrating render can differ from the server's markup.diff --git a/docs/specs/components/BottomSheet/BottomSheet.spec.md b/docs/specs/components/BottomSheet/BottomSheet.spec.mdindex 0a52aa06a3..d0e4da2156 100644--- a/docs/specs/components/BottomSheet/BottomSheet.spec.md+++ b/docs/specs/components/BottomSheet/BottomSheet.spec.md@@ -163,6 +163,7 @@ remain documented in `BottomSheet.doc.mjs`.| FR14 | When a non-modal sheet enters the top layer, 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 sheet. | DEC-2; `architecture:layer-runtime` || FR15 | Under `prefers-reduced-motion: reduce` the recede, the return from receded, a push's entrance, a pop's exit and the replace handoff — and a `BottomSheetSwitcher` step's, which shares the sheet panel's motion — follow `design:reduced-motion`, keyed on its queries (`prefers-reduced-motion: reduce`, with `pointer: coarse` for the cross-fade): no transform motion runs (DR1) — a covered sheet appears in its receded place and size the frame the push lands and returns the same way, the entering sheet appears in its final place, the retained sheet does not align down; on a coarse pointer the entering sheet fades in and the leaving or retained sheet fades out where it is, opacity only, in 200 ms or less (DR2); a dismissal the release of a touch drag started (a swipe past the dismiss line) fades out in place the same way on every pointer (DR2's drag-release clause); on any other pointer every other change is immediate (DR3); the handoff's steps run in the released order, so the retained sheet is hidden and its dialog closed once its fade ends. The constant page dim through a push, a pop and a handoff (FR6) holds as it does with motion. | DEC-2; `design:reduced-motion` || FR16 | An open modal sheet is a focus region through Core's shared focus-region module (`component:Dialog/DEC-2`): in the top sheet, Tab from the last tabbable control moves focus to the first and Shift+Tab from the first moves focus to the last, so focus never leaves the sheet for the browser's own interface. A covered or closing sheet does not answer Tab, and a non-modal sheet contains nothing (FR11). | `component:Dialog/DEC-2` |+| FR17 | A BottomSheet open on the server, by its own `isOpen` or as a `BottomSheetSwitcher`'s active sheet, renders closed until hydration (no open styles, no `aria-modal`, the markup of a closed sheet) and opens in the render after hydration, the first that can enter its native host; it never claims a modality it does not have (`spec:AST-020` FR1, WCAG 2.2 SC 4.1.2). The server and hydrating renders produce the same markup (`spec:AST-013` FR9), and the open after hydration is settled, with no entry motion; later opens and closes animate as usual (`spec:AST-013` FR13). | `spec:AST-020` FR1 |### Allowed variation@@ -381,6 +382,7 @@ a decision that they must remain unthemeable.| FR10–FR11 | Replace unit suite (jsdom); real-browser parity of the standalone flow against the switcher's handoff — per-frame transforms, opacity, page dim, focus, settled pixels — in Chromium and WebKit, and real Safari for hosting, dim, toast order, and focus; a per-engine lone-open focus probe in Chromium, Firefox and WebKit comparing the sheet's focus on open against that engine's bare `show()` and `showModal()` on the same markup, and recording the focus and blur events the sheet's first control receives on open (none) | push, pop, different updates, covered close, nested, a replace above a covered sheet (the bottom sheet keeps the scrim, the retained sheet only fades), switcher flow, a lone sheet; handoff in both completion orders; reversal mid-handoff in both directions and both tree orders; unrelated owners from a page control; non-modal replace, reversal, `show()` fallback; a non-modal sheet opened from a modal sheet or a `Dialog` and rendered outside it (while the modal is open, and once it has closed, with positioned page content), one opened in the update that closes a modal sheet, and one rendered inside the modal's content | A replace is recognized for unrelated owners or missed for a real step flow, the retained sheet is exposed or dismissable, the scrim dips, the replaced step stays on screen after a reversal, focus does not enter the step or return to the flow's opener, a non-modal sheet carries a page-level `z-index`, a toast paints under a non-modal sheet, or a lone sheet's focus on open, modal or not, differs from where that engine's released native host (`showModal()`, or `show()` for a non-modal sheet) puts it — in Chromium the panel, with a ring only after keyboard input and a `data-autofocus` field left unfocused; in Firefox the first focusable control — a control inside the sheet receives a focus or a blur on a lone open that `show()` would not have given it, or a replacement entry fails to focus its `data-autofocus` field. A non-modal sheet rendered outside an open modal paints above it while a press lands on the modal, or stays beneath page content once that modal has gone. | `audit:BottomSheet/behavior` || FR13–FR14 | Toast viewport hosting suite (jsdom, native dialog methods and popover state stubbed); real-browser hit-testing of a toast raised from the top sheet, from a Dialog opened from a sheet after an inner sheet closed, from a sheet re-shown by a reversal, and over a non-modal sheet | a lone sheet; a stack of two; sheet → Dialog → sheet → close the inner sheet; a reversal and a reopen during exit, with the stale native `close`; a non-modal sheet shown after the viewport; a modal switcher flow alone, through a handoff and its close; a flow stacked over a standalone sheet and a standalone sheet over a flow; a non-modal flow | A toast renders in a covered or inert sheet, a Dialog opened from a sheet loses the toast to the sheet beneath it, a re-shown sheet loses its outlet to the stale `close`, a toast raised from a switcher step lands behind the flow or in its retained step, or a toast paints beneath a non-modal sheet. | `audit:BottomSheet/behavior` || FR16 | `BottomSheet.test.tsx` focus-region suite | Modal and non-modal sheets; Tab and Shift+Tab at the sheet's edge | Tab from the last control leaves a modal sheet, or a non-modal sheet captures Tab | `audit:BottomSheet/accessibility` |+| FR17 | `BottomSheet.ssr.test.tsx`; `BottomSheetSwitcher.test.tsx` flow that mounts open | Open on the server; hydration; a closed sheet's markup | An open server render with `aria-modal`, open styles, or markup unlike a closed one, a hydration error, no `showModal()` after hydration, an entry motion on the open right after hydration, or none on a later open fails. | `audit:BottomSheet/accessibility` |Existing tests directly assert the Sheet panel target, Content area placement,Handle structure, and scrim behavior. Source and public target metadata confirmdiff --git a/docs/specs/components/BottomSheet/BottomSheetSwitcher.spec.md b/docs/specs/components/BottomSheet/BottomSheetSwitcher.spec.mdindex 41039ff0ca..a9eabeb222 100644--- a/docs/specs/components/BottomSheet/BottomSheetSwitcher.spec.md+++ b/docs/specs/components/BottomSheet/BottomSheetSwitcher.spec.md@@ -63,9 +63,12 @@ modality, identifier, and theming questions below stay open.change under `spec:AST-017` FR3. The element the `ref` resolvesto, and that it changes on a handoff, is implementation rather than publiccontract (DEC-2). A switcher flow presented on its own behaves as released,- with one fix: a toast raised from a step renders above the flow and can be+ with two fixes: a toast raised from a step renders above the flow and can bepressed (FR10, `component:BottomSheet` FR13), where it rendered behind the- flow before.+ flow before; and a flow whose active sheet is set on the server renders+ closed until hydration, then opens that sheet settled, with no entry motion+ (`component:BottomSheet` FR17), where it painted open over a live page+ before.A switcher flow presented while other sheets are open is one level of thestack `component:BottomSheet` FR12 describes; that is behavior of the stack,not a change to the switcher's own contractdiff --git a/docs/specs/components/Dialog/Dialog.spec.md b/docs/specs/components/Dialog/Dialog.spec.mdindex 12e82e4519..e5eeb1f4d0 100644--- a/docs/specs/components/Dialog/Dialog.spec.md+++ b/docs/specs/components/Dialog/Dialog.spec.md@@ -81,15 +81,16 @@ 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 |+| 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 |### Allowed variation@@ -143,13 +144,14 @@ component design and theming owners.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------ | ------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- |-| FR1–FR3, AR1 | shared modal-dialog binding in `Dialog.a11y.test.tsx` and `Dialog.a11y.chromium.spec.ts`; local DialogHeader focus tests | header default, explicit descendant, no request | the shared contract fails when focus is applied before native modality, misses the declared target, or leaves the visible modal on native fallback | audit:Dialog/accessibility |-| FR4, AR2 | shared modal-dialog browser binding plus the local unavailable-invoker close test | external trigger, descendant mount focus, removed trigger | the shared contract records an exact current failure when descendant focus replaces the return owner; the local test keeps close safe after invoker removal | audit:Dialog/behavior |-| FR5 | inline Dialog tests | DialogHeader and focusable children | inline preview steals focus or invokes native modal methods | audit:Dialog/behavior |-| 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 |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------ | ------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- |+| FR1–FR3, AR1 | shared modal-dialog binding in `Dialog.a11y.test.tsx` and `Dialog.a11y.chromium.spec.ts`; local DialogHeader focus tests | header default, explicit descendant, no request | the shared contract fails when focus is applied before native modality, misses the declared target, or leaves the visible modal on native fallback | audit:Dialog/accessibility |+| FR4, AR2 | shared modal-dialog browser binding plus the local unavailable-invoker close test | external trigger, descendant mount focus, removed trigger | the shared contract records an exact current failure when descendant focus replaces the return owner; the local test keeps close safe after invoker removal | audit:Dialog/behavior |+| FR5 | inline Dialog tests | DialogHeader and focusable children | inline preview steals focus or invokes native modal methods | audit:Dialog/behavior |+| 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 |## Decision logdiff --git a/docs/specs/components/Drawer/Drawer.spec.md b/docs/specs/components/Drawer/Drawer.spec.mdindex 2b8c5cfa5d..791b55d7bf 100644--- a/docs/specs/components/Drawer/Drawer.spec.md+++ b/docs/specs/components/Drawer/Drawer.spec.md@@ -159,7 +159,7 @@ Consumer prop syntax and examples remain in `Drawer.doc.mjs`.| 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`. 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 |+| 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 modal root/backdrop click (`target === currentTarget` while live `hasScrim` is true) MUST request close when `purpose` is `info`, and MUST NOT for `form` or `required`. 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 || 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 |@@ -172,6 +172,7 @@ Consumer prop syntax and examples remain in `Drawer.doc.mjs`.| 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 |### Allowed variation@@ -309,18 +310,19 @@ block is optional during migration, so the map is deferred.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| --------------- | ------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- |-| FR1–FR7 | `Drawer.test.tsx` render, initial-mode, click, sizing, side, and control suites | closed/open, both edges, initial modal/non-modal modes, mobile widths | Layout reflows; an initial mode gains the wrong semantics; uncanceled root-click or full-mobile sizing becomes nondeterministic. | `audit:Drawer/behavior` |-| FR11 | Drawer source and focused keyboard composition/cancellation tests | filtered `open`, merged styling/ref, forwarded unclaimed props, owned ARIA/cancel, composed click, forwarded keydown | Current forwarding changes without review or shared-stack Escape ignores documented consumer cancellation. | `audit:Drawer/public-api` |-| FR8, AR1–AR5 | `Drawer.test.tsx` label forwarding, autofocus, close, and focus-return suites plus the browser guard's final-focus checks | initial modal/non-modal modes, autofocus target, connected previously focused element, close listener retargeting focus | Focus moves before presentation, completed controlled close fails to restore focus, the synthetic close overrides a consumer listener's focus target, or label forwarding/dismissal naming breaks. | `audit:Drawer/accessibility` |-| FR9, PR1–PR2 | close timing tests, browser close-visibility guard, and presence-hook source inspection | controlled close, transform end, unrelated transition, lost-event backstop | Native presentation ends before visible exit, the host is stranded, cleanup paths retain resources, or an intermediate frame paints outside native presentation. | `audit:Drawer/motion` |-| FR10, FR13, AR3 | Drawer shared-stack suites plus `useLayerDismissal` and family tests | siblings, closing top, reopen, unmount, nested descendant | One Escape closes two surfaces, a closing host drops ownership, or a reopened sibling keeps stale order. | `audit:Drawer/layers` |-| FR14 | Drawer source plus `spec:AST-027` impact inventory and native-host browser guard | modal host, manual-popover host, reduced fallback | Non-modal presentation returns to a page-level band or loses native-host ordering. | `audit:Drawer/layers` |-| FR15 | `Drawer.test.tsx` purpose suite | `info`, `form`, `required`; modal and non-modal; a sibling behind a required drawer | A `form` drawer closes on a scrim click, a `required` drawer closes or lets Escape reach the drawer behind it, or its role semantics drift. | `audit:Drawer/behavior` |-| FR12 | source, `Drawer.doc.mjs`, and current target discovery | start/end root Panel and inherited container context | Current root target/axis or padding reset changes, or the record claims an unreachable child target or decides future admission. | `audit:Drawer/theming` |-| FR16 | `Drawer.test.tsx` container padding suites; `defineTheme.test.ts` drawer mapping; browser evidence | default, `padding` prop, theme `padding`, lone padded Section child, Layout composition | The published inset differs from the applied padding, the default drawer changes geometry, or the block-end safe area is lost or double-subtracted. | `audit:Drawer/theming` |-| AR6 | `DrawerDirection.test.tsx` DOM-direction and closed/entry parity suites plus exact-head Storybook RTL evidence | start/end; self-applied, inherited, and nested opposite `dir`; closed and opening transforms | Any effective DOM direction or local override moves the panel from a different edge than its logical placement, or closed and opening transforms diverge. | `audit:Drawer/accessibility` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| --------------- | ------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- |+| FR1–FR7 | `Drawer.test.tsx` render, initial-mode, click, sizing, side, and control suites | closed/open, both edges, initial modal/non-modal modes, mobile widths | Layout reflows; an initial mode gains the wrong semantics; uncanceled root-click or full-mobile sizing becomes nondeterministic. | `audit:Drawer/behavior` |+| FR11 | Drawer source and focused keyboard composition/cancellation tests | filtered `open`, merged styling/ref, forwarded unclaimed props, owned ARIA/cancel, composed click, forwarded keydown | Current forwarding changes without review or shared-stack Escape ignores documented consumer cancellation. | `audit:Drawer/public-api` |+| FR8, AR1–AR5 | `Drawer.test.tsx` label forwarding, autofocus, close, and focus-return suites plus the browser guard's final-focus checks | initial modal/non-modal modes, autofocus target, connected previously focused element, close listener retargeting focus | Focus moves before presentation, completed controlled close fails to restore focus, the synthetic close overrides a consumer listener's focus target, or label forwarding/dismissal naming breaks. | `audit:Drawer/accessibility` |+| FR9, PR1–PR2 | close timing tests, browser close-visibility guard, and presence-hook source inspection | controlled close, transform end, unrelated transition, lost-event backstop | Native presentation ends before visible exit, the host is stranded, cleanup paths retain resources, or an intermediate frame paints outside native presentation. | `audit:Drawer/motion` |+| FR10, FR13, AR3 | Drawer shared-stack suites plus `useLayerDismissal` and family tests | siblings, closing top, reopen, unmount, nested descendant | One Escape closes two surfaces, a closing host drops ownership, or a reopened sibling keeps stale order. | `audit:Drawer/layers` |+| FR14 | Drawer source plus `spec:AST-027` impact inventory and native-host browser guard | modal host, manual-popover host, reduced fallback | Non-modal presentation returns to a page-level band or loses native-host ordering. | `audit:Drawer/layers` |+| FR15 | `Drawer.test.tsx` purpose suite | `info`, `form`, `required`; modal and non-modal; a sibling behind a required drawer | A `form` drawer closes on a scrim click, a `required` drawer closes or lets Escape reach the drawer behind it, or its role semantics drift. | `audit:Drawer/behavior` |+| FR12 | source, `Drawer.doc.mjs`, and current target discovery | start/end root Panel and inherited container context | Current root target/axis or padding reset changes, or the record claims an unreachable child target or decides future admission. | `audit:Drawer/theming` |+| FR16 | `Drawer.test.tsx` container padding suites; `defineTheme.test.ts` drawer mapping; browser evidence | default, `padding` prop, theme `padding`, lone padded Section child, Layout composition | The published inset differs from the applied padding, the default drawer changes geometry, or the block-end safe area is lost or double-subtracted. | `audit:Drawer/theming` |+| AR6 | `DrawerDirection.test.tsx` DOM-direction and closed/entry parity suites plus exact-head Storybook RTL evidence | start/end; self-applied, inherited, and nested opposite `dir`; closed and opening transforms | Any effective DOM direction or local override moves the panel from a different edge than its logical placement, or closed and opening transforms diverge. | `audit:Drawer/accessibility` |+| 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` |Read from source, with no focused test yet:diff --git a/packages/core/src/BottomSheet/BottomSheet.ssr.test.tsx b/packages/core/src/BottomSheet/BottomSheet.ssr.test.tsxnew file mode 100644index 0000000000..bd90af95f1--- /dev/null+++ b/packages/core/src/BottomSheet/BottomSheet.ssr.test.tsx@@ -0,0 +1,187 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file BottomSheet.ssr.test.tsx+ * @input BottomSheet server markup and React hydration+ * @output Proves a BottomSheet open on the server renders closed until hydration+ * (no open styles, no `aria-modal`, the same markup as a closed one) and+ * opens in the render after hydration, without a hydration error+ * (`component:BottomSheet` FR17)+ * @position SSR acceptance test for BottomSheet+ */++import {act} from 'react';+import {fireEvent} from '@testing-library/react';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {createRoot, hydrateRoot} from 'react-dom/client';+import {renderToString} from 'react-dom/server';+import {BottomSheet} from './BottomSheet';+import {BottomSheetSwitcher} from './BottomSheetSwitcher';++beforeEach(() => {+ HTMLDialogElement.prototype.showModal = vi.fn(function (+ this: HTMLDialogElement,+ ) {+ this.setAttribute('open', '');+ });+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {+ this.removeAttribute('open');+ });+});++afterEach(() => {+ vi.restoreAllMocks();+ document.body.replaceChildren();+});++const tree = (isOpen: boolean) => (+ <BottomSheet isOpen={isOpen} onOpenChange={() => {}} label="Sort">+ <p>Sheet body</p>+ </BottomSheet>+);++/** The server markup's root `<dialog>`, parsed. */+function serverDialog(isOpen: boolean): HTMLDialogElement {+ const container = document.createElement('div');+ container.innerHTML = renderToString(tree(isOpen));+ const dialog = container.querySelector('dialog');+ if (dialog == null) {+ throw new Error('no <dialog> in the server markup');+ }+ return dialog;+}++describe('BottomSheet: open on the server (FR17)', () => {+ it('renders closed on the server: no aria-modal and the same classes as a closed BottomSheet', () => {+ const open = serverDialog(true);+ const closed = serverDialog(false);+ expect(open).not.toHaveAttribute('aria-modal');+ expect(open).not.toHaveAttribute('open');+ expect(open.className).toBe(closed.className);+ });++ it('opens modally in the render after hydration, without a hydration error', async () => {+ const container = document.createElement('div');+ container.innerHTML = renderToString(tree(true));+ document.body.appendChild(container);+ const logged = vi.spyOn(console, 'error');+ const recoverableErrors: unknown[] = [];+ let root!: ReturnType<typeof hydrateRoot>;+ await act(async () => {+ root = hydrateRoot(container, tree(true), {+ onRecoverableError: error => recoverableErrors.push(error),+ });+ });+ const dialog = container.querySelector('dialog');+ expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalledTimes(1);+ expect(dialog).toHaveAttribute('open');+ expect(dialog).toHaveAttribute('aria-modal', 'true');+ expect(dialog?.className).not.toBe(serverDialog(false).className);+ expect(recoverableErrors).toEqual([]);+ expect(logged).not.toHaveBeenCalled();+ await act(async () => root.unmount());+ });++ it('opens settled after hydration, without its rise, and animates a later open (spec:AST-013 FR13)', async () => {+ const entryMotion = (dialog: HTMLDialogElement) =>+ getComputedStyle(+ dialog.querySelector('.astryx-bottom-sheet') as HTMLElement,+ ).transitionDuration;+ // A client-opened BottomSheet plays its rise.+ const client = document.createElement('div');+ document.body.appendChild(client);+ const clientRoot = createRoot(client);+ await act(async () => clientRoot.render(tree(true)));+ const clientMotion = entryMotion(+ client.querySelector('dialog') as HTMLDialogElement,+ );+ expect(clientMotion).not.toBe('.01s');+ await act(async () => clientRoot.unmount());++ // One open on the server opens where it rests once hydrated.+ const container = document.createElement('div');+ container.innerHTML = renderToString(tree(true));+ document.body.appendChild(container);+ let root!: ReturnType<typeof hydrateRoot>;+ await act(async () => {+ root = hydrateRoot(container, tree(true));+ });+ const dialog = container.querySelector('dialog') as HTMLDialogElement;+ expect(entryMotion(dialog)).toBe('.01s');++ // Closed and opened again, it animates as a client open does.+ await act(async () => root.render(tree(false)));+ await act(async () => root.render(tree(true)));+ expect(+ entryMotion(container.querySelector('dialog') as HTMLDialogElement),+ ).toBe(clientMotion);+ await act(async () => root.unmount());+ });++ it('opens a sheet and a switcher flow nested in a server-open sheet settled too (spec:AST-013 FR13)', async () => {+ // While the host hydrates it reads as closed to the sheets inside it, so+ // each latches on its own request.+ const nested = (+ <BottomSheet isOpen onOpenChange={() => {}} label="Host">+ <BottomSheet isOpen onOpenChange={() => {}} label="Inner">+ <p>Inner body</p>+ </BottomSheet>+ <BottomSheetSwitcher activeSheet="step" onActiveSheetChange={() => {}}>+ <BottomSheet sheetId="step" label="Step">+ <p>Step body</p>+ </BottomSheet>+ </BottomSheetSwitcher>+ </BottomSheet>+ );+ const container = document.createElement('div');+ container.innerHTML = renderToString(nested);+ document.body.appendChild(container);+ let root!: ReturnType<typeof hydrateRoot>;+ await act(async () => {+ root = hydrateRoot(container, nested);+ });+ for (const label of ['Host', 'Inner', 'Step']) {+ const dialog = container.querySelector(+ `dialog[aria-label="${label}"]`,+ ) as HTMLDialogElement;+ expect(dialog).toHaveAttribute('aria-modal', 'true');+ expect(+ getComputedStyle(+ dialog.querySelector('.astryx-bottom-sheet') as HTMLElement,+ ).transitionDuration,+ ).toBe('.01s');+ }+ await act(async () => root.unmount());+ });++ it('releases the settled transition once the settled entry ends, so a drag settles with its usual glide', async () => {+ const panelDuration = (container: HTMLElement) =>+ getComputedStyle(+ container.querySelector('.astryx-bottom-sheet') as HTMLElement,+ ).transitionDuration;+ // A client-opened sheet's usual transition.+ const client = document.createElement('div');+ document.body.appendChild(client);+ const clientRoot = createRoot(client);+ await act(async () => clientRoot.render(tree(true)));+ const usual = panelDuration(client);+ await act(async () => clientRoot.unmount());++ const container = document.createElement('div');+ container.innerHTML = renderToString(tree(true));+ document.body.appendChild(container);+ let root!: ReturnType<typeof hydrateRoot>;+ await act(async () => {+ root = hydrateRoot(container, tree(true));+ });+ expect(panelDuration(container)).toBe('.01s');+ // The settled rise ends; the sheet stays open with its usual transition.+ fireEvent.transitionEnd(+ container.querySelector('.astryx-bottom-sheet') as HTMLElement,+ {propertyName: 'transform'},+ );+ expect(container.querySelector('dialog')).toHaveAttribute('open');+ expect(panelDuration(container)).toBe(usual);+ await act(async () => root.unmount());+ });+});diff --git a/packages/core/src/BottomSheet/BottomSheet.tsx b/packages/core/src/BottomSheet/BottomSheet.tsxindex 4be03d1c39..2547976f52 100644--- a/packages/core/src/BottomSheet/BottomSheet.tsx+++ b/packages/core/src/BottomSheet/BottomSheet.tsx@@ -87,6 +87,8 @@ import {type RefObject,type ReactNode,} from 'react';+import {useIsHydrating} from '../hooks/useIsHydrating';+import {useSettledOpen} from '../hooks/useSettledOpen';import * as stylex from '@stylexjs/stylex';import type {BaseProps} from '../BaseProps';import type {DialogPurpose} from '../Dialog';@@ -216,6 +218,13 @@ const styles = stylex.create({},},},+ // A sheet present on page load dims at once (spec:AST-013 FR13): the+ // collapse reduced motion uses, so the transition still ends.+ scrimSettled: {+ '::backdrop': {+ transitionDuration: '0.01s',+ },+ },/*** The dim leaves with the sheet, on a curve that matches.*@@ -423,7 +432,24 @@ function StandaloneBottomSheet({// state stays the consumer's; nothing here writes it.const host = use(BottomSheetHostContext);const isHostOpen = host?.isOpen ?? true;- const isOpen = isOpenProp && isHostOpen;+ // A sheet open on the server renders closed until hydration, and opens in+ // the render after it, the first one that can enter its native host: a+ // <dialog> painted open with aria-modal before it is modal claims a state it+ // does not have (FR17).+ const isHydrating = useIsHydrating();+ const isOpen = isOpenProp && isHostOpen && !isHydrating;+ // A sheet open on the server was present on page load, so it opens settled,+ // with no rise or fade-in; its later opens and closes animate as usual+ // (spec:AST-013 FR13). It latches on its own request, not its host's state:+ // a host sheet hydrating reads as closed to the sheets inside it.+ // The latch is released when the settled entry's transition ends, so a+ // drag's settle later in the same open glides as usual.+ const [settledOpen, releaseSettledOpen] = useSettledOpen(+ isOpenProp,+ isOpen,+ false,+ );+ const isEntrySettled = settledOpen && isOpen;// Presentation outlives the controlled prop: a closing sheet stays mounted// and in its native host through its exit, and only its motion completion// (or a replace finishing) clears it. The open flip is derived during@@ -796,6 +822,7 @@ function StandaloneBottomSheet({// one. The backdrop is not a descendant and stays put....stackPositionerStyles(stackView),hasScrim && styles.scrim,+ hasScrim && isEntrySettled && styles.scrimSettled,hasScrim && isExiting && styles.scrimClosing,!hasScrim && styles.dialogNonModal,)}@@ -823,6 +850,8 @@ function StandaloneBottomSheet({{...props}ref={ref}state={panelState}+ isEntrySettled={isEntrySettled}+ onEntrySettled={releaseSettledOpen}isOpenRequested={isOpen}height={height}label={label}@@ -897,6 +926,8 @@ function SwitcherBottomSheetItem({onDialogCancel,onDialogClick,onDialogKeyDown,+ settledSheet,+ releaseSettledSheet,} = switcher;const hasValidSheetId = typeof sheetId === 'string' && sheetId.length > 0;const phase = hasValidSheetId ? getSheetPhase(sheetId) : 'hidden';@@ -911,6 +942,9 @@ function SwitcherBottomSheetItem({phase === 'fading' ||phase === 'exiting';const isPresented = phase !== 'hidden';+ // The step open on the server opens settled (spec:AST-013 FR13).+ const isEntrySettled =+ hasValidSheetId && isPresented && settledSheet === sheetId;const isTopSheet = phase === 'active' || phase === 'entering';const ownsScrim = hasValidSheetId && isScrimOwner(sheetId);// The flow is one level of the bottom-sheet stack; a sheet outside the flow@@ -1108,6 +1142,7 @@ function SwitcherBottomSheetItem({styles.dialog,isPresented && styles.dialogOpen,hasScrim && styles.scrim,+ hasScrim && isEntrySettled && styles.scrimSettled,hasScrim && ownsScrim && isFlowClosing && styles.scrimClosing,!hasScrim && styles.dialogNonModalItem,!hasScrim && isTopSheet && styles.dialogNonModalItemTop,@@ -1160,6 +1195,8 @@ function SwitcherBottomSheetItem({{...props}ref={ref}state={panelState}+ isEntrySettled={isEntrySettled}+ onEntrySettled={releaseSettledSheet}isOpenRequested={hasValidSheetId && activeSheet === sheetId}height={height}label={label}diff --git a/packages/core/src/BottomSheet/BottomSheetPanel.tsx b/packages/core/src/BottomSheet/BottomSheetPanel.tsxindex b5fe330d10..1a3113917b 100644--- a/packages/core/src/BottomSheet/BottomSheetPanel.tsx+++ b/packages/core/src/BottomSheet/BottomSheetPanel.tsx@@ -200,6 +200,11 @@ const styles = stylex.create({transitionTimingFunction: easeVars['--ease-standard'],willChange: 'transform, opacity',},+ // A sheet present on page load opens where it rests (spec:AST-013 FR13):+ // the collapse reduced motion uses, so the transition still ends.+ sheetSettled: {+ transitionDuration: '0.01s',+ },/*** The exit is its own motion, not the entrance played backwards.*@@ -358,6 +363,16 @@ interface BottomSheetPanelProps extends BaseProps<HTMLDivElement> {/** Ref forwarded to the visual sheet panel. */ref?: React.Ref<HTMLDivElement>;state: BottomSheetPanelState;+ /**+ * Whether the sheet was open on page load: it then opens where it rests,+ * with no entry motion (spec:AST-013 FR13).+ */+ isEntrySettled?: boolean;+ /**+ * Called when the settled entry's transition ends, so the host can release+ * it and later motion in the same open (a drag's settle) animates as usual.+ */+ onEntrySettled?: () => void;/*** The host's controlled open state — false as soon as the host has taken* a close, true while it is open or has refused one — distinct from@@ -521,6 +536,9 @@ export function BottomSheetPanel({style,tabIndex,xstyle,+ isEntrySettled = false,+ onEntrySettled,+ onTransitionEnd,isSwipeDismissAllowed = true,isPageScrollLocked = false,onDismiss,@@ -850,6 +868,12 @@ export function BottomSheetPanel({{...props}ref={setElement}tabIndex={tabIndex ?? -1}+ onTransitionEnd={event => {+ onTransitionEnd?.(event);+ if (isEntrySettled && event.target === event.currentTarget) {+ onEntrySettled?.();+ }+ }}{...mergeProps(themeProps('bottom-sheet'),stylex.props(@@ -862,6 +886,7 @@ export function BottomSheetPanel({isClosing && isCrossFade && styles.sheetClosingCrossFade,isFading && styles.sheetFading,isInactive && styles.sheetInactive,+ isEntrySettled && styles.sheetSettled,xstyle,),className,diff --git a/packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx b/packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsxindex 4e17547d60..4c512f5535 100644--- a/packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx+++ b/packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx@@ -1562,10 +1562,11 @@ describe('BottomSheetSwitcher', () => {expect(withId()).toEqual([dialogs[1]]);});- it("renders the switcher id and data-testid once, on the active sheet's dialog, in the server markup of a flow that mounts open", () => {- // The active sheet is known from props, so the host needs no commit:- // server markup carries both attributes on that sheet's dialog, once.- const markup = renderToString(+ it('renders a flow that mounts open closed in server markup, then opens its active sheet, with the switcher id once, after hydration (component:BottomSheet FR17)', () => {+ // Nothing can enter a native host before hydration, so a flow with an+ // active sheet renders as a closed one on the server: no dialog open,+ // none claiming aria-modal, the id on no element.+ const flow = (<BottomSheetSwitcherid="checkout"data-testid="checkout-flow"@@ -1577,18 +1578,40 @@ describe('BottomSheetSwitcher', () => {<BottomSheet sheetId="confirm" label="Confirm">Content</BottomSheet>- </BottomSheetSwitcher>,+ </BottomSheetSwitcher>);+ const markup = renderToString(flow);const dialogs = markup.match(/<dialog\b[^>]*>/g) ?? [];expect(dialogs).toHaveLength(2);- expect(markup.match(/id="checkout"/g)).toHaveLength(1);- expect(markup.match(/data-testid="checkout-flow"/g)).toHaveLength(1);- const host = dialogs.find(tag => tag.includes('id="checkout"'));- expect(host).toContain('aria-label="Confirm"');- expect(host).toContain('data-testid="checkout-flow"');+ expect(markup).not.toMatch(/<dialog[^>]*\sopen/);+ expect(markup).not.toContain('aria-modal');+ expect(markup.match(/id="checkout"/g) ?? []).toHaveLength(0);++ // Hydrating opens the active sheet in the render after it, with the+ // id and data-testid on its dialog, once.+ const container = document.createElement('div');+ container.innerHTML = markup;+ document.body.appendChild(container);+ let root!: ReturnType<typeof hydrateRoot>;+ act(() => {+ root = hydrateRoot(container, flow);+ });+ const withId = container.querySelectorAll('[id="checkout"]');+ expect(withId).toHaveLength(1);+ expect(withId[0]).toHaveAttribute('aria-label', 'Confirm');+ expect(withId[0]).toHaveAttribute('data-testid', 'checkout-flow');+ expect(withId[0]).toHaveAttribute('aria-modal', 'true');+ // Present on page load, the active sheet opens where it rests+ // (spec:AST-013 FR13).expect(- dialogs.find(tag => tag.includes('aria-label="Details"')),- ).not.toContain('id=');+ getComputedStyle(+ withId[0].querySelector('.astryx-bottom-sheet') as HTMLElement,+ ).transitionDuration,+ ).toBe('.01s');+ // The open flow holds the sheet stack and the page's scroll lock; leave+ // nothing behind for the next test.+ act(() => root.unmount());+ container.remove();});it('renders every sheet dialog closed in server markup, with the switcher id on no element until the first commit', () => {diff --git a/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx b/packages/core/src/BottomSheet/BottomSheetSwitcher.tsxindex ffb14203ce..12f76cbc71 100644--- a/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx+++ b/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx@@ -87,6 +87,8 @@ import {type ReactNode,type SyntheticEvent,} from 'react';+import {useIsHydrating} from '../hooks/useIsHydrating';+import {useSettledOpen} from '../hooks/useSettledOpen';import * as stylex from '@stylexjs/stylex';import type {BaseProps} from '../BaseProps';import type {DialogPurpose} from '../Dialog';@@ -250,9 +252,11 @@ function takeOverScrim(dialog: HTMLDialogElement, opacity: number): void {* by one state value that names the open step; closing the top sheet and* opening the next in the same update, from inside the open step, runs the* same replace handoff (see BottomSheet, "Replacing a sheet"). Keeps working until a future minor- * release removes it: on its own as released (plus two fixes: a toast raised- * from a step now renders above the flow and can be pressed, and reduced motion- * follows design:reduced-motion), as one stack level when stacked.+ * release removes it: on its own as released (plus three fixes: a toast raised+ * from a step now renders above the flow and can be pressed, reduced motion+ * follows design:reduced-motion, and a flow whose active sheet is set on the+ * server renders closed until hydration, then opens that sheet settled), as+ * one stack level when stacked.*/export interface BottomSheetSwitcherProps extends BaseProps<HTMLDialogElement> {/**@@ -309,10 +313,11 @@ export interface BottomSheetSwitcherProps extends BaseProps<HTMLDialogElement> {* `sheetId` and no switcher, for modal and `hasScrim={false}` flows alike; a* step changed from outside the flow's sheets closes and opens with the* sheets' own motion. The switcher keeps working until a future- * minor release removes it: on its own as released (plus two fixes: a toast- * raised from a step now renders above the flow and can be pressed, and reduced- * motion follows design:reduced-motion), and as one level of the stack when- * stacked with other sheets.+ * minor release removes it: on its own as released (plus three fixes: a toast+ * raised from a step now renders above the flow and can be pressed, reduced+ * motion follows design:reduced-motion, and a flow whose active sheet is set+ * on the server renders closed until hydration, then opens that sheet+ * settled), and as one level of the stack when stacked with other sheets.*/export function BottomSheetSwitcher({activeSheet: activeSheetProp,@@ -335,7 +340,21 @@ export function BottomSheetSwitcher({// for it; with the host closed the flow simply reads as closed.const host = use(BottomSheetHostContext);const isHostOpen = host?.isOpen ?? true;- const activeSheet = isHostOpen ? activeSheetProp : null;+ // A flow with an active sheet on the server reads as closed until+ // hydration, and opens in the render after it, the first one that can enter+ // its native host: a <dialog> painted open with aria-modal before it is+ // modal claims a state it does not have (`component:BottomSheet` FR17).+ const isHydrating = useIsHydrating();+ const activeSheet = isHostOpen && !isHydrating ? activeSheetProp : null;+ // The step active on the server was present on page load, so it opens+ // settled, with no entry motion; the first change of step animates as+ // usual (spec:AST-013 FR13). It latches on the flow's own request: a host+ // sheet hydrating reads as closed to a flow inside it.+ const [settledSheet, releaseSettledSheet] = useSettledOpen(+ activeSheetProp,+ activeSheet,+ null,+ );// Every sheet host applies the switcher's dialog surface to its own dialog.const dialogProps = useShallowStable<BottomSheetSwitcherDialogProps>({...restDialogProps,@@ -1033,6 +1052,8 @@ export function BottomSheetSwitcher({const contextValue = useMemo<BottomSheetSwitcherContextValue>(() => ({activeSheet,+ settledSheet,+ releaseSettledSheet,hasScrim,onActiveSheetChange,getSheetPhase,@@ -1075,6 +1096,8 @@ export function BottomSheetSwitcher({registerSheetDialog,registerSheetElement,registerSheetPurpose,+ releaseSettledSheet,+ settledSheet,stackView,],);diff --git a/packages/core/src/BottomSheet/BottomSheetSwitcherContext.ts b/packages/core/src/BottomSheet/BottomSheetSwitcherContext.tsindex 9d594a74b0..51b0b4ef6c 100644--- a/packages/core/src/BottomSheet/BottomSheetSwitcherContext.ts+++ b/packages/core/src/BottomSheet/BottomSheetSwitcherContext.ts@@ -50,6 +50,14 @@ export type BottomSheetSwitcherDialogProps = Omit<export interface BottomSheetSwitcherContextValue {activeSheet: string | null;+ /**+ * The sheet that was active on page load, until the active sheet first+ * changes: it opens where it rests, with no entry motion+ * (spec:AST-013 FR13).+ */+ settledSheet: string | null;+ /** Releases `settledSheet` once its settled entry's transition ends. */+ releaseSettledSheet: () => void;hasScrim: boolean;onActiveSheetChange: (sheetId: string | null) => void;getSheetPhase: (sheetId: string) => BottomSheetSwitcherPhase;diff --git a/packages/core/src/Dialog/Dialog.ssr.test.tsx b/packages/core/src/Dialog/Dialog.ssr.test.tsxnew file mode 100644index 0000000000..f530f63b74--- /dev/null+++ b/packages/core/src/Dialog/Dialog.ssr.test.tsx@@ -0,0 +1,116 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Dialog.ssr.test.tsx+ * @input Dialog server markup and React hydration+ * @output Proves a Dialog open on the server renders closed until hydration+ * (no open styles, no `aria-modal`, the same markup as a closed one) and+ * opens in the render after hydration, without a hydration error+ * (`component:Dialog` FR8)+ * @position SSR acceptance test for Dialog+ */++import {act} from 'react';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {createRoot, hydrateRoot} from 'react-dom/client';+import {renderToString} from 'react-dom/server';+import {Dialog} from './Dialog';++beforeEach(() => {+ HTMLDialogElement.prototype.showModal = vi.fn(function (+ this: HTMLDialogElement,+ ) {+ this.setAttribute('open', '');+ });+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {+ this.removeAttribute('open');+ });+});++afterEach(() => {+ vi.restoreAllMocks();+ document.body.replaceChildren();+});++const tree = (isOpen: boolean) => (+ <Dialog isOpen={isOpen} onOpenChange={() => {}} aria-label="Edit">+ <p>Dialog body</p>+ </Dialog>+);++/** The server markup's root `<dialog>`, parsed. */+function serverDialog(isOpen: boolean): HTMLDialogElement {+ const container = document.createElement('div');+ container.innerHTML = renderToString(tree(isOpen));+ const dialog = container.querySelector('dialog');+ if (dialog == null) {+ throw new Error('no <dialog> in the server markup');+ }+ return dialog;+}++describe('Dialog: open on the server (FR8)', () => {+ it('renders closed on the server: no aria-modal and the same classes as a closed Dialog', () => {+ const open = serverDialog(true);+ const closed = serverDialog(false);+ expect(open).not.toHaveAttribute('aria-modal');+ expect(open).not.toHaveAttribute('open');+ expect(open.className).toBe(closed.className);+ });++ it('opens modally in the render after hydration, without a hydration error', async () => {+ const container = document.createElement('div');+ container.innerHTML = renderToString(tree(true));+ document.body.appendChild(container);+ const logged = vi.spyOn(console, 'error');+ const recoverableErrors: unknown[] = [];+ let root!: ReturnType<typeof hydrateRoot>;+ await act(async () => {+ root = hydrateRoot(container, tree(true), {+ onRecoverableError: error => recoverableErrors.push(error),+ });+ });+ const dialog = container.querySelector('dialog');+ expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalledTimes(1);+ expect(dialog).toHaveAttribute('open');+ expect(dialog).toHaveAttribute('aria-modal', 'true');+ expect(dialog?.className).not.toBe(serverDialog(false).className);+ expect(recoverableErrors).toEqual([]);+ expect(logged).not.toHaveBeenCalled();+ await act(async () => root.unmount());+ });++ it('opens settled after hydration, without its entry animation, and animates a later open (spec:AST-013 FR13)', async () => {+ const entryMotion = (dialog: HTMLDialogElement) =>+ getComputedStyle(dialog).animationName;+ // A client-opened Dialog plays its entry animation.+ const client = document.createElement('div');+ document.body.appendChild(client);+ const clientRoot = createRoot(client);+ await act(async () => clientRoot.render(tree(true)));+ const clientMotion = entryMotion(+ client.querySelector('dialog') as HTMLDialogElement,+ );+ expect(clientMotion).not.toBe('none');+ await act(async () => clientRoot.unmount());++ // One open on the server opens where it rests once hydrated.+ const container = document.createElement('div');+ container.innerHTML = renderToString(tree(true));+ document.body.appendChild(container);+ let root!: ReturnType<typeof hydrateRoot>;+ await act(async () => {+ root = hydrateRoot(container, tree(true));+ });+ const dialog = container.querySelector('dialog') as HTMLDialogElement;+ expect(entryMotion(dialog)).toBe('none');++ // Closed and opened again, it animates as a client open does.+ await act(async () => root.render(tree(false)));+ await act(async () => root.render(tree(true)));+ expect(+ entryMotion(container.querySelector('dialog') as HTMLDialogElement),+ ).toBe(clientMotion);+ await act(async () => root.unmount());+ });+});diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsxindex 97592f8164..a0839b346d 100644--- a/packages/core/src/Dialog/Dialog.tsx+++ b/packages/core/src/Dialog/Dialog.tsx@@ -41,6 +41,8 @@ import {useRef,type ReactNode,} from 'react';+import {useIsHydrating} from '../hooks/useIsHydrating';+import {useSettledOpen} from '../hooks/useSettledOpen';import type {BaseProps} from '../BaseProps';import * as stylex from '@stylexjs/stylex';import {useScrollLock} from '../hooks/useScrollLock';@@ -226,6 +228,10 @@ const styles = stylex.create({'none',},},+ // A dialog present on page load opens where it rests (spec:AST-013 FR13).+ openSettled: {+ animationName: 'none',+ },// Backdrop using ::backdrop pseudo-elementbackdrop: {'::backdrop': {@@ -463,7 +469,7 @@ export interface DialogProps extends BaseProps<HTMLDialogElement> {* ```*/export function Dialog({- isOpen,+ isOpen: isOpenProp,isInline = false,onOpenChange,width = 400,@@ -479,6 +485,17 @@ export function Dialog({ref,...props}: DialogProps) {+ // A modal dialog open on the server renders closed until hydration, and+ // opens in the render after it, the first one that can call showModal(): a+ // <dialog> painted open with aria-modal before it is modal claims a state it+ // does not have, over a live page (FR8). An inline dialog is not modal and+ // renders as it is.+ const isHydrating = useIsHydrating();+ const isOpen = isOpenProp && (isInline || !isHydrating);+ // A dialog open on the server was present on page load, so it opens settled,+ // with no entry motion; its later opens animate as usual (spec:AST-013 FR13).+ const [settledOpen] = useSettledOpen(isOpenProp && !isInline, isOpen, false);+ const opensSettled = settledOpen && isOpen;// When no explicit padding prop, use theme default (--astryx-dialog-padding)const useThemeDefault = padding == null;const effectivePadding = padding ?? 4;@@ -826,6 +843,7 @@ export function Dialog({})(),isFullscreen && styles.fullscreen,isFullscreen && isOpen && styles.fullscreenOpen,+ opensSettled && styles.openSettled,xstyle,),className,@@ -833,7 +851,7 @@ export function Dialog({)}onClick={chainEventHandlers(handleClick, onClickProp)}onCancel={handleCancel}- aria-modal="true"+ aria-modal={isHydrating ? undefined : 'true'}// The default aria-labelledby (from a DialogHeader title) is set// imperatively in `attachDialog`; a consumer-provided aria-labelledby// flows through {...safeProps} above and wins.diff --git a/packages/core/src/Drawer/Drawer.ssr.test.tsx b/packages/core/src/Drawer/Drawer.ssr.test.tsxnew file mode 100644index 0000000000..bd5b2d7fcc--- /dev/null+++ b/packages/core/src/Drawer/Drawer.ssr.test.tsx@@ -0,0 +1,116 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Drawer.ssr.test.tsx+ * @input Drawer server markup and React hydration+ * @output Proves a Drawer open on the server renders closed until hydration+ * (no open styles, no `aria-modal`, the same markup as a closed one) and+ * opens in the render after hydration, without a hydration error+ * (`component:Drawer` FR17)+ * @position SSR acceptance test for Drawer+ */++import {act} from 'react';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {createRoot, hydrateRoot} from 'react-dom/client';+import {renderToString} from 'react-dom/server';+import {Drawer} from './Drawer';++beforeEach(() => {+ HTMLDialogElement.prototype.showModal = vi.fn(function (+ this: HTMLDialogElement,+ ) {+ this.setAttribute('open', '');+ });+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {+ this.removeAttribute('open');+ });+});++afterEach(() => {+ vi.restoreAllMocks();+ document.body.replaceChildren();+});++const tree = (isOpen: boolean) => (+ <Drawer isOpen={isOpen} onOpenChange={() => {}} label="Filters">+ <p>Drawer body</p>+ </Drawer>+);++/** The server markup's root `<dialog>`, parsed. */+function serverDialog(isOpen: boolean): HTMLDialogElement {+ const container = document.createElement('div');+ container.innerHTML = renderToString(tree(isOpen));+ const dialog = container.querySelector('dialog');+ if (dialog == null) {+ throw new Error('no <dialog> in the server markup');+ }+ return dialog;+}++describe('Drawer: open on the server (FR17)', () => {+ it('renders closed on the server: no aria-modal and the same classes as a closed Drawer', () => {+ const open = serverDialog(true);+ const closed = serverDialog(false);+ expect(open).not.toHaveAttribute('aria-modal');+ expect(open).not.toHaveAttribute('open');+ expect(open.className).toBe(closed.className);+ });++ it('opens modally in the render after hydration, without a hydration error', async () => {+ const container = document.createElement('div');+ container.innerHTML = renderToString(tree(true));+ document.body.appendChild(container);+ const logged = vi.spyOn(console, 'error');+ const recoverableErrors: unknown[] = [];+ let root!: ReturnType<typeof hydrateRoot>;+ await act(async () => {+ root = hydrateRoot(container, tree(true), {+ onRecoverableError: error => recoverableErrors.push(error),+ });+ });+ const dialog = container.querySelector('dialog');+ expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalledTimes(1);+ expect(dialog).toHaveAttribute('open');+ expect(dialog).toHaveAttribute('aria-modal', 'true');+ expect(dialog?.className).not.toBe(serverDialog(false).className);+ expect(recoverableErrors).toEqual([]);+ expect(logged).not.toHaveBeenCalled();+ await act(async () => root.unmount());+ });++ it('opens settled after hydration, without its slide-in, and animates a later open (spec:AST-013 FR13)', async () => {+ const entryMotion = (dialog: HTMLDialogElement) =>+ getComputedStyle(dialog).transitionDuration;+ // A client-opened Drawer plays its slide-in.+ const client = document.createElement('div');+ document.body.appendChild(client);+ const clientRoot = createRoot(client);+ await act(async () => clientRoot.render(tree(true)));+ const clientMotion = entryMotion(+ client.querySelector('dialog') as HTMLDialogElement,+ );+ expect(clientMotion).not.toBe('.01s');+ await act(async () => clientRoot.unmount());++ // One open on the server opens where it rests once hydrated.+ const container = document.createElement('div');+ container.innerHTML = renderToString(tree(true));+ document.body.appendChild(container);+ let root!: ReturnType<typeof hydrateRoot>;+ await act(async () => {+ root = hydrateRoot(container, tree(true));+ });+ const dialog = container.querySelector('dialog') as HTMLDialogElement;+ expect(entryMotion(dialog)).toBe('.01s');++ // Closed and opened again, it animates as a client open does.+ await act(async () => root.render(tree(false)));+ await act(async () => root.render(tree(true)));+ expect(+ entryMotion(container.querySelector('dialog') as HTMLDialogElement),+ ).toBe(clientMotion);+ await act(async () => root.unmount());+ });+});diff --git a/packages/core/src/Drawer/Drawer.tsx b/packages/core/src/Drawer/Drawer.tsxindex 135e500d66..8ad2660408 100644--- a/packages/core/src/Drawer/Drawer.tsx+++ b/packages/core/src/Drawer/Drawer.tsx@@ -60,6 +60,8 @@*/import {useCallback, useRef, useState, type ReactNode} from 'react';+import {useIsHydrating} from '../hooks/useIsHydrating';+import {useSettledOpen} from '../hooks/useSettledOpen';import * as stylex from '@stylexjs/stylex';import type {BaseProps} from '../BaseProps';import {@@ -203,6 +205,14 @@ const styles = stylex.create({},},},+ // A drawer present on page load opens where it rests (spec:AST-013 FR13):+ // the collapse reduced motion uses, so the transition still ends.+ openSettled: {+ transitionDuration: '0.01s',+ '::backdrop': {+ transitionDuration: '0.01s',+ },+ },// Scrim via the browser's ::backdrop pseudo-element (top layer).scrim: {'::backdrop': {@@ -426,7 +436,7 @@ export interface DrawerProps extends BaseProps<HTMLDialogElement> {* ```*/export function Drawer({- isOpen,+ isOpen: isOpenProp,onOpenChange,side = 'end',width = 400,@@ -444,6 +454,17 @@ export function Drawer({ref,...props}: DrawerProps) {+ // A drawer open on the server renders closed until hydration, and opens in+ // the render after it, the first one that can enter its native host: a+ // <dialog> painted open with aria-modal before it is modal claims a state it+ // does not have (FR17).+ const isHydrating = useIsHydrating();+ const isOpen = isOpenProp && !isHydrating;+ // A drawer open on the server was present on page load, so it opens settled,+ // with no slide-in; its later opens and closes animate as usual+ // (spec:AST-013 FR13).+ const [settledOpen] = useSettledOpen(isOpenProp, isOpen, false);+ const opensSettled = settledOpen && isOpen;const dialogRef = useRef<HTMLDialogElement>(null);const {containerRef: focusTrapRef} = useFocusTrap<HTMLDialogElement>({isActive: isOpen && hasScrim,@@ -567,6 +588,7 @@ export function Drawer({isOpen && sideOpenStyle,hasScrim && styles.scrim,hasScrim && isOpen && styles.scrimOpen,+ opensSettled && styles.openSettled,xstyle,),className,@@ -575,7 +597,7 @@ export function Drawer({{...safeProps}popover={hasScrim ? undefined : 'manual'}aria-label={label}- aria-modal={hasScrim ? 'true' : undefined}+ aria-modal={hasScrim && !isHydrating ? 'true' : undefined}{...(purpose === 'required' && hasScrim? {role: 'alertdialog'}: undefined)}diff --git a/packages/core/src/hooks/useSettledOpen.ts b/packages/core/src/hooks/useSettledOpen.tsnew file mode 100644index 0000000000..b7fbdd1201--- /dev/null+++ b/packages/core/src/hooks/useSettledOpen.ts@@ -0,0 +1,51 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useSettledOpen.ts+ * @input Uses React useState and useIsHydrating+ * @output Exports useSettledOpen (internal; not re-exported from hooks/index.ts)+ * @position Internal utility; read by Dialog, Drawer, BottomSheet and+ * BottomSheetSwitcher so an overlay open on the server opens settled after+ * hydration (spec:AST-013 FR13)+ *+ * An overlay open on the server renders closed until hydration, since nothing+ * can make it modal before then. It was still present on page load, so the+ * open right after hydration plays no entry motion. This hook remembers what+ * was open on the server (an open flag, or a switcher's active step) until+ * that first stops being in effect after hydration; later opens animate.+ */++import {useCallback, useState} from 'react';+import {useIsHydrating} from './useIsHydrating';++/**+ * Returns `requested` as it was on the server and in the hydrating render,+ * until `current` first differs from it after hydration or the caller+ * releases it; `none` otherwise. Compare the result with `current` to know+ * whether the open in effect is the settled one. The second element releases+ * it: an overlay whose settled entry still runs a transition (a sheet's+ * collapsed rise) calls it when that transition ends, so motion within the+ * same open (a drag's settle) animates as usual.+ *+ * @param requested What the caller asks to have open (the `isOpen` prop, or+ * the switcher's `activeSheet` prop).+ * @param current What is open in this render, once hydrated.+ * @param none The value meaning nothing is open (`false` or `null`).+ */+export function useSettledOpen<T>(+ requested: T,+ current: T,+ none: T,+): [settled: T, release: () => void] {+ const isHydrating = useIsHydrating();+ const [settled, setSettled] = useState<T>(() =>+ isHydrating ? requested : none,+ );+ if (settled !== none && !isHydrating && current !== settled) {+ setSettled(none);+ }+ const release = useCallback(() => setSettled(none), [none]);+ return [settled, release];+}