An open source design system that's fully customizable and agent ready
TypeScript
feat(core): BottomSheetSwitcher presents each sheet in its own native dialog (#7720)
Xinzi Zhou36515dccd11c
diff --git a/.changeset/bottom-sheet-switcher-anatomy-sheet-dialogs.md b/.changeset/bottom-sheet-switcher-anatomy-sheet-dialogs.mdnew file mode 100644index 0000000000..6d4c6c8538--- /dev/null+++ b/.changeset/bottom-sheet-switcher-anatomy-sheet-dialogs.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[docs] `BottomSheetSwitcher` anatomy names its host part `Sheet dialogs` — one native dialog per child sheet, the one hosting the active sheet carrying the flow's ref, id, modality, and dismissal — instead of `Shared dialog`.++@imdreamrunnerdiff --git a/.changeset/bottom-sheet-switcher-dialog-per-sheet.md b/.changeset/bottom-sheet-switcher-dialog-per-sheet.mdnew file mode 100644index 0000000000..3caa7bdab3--- /dev/null+++ b/.changeset/bottom-sheet-switcher-dialog-per-sheet.md@@ -0,0 +1,9 @@+---+'@astryxdesign/core': patch+---++[feat] `BottomSheetSwitcher` presents each step in its own native `<dialog>`. Every child `BottomSheet` owns a dialog exactly like a standalone sheet; the switcher presents the selected sheet's dialog (`showModal()` with a scrim, `show()` without), keeps the previous sheet's dialog open and inert beneath the entering one through the handoff, and closes it once its panel has faded. One backdrop paints at a time: the retained dialog keeps the scrim until it closes, then the new dialog takes it over without a fade, so the page is never dimmed twice and the previous panel is never dimmed. Focus containment is the browser's own modal-dialog containment (as for `Dialog`) instead of a script trap; the page scroll lock (the shared body lock, held once by the switcher for the whole modal flow, through a handoff and until after the exit), Escape and platform-close routing, `purpose` dismissal rules, and focus return to the opener are unchanged. Going back to a sheet whose dialog is still fading closes and re-presents that dialog so the interactive sheet is the topmost layer again.++Public props, defaults, and exports are unchanged. Two observable details move with the structure. The switcher's `ref` resolves to the dialog hosting the flow — the active sheet's dialog, which changes on a handoff; the exiting sheet's through its exit; and, while the flow is closed, the dialog that hosted it last (or the first mounted sheet's) — instead of one persistent element; it is never `null` while a sheet is mounted, from the first commit on, and a callback ref's returned cleanup runs on each detach. `onCancel` and the forwarded dialog props apply to each sheet's dialog (a `role` given to the switcher included, except on a `required` step, which is an `alertdialog` as before), except `id` and `data-testid`, which render once, on the dialog the `ref` resolves to, from the first commit's synchronous re-render on; server markup of a flow that mounts closed carries them on no element (the shared dialog carried them). A non-modal flow orders its sheet dialogs inside a switcher-owned isolated wrapper that carries the one overlay value the shared dialog carried before.++@imdreamrunnerdiff --git a/.changeset/cli-bottom-sheet-switcher-template-docs.md b/.changeset/cli-bottom-sheet-switcher-template-docs.mdnew file mode 100644index 0000000000..87910e6d73--- /dev/null+++ b/.changeset/cli-bottom-sheet-switcher-template-docs.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[docs] The `BottomSheetSwitcher` template docs (`BottomSheetSwitcherShowcase`, `BottomSheetSwitcherReviewFlow`) describe each step as its own native dialog under one scrim, as the component now renders, instead of "one shared dialog".++@imdreamrunnerdiff --git a/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.doc.mjs b/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.doc.mjsindex 9556267b71..fbc7974c0e 100644--- a/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.doc.mjs@@ -7,7 +7,7 @@ export const doc = {name: 'Bottom Sheet Switcher — Review flow',displayName: 'Bottom Sheet Switcher — Review flow',description:- 'A two-step form flow that lets a person review settings, confirm them, or move back without replacing the shared dialog.',+ 'A two-step form flow that lets a person review settings, confirm them, or move back, each step in its own native dialog under one scrim.',isReady: true,isShowcase: false,aspectRatio: 3 / 4,diff --git a/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.doc.mjs b/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.doc.mjsindex 878f6e9209..06bd27c387 100644--- a/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.doc.mjs@@ -7,7 +7,7 @@ export const doc = {name: 'Bottom Sheet Switcher',displayName: 'Bottom Sheet Switcher',description:- 'A three-step flow that transitions between content-hugging sheets of different heights inside one shared dialog.',+ 'A three-step flow that transitions between content-hugging sheets of different heights, each step in its own native dialog with one scrim handed between them.',isReady: true,isShowcase: true,aspectRatio: 3 / 4,diff --git a/packages/core/src/BottomSheet/BottomSheet.doc.mjs b/packages/core/src/BottomSheet/BottomSheet.doc.mjsindex baef1d9493..00b9e05937 100644--- a/packages/core/src/BottomSheet/BottomSheet.doc.mjs+++ b/packages/core/src/BottomSheet/BottomSheet.doc.mjs@@ -95,7 +95,7 @@ export const docs = {derived: [{property: 'padding', expand: 'container'}],},description:- "A mobile touch sheet that rises from the bottom edge, with animated entrance and exit, a grab handle, optional drag-to-resize snap points, and purpose-controlled dismissal. Like Dialog, it is a padded container: content starts at the theme's bottom-sheet padding (--spacing-4 by default), and a lone Section child or bleed children such as Table and Divider align against it. A standalone sheet owns a native <dialog>; inside BottomSheetSwitcher it renders a panel in the switcher's shared dialog. In both modes, ref and shared DOM props target the visual panel <div>.",+ "A mobile touch sheet that rises from the bottom edge, with animated entrance and exit, a grab handle, optional drag-to-resize snap points, and purpose-controlled dismissal. Like Dialog, it is a padded container: content starts at the theme's bottom-sheet padding (--spacing-4 by default), and a lone Section child or bleed children such as Table and Divider align against it. A sheet always owns a native <dialog>; inside BottomSheetSwitcher the switcher presents and closes that dialog as the flow moves between steps. In both modes, ref and shared DOM props target the visual panel <div>.",props: [{name: 'isOpen',@@ -165,7 +165,7 @@ export const docs = {name: 'hasScrim',type: 'boolean',description:- "For a standalone BottomSheet, whether to render a scrim, the semi-transparent overlay that covers and blocks the background. true (default) uses showModal(): top layer, focus trap, ::backdrop scrim, body scroll lock, and tap-scrim-to-dismiss when purpose='info', with the background inert. false uses show() with no scrim, leaving the page behind interactive and scrollable. For a multi-step flow, configure hasScrim on BottomSheetSwitcher instead; it owns one shared dialog across every child.",+ "For a standalone BottomSheet, whether to render a scrim, the semi-transparent overlay that covers and blocks the background. true (default) uses showModal(): top layer, native focus containment, ::backdrop scrim, body scroll lock, and tap-scrim-to-dismiss when purpose='info', with the background inert. false uses show() with no scrim, leaving the page behind interactive and scrollable. For a multi-step flow, configure hasScrim on BottomSheetSwitcher instead; it applies to every child's dialog.",default: 'true',},],diff --git a/packages/core/src/BottomSheet/BottomSheet.spec.md b/packages/core/src/BottomSheet/BottomSheet.spec.mdindex 175e227be7..a91c855c5e 100644--- a/packages/core/src/BottomSheet/BottomSheet.spec.md+++ b/packages/core/src/BottomSheet/BottomSheet.spec.md@@ -66,9 +66,7 @@ Consumer migration instructions belong in consumer docs and release notes.`architecture:container-padding`.- Standalone sheet presentation, including its optional native-dialog Scrim.- The native dialog every sheet renders, standalone or switcher-managed- (`component:BottomSheetSwitcher` DEC-1). Implementation gap: a- switcher-managed sheet renders a panel inside the switcher's one shared- dialog and owns no dialog of its own.+ (`component:BottomSheetSwitcher` DEC-1).**Does not own / non-goals**@@ -107,8 +105,7 @@ in `BottomSheet.doc.mjs`.without a Scrim.- A switcher-managed sheet renders the same panel anatomy in its own dialog whileBottomSheetSwitcher coordinates that dialog's lifecycle and the flow's one Scrim- (`component:BottomSheetSwitcher` DEC-1). Implementation gap: the panel- renders inside the switcher's one shared dialog.+ (`component:BottomSheetSwitcher` DEC-1).### Transformation and precedence orderdiff --git a/packages/core/src/BottomSheet/BottomSheet.tsx b/packages/core/src/BottomSheet/BottomSheet.tsxindex c091002eab..3ecca09133 100644--- a/packages/core/src/BottomSheet/BottomSheet.tsx+++ b/packages/core/src/BottomSheet/BottomSheet.tsx@@ -10,10 +10,22 @@** BottomSheet selects one of two focused hosts. A standalone host owns its* native dialog lifecycle and joins the shared layer dismissal stack; a- * switcher item participates in the parent's shared dialog, transition state- * machine, and dismissal registration. Both render the same BottomSheetPanel,- * which owns sheet presentation, content padding, gestures, mobile-keyboard- * accommodation, and motion completion.+ * switcher item owns a native dialog of its own too, but hands its lifecycle+ * to the parent's transition state machine, scrim ownership, and dismissal+ * registration. Both render the same BottomSheetPanel, which owns sheet+ * presentation, content padding, gestures, mobile-keyboard accommodation,+ * and motion completion.+ *+ * Every sheet dialog is native first. A scrim-backed sheet is presented with+ * showModal(): the browser makes the page inert and keeps focus inside the+ * dialog, delivers Escape and the platform close as `cancel`, paints the+ * scrim as `::backdrop`, and returns focus to the opener on close(). Page+ * scroll is locked by the shared useScrollLock hook, as for Dialog: a+ * standalone sheet holds it while presented, a switcher holds one for the+ * whole modal flow. The remaining script is what no single dialog can+ * decide: gating `cancel` by `purpose` and the shared dismissal stack, and,+ * in a switcher, handing one scrim between two dialogs and keeping focus in+ * the active sheet when a retained dialog closes.** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/BottomSheet/BottomSheetPanel.tsx@@ -44,6 +56,7 @@ import type {DialogPurpose} from '../Dialog';import type {SpacingStep} from '../utils/types';import {colorVars, durationVars, easeVars} from '../theme/tokens.stylex';import {useDevWarning, useScrollLock} from '../hooks';+import {mergeProps} from '../utils';import {LayerDepthProvider} from '../Layer/LayerDepthContext';import {useLayerDismissal} from '../Layer/useLayerDismissal';import {focusForLastInput} from '../utils/focusReturn';@@ -97,14 +110,31 @@ const styles = stylex.create({'@starting-style': 0,},transitionProperty: 'opacity, display',- transitionDuration: durationVars['--duration-medium'],+ // A switcher hands its one scrim from a fading dialog to the next by+ // pinning this duration for the swap; a standalone sheet never sets it.+ transitionDuration: `var(--_sheet-scrim-duration, ${durationVars['--duration-medium']})`,transitionTimingFunction: easeVars['--ease-standard'],transitionBehavior: 'allow-discrete','@media (prefers-reduced-motion: reduce)': {- transitionDuration: '0.01s',+ // The switcher's scrim takeover pins the duration to 0s for one style+ // flush; a literal here would override that pin and paint a frame+ // with no scrim under reduced motion.+ transitionDuration: 'var(--_sheet-scrim-duration, 0.01s)',},},},+ // A non-modal switcher dialog does not enter the top layer, so DOM order+ // would decide which sheet paints in front during a handoff. The switcher's+ // flow wrapper is the isolated surface for that relationship; inside it the+ // sheet dialogs use local values only, the interactive sheet's on top.+ dialogNonModalItem: {+ pointerEvents: 'none',+ width: '100%',+ height: '100%',+ },+ dialogNonModalItemTop: {+ zIndex: 1,+ },/*** The dim leaves with the sheet, on a curve that matches.*@@ -235,6 +265,43 @@ function focusPanel(panel: HTMLElement | null, isModal: boolean): void {}}+/**+ * Present a switcher step's dialog modally with no focus to return to.+ * showModal() records the element focused at that moment and close() moves+ * focus back to it, in Chromium and WebKit even when focus is in another+ * dialog by then. For a step that element is the control that advanced the+ * flow (Continue, Back) or the flow's opener, and the dialog closes a fade+ * later, while the user is in the next step: the return would pull focus+ * off the active panel with no user action. Blurring first leaves nothing+ * recorded, so the close moves nothing; the entering step then focuses its+ * own panel, and the switcher returns focus to the opener itself when the+ * flow ends. The blur happens in the same task as the present, so no frame+ * paints without focus.+ */+function presentStepModally(dialog: HTMLDialogElement): void {+ const focused = dialog.ownerDocument.activeElement;+ if (focused instanceof HTMLElement && focused !== dialog.ownerDocument.body) {+ focused.blur();+ }+ dialog.showModal();+}++/**+ * Present a switcher dialog whose backdrop must start, and stay, clear: the+ * opacity is set with the scrim transition pinned to 0s, the dialog is+ * presented, and the pin is lifted only after a style flush has applied the+ * clear backdrop, so no frame eases from a previous backdrop value.+ */+function presentWithClearScrim(dialog: HTMLDialogElement): void {+ dialog.style.setProperty('--_sheet-scrim-duration', '0s');+ dialog.style.setProperty('--_sheet-scrim-opacity', '0');+ presentStepModally(dialog);+ if (typeof getComputedStyle === 'function') {+ void getComputedStyle(dialog, '::backdrop').opacity;+ }+ dialog.style.removeProperty('--_sheet-scrim-duration');+}+function StandaloneBottomSheet({ref,isOpen,@@ -449,12 +516,21 @@ function SwitcherBottomSheetItem({onActiveSheetChange,getSheetPhase,getSheetAlignmentOffset,+ hostSheet,+ isScrimOwner,+ isFlowClosing,registerSheetElement,- registerSheetLabel,+ registerSheetDialog,registerSheetPurpose,+ onBeforeSheetPresent,+ isCoveredInTopLayer,onSheetEnterStart,onSheetTransitionComplete,onSheetScrimOpacityChange,+ dialogProps,+ onDialogCancel,+ onDialogClick,+ onDialogKeyDown,} = switcher;const hasValidSheetId = typeof sheetId === 'string' && sheetId.length > 0;const phase = hasValidSheetId ? getSheetPhase(sheetId) : 'hidden';@@ -470,6 +546,10 @@ function SwitcherBottomSheetItem({phase === 'exiting';const isPresented = phase !== 'hidden';const isTopSheet = phase === 'active' || phase === 'entering';+ const ownsScrim = hasValidSheetId && isScrimOwner(sheetId);+ const isHostSheet = hasValidSheetId && hostSheet === sheetId;+ const dialogRef = useRef<HTMLDialogElement | null>(null);+ const dialogModeRef = useRef<'modal' | 'non-modal' | null>(null);const panelRef = useRef<HTMLDivElement | null>(null);const previousPhaseRef = useRef(phase);const previousPhase = previousPhaseRef.current;@@ -493,6 +573,15 @@ function SwitcherBottomSheetItem({},[hasValidSheetId, registerSheetElement, sheetId],);+ const handleDialogElementChange = useCallback(+ (element: HTMLDialogElement | null) => {+ dialogRef.current = element;+ if (hasValidSheetId) {+ registerSheetDialog(sheetId, element);+ }+ },+ [hasValidSheetId, registerSheetDialog, sheetId],+ );const handleMotionStart = useCallback((motion: BottomSheetPanelMotion) => {if (motion === 'entering' && hasValidSheetId) {@@ -522,17 +611,90 @@ function SwitcherBottomSheetItem({if (!hasValidSheetId) {return;}- registerSheetLabel(sheetId, label);- return () => registerSheetLabel(sheetId, null);- }, [hasValidSheetId, label, registerSheetLabel, sheetId]);+ registerSheetPurpose(sheetId, purpose);+ return () => registerSheetPurpose(sheetId, null);+ }, [hasValidSheetId, purpose, registerSheetPurpose, sheetId]);+ // Present this sheet's own dialog while the switcher keeps the sheet on+ // screen, and close it once the sheet is hidden. A scrim flow presents+ // modally: an entering dialog is shown above the retained one in the top+ // layer, and the retained dialog closes only after its panel has faded. A+ // modal dialog that is still open beneath a newer one -- the user went back+ // to a sheet that was still fading -- re-presents to become topmost again:+ // the document is blocked by the topmost modal dialog, so a lower one is+ // inert whatever the switcher calls it.+ //+ // Every present blurs first, so no step dialog records an element to+ // return focus to: a close while another sheet is active moves nothing,+ // and when the flow ends the switcher focuses the flow's opener itself.useLayoutEffect(() => {- if (!hasValidSheetId) {+ const dialog = dialogRef.current;+ if (dialog == null || !hasValidSheetId) {return;}- registerSheetPurpose(sheetId, purpose);- return () => registerSheetPurpose(sheetId, null);- }, [hasValidSheetId, purpose, registerSheetPurpose, sheetId]);+ if (!isPresented) {+ if (dialog.open) {+ dialog.close();+ }+ dialogModeRef.current = null;+ return;+ }+ const nextMode = hasScrim ? 'modal' : 'non-modal';+ if (dialog.open && dialogModeRef.current !== nextMode) {+ dialog.close();+ }+ if (+ dialog.open &&+ hasScrim &&+ isInteractive &&+ isCoveredInTopLayer(sheetId)+ ) {+ dialog.close();+ }+ if (!dialog.open) {+ if (hasScrim) {+ onBeforeSheetPresent(sheetId);+ if (ownsScrim) {+ presentStepModally(dialog);+ } else {+ // Entering above a retained dialog whose backdrop already dims the+ // page: present with a clear backdrop so the page is not dimmed+ // twice and the previous panel stays undimmed beneath this one.+ // Pinned to 0s across the present: a dialog re-presented from the+ // retained position (the user went back while it was fading)+ // closed with its backdrop at 1, and would otherwise ease it down+ // over the scrim duration on top of the new owner's backdrop.+ presentWithClearScrim(dialog);+ }+ } else {+ dialog.show();+ }+ }+ dialogModeRef.current = nextMode;+ }, [+ hasScrim,+ hasValidSheetId,+ isCoveredInTopLayer,+ isInteractive,+ isPresented,+ onBeforeSheetPresent,+ ownsScrim,+ sheetId,+ ]);++ // A sheet removed while presented -- a consumer unmounts the closing sheet+ // in the same update that closes the flow -- takes its dialog out of the+ // top layer with it, but the element would keep its `open` state. Close it+ // while it is still attached so the native lifecycle ends cleanly.+ useLayoutEffect(+ () => () => {+ const dialog = dialogRef.current;+ if (dialog?.open) {+ dialog.close();+ }+ },+ [],+ );useEffect(() => {if (isInteractive) {@@ -554,45 +716,96 @@ function SwitcherBottomSheetItem({isInteractive && !label,);+ // The switcher's dialog surface applies to every sheet dialog, except the+ // attributes that identify one element: those render on the host dialog+ // only, the one the switcher's ref resolves to. Of the attributes set+ // explicitly below, only `role` has a consumer value to keep: a required+ // step forces `alertdialog`, otherwise the switcher's `role` stands, as on+ // a shared dialog. `aria-label`/`aria-labelledby` keep consumer precedence+ // above; `aria-modal`, `aria-hidden`, and `inert` are the host's own state.+ const {+ className: switcherClassName,+ style: switcherStyle,+ xstyle: switcherXstyle,+ 'aria-label': switcherAriaLabel,+ 'aria-labelledby': switcherAriaLabelledBy,+ id: switcherId,+ 'data-testid': switcherTestId,+ ...switcherDialogProps+ } = dialogProps;+ const dialogPresentationProps = mergeProps(+ stylex.props(+ styles.dialog,+ isPresented && styles.dialogOpen,+ hasScrim && styles.scrim,+ hasScrim && ownsScrim && isFlowClosing && styles.scrimClosing,+ !hasScrim && styles.dialogNonModalItem,+ !hasScrim && isTopSheet && styles.dialogNonModalItemTop,+ switcherXstyle,+ ),+ switcherClassName,+ switcherStyle,+ );+return (- <div- {...stylex.props(- styles.positioner,- !isPresented && styles.positionerHidden,- isTopSheet && styles.positionerTop,- )}- hidden={!isPresented}+ <dialog+ {...switcherDialogProps}+ {...dialogPresentationProps}+ id={isHostSheet ? switcherId : undefined}+ data-testid={isHostSheet ? switcherTestId : undefined}+ ref={handleDialogElementChange}+ aria-label={+ switcherAriaLabel ??+ (switcherAriaLabelledBy == null ? label : undefined)+ }+ aria-labelledby={switcherAriaLabelledBy}+ aria-modal={hasScrim && isInteractive ? 'true' : undefined}aria-hidden={isInactive ? 'true' : undefined}- inert={isInactive ? true : undefined}>- <BottomSheetPanel- {...props}- ref={ref}- state={panelState}- height={height}- label={label}- snapPoints={snapPoints}- isSwipeDismissAllowed={purpose === 'info'}- isPageScrollLocked={hasScrim}- xstyle={xstyle}- onDismiss={dismissOnSwipe}- onScrimOpacity={handleScrimOpacity}- onElementChange={handlePanelElementChange}- onMotionStart={handleMotionStart}- onMotionComplete={handleMotionComplete}>- {/* A switcher item consumes its parent controller. Its content starts a- fresh ownership scope so a nested BottomSheet is standalone unless- it establishes a nested BottomSheetSwitcher of its own. */}- <BottomSheetSwitcherContext value={null}>- {children}- </BottomSheetSwitcherContext>- </BottomSheetPanel>- </div>+ inert={isInactive ? true : undefined}+ role={purpose === 'required' ? 'alertdialog' : switcherDialogProps.role}+ onCancel={onDialogCancel}+ onClick={onDialogClick}+ onKeyDown={onDialogKeyDown}>+ <div+ {...stylex.props(+ styles.positioner,+ !isPresented && styles.positionerHidden,+ isTopSheet && styles.positionerTop,+ )}+ hidden={!isPresented}+ aria-hidden={isInactive ? 'true' : undefined}+ inert={isInactive ? true : undefined}>+ <BottomSheetPanel+ {...props}+ ref={ref}+ state={panelState}+ height={height}+ label={label}+ snapPoints={snapPoints}+ isSwipeDismissAllowed={purpose === 'info'}+ isPageScrollLocked={hasScrim}+ xstyle={xstyle}+ onDismiss={dismissOnSwipe}+ onScrimOpacity={handleScrimOpacity}+ onElementChange={handlePanelElementChange}+ onMotionStart={handleMotionStart}+ onMotionComplete={handleMotionComplete}>+ {/* A switcher item consumes its parent controller. Its content starts a+ fresh ownership scope so a nested BottomSheet is standalone unless+ it establishes a nested BottomSheetSwitcher of its own. */}+ <BottomSheetSwitcherContext value={null}>+ <LayerDepthProvider>{children}</LayerDepthProvider>+ </BottomSheetSwitcherContext>+ </BottomSheetPanel>+ </div>+ {isPresented && <BottomSheetEdgeTint />}+ </dialog>);}/**- * A mobile touch sheet that either owns a native dialog or participates in a- * BottomSheetSwitcher shared dialog when given a sheetId inside that context.+ * A mobile touch sheet that owns a native dialog. Given a sheetId inside a+ * BottomSheetSwitcher, that switcher coordinates the dialog's lifecycle.*/export function BottomSheet(props: BottomSheetProps) {const switcher = use(BottomSheetSwitcherContext);diff --git a/packages/core/src/BottomSheet/BottomSheetEdgeTint.test.tsx b/packages/core/src/BottomSheet/BottomSheetEdgeTint.test.tsxindex 7922fa0d4e..31e9461028 100644--- a/packages/core/src/BottomSheet/BottomSheetEdgeTint.test.tsx+++ b/packages/core/src/BottomSheet/BottomSheetEdgeTint.test.tsx@@ -127,8 +127,10 @@ describe('BottomSheetEdgeTint', () => {expect(tints()).toHaveLength(0);});- // The switcher owns one shared dialog for the whole flow, so the tint- // belongs to that dialog and must not be minted per child sheet.+ // Each switcher step owns a dialog and tints it while presented: one tint+ // at rest, one per open dialog through a handoff (the retained dialog's+ // sits beneath the entering dialog), none for a sheet that is not+ // presented.it('gives a non-modal switcher flow exactly one tint', () => {render(<BottomSheetSwitcherdiff --git a/packages/core/src/BottomSheet/BottomSheetSwitcher.doc.mjs b/packages/core/src/BottomSheet/BottomSheetSwitcher.doc.mjsindex 840f31295d..100458ea56 100644--- a/packages/core/src/BottomSheet/BottomSheetSwitcher.doc.mjs+++ b/packages/core/src/BottomSheet/BottomSheetSwitcher.doc.mjs@@ -3,10 +3,10 @@const anatomy = [{- name: 'Shared dialog',+ name: 'Sheet dialogs',required: true,description:- 'One native dialog that owns modality, focus, dismissal, and lifecycle for the complete flow.',+ "One native dialog per child sheet, presented and closed by the switcher; the dialog hosting the active sheet carries the flow's ref, id, modality, and dismissal.",},{name: 'Sheet panels',@@ -18,7 +18,7 @@ const anatomy = [name: 'Scrim',required: false,description:- 'Native dialog backdrop shown by the default scrim-backed modal presentation.',+ 'Native dialog backdrop shown by the default scrim-backed modal presentation; one sheet dialog paints it at a time, so a handoff never dims the page twice.',},];@@ -142,18 +142,19 @@ export const docs = {},},description:- 'Coordinates multiple BottomSheets as a mutually exclusive flow. One activeSheet ID selects the only interactive sheet; during a handoff, the new sheet enters above the inert previous sheet. If the new sheet is shorter, the previous sheet simultaneously moves down until their top edges align, then fades after both transforms complete. The switcher owns one shared native <dialog>: modal flows call showModal() once for one top-layer boundary and one ::backdrop across the whole flow, while no-scrim flows use a non-modal show() shell. Its ref and shared DOM props target that dialog.',+ 'Coordinates multiple BottomSheets as a mutually exclusive flow. One activeSheet ID selects the only interactive sheet; during a handoff, the new sheet enters above the inert previous sheet. If the new sheet is shorter, the previous sheet simultaneously moves down until their top edges align, then fades after both transforms complete. Each child sheet renders its own native <dialog>, exactly like a standalone sheet: modal flows present each sheet with showModal(), no-scrim flows with show(). The browser supplies modality: the page is inert and focus stays in the top-layer dialog, so both hold across a handoff; the switcher holds the shared body scroll lock once for the whole modal flow. The switcher coordinates the rest: one scrim paints at a time, focus returns to the element that opened the flow, its ref, id, and data-testid resolve to the dialog hosting the active sheet, and its other dialog props and handlers apply to every sheet dialog.',props: [{name: 'ref',type: 'Ref<HTMLDialogElement>',- description: 'Ref forwarded to the one shared native dialog.',+ description:+ "Ref resolved to the native dialog hosting the flow: the active sheet's dialog, which changes to the next sheet's on a handoff; the exiting sheet's through its exit; and, while the flow is closed, the dialog that hosted it last (or the first mounted sheet's). It is never null while a sheet is mounted, from the first commit on. id and data-testid render on this dialog only: a flow that mounts open carries them on the active sheet's dialog in server markup too; a flow that mounts closed carries them from the first commit's synchronous re-render on, and its server markup carries them on no element. Other dialog props apply to every sheet dialog.",},{name: 'onCancel',type: '(event: SyntheticEvent<HTMLDialogElement>) => void',description:- 'Called before the switcher handles a native dialog cancel request. Calling preventDefault() keeps the controlled flow open.',+ "Called before the switcher handles a native cancel request (Escape or the platform close). Attached to every sheet dialog; the browser raises cancel on the dialog it is presenting, the active sheet's. Calling preventDefault() keeps the controlled flow open.",},{name: 'activeSheet',@@ -173,7 +174,7 @@ export const docs = {name: 'hasScrim',type: 'boolean',description:- "Whether the shared dialog is modal. true uses showModal() once for one native ::backdrop, focus trap, scroll lock, and click-to-dismiss when the active BottomSheet has purpose='info'. false uses show() with no backdrop and leaves the page interactive; avoid transformed, contained, or clipping ancestors because the non-modal dialog remains in its containing context.",+ "Whether the sheet dialogs are modal. true presents each sheet with showModal() for a native ::backdrop, native focus containment, one body scroll lock held for the whole flow, and click-to-dismiss when the active BottomSheet has purpose='info'; only one backdrop paints at a time. false uses show() with no backdrop and leaves the page interactive; avoid transformed, contained, or clipping ancestors because a non-modal dialog remains in its containing context.",default: 'true',},{@@ -186,7 +187,7 @@ export const docs = {usage: {anatomy,description:- "Coordinates a multi-step bottom-sheet flow in one shared dialog; set activeSheet to a nested BottomSheet's sheetId to open or switch steps, and to null to close.",+ "Coordinates a multi-step bottom-sheet flow, one native dialog per sheet; set activeSheet to a nested BottomSheet's sheetId to open or switch steps, and to null to close.",bestPractices: [{guidance: true,@@ -243,11 +244,11 @@ export const docs = {/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */export const docsDense = {description:- 'controller with one shared native dialog for mutually exclusive multi-step BottomSheets',+ 'controller for mutually exclusive multi-step BottomSheets, one native dialog per sheet',usage: {anatomy,description:- "Coordinates a multi-step bottom-sheet flow in one shared dialog; set activeSheet to a nested BottomSheet's sheetId to open or switch steps, and to null to close.",+ "Coordinates a multi-step bottom-sheet flow, one native dialog per sheet; set activeSheet to a nested BottomSheet's sheetId to open or switch steps, and to null to close.",bestPractices: [{guidance: true,diff --git a/packages/core/src/BottomSheet/BottomSheetSwitcher.spec.md b/packages/core/src/BottomSheet/BottomSheetSwitcher.spec.mdindex 18c040a887..440ea84656 100644--- a/packages/core/src/BottomSheet/BottomSheetSwitcher.spec.md+++ b/packages/core/src/BottomSheet/BottomSheetSwitcher.spec.md@@ -57,8 +57,6 @@ Consumer migration instructions belong in consumer docs and release notes.- The presentation lifecycle of every directly nested BottomSheet child's nativedialog: which is presented, retained during a handoff, or closed.- Implementation gap: the switcher renders one dialog of its own and hosts- every child as a panel inside it; no child owns a dialog yet.- Which child sheet is active, retained during a handoff, or hidden.- Which sheet dialog hosts the flow (its ref, `id`, and dismissalregistration) and which paints the flow's one scrim, plus@@ -79,27 +77,27 @@ Consumer migration instructions belong in consumer docs and release notes.## Public concepts-| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |-| ------------------- | ---------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | -------------------------------------- | ------------------------------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------ |-| Active sheet | `null` or one nested BottomSheet `sheetId` | Selects the only interactive child, or closes the flow | All presentations | `null` is closed; the prop is required | `component:BottomSheetSwitcher` | released | A non-matching or duplicate id is not given a safe public fallback by the current contract |-| Shared presentation | `true` / `false` through `hasScrim` | Selects the current modal scrim-backed host or non-modal no-scrim host | Entire flow | `true` | `component:BottomSheetSwitcher` | released | Boolean only |-| Child identity | Non-empty `sheetId` on each direct BottomSheet child | Associates controlled selection, labeling, purpose, and transition state with a child | Direct nested BottomSheet children | none | `component:BottomSheet` | released | Empty ids warn and stay hidden; duplicate-id behavior is not specified |-| Dismissal request | `onActiveSheetChange(null)` | Reports an allowed implicit close without taking control from the caller | Escape/platform close, scrim click, or swipe according to active child purpose | none | `component:BottomSheetSwitcher`; `family:overlay-dismissal` owns ordering | released | The caller may retain its controlled value |-| Dialog surface | inherited dialog props plus `ref` and `onCancel` | Dialog props and handlers, `onCancel` included, reach every sheet dialog; `ref`, `id`, and `data-testid` resolve to the host dialog, which is never null for an object ref while a sheet is mounted (DEC-2). Implementation gap: every dialog prop, `ref`, `id`, and `data-testid` reaches the switcher's one shared dialog | Entire flow | none | `component:BottomSheetSwitcher` | released | Component-owned semantics and handlers retain precedence |+| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |+| ------------------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | -------------------------------------- | ------------------------------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------ |+| Active sheet | `null` or one nested BottomSheet `sheetId` | Selects the only interactive child, or closes the flow | All presentations | `null` is closed; the prop is required | `component:BottomSheetSwitcher` | released | A non-matching or duplicate id is not given a safe public fallback by the current contract |+| Shared presentation | `true` / `false` through `hasScrim` | Selects the current modal scrim-backed host or non-modal no-scrim host | Entire flow | `true` | `component:BottomSheetSwitcher` | released | Boolean only |+| Child identity | Non-empty `sheetId` on each direct BottomSheet child | Associates controlled selection, labeling, purpose, and transition state with a child | Direct nested BottomSheet children | none | `component:BottomSheet` | released | Empty ids warn and stay hidden; duplicate-id behavior is not specified |+| Dismissal request | `onActiveSheetChange(null)` | Reports an allowed implicit close without taking control from the caller | Escape/platform close, scrim click, or swipe according to active child purpose | none | `component:BottomSheetSwitcher`; `family:overlay-dismissal` owns ordering | released | The caller may retain its controlled value |+| Dialog surface | inherited dialog props plus `ref` and `onCancel` | Dialog props and handlers, `onCancel` included, reach every sheet dialog; `ref`, `id`, and `data-testid` resolve to the host dialog, which is never null for an object ref while a sheet is mounted (DEC-2). | Entire flow | none | `component:BottomSheetSwitcher` | released | Component-owned semantics and handlers retain precedence |## Behavioral and layout contract-| ID | Invariant | Basis |-| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- |-| FR1 | Zero or one child sheet is interactive for each controlled `activeSheet` value; all other children are hidden or retained inert and `aria-hidden` during a transition. | Current source, docs, and tests |-| FR2 | Each child sheet owns one native dialog. Opening a sheet presents its dialog once; a handoff presents the entering sheet's dialog above the retained one and closes the retained dialog only after its panel has faded. Returning to a sheet whose dialog is still open beneath a newer one re-presents it so the interactive sheet is the topmost layer. Implementation gap: the switcher presents one shared dialog once per flow and hosts every child as a panel inside it; a handoff swaps panels in that dialog, and no dialog is re-presented. | DEC-1 |-| FR3 | During a handoff, the entering sheet is above the retained sheet. A taller retained sheet aligns down to a shorter entering sheet, and the retained sheet fades only after required transform motion completes. | Current source and transition tests |-| FR4 | Closing retains the outgoing sheet through its exit, then closes the dialog. A modal flow restores focus to the element captured when that modal flow opened. | Current source and focus tests |-| FR5 | `hasScrim=true` uses `showModal()`, a native backdrop, and native focus containment, and locks page scroll: the page does not scroll while a modal flow is presented; the lock is held continuously across a handoff, never released and re-acquired between steps; it still holds beneath a `Dialog` opened from a step; it is released after the flow's exit (DEC-1). `hasScrim=false` uses `show()` without a backdrop or scroll lock and leaves the page interactive. In a non-modal flow the sheet dialogs order themselves with local values inside the switcher's isolated flow wrapper (DEC-1); the page-level value that wrapper carries remains a `spec:AST-027` conformance gap. Implementation gap: a script focus trap runs on top of the modal dialog's native containment; a non-modal flow is one shared dialog carrying the page-level value itself, with no flow wrapper. | DEC-1; `spec:AST-027` FR2, FR4, FR8 |-| FR6 | The active child purpose governs implicit dismissal: `info` allows Escape, scrim click, and swipe; `form` allows Escape; `required` blocks all three and exposes `alertdialog`. | Current BottomSheet docs and switcher tests |-| FR7 | While visible, the switcher participates in `family:overlay-dismissal`; one Escape or platform close request reaches only the topmost present layer, and descendants receive a deeper logical layer scope. | `family:overlay-dismissal` and the audit regression test |-| FR8 | One backdrop paints the flow's scrim at a time: the retained sheet's dialog keeps it through a handoff and the entering dialog takes it over without a fade when the retained dialog closes. A stale gesture from an outgoing sheet cannot change the flow's scrim, and unmounting a retained sheet cannot keep its dialog open or the flow's modal layer held. Implementation gap: the one backdrop is the shared dialog's, so no takeover between dialogs happens. | DEC-1; current tests |-| FR9 | The switcher forwards neutral dialog attributes, styling inputs, and composed handlers, `onCancel` included, to every sheet dialog, so a handler fires for whichever sheet dialog raises the event; renders `id` and `data-testid` on the host dialog only, so each appears once in the document; attaches its ref to the host dialog; and preserves its owned ARIA and dismissal behavior. An object ref's `current` is never `null` while a sheet is mounted. A callback ref follows React's semantics on a handoff: a cleanup it returned runs when it detaches from the old host; a callback ref without a cleanup is called with `null` on detach, then with the new host. Implementation gap: every forwarded input, `ref`, `id`, and `data-testid` reaches the one shared dialog, which never changes on a handoff. | DEC-1, DEC-2; `architecture:public-component-api` INV8 |+| ID | Invariant | Basis |+| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- |+| FR1 | Zero or one child sheet is interactive for each controlled `activeSheet` value; all other children are hidden or retained inert and `aria-hidden` during a transition. | Current source, docs, and tests |+| FR2 | Each child sheet owns one native dialog. Opening a sheet presents its dialog once; a handoff presents the entering sheet's dialog above the retained one and closes the retained dialog only after its panel has faded. Returning to a sheet whose dialog is still open beneath a newer one re-presents it so the interactive sheet is the topmost layer. | DEC-1 |+| FR3 | During a handoff, the entering sheet is above the retained sheet. A taller retained sheet aligns down to a shorter entering sheet, and the retained sheet fades only after required transform motion completes. | Current source and transition tests |+| FR4 | Closing retains the outgoing sheet through its exit, then closes the dialog. A modal flow restores focus to the element captured when that modal flow opened. | Current source and focus tests |+| FR5 | `hasScrim=true` uses `showModal()`, a native backdrop, and native focus containment, and locks page scroll: the page does not scroll while a modal flow is presented; the lock is held continuously across a handoff, never released and re-acquired between steps; it still holds beneath a `Dialog` opened from a step; it is released after the flow's exit (DEC-1). `hasScrim=false` uses `show()` without a backdrop or scroll lock and leaves the page interactive. In a non-modal flow the sheet dialogs order themselves with local values inside the switcher's isolated flow wrapper (DEC-1); the page-level value that wrapper carries remains a `spec:AST-027` conformance gap. | DEC-1; `spec:AST-027` FR2, FR4, FR8 |+| FR6 | The active child purpose governs implicit dismissal: `info` allows Escape, scrim click, and swipe; `form` allows Escape; `required` blocks all three and exposes `alertdialog`. | Current BottomSheet docs and switcher tests |+| FR7 | While visible, the switcher participates in `family:overlay-dismissal`; one Escape or platform close request reaches only the topmost present layer, and descendants receive a deeper logical layer scope. | `family:overlay-dismissal` and the audit regression test |+| FR8 | One backdrop paints the flow's scrim at a time: the retained sheet's dialog keeps it through a handoff and the entering dialog takes it over without a fade when the retained dialog closes. A stale gesture from an outgoing sheet cannot change the flow's scrim, and unmounting a retained sheet cannot keep its dialog open or the flow's modal layer held. | DEC-1; current tests |+| FR9 | The switcher forwards neutral dialog attributes, styling inputs, and composed handlers, `onCancel` included, to every sheet dialog, so a handler fires for whichever sheet dialog raises the event; renders `id` and `data-testid` on the host dialog only, so each appears once in the document; attaches its ref to the host dialog; and preserves its owned ARIA and dismissal behavior. An object ref's `current` is never `null` while a sheet is mounted. A callback ref follows React's semantics on a handoff: a cleanup it returned runs when it detaches from the old host; a callback ref without a cleanup is called with `null` on detach, then with the new host. | DEC-1, DEC-2; `architecture:public-component-api` INV8 |### Allowed variation@@ -111,17 +109,13 @@ Consumer migration instructions belong in consumer docs and release notes.### Representative states-Where a state names a sheet's own dialog, the retained dialog, or the flow-wrapper, the shipped switcher meets it with its one shared dialog instead; FR2-and FR5 record that implementation gap.-| State | Required invariant | Allowed variation || ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- || Closed | Every sheet dialog is closed and no child is interactive. | Child panels may remain mounted but hidden. || First open | Matching child is visible and interactive in its own dialog. | Child-owned height and content. || Handoff | Entering child is interactive in its own dialog; retained child's dialog stays open, inert, and hidden from accessibility APIs until it fades, and keeps painting the one scrim. | Alignment offset depends on measured panel geometry. || Closing | Outgoing child is retained inert while exit motion completes; modal focus and scroll ownership remain until close. | Theme-controlled duration. |-| Modal | Native modal host, backdrop, native focus containment, and the page scroll lock are active. Implementation gap: a script focus trap runs on top of the native containment. | Active child's `purpose` controls implicit dismissal. |+| Modal | Native modal host, backdrop, native focus containment, and the page scroll lock are active. | Active child's `purpose` controls implicit dismissal. || Non-modal | Native non-modal host has no backdrop or scroll lock and background content remains interactive. | The current clipping/stacking limitation is a conformance gap, not an allowed exception. |### Transformation and precedence order@@ -140,8 +134,7 @@ and FR5 record that implementation gap.Native modality holds across a modal flow's child handoffs because a sheetdialog is modal throughout, and the one page scroll lock is held for thewhole flow rather than per step. A non-modal flow paints no backdrop and- holds no lock. Implementation gap: one shared dialog is presented- throughout, so a handoff has one dialog open, not two.+ holds no lock.- **PR2 — Stable child registration.** Parent rerenders and changing consumer refidentities do not unregister a mounted child or cancel an active handoff.@@ -157,11 +150,11 @@ and FR5 record that implementation gap.## Design relationships-| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |-| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------- | -------------- | ------------------ |-| Shared dialog | Transparent host for the flow's interaction and accessibility boundary, one per child sheet (DEC-1). Implementation gap: one such host serves the whole flow | Current source and public docs; DEC-1 for the per-sheet clause | Structural | FR2, FR5, AR1 |-| Sheet panels | Delegate visible panel, content, handle, and gesture presentation to BottomSheet | `component:BottomSheet` as observational context | Prominent | FR1, FR3 |-| Scrim | Optional native backdrop that dims and blocks the page in modal presentation; one sheet dialog paints it at a time (DEC-1) | Current source and public docs; DEC-1 for the one-painter clause | Supporting | FR5, FR8 |+| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |+| ---------------- | -------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | -------------- | ------------------ |+| Sheet dialogs | Transparent per-sheet hosts; the active sheet's is the flow's interaction and accessibility boundary (DEC-1) | Current source and public docs; DEC-1 for the per-sheet clause | Structural | FR2, FR5, AR1 |+| Sheet panels | Delegate visible panel, content, handle, and gesture presentation to BottomSheet | `component:BottomSheet` as observational context | Prominent | FR1, FR3 |+| Scrim | Optional native backdrop that dims and blocks the page in modal presentation; one sheet dialog paints it at a time (DEC-1) | Current source and public docs; DEC-1 for the one-painter clause | Supporting | FR5, FR8 |### Theming anatomy@@ -169,9 +162,9 @@ and FR5 record that implementation gap.```json{- "Shared dialog": {+ "Sheet dialogs": {"none": {- "reason": "intentional: The transparent dialog is hosting, positioning, event, and focus machinery rather than a stable painted part."+ "reason": "intentional: The transparent dialogs are hosting, positioning, event, and focus machinery rather than a stable painted part."}},"Sheet panels": {@@ -179,7 +172,7 @@ and FR5 record that implementation gap.},"Scrim": {"none": {- "reason": "reachability-gap: The switcher-coordinated native backdrop paints the scrim but has no current public theming target."+ "reason": "reachability-gap: The native backdrop of the sheet dialog that owns the scrim paints it but has no current public theming target."}}}diff --git a/packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx b/packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsxindex 0e2f01d7c9..25f0d0f133 100644--- a/packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx+++ b/packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx@@ -12,7 +12,10 @@import {fireEvent, render, screen} from '@testing-library/react';import {+ StrictMode,createRef,+ useEffect,+ useLayoutEffect,useState,type KeyboardEvent as ReactKeyboardEvent,} from 'react';@@ -22,17 +25,23 @@ import {useLayerDismissal} from '../Layer/useLayerDismissal';import {BottomSheet} from './BottomSheet';import {BottomSheetSwitcher} from './BottomSheetSwitcher';+// jsdom implements no <dialog> presentation. The stubs record which open+// dialogs are modal, standing in for the `:modal` pseudo-class jsdom cannot+// match.+const modalDialogs = new WeakSet<HTMLDialogElement>();beforeEach(() => {HTMLDialogElement.prototype.showModal = vi.fn(function (this: HTMLDialogElement,) {this.setAttribute('open', '');+ modalDialogs.add(this);});HTMLDialogElement.prototype.show = vi.fn(function (this: HTMLDialogElement) {this.setAttribute('open', '');});HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {this.removeAttribute('open');+ modalDialogs.delete(this);});window.scrollTo = vi.fn();vi.stubGlobal(@@ -224,10 +233,156 @@ function ModeSwitchFlow() {);}-function getSharedDialog(): HTMLDialogElement {+function RequiredConfirmFlow() {+ const [activeSheet, setActiveSheet] = useState<string | null>('details');+ return (+ <BottomSheetSwitcher+ activeSheet={activeSheet}+ onActiveSheetChange={setActiveSheet}>+ <BottomSheet+ sheetId="details"+ label="Details"+ data-testid="details-sheet">+ <button type="button" onClick={() => setActiveSheet('confirm')}>+ Continue+ </button>+ </BottomSheet>+ <BottomSheet+ sheetId="confirm"+ label="Confirm"+ purpose="required"+ data-testid="confirm-sheet">+ <button type="button" onClick={() => setActiveSheet(null)}>+ Done+ </button>+ </BottomSheet>+ </BottomSheetSwitcher>+ );+}++function HostFlow({+ dialogRef,+ dialogProps,+ hasScrim = true,+ initialSheet = null,+ onMountLayout,+ onMountPassive,+}: {+ dialogRef?: React.Ref<HTMLDialogElement>;+ dialogProps?: Record<string, string>;+ hasScrim?: boolean;+ initialSheet?: string | null;+ onMountLayout?: () => void;+ onMountPassive?: () => void;+}) {+ const [activeSheet, setActiveSheet] = useState<string | null>(initialSheet);+ useLayoutEffect(() => onMountLayout?.(), [onMountLayout]);+ useEffect(() => onMountPassive?.(), [onMountPassive]);+ return (+ <>+ <button type="button" onClick={() => setActiveSheet('details')}>+ Start flow+ </button>+ <BottomSheetSwitcher+ ref={dialogRef}+ {...dialogProps}+ activeSheet={activeSheet}+ onActiveSheetChange={setActiveSheet}+ hasScrim={hasScrim}>+ <BottomSheet+ sheetId="details"+ label="Details"+ data-testid="details-sheet">+ <button type="button" onClick={() => setActiveSheet('confirm')}>+ Continue+ </button>+ </BottomSheet>+ <BottomSheet+ sheetId="confirm"+ label="Confirm"+ data-testid="confirm-sheet">+ <button type="button" onClick={() => setActiveSheet(null)}>+ Done+ </button>+ </BottomSheet>+ <BottomSheet sheetId="extra" label="Extra">+ Content+ </BottomSheet>+ </BottomSheetSwitcher>+ </>+ );+}++/**+ * The dialog hosting the active sheet. A retained sheet's dialog is inert and+ * `aria-hidden`, so only the active sheet's dialog is exposed by role.+ */+function getActiveDialog(): HTMLDialogElement {return screen.getByRole<HTMLDialogElement>('dialog');}+function getSheetDialog(testId: string): HTMLDialogElement {+ const dialog = screen.getByTestId(testId).closest('dialog');+ if (dialog == null) {+ throw new Error('sheet dialog not found');+ }+ return dialog;+}++function openDialogs(): HTMLDialogElement[] {+ return Array.from(+ document.querySelectorAll<HTMLDialogElement>('dialog[open]'),+ );+}++/**+ * Whether the shared page-scroll lock (useScrollLock, as Dialog uses) is+ * engaged: it pins <body>. The browser spec measures the lock's effect on+ * scrolling; this reads its pin.+ */+function isScrollLockEngaged(): boolean {+ return document.body.style.position === 'fixed';+}++/**+ * Records every native dialog call with the dialog's accessible label, and+ * returns focus the way Chromium and WebKit do: close() on a dialog presented+ * with showModal() focuses the element that was focused when it was+ * presented, wherever focus is by then (measured: both engines return it+ * even when focus sits in another open dialog).+ */+function recordDialogCalls(): string[] {+ const log: string[] = [];+ const focusedAtPresent = new WeakMap<HTMLDialogElement, Element | null>();+ const record = (name: string) =>+ vi.fn(function (this: HTMLDialogElement) {+ log.push(`${name}:${this.getAttribute('aria-label') ?? '?'}`);+ if (name === 'close') {+ this.removeAttribute('open');+ const wasModal = modalDialogs.delete(this);+ const previouslyFocused = focusedAtPresent.get(this);+ focusedAtPresent.delete(this);+ if (+ wasModal &&+ previouslyFocused instanceof HTMLElement &&+ previouslyFocused.isConnected+ ) {+ previouslyFocused.focus();+ }+ } else {+ if (name === 'showModal') {+ focusedAtPresent.set(this, document.activeElement);+ modalDialogs.add(this);+ }+ this.setAttribute('open', '');+ }+ });+ HTMLDialogElement.prototype.showModal = record('showModal');+ HTMLDialogElement.prototype.show = record('show');+ HTMLDialogElement.prototype.close = record('close');+ return log;+}+function finishSheetTransition(element: HTMLElement,propertyName: 'transform' | 'opacity',@@ -288,11 +443,11 @@ describe('BottomSheetSwitcher', () => {expect(document.querySelectorAll('dialog[open]')).toHaveLength(1);expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalledTimes(1);expect(HTMLDialogElement.prototype.show).not.toHaveBeenCalled();- expect(getSharedDialog()).toHaveAttribute('aria-modal', 'true');- expect(getSharedDialog()).toHaveAccessibleName('Details');+ expect(getActiveDialog()).toHaveAttribute('aria-modal', 'true');+ expect(getActiveDialog()).toHaveAccessibleName('Details');});- it('forwards sheet DOM props and refs to its panel in the shared dialog', () => {+ it('forwards sheet DOM props and refs to its panel in its dialog', () => {const panelRef = createRef<HTMLDivElement>();render(@@ -312,10 +467,10 @@ describe('BottomSheetSwitcher', () => {expect(panelRef.current).toBe(panel);expect(panel).toHaveClass('astryx-bottom-sheet');expect(panel).toHaveAttribute('data-sheet-owner', 'settings');- expect(getSharedDialog()).toContainElement(panel);+ expect(getActiveDialog()).toContainElement(panel);});- it('forwards switcher DOM props, events, styles, and refs to the shared dialog', () => {+ it("forwards switcher DOM props, events, styles, and refs to the active sheet's dialog", () => {const dialogRef = createRef<HTMLDialogElement>();const onClick = vi.fn();const onActiveSheetChange = vi.fn();@@ -336,7 +491,7 @@ describe('BottomSheetSwitcher', () => {</BottomSheetSwitcher>,);- const dialog = getSharedDialog();+ const dialog = getActiveDialog();expect(dialogRef.current).toBe(dialog);expect(dialog).toHaveAccessibleName('Notification setup');expect(dialog).toHaveAttribute('data-flow-owner', 'settings');@@ -366,14 +521,16 @@ describe('BottomSheetSwitcher', () => {finishSheetTransition(nestedDialog, 'transform');expect(nestedDialog).not.toHaveAttribute('open');- expect(getSharedDialog()).toHaveAttribute('open');+ expect(getActiveDialog()).toHaveAttribute('open');expect(opener).toHaveFocus();});it('keeps the previous sheet stationary until the new entrance finishes, then fades it', () => {render(<Flow />);fireEvent.click(screen.getByRole('button', {name: 'Start flow'}));- const sharedDialog = getSharedDialog();+ const detailsDialog = getSheetDialog('details-sheet');+ const confirmDialog = getSheetDialog('confirm-sheet');+ expect(getActiveDialog()).toBe(detailsDialog);const detailsSheet = getSheetLayer('details-sheet');const confirmSheet = getSheetLayer('confirm-sheet');@@ -384,9 +541,11 @@ describe('BottomSheetSwitcher', () => {expect(detailsSheet).toHaveAttribute('aria-hidden', 'true');expect(confirmSheet).not.toHaveAttribute('hidden');expect(confirmSheet).not.toHaveAttribute('inert');- expect(document.querySelectorAll('dialog[open]')).toHaveLength(1);- expect(getSharedDialog()).toBe(sharedDialog);- expect(sharedDialog).toHaveAccessibleName('Confirm');+ // Both dialogs stay open through the handoff; the retained one is inert.+ expect(openDialogs()).toEqual([detailsDialog, confirmDialog]);+ expect(detailsDialog).toHaveAttribute('inert');+ expect(getActiveDialog()).toBe(confirmDialog);+ expect(confirmDialog).toHaveAccessibleName('Confirm');// The previous sheet is covered, not exiting: neither transform nor// opacity completion may release it before the new entrance completes.@@ -401,8 +560,8 @@ describe('BottomSheetSwitcher', () => {expect(detailsSheet).toHaveAttribute('hidden');expect(confirmSheet).not.toHaveAttribute('hidden');- expect(document.querySelectorAll('dialog[open]')).toHaveLength(1);- expect(getSharedDialog()).toBe(sharedDialog);+ expect(openDialogs()).toEqual([confirmDialog]);+ expect(getActiveDialog()).toBe(confirmDialog);fireEvent.click(screen.getByRole('button', {name: 'Back'}));@@ -415,8 +574,8 @@ describe('BottomSheetSwitcher', () => {expect(detailsSheet).not.toHaveAttribute('hidden');expect(confirmSheet).toHaveAttribute('hidden');- expect(document.querySelectorAll('dialog[open]')).toHaveLength(1);- expect(getSharedDialog()).toBe(sharedDialog);+ expect(openDialogs()).toEqual([detailsDialog]);+ expect(getActiveDialog()).toBe(detailsDialog);});it('moves a taller previous sheet down while the shorter new sheet enters, then waits for both', () => {@@ -483,11 +642,69 @@ describe('BottomSheetSwitcher', () => {expect(detailsSheet).not.toHaveAttribute('inert');expect(confirmSheet).not.toHaveAttribute('hidden');expect(confirmSheet).toHaveAttribute('inert');- expect(document.querySelectorAll('dialog[open]')).toHaveLength(1);+ // The returning sheet re-presents above the one it replaces: a modal+ // dialog beneath another modal dialog is inert in the top layer.+ expect(openDialogs()).toHaveLength(2);+ expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalledTimes(3);+ expect(getActiveDialog()).toBe(getSheetDialog('details-sheet'));finishSheetTransition(confirmSheet, 'opacity');expect(detailsSheet).not.toHaveAttribute('hidden');expect(confirmSheet).toHaveAttribute('hidden');+ expect(openDialogs()).toEqual([getSheetDialog('details-sheet')]);+ });++ it('re-presents a returning sheet with its backdrop cleared instantly, so the handed-over scrim is never doubled', () => {+ // Going back while the previous sheet is still fading re-presents its+ // dialog beneath the new scrim owner. That dialog closed with its+ // backdrop at 1; the clear must apply with the scrim transition pinned+ // to 0s across showModal(), or the backdrop eases 1 -> 0 on top of the+ // other dialog's and the page is dimmed twice for a dozen frames.+ const atPresent: {label: string; duration: string; opacity: string}[] = [];+ HTMLDialogElement.prototype.showModal = vi.fn(function (+ this: HTMLDialogElement,+ ) {+ this.setAttribute('open', '');+ modalDialogs.add(this);+ atPresent.push({+ label: this.getAttribute('aria-label') ?? '?',+ duration: this.style.getPropertyValue('--_sheet-scrim-duration'),+ opacity: this.style.getPropertyValue('--_sheet-scrim-opacity'),+ });+ });+ render(<Flow />);+ fireEvent.click(screen.getByRole('button', {name: 'Start flow'}));+ fireEvent.click(screen.getByRole('button', {name: 'Continue'}));+ const detailsDialog = getSheetDialog('details-sheet');+ const confirmDialog = getSheetDialog('confirm-sheet');+ // Mid-handoff: Details retains the scrim, Confirm entered clear.+ expect(detailsDialog).toHaveStyle({'--_sheet-scrim-opacity': '1'});+ expect(confirmDialog).toHaveStyle({'--_sheet-scrim-opacity': '0'});++ fireEvent.click(screen.getByRole('button', {name: 'Back'}));++ // Confirm, now retained, took the scrim over; Details re-presented clear+ // with the transition pinned for the present, and the pin lifted after.+ expect(atPresent.at(-1)).toEqual({+ label: 'Details',+ duration: '0s',+ opacity: '0',+ });+ expect(detailsDialog).toHaveStyle({'--_sheet-scrim-opacity': '0'});+ expect(+ detailsDialog.style.getPropertyValue('--_sheet-scrim-duration'),+ ).toBe('');+ expect(confirmDialog).toHaveStyle({'--_sheet-scrim-opacity': '1'});+ expect(+ confirmDialog.style.getPropertyValue('--_sheet-scrim-duration'),+ ).toBe('');+ // Exactly one dialog carries the scrim.+ expect(+ openDialogs().filter(+ dialog =>+ dialog.style.getPropertyValue('--_sheet-scrim-opacity') === '1',+ ),+ ).toEqual([confirmDialog]);});it('ignores late scrim updates from an outgoing sheet gesture', () => {@@ -513,19 +730,24 @@ describe('BottomSheetSwitcher', () => {clientY: 600,timeStamp: 16,});+ const detailsDialog = getSheetDialog('details-sheet');expect(- getSharedDialog().style.getPropertyValue('--_sheet-scrim-opacity'),+ detailsDialog.style.getPropertyValue('--_sheet-scrim-opacity'),).not.toBe('1');+ // The retained dialog owns the flow's scrim through the handoff; the+ // entering dialog's backdrop stays clear above it.fireEvent.click(screen.getByRole('button', {name: 'Continue'}));- expect(getSharedDialog()).toHaveStyle({'--_sheet-scrim-opacity': '1'});+ expect(detailsDialog).toHaveStyle({'--_sheet-scrim-opacity': '1'});+ expect(getActiveDialog()).toHaveStyle({'--_sheet-scrim-opacity': '0'});fireEvent.pointerMove(handle, {pointerId: 1,clientY: 680,timeStamp: 32,});- expect(getSharedDialog()).toHaveStyle({'--_sheet-scrim-opacity': '1'});+ expect(detailsDialog).toHaveStyle({'--_sheet-scrim-opacity': '1'});+ expect(getActiveDialog()).toHaveStyle({'--_sheet-scrim-opacity': '0'});});it('keeps an active handoff when a consumer callback ref changes', () => {@@ -547,41 +769,42 @@ describe('BottomSheetSwitcher', () => {expect(confirmSheet).not.toHaveAttribute('hidden');});- it('dismisses the flow from the one shared scrim', () => {+ it("dismisses the flow from the active sheet's scrim", () => {render(<Flow />);fireEvent.click(screen.getByRole('button', {name: 'Start flow'}));- const sharedDialog = getSharedDialog();+ const activeDialog = getActiveDialog();- fireEvent.click(sharedDialog);+ fireEvent.click(activeDialog);const outgoingSheet = getSheetLayer('details-sheet');expect(outgoingSheet).not.toHaveAttribute('hidden');expect(outgoingSheet).toHaveAttribute('inert');- expect(sharedDialog).toHaveStyle({'--_sheet-scrim-opacity': '0'});- expect(document.body.style.position).toBe('fixed');+ expect(activeDialog).toHaveStyle({'--_sheet-scrim-opacity': '0'});+ // Scroll stays locked through the exit.+ expect(isScrollLockEngaged()).toBe(true);finishSheetTransition(outgoingSheet, 'transform');- expect(sharedDialog).not.toHaveAttribute('open');- expect(document.body.style.position).not.toBe('fixed');+ expect(activeDialog).not.toHaveAttribute('open');+ expect(isScrollLockEngaged()).toBe(false);});- it('releases the shared modal layer when the closing sheet unmounts immediately', () => {+ it('releases the modal layer when the closing sheet unmounts immediately', () => {render(<ConditionalFlow />);fireEvent.click(screen.getByRole('button', {name: 'Start conditional flow'}),);- const sharedDialog = screen.getByRole('dialog', {+ const dialog = screen.getByRole('dialog', {name: 'Conditional details',});- fireEvent.keyDown(sharedDialog, {key: 'Escape'});+ fireEvent.keyDown(dialog, {key: 'Escape'});- expect(sharedDialog).not.toHaveAttribute('open');- expect(document.body.style.position).not.toBe('fixed');+ expect(dialog).not.toHaveAttribute('open');+ expect(isScrollLockEngaged()).toBe(false);});- it('keeps the shared dialog inline and opens it modally', () => {+ it('keeps a sheet dialog inline and opens it modally', () => {render(<divdata-testid="clipping-ancestor"@@ -603,7 +826,7 @@ describe('BottomSheetSwitcher', () => {expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalledTimes(1);});- it('keeps focus in a modal sheet that has no tabbable controls', () => {+ it('focuses the panel of a modal sheet with no tabbable controls and leaves Tab to the native modal dialog', () => {render(<><button type="button">Background action</button>@@ -617,14 +840,18 @@ describe('BottomSheetSwitcher', () => {</>,);- const dialog = screen.getByRole('dialog', {name: 'Read-only details'});+ const dialog = screen.getByRole<HTMLDialogElement>('dialog', {+ name: 'Read-only details',+ });const panel = getSheetPanel(dialog);expect(panel).toHaveFocus();- expect(fireEvent.keyDown(panel, {key: 'Tab'})).toBe(false);+ // Containment is the browser's: the dialog was presented with showModal(),+ // which makes everything outside it inert, so no script intercepts Tab.+ // BottomSheetNativeModal.a11y.browser.spec.ts proves the key in engines.+ expect(modalDialogs.has(dialog)).toBe(true);+ expect(dialog).toHaveAttribute('aria-modal', 'true');+ expect(fireEvent.keyDown(panel, {key: 'Tab'})).toBe(true);expect(panel).toHaveFocus();- expect(- screen.getByRole('button', {name: 'Background action'}),- ).not.toHaveFocus();});it('can coordinate a non-modal flow without rendering a scrim', () => {@@ -639,12 +866,12 @@ describe('BottomSheetSwitcher', () => {</BottomSheetSwitcher>,);- const dialog = getSharedDialog();+ const dialog = getActiveDialog();expect(dialog).not.toHaveAttribute('aria-modal');expect(dialog).toHaveAttribute('open');expect(HTMLDialogElement.prototype.show).toHaveBeenCalledTimes(1);expect(HTMLDialogElement.prototype.showModal).not.toHaveBeenCalled();- expect(document.body.style.position).not.toBe('fixed');+ expect(isScrollLockEngaged()).toBe(false);});it('requests activeSheet=null when the active sheet dismisses', () => {@@ -680,7 +907,7 @@ describe('BottomSheetSwitcher', () => {</BottomSheet></BottomSheetSwitcher>,);- const dialog = getSharedDialog();+ const dialog = getActiveDialog();const panel = getSheetPanel(dialog);const handle = panel.firstElementChild;if (!(handle instanceof HTMLElement)) {@@ -710,7 +937,7 @@ describe('BottomSheetSwitcher', () => {it('keeps the flow open when a file picker inside a step is dismissed, and still closes on its own close request', () => {// A file input fires a bubbling `cancel` at itself when its picker is- // dismissed. A step renders no dialog, so it reaches the switcher's.+ // dismissed. It bubbles to the step's own dialog, which leaves it alone.const onActiveSheetChange = vi.fn();render(<BottomSheetSwitcher@@ -728,7 +955,7 @@ describe('BottomSheetSwitcher', () => {expect(onActiveSheetChange).not.toHaveBeenCalled();expect(fromPicker.defaultPrevented).toBe(false);- fireEvent(getSharedDialog(), new Event('cancel', {cancelable: true}));+ fireEvent(getActiveDialog(), new Event('cancel', {cancelable: true}));expect(onActiveSheetChange).toHaveBeenCalledTimes(1);expect(onActiveSheetChange).toHaveBeenCalledWith(null);@@ -782,7 +1009,7 @@ describe('BottomSheetSwitcher', () => {</BottomSheet></BottomSheetSwitcher>,);- const dialog = getSharedDialog();+ const dialog = getActiveDialog();const panel = getSheetPanel(dialog);const handle = panel.firstElementChild;if (!(handle instanceof HTMLElement)) {@@ -878,7 +1105,7 @@ describe('BottomSheetSwitcher', () => {</BottomSheetSwitcher>,);- fireEvent.keyDown(getSharedDialog(), {key: 'Escape'});+ fireEvent.keyDown(getActiveDialog(), {key: 'Escape'});expect(onKeyDown).toHaveBeenCalledTimes(1);expect(onActiveSheetChange).toHaveBeenCalledWith(null);@@ -901,7 +1128,7 @@ describe('BottomSheetSwitcher', () => {</BottomSheetSwitcher>,);- fireEvent.keyDown(getSharedDialog(), {key: 'Escape'});+ fireEvent.keyDown(getActiveDialog(), {key: 'Escape'});expect(onKeyDown).toHaveBeenCalledTimes(1);expect(onActiveSheetChange).not.toHaveBeenCalled();@@ -949,7 +1176,7 @@ describe('BottomSheetSwitcher', () => {);const event = new Event('cancel', {cancelable: true});- getSharedDialog().dispatchEvent(event);+ getActiveDialog().dispatchEvent(event);expect(event.defaultPrevented).toBe(true);expect(onNestedDismiss).not.toHaveBeenCalled();@@ -1005,4 +1232,559 @@ describe('BottomSheetSwitcher', () => {expect(backButton).toHaveFocus();});++ describe('one native dialog per sheet', () => {+ it('renders a closed dialog for every sheet and presents only the selected one', () => {+ render(<Flow />);+ const detailsDialog = getSheetDialog('details-sheet');+ const confirmDialog = getSheetDialog('confirm-sheet');+ expect(detailsDialog).not.toBe(confirmDialog);+ expect(openDialogs()).toEqual([]);++ fireEvent.click(screen.getByRole('button', {name: 'Start flow'}));++ expect(openDialogs()).toEqual([detailsDialog]);+ expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalledTimes(1);+ expect(confirmDialog).not.toHaveAttribute('open');+ expect(confirmDialog).not.toHaveAttribute('aria-modal');+ expect(detailsDialog).toHaveAttribute('aria-modal', 'true');+ expect(detailsDialog).toContainElement(+ screen.getByTestId('details-sheet'),+ );+ expect(confirmDialog).toContainElement(+ screen.getByTestId('confirm-sheet'),+ );+ });++ it('presents the entering dialog once and closes the retained dialog only after it fades', () => {+ const log = recordDialogCalls();+ render(<Flow />);+ fireEvent.click(screen.getByRole('button', {name: 'Start flow'}));+ expect(log).toEqual(['showModal:Details']);++ fireEvent.click(screen.getByRole('button', {name: 'Continue'}));+ expect(log).toEqual(['showModal:Details', 'showModal:Confirm']);++ finishSheetTransition(getSheetLayer('confirm-sheet'), 'transform');+ expect(log).toEqual(['showModal:Details', 'showModal:Confirm']);+ finishSheetTransition(getSheetLayer('details-sheet'), 'opacity');+ expect(log).toEqual([+ 'showModal:Details',+ 'showModal:Confirm',+ 'close:Details',+ ]);++ fireEvent.keyDown(getActiveDialog(), {key: 'Escape'});+ expect(log).toHaveLength(3);+ finishSheetTransition(getSheetLayer('confirm-sheet'), 'transform');+ expect(log.at(-1)).toBe('close:Confirm');+ expect(openDialogs()).toEqual([]);+ });++ it('holds one page scroll lock for the whole flow: engaged continuously through a handoff, released once after the exit', () => {+ // The shared lock restores the saved offset with window.scrollTo on its+ // last release, so the call count is the release count: a flow that+ // released and re-acquired between steps would scroll the page back+ // mid-handoff.+ vi.spyOn(window, 'scrollY', 'get').mockReturnValue(300);+ render(<Flow />);+ expect(isScrollLockEngaged()).toBe(false);++ fireEvent.click(screen.getByRole('button', {name: 'Start flow'}));+ expect(isScrollLockEngaged()).toBe(true);+ expect(document.body.style.top).toBe('-300px');+ expect(window.scrollTo).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole('button', {name: 'Continue'}));+ // Two modal sheet dialogs are open: still the one lock.+ expect(openDialogs()).toHaveLength(2);+ expect(isScrollLockEngaged()).toBe(true);+ expect(window.scrollTo).not.toHaveBeenCalled();++ finishSheetTransition(getSheetLayer('confirm-sheet'), 'transform');+ finishSheetTransition(getSheetLayer('details-sheet'), 'opacity');+ expect(openDialogs()).toHaveLength(1);+ expect(isScrollLockEngaged()).toBe(true);+ expect(window.scrollTo).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole('button', {name: 'Back'}));+ finishSheetTransition(getSheetLayer('details-sheet'), 'transform');+ finishSheetTransition(getSheetLayer('confirm-sheet'), 'opacity');+ expect(isScrollLockEngaged()).toBe(true);+ expect(window.scrollTo).not.toHaveBeenCalled();++ fireEvent.keyDown(getActiveDialog(), {key: 'Escape'});+ // Still held through the exit motion.+ expect(isScrollLockEngaged()).toBe(true);+ expect(window.scrollTo).not.toHaveBeenCalled();+ finishSheetTransition(getSheetLayer('details-sheet'), 'transform');+ expect(isScrollLockEngaged()).toBe(false);+ expect(document.body.style.top).toBe('');+ expect(window.scrollTo).toHaveBeenCalledTimes(1);+ expect(window.scrollTo).toHaveBeenCalledWith(0, 300);+ });++ it('keeps the lock through a StrictMode replay of a flow mounted open, and releases it when the flow unmounts while presented', () => {+ vi.spyOn(window, 'scrollY', 'get').mockReturnValue(120);+ const mounted = render(+ <StrictMode>+ <HostFlow initialSheet="details" />+ </StrictMode>,+ );+ // StrictMode runs the lock's effect, its cleanup, and the effect again+ // in one commit: the pin must stand afterwards, and the one real+ // release has not happened.+ expect(isScrollLockEngaged()).toBe(true);+ expect(document.body.style.top).toBe('-120px');+ expect(window.scrollTo).toHaveBeenCalledTimes(1);+ vi.mocked(window.scrollTo).mockClear();++ fireEvent.click(screen.getByRole('button', {name: 'Continue'}));+ expect(openDialogs()).toHaveLength(2);+ expect(isScrollLockEngaged()).toBe(true);+ expect(window.scrollTo).not.toHaveBeenCalled();++ // Unmounted while presented, two dialogs open: one release.+ mounted.unmount();+ expect(isScrollLockEngaged()).toBe(false);+ expect(document.body.style.top).toBe('');+ expect(window.scrollTo).toHaveBeenCalledTimes(1);+ expect(window.scrollTo).toHaveBeenCalledWith(0, 120);+ });++ it("resolves the switcher ref to the host sheet's dialog and never to null while a sheet is mounted, from the first commit on", () => {+ const dialogRef = createRef<HTMLDialogElement>();+ const seenAtMount: {layout?: Element | null; passive?: Element | null} =+ {};+ const {unmount} = render(+ <HostFlow+ dialogRef={dialogRef}+ onMountLayout={() => {+ seenAtMount.layout = dialogRef.current;+ }}+ onMountPassive={() => {+ seenAtMount.passive = dialogRef.current;+ }}+ />,+ );+ // Closed, never opened: the first sheet's closed dialog, as the shared+ // dialog once was a closed element rather than null -- already in the+ // consumer's own mount effects, layout and passive alike.+ const detailsDialog = getSheetDialog('details-sheet');+ expect(seenAtMount.layout).toBe(detailsDialog);+ expect(seenAtMount.passive).toBe(detailsDialog);+ expect(dialogRef.current).toBe(detailsDialog);+ expect(dialogRef.current).not.toHaveAttribute('open');++ fireEvent.click(screen.getByRole('button', {name: 'Start flow'}));+ expect(dialogRef.current).toBe(detailsDialog);+ expect(dialogRef.current).toHaveAttribute('open');++ fireEvent.click(screen.getByRole('button', {name: 'Continue'}));+ expect(dialogRef.current).toBe(getSheetDialog('confirm-sheet'));++ fireEvent.click(screen.getByRole('button', {name: 'Done'}));+ // The exiting sheet's dialog hosts the flow through its exit motion and+ // stays the host once the flow is closed.+ expect(dialogRef.current).toBe(getSheetDialog('confirm-sheet'));+ finishSheetTransition(getSheetLayer('confirm-sheet'), 'transform');+ expect(dialogRef.current).toBe(getSheetDialog('confirm-sheet'));+ expect(dialogRef.current).not.toHaveAttribute('open');++ unmount();+ expect(dialogRef.current).toBeNull();+ });++ it('runs a callback ref cleanup exactly once per detach and never passes it null', () => {+ const received: (HTMLDialogElement | null)[] = [];+ const cleanups: HTMLDialogElement[] = [];+ const callbackRef = (dialog: HTMLDialogElement | null) => {+ received.push(dialog);+ return () => {+ if (dialog != null) {+ cleanups.push(dialog);+ }+ };+ };+ const {unmount} = render(<HostFlow dialogRef={callbackRef} />);+ const detailsDialog = getSheetDialog('details-sheet');+ const confirmDialog = getSheetDialog('confirm-sheet');+ expect(received).toEqual([detailsDialog]);+ expect(cleanups).toEqual([]);++ fireEvent.click(screen.getByRole('button', {name: 'Start flow'}));+ // Same host: the ref is not detached and re-attached.+ expect(received).toEqual([detailsDialog]);++ fireEvent.click(screen.getByRole('button', {name: 'Continue'}));+ // Host moved: the Details attachment is cleaned up once, then Confirm+ // is attached; no `null` call stands in for the cleanup.+ expect(cleanups).toEqual([detailsDialog]);+ expect(received).toEqual([detailsDialog, confirmDialog]);++ fireEvent.click(screen.getByRole('button', {name: 'Done'}));+ finishSheetTransition(getSheetLayer('confirm-sheet'), 'transform');+ expect(cleanups).toEqual([detailsDialog]);+ expect(received).toEqual([detailsDialog, confirmDialog]);++ unmount();+ expect(cleanups).toEqual([detailsDialog, confirmDialog]);+ expect(received).toEqual([detailsDialog, confirmDialog]);+ expect(received).not.toContain(null);+ });++ it('renders the switcher id and test id once, on the host dialog, and moves them with it', () => {+ render(+ <HostFlow+ dialogProps={{+ id: 'checkout',+ 'data-testid': 'checkout-flow',+ 'data-flow-owner': 'settings',+ }}+ />,+ );+ const dialogs = Array.from(document.querySelectorAll('dialog'));+ expect(dialogs).toHaveLength(3);+ const withId = () =>+ Array.from(document.querySelectorAll('[id="checkout"]'));+ // Closed: exactly one element carries the id, the first sheet's dialog.+ expect(withId()).toEqual([dialogs[0]]);+ expect(screen.getByTestId('checkout-flow')).toBe(dialogs[0]);+ // The remaining dialog props still reach every sheet dialog.+ for (const dialog of dialogs) {+ expect(dialog).toHaveAttribute('data-flow-owner', 'settings');+ }++ fireEvent.click(screen.getByRole('button', {name: 'Start flow'}));+ expect(withId()).toEqual([dialogs[0]]);+ expect(document.getElementById('checkout')).toHaveAttribute('open');++ fireEvent.click(screen.getByRole('button', {name: 'Continue'}));+ // Mid-handoff two dialogs are open; the id names the active one only.+ expect(openDialogs()).toHaveLength(2);+ expect(withId()).toEqual([dialogs[1]]);+ expect(screen.getByTestId('checkout-flow')).toBe(dialogs[1]);+ expect(document.getElementById('checkout')).toHaveAccessibleName(+ 'Confirm',+ );++ fireEvent.click(screen.getByRole('button', {name: 'Done'}));+ finishSheetTransition(getSheetLayer('confirm-sheet'), 'transform');+ expect(withId()).toEqual([dialogs[1]]);+ });++ it('orders a non-modal handoff inside the switcher-owned isolation surface, with no page-wide z-index on a sheet dialog', () => {+ render(<HostFlow hasScrim={false} initialSheet="details" />);+ const detailsDialog = getSheetDialog('details-sheet');+ const confirmDialog = getSheetDialog('confirm-sheet');+ const flow = detailsDialog.parentElement;+ if (flow == null) {+ throw new Error('flow wrapper not found');+ }+ expect(flow).toBe(confirmDialog.parentElement);+ // The wrapper is the isolated surface for the flow (`spec:AST-027`+ // FR2) and carries the one overlay value the shared shell carried.+ expect(getComputedStyle(flow).isolation).toBe('isolate');+ expect(getComputedStyle(flow).zIndex).toBe('1000');++ fireEvent.click(screen.getByRole('button', {name: 'Continue'}));+ expect(openDialogs()).toEqual([detailsDialog, confirmDialog]);+ // Inside it the dialogs use local values only: the interactive sheet+ // on top at 1, the retained sheet at auto. Neither is in a page band.+ expect(getComputedStyle(confirmDialog).zIndex).toBe('1');+ // jsdom reports an unset z-index as '' where a browser says 'auto'.+ expect(['', 'auto']).toContain(getComputedStyle(detailsDialog).zIndex);+ for (const dialog of [detailsDialog, confirmDialog]) {+ expect(Number(getComputedStyle(dialog).zIndex) >= 1000).toBe(false);+ }+ });++ it('applies the switcher dialog props to each sheet dialog, with a consumer role kept unless a required step forces alertdialog', () => {+ const onToggle = vi.fn();+ render(+ <BottomSheetSwitcher+ activeSheet="details"+ onActiveSheetChange={() => {}}+ className="consumer-switcher"+ style={{insetInlineStart: 12}}+ role="alertdialog"+ aria-describedby="flow-help"+ data-flow-owner="settings"+ onToggle={onToggle}>+ <BottomSheet sheetId="details" label="Details" data-testid="a">+ Content+ </BottomSheet>+ <BottomSheet sheetId="confirm" label="Confirm" data-testid="b">+ Content+ </BottomSheet>+ <BottomSheet+ sheetId="danger"+ label="Danger"+ purpose="required"+ data-testid="c">+ Content+ </BottomSheet>+ </BottomSheetSwitcher>,+ );+ // Every switcher prop the shared dialog honoured reaches every sheet+ // dialog, explicit attributes included: a consumer `role` is kept+ // (the shared dialog let it through) and a `required` step still+ // forces `alertdialog`.+ for (const testId of ['a', 'b', 'c']) {+ const dialog = getSheetDialog(testId);+ expect(dialog).toHaveClass('consumer-switcher');+ expect(dialog).toHaveStyle({insetInlineStart: '12px'});+ expect(dialog).toHaveAttribute('data-flow-owner', 'settings');+ expect(dialog).toHaveAttribute('aria-describedby', 'flow-help');+ expect(dialog).toHaveAttribute('role', 'alertdialog');+ fireEvent(dialog, new Event('toggle'));+ }+ expect(onToggle).toHaveBeenCalledTimes(3);+ expect(getSheetDialog('a')).toHaveAttribute('aria-label', 'Details');+ expect(getSheetDialog('b')).toHaveAttribute('aria-label', 'Confirm');+ });++ it('paints one scrim through a handoff and hands it over without a fade', () => {+ render(<Flow />);+ fireEvent.click(screen.getByRole('button', {name: 'Start flow'}));+ const detailsDialog = getSheetDialog('details-sheet');+ const confirmDialog = getSheetDialog('confirm-sheet');+ expect(detailsDialog).toHaveStyle({'--_sheet-scrim-opacity': '1'});++ fireEvent.click(screen.getByRole('button', {name: 'Continue'}));+ // The retained dialog's backdrop is the scrim; the entering dialog's+ // backdrop, painted above the retained panel, stays clear.+ expect(detailsDialog).toHaveStyle({'--_sheet-scrim-opacity': '1'});+ expect(confirmDialog).toHaveStyle({'--_sheet-scrim-opacity': '0'});++ finishSheetTransition(getSheetLayer('confirm-sheet'), 'transform');+ expect(detailsDialog).toHaveStyle({'--_sheet-scrim-opacity': '1'});+ expect(confirmDialog).toHaveStyle({'--_sheet-scrim-opacity': '0'});++ finishSheetTransition(getSheetLayer('details-sheet'), 'opacity');+ expect(detailsDialog).not.toHaveAttribute('open');+ expect(confirmDialog).toHaveStyle({'--_sheet-scrim-opacity': '1'});+ // The swap pins the backdrop transition for one style flush only.+ expect(+ confirmDialog.style.getPropertyValue('--_sheet-scrim-duration'),+ ).toBe('');++ fireEvent.keyDown(confirmDialog, {key: 'Escape'});+ expect(confirmDialog).toHaveStyle({'--_sheet-scrim-opacity': '0'});+ });++ it('moves focus into the entering sheet while the retained dialog is inert', () => {+ render(<Flow />);+ const opener = screen.getByRole('button', {name: 'Start flow'});+ opener.focus();+ fireEvent.click(opener);+ expect(getSheetPanel(getSheetDialog('details-sheet'))).toHaveFocus();++ fireEvent.click(screen.getByRole('button', {name: 'Continue'}));++ expect(getSheetPanel(getSheetDialog('confirm-sheet'))).toHaveFocus();+ expect(getSheetDialog('details-sheet')).toHaveAttribute('inert');+ expect(getSheetDialog('details-sheet')).toHaveAttribute(+ 'aria-hidden',+ 'true',+ );+ expect(getSheetDialog('confirm-sheet')).not.toHaveAttribute('inert');++ finishSheetTransition(getSheetLayer('confirm-sheet'), 'transform');+ finishSheetTransition(getSheetLayer('details-sheet'), 'opacity');+ fireEvent.keyDown(getSheetDialog('confirm-sheet'), {key: 'Escape'});+ finishSheetTransition(getSheetLayer('confirm-sheet'), 'transform');++ expect(opener).toHaveFocus();+ });++ it('moves focus only when a step is entered or the flow ends: a retained dialog closing after its fade fires no focus event', () => {+ // close() on a modal dialog returns focus to the element focused when+ // it was presented -- the Continue or Back that advanced the flow, or+ // the opener -- and the retained dialog closes a fade after the user+ // is in the next step. Each step presents with nothing recorded, so+ // the close moves nothing: no focus/blur/focusin/focusout anywhere+ // while a retained dialog closes, after Continue, after Back, and+ // after a reversal mid-handoff.+ recordDialogCalls();+ render(<Flow />);+ const events: string[] = [];+ const record = (event: Event) => {+ const target = event.target as HTMLElement;+ events.push(+ `${event.type}:${target.getAttribute('aria-label') ?? target.textContent?.trim() ?? target.tagName}`,+ );+ };+ for (const type of ['focus', 'blur', 'focusin', 'focusout']) {+ document.addEventListener(type, record, true);+ }+ const take = () => events.splice(0, events.length);++ const opener = screen.getByRole('button', {name: 'Start flow'});+ opener.focus();+ fireEvent.click(opener);+ const detailsPanel = getSheetPanel(getSheetDialog('details-sheet'));+ const confirmPanel = getSheetPanel(getSheetDialog('confirm-sheet'));+ expect(detailsPanel).toHaveFocus();+ take();++ // Continue: focus moves once, from the control into the entering step.+ const continueButton = screen.getByRole('button', {name: 'Continue'});+ continueButton.focus();+ fireEvent.click(continueButton);+ expect(confirmPanel).toHaveFocus();+ take();+ // The retained Details dialog closes after its fade: nothing moves.+ finishSheetTransition(getSheetLayer('confirm-sheet'), 'transform');+ finishSheetTransition(getSheetLayer('details-sheet'), 'opacity');+ expect(getSheetDialog('details-sheet')).not.toHaveAttribute('open');+ expect(take()).toEqual([]);+ expect(confirmPanel).toHaveFocus();++ // Back: the same, with the retained Confirm dialog closing.+ const backButton = screen.getByRole('button', {name: 'Back'});+ backButton.focus();+ fireEvent.click(backButton);+ expect(detailsPanel).toHaveFocus();+ take();+ finishSheetTransition(getSheetLayer('details-sheet'), 'transform');+ finishSheetTransition(getSheetLayer('confirm-sheet'), 'opacity');+ expect(getSheetDialog('confirm-sheet')).not.toHaveAttribute('open');+ expect(take()).toEqual([]);+ expect(detailsPanel).toHaveFocus();++ // Reversal mid-handoff: Continue, then Back before Confirm settles.+ continueButton.focus();+ fireEvent.click(continueButton);+ expect(confirmPanel).toHaveFocus();+ backButton.focus();+ fireEvent.click(backButton);+ expect(detailsPanel).toHaveFocus();+ take();+ finishSheetTransition(getSheetLayer('details-sheet'), 'transform');+ finishSheetTransition(getSheetLayer('confirm-sheet'), 'opacity');+ expect(getSheetDialog('confirm-sheet')).not.toHaveAttribute('open');+ expect(take()).toEqual([]);+ expect(detailsPanel).toHaveFocus();++ // Ending the flow: the switcher returns focus to the opener itself.+ fireEvent.keyDown(getSheetDialog('details-sheet'), {key: 'Escape'});+ finishSheetTransition(getSheetLayer('details-sheet'), 'transform');+ expect(opener).toHaveFocus();+ for (const type of ['focus', 'blur', 'focusin', 'focusout']) {+ document.removeEventListener(type, record, true);+ }+ });++ it("answers a native cancel by the active sheet's purpose after a handoff", () => {+ const log = recordDialogCalls();+ render(<RequiredConfirmFlow />);+ expect(screen.queryByRole('alertdialog')).toBeNull();++ fireEvent.click(screen.getByRole('button', {name: 'Continue'}));+ finishSheetTransition(getSheetLayer('confirm-sheet'), 'transform');+ finishSheetTransition(getSheetLayer('details-sheet'), 'opacity');++ const confirmDialog = getSheetDialog('confirm-sheet');+ expect(confirmDialog).toHaveAttribute('role', 'alertdialog');+ expect(getSheetDialog('details-sheet')).not.toHaveAttribute('role');++ fireEvent.keyDown(confirmDialog, {key: 'Escape'});+ const cancel = new Event('cancel', {cancelable: true});+ confirmDialog.dispatchEvent(cancel);+ fireEvent.click(confirmDialog);++ // Always prevented: the browser never closes a controlled dialog.+ expect(cancel.defaultPrevented).toBe(true);+ expect(confirmDialog).toHaveAttribute('open');+ expect(log.filter(entry => entry.startsWith('close:'))).toEqual([+ 'close:Details',+ ]);++ fireEvent.click(screen.getByRole('button', {name: 'Done'}));+ finishSheetTransition(getSheetLayer('confirm-sheet'), 'transform');+ expect(openDialogs()).toEqual([]);+ });++ it("dismisses an info flow from a cancel on any sheet dialog, and from a backdrop click on the active sheet's dialog only", () => {+ const onActiveSheetChange = vi.fn();+ render(+ <BottomSheetSwitcher+ activeSheet="confirm"+ onActiveSheetChange={onActiveSheetChange}>+ <BottomSheet sheetId="details" label="Details" data-testid="a">+ Content+ </BottomSheet>+ <BottomSheet sheetId="confirm" label="Confirm" data-testid="b">+ <button type="button">Inside</button>+ </BottomSheet>+ </BottomSheetSwitcher>,+ );+ const activeDialog = getSheetDialog('b');++ const cancel = new Event('cancel', {cancelable: true});+ activeDialog.dispatchEvent(cancel);+ expect(cancel.defaultPrevented).toBe(true);+ expect(onActiveSheetChange).toHaveBeenNthCalledWith(1, null);++ // A `::backdrop` click targets the dialog element itself.+ fireEvent.click(activeDialog);+ expect(onActiveSheetChange).toHaveBeenNthCalledWith(2, null);++ // A click that is not on a backdrop, or on a dialog other than the+ // host's, dismisses nothing.+ fireEvent.click(screen.getByRole('button', {name: 'Inside'}));+ fireEvent.click(getSheetDialog('a'));+ expect(onActiveSheetChange).toHaveBeenCalledTimes(2);++ // The composed cancel handler is on every sheet dialog, not the host+ // only: the browser raises `cancel` on the dialog it presents, so in+ // engines this is the active sheet's, but the switcher does not guard+ // it by host.+ const cancelElsewhere = new Event('cancel', {cancelable: true});+ getSheetDialog('a').dispatchEvent(cancelElsewhere);+ expect(cancelElsewhere.defaultPrevented).toBe(true);+ expect(onActiveSheetChange).toHaveBeenNthCalledWith(3, null);+ });++ it('presents a non-modal flow with show() on each sheet dialog', () => {+ const log = recordDialogCalls();+ render(<HostFlow hasScrim={false} initialSheet="details" />);+ expect(log).toEqual(['show:Details']);++ fireEvent.click(screen.getByRole('button', {name: 'Continue'}));++ expect(log).toEqual(['show:Details', 'show:Confirm']);+ expect(openDialogs()).toHaveLength(2);+ expect(getSheetDialog('confirm-sheet')).not.toHaveAttribute('aria-modal');+ expect(isScrollLockEngaged()).toBe(false);++ finishSheetTransition(getSheetLayer('confirm-sheet'), 'transform');+ finishSheetTransition(getSheetLayer('details-sheet'), 'opacity');+ expect(log).toEqual(['show:Details', 'show:Confirm', 'close:Details']);+ });++ it('re-presents a sheet that is still fading when the flow returns to it', () => {+ const log = recordDialogCalls();+ render(<Flow />);+ fireEvent.click(screen.getByRole('button', {name: 'Start flow'}));+ fireEvent.click(screen.getByRole('button', {name: 'Continue'}));+ fireEvent.click(screen.getByRole('button', {name: 'Back'}));++ // Details was still open beneath Confirm in the top layer; it closes and+ // presents again so the interactive sheet is the topmost modal layer.+ expect(log).toEqual([+ 'showModal:Details',+ 'showModal:Confirm',+ 'close:Details',+ 'showModal:Details',+ ]);+ expect(getActiveDialog()).toBe(getSheetDialog('details-sheet'));+ expect(getSheetDialog('confirm-sheet')).toHaveAttribute('inert');++ finishSheetTransition(getSheetLayer('confirm-sheet'), 'opacity');+ expect(log.at(-1)).toBe('close:Confirm');+ expect(openDialogs()).toEqual([getSheetDialog('details-sheet')]);+ });+ });});diff --git a/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx b/packages/core/src/BottomSheet/BottomSheetSwitcher.tsxindex 3b4df57075..d9da5e7ea8 100644--- a/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx+++ b/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx@@ -4,7 +4,7 @@/*** @file BottomSheetSwitcher.tsx- * @input Uses React context, StyleX, theme tokens, shared layer dismissal, focus/scroll-lock hooks, BottomSheetSwitcherContext+ * @input Uses React context, StyleX, shared layer dismissal, BottomSheetSwitcherContext* @output Exports BottomSheetSwitcher and BottomSheetSwitcherProps* @position Core switcher for mutually exclusive BottomSheet flows*@@ -15,14 +15,37 @@* down at the same time until their top edges align; otherwise it stays* stationary. The previous sheet fades only after both motions complete.*- * All child sheets render as panels inside one switcher-owned `<dialog>`. A- * scrim flow calls showModal() once and keeps that native top-layer dialog open- * across every handoff. A no-scrim flow calls show() on the same non-modal shell.- * This keeps one modal boundary and one native ::backdrop without a portal.+ * Every child sheet owns a native `<dialog>`, exactly like a standalone+ * sheet: a scrim flow presents each sheet with showModal(), a no-scrim flow+ * with show(). The browser then does what a modal dialog does -- the page is+ * inert, focus stays in the top-layer dialog, Escape and the platform close+ * arrive as `cancel`. The switcher is the coordinator: it decides which+ * sheet dialog is presented, retained, or hidden, keeps one scrim painted+ * across a handoff (the retained sheet's backdrop until it fades, then the+ * new sheet's, swapped without a fade), holds the flow's one page scroll+ * lock (the shared useScrollLock, as Dialog uses, acquired once while the+ * flow is presented and released after its exit, never per step) and the+ * one layer-dismissal registration, and returns focus to the flow's opener+ * when the flow ends, which no single dialog can know.+ *+ * The switcher's one element is a flow wrapper. In a scrim flow it has no box+ * (`display: contents`): the dialogs sit in the top layer. In a no-scrim flow+ * it is the isolated surface that orders the sheet dialogs locally, the way+ * the shared shell once did, so no sheet needs a page-level value of its own.+ *+ * Its `ref` resolves to the host dialog: the one presenting the active sheet,+ * the exiting sheet's through its exit, and the last host's (or the first+ * mounted sheet's) while the flow is closed, so the ref is never null while a+ * sheet is mounted. `id` and `data-testid` render on the host dialog only:+ * a flow that mounts open carries them on the active sheet's dialog in server+ * markup too; a flow that mounts closed carries them from the first commit's+ * synchronous re-render on, and its server markup carries them on no element.+ * Every other dialog prop and handler, `onCancel` included, applies to every+ * sheet dialog; the browser raises `cancel` on the dialog it presents.** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/BottomSheet/BottomSheet.tsx- * - /packages/core/src/BottomSheet/BottomSheetEdgeTint.tsx+ * - /packages/core/src/BottomSheet/BottomSheetSwitcherContext.ts* - /packages/core/src/BottomSheet/BottomSheetSwitcher.doc.mjs* - /packages/core/src/BottomSheet/BottomSheetSwitcher.spec.md* - /packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx@@ -45,78 +68,42 @@ import {import * as stylex from '@stylexjs/stylex';import type {BaseProps} from '../BaseProps';import type {DialogPurpose} from '../Dialog';-import {colorVars, durationVars, easeVars} from '../theme/tokens.stylex';import {useScrollLock} from '../hooks';-import {- useFocusTrap,- useFocusTrapEscapeCompatibilitySignal,-} from '../hooks/useFocusTrap';-import {LayerDepthProvider} from '../Layer/LayerDepthContext';+import {useFocusTrapEscapeCompatibilitySignal} from '../hooks/useFocusTrap';import {dispatchLayerEscapeKeyDown} from '../Layer/layerStack';import {useLayerDismissal} from '../Layer/useLayerDismissal';-import {composeEventHandlers, mergeProps} from '../utils';-import {BottomSheetEdgeTint} from './BottomSheetEdgeTint';+import {composeEventHandlers} from '../utils';+import {mergeRefs} from '../utils/mergeRefs';import {BottomSheetSwitcherContext,type BottomSheetSwitcherContextValue,+ type BottomSheetSwitcherDialogProps,type BottomSheetSwitcherPhase,type BottomSheetSwitcherTransitionEvent,} from './BottomSheetSwitcherContext';-import {useMergedRefs} from '../hooks/useMergedRefs';const styles = stylex.create({- dialog: {- position: 'fixed',- inset: 0,- width: '100dvw',- height: '100dvh',- maxWidth: 'none',- maxHeight: 'none',- margin: 0,- padding: 0,- borderWidth: 0,- borderStyle: 'none',- backgroundColor: 'transparent',- overflow: 'visible',- display: 'none',- outline: 'none',+ // A scrim flow's dialogs live in the top layer; the wrapper has no box.+ flow: {+ display: 'contents',},- dialogOpen: {+ // show() leaves a no-scrim flow in the normal rendering tree, where DOM+ // order would decide which sheet dialog paints in front during a handoff.+ // The wrapper is then the flow's isolated surface: the sheet dialogs order+ // themselves locally inside it (`spec:AST-027` FR2), and the wrapper itself+ // keeps the one overlay value the shared shell carried before, which+ // `spec:AST-027` records as the non-modal migration gap. It passes pointer+ // input through to the live page; each sheet panel opts back in. Consumers+ // of this non-modal mode must still avoid transformed or clipping ancestors.+ flowNonModal: {display: 'block',- },- // show() leaves a no-scrim flow in the normal rendering tree. The shell must- // pass pointer input through to the live page; each sheet panel opts back in.- // width/height 100% avoids overflowing a transformed containing block, but- // consumers of this non-modal mode must still avoid clipping ancestors.- dialogNonModal: {- pointerEvents: 'none',- zIndex: 1000,+ position: 'fixed',+ inset: 0,width: '100%',height: '100%',- },- scrim: {- '::backdrop': {- backgroundColor: colorVars['--color-overlay'],- opacity: {- default: 'var(--_sheet-scrim-opacity, 1)',- '@starting-style': 0,- },- transitionProperty: 'opacity, display',- transitionDuration: durationVars['--duration-medium'],- transitionTimingFunction: easeVars['--ease-standard'],- transitionBehavior: 'allow-discrete',- '@media (prefers-reduced-motion: reduce)': {- transitionDuration: '0.01s',- },- },- },- // The flow's dim leaves with its last panel. Same rule, same reasoning, as- // a standalone sheet's -- see `scrimClosing` in BottomSheet.tsx. A handoff- // between two sheets is not a close, and keeps the entrance curve.- scrimClosing: {- '::backdrop': {- transitionTimingFunction: 'linear',- },+ pointerEvents: 'none',+ isolation: 'isolate',+ zIndex: 1000,},});@@ -179,11 +166,54 @@ function alignmentOffsetForElements(return Math.max(0, enteringTop - retainedElement.getBoundingClientRect().top);}+/**+ * Keeps one object identity while its own enumerable entries are unchanged, so+ * the consumer's rest props can sit in a memoized context value without+ * refreshing every sheet host on each switcher render.+ */+function useShallowStable<T extends object>(value: T): T {+ const stableRef = useRef(value);+ const previous = stableRef.current;+ const previousKeys = Object.keys(previous) as (keyof T)[];+ const nextKeys = Object.keys(value) as (keyof T)[];+ const isSame =+ previousKeys.length === nextKeys.length &&+ nextKeys.every(key => Object.is(previous[key], value[key]));+ if (!isSame) {+ stableRef.current = value;+ }+ return stableRef.current;+}++/**+ * Hands the flow's scrim to `dialog` without a fade. The backdrop's opacity+ * transition would otherwise ease from the transparent value the entering+ * dialog was presented with, dipping the page's dim for one motion token+ * exactly when the previous dialog's backdrop disappears. Even a near-zero+ * duration paints its first frame at the start value, so the swap disables+ * the transition outright, flushes style so the new value is committed under+ * that rule, then restores the token for later gesture and exit fades.+ */+function takeOverScrim(dialog: HTMLDialogElement, opacity: number): void {+ dialog.style.setProperty('--_sheet-scrim-duration', '0s');+ dialog.style.setProperty('--_sheet-scrim-opacity', String(opacity));+ if (typeof getComputedStyle === 'function') {+ void getComputedStyle(dialog, '::backdrop').opacity;+ }+ dialog.style.removeProperty('--_sheet-scrim-duration');+}+export interface BottomSheetSwitcherProps extends BaseProps<HTMLDialogElement> {- /** Ref forwarded to the shared native dialog. */+ /**+ * Ref resolved to the native dialog hosting the flow: the active sheet's+ * dialog, which changes on a handoff; the exiting sheet's through its exit;+ * and, while the flow is closed, the dialog that hosted it last (or the+ * first mounted sheet's), so it is never null while a sheet is mounted,+ * from the first commit on.+ */ref?: React.Ref<HTMLDialogElement>;- /** Called when the shared native dialog receives a cancel event. */+ /** Called when the active sheet's native dialog receives a cancel event. */onCancel?: (event: SyntheticEvent<HTMLDialogElement>) => void;/**@@ -198,7 +228,7 @@ export interface BottomSheetSwitcherProps extends BaseProps<HTMLDialogElement> {onActiveSheetChange: (sheetId: string | null) => void;/**- * Whether to open the shared dialog modally with its native ::backdrop.+ * Whether each sheet dialog opens modally with a native ::backdrop.* Disable for a viewport-anchored, non-modal flow over an interactive page.* @default true*/@@ -209,8 +239,8 @@ export interface BottomSheetSwitcherProps extends BaseProps<HTMLDialogElement> {}/**- * Coordinates a set of BottomSheets so zero or one is active at a time inside- * one shared native dialog. During a handoff the previous panel stays visible+ * Coordinates a set of BottomSheets so zero or one is active at a time, each+ * in its own native dialog. During a handoff the previous panel stays visible* and inert beneath the entering panel, then fades after motion completes.** @example@@ -229,22 +259,40 @@ export function BottomSheetSwitcher({hasScrim = true,children,ref,- xstyle,- className,- style,onCancel,onClick,onKeyDown,- ...props+ className,+ style,+ xstyle,+ ...restDialogProps}: BottomSheetSwitcherProps) {- const dialogRef = useRef<HTMLDialogElement | null>(null);- const dialogModeRef = useRef<'modal' | 'non-modal' | null>(null);+ // Every sheet host applies the switcher's dialog surface to its own dialog.+ const dialogProps = useShallowStable<BottomSheetSwitcherDialogProps>({+ ...restDialogProps,+ className,+ style,+ xstyle,+ });+ const hostDialogRef = useRef<HTMLDialogElement | null>(null);+ const sheetDialogsRef = useRef(new Map<string, HTMLDialogElement>());+ // Sheet ids in the order their dialogs mounted (tree order on first mount).+ // State, not a ref: the resting host below is rendered -- it carries the+ // consumer's `id` -- so a sheet mounting or leaving must re-render.+ const [sheetOrder, setSheetOrder] = useState<ReadonlyArray<string>>([]);+ // The sheet that hosted the flow last, kept while the flow is closed so the+ // ref and `id` stay on the dialog the person last used. State adjusted+ // during render (not a ref read during render): it changes exactly when+ // the presented host does, and the next render reads it.+ const [lastHostSheet, setLastHostSheet] = useState<string | null>(null);+ const presentationOrderRef = useRef(new Map<string, number>());+ const presentationCounterRef = useRef(0);+ const modalFlowRef = useRef(false);const triggerRef = useRef<HTMLElement | null>(null);const sheetElementsRef = useRef(new Map<string, HTMLElement>());const committedActiveSheetRef = useRef(activeSheet);- const [sheetLabels, setSheetLabels] = useState<ReadonlyMap<string, string>>(- () => new Map(),- );+ const scrimOpacityRef = useRef(1);+ const scrimOwnerRef = useRef<string | null>(null);const [sheetPurposes, setSheetPurposes] = useState<ReadonlyMap<string, DialogPurpose>>(() => new Map());@@ -261,11 +309,42 @@ export function BottomSheetSwitcher({activeSheet,): transition;+ const presentedActiveSheet =+ activeSheet != null && !unmountedSheetIds.has(activeSheet)+ ? activeSheet+ : null;+ const presentedRetainedSheet =+ visibleTransition.retainedSheet != null &&+ !unmountedSheetIds.has(visibleTransition.retainedSheet)+ ? visibleTransition.retainedSheet+ : null;const isFlowVisible =- (activeSheet != null && !unmountedSheetIds.has(activeSheet)) ||- (visibleTransition.retainedSheet != null &&- !unmountedSheetIds.has(visibleTransition.retainedSheet));+ presentedActiveSheet != null || presentedRetainedSheet != null;const isModal = hasScrim && isFlowVisible;+ // The dialog that hosts the flow for its ref, its single-instance+ // attributes, and its dismissal registration: the active sheet's, the+ // retained sheet's while the flow closes through its exit, and while the+ // flow is closed the dialog that hosted it last (or the first mounted+ // sheet's before any open), so the ref resolves to a closed dialog element+ // rather than to null, as the shared dialog did. Which sheet mounts first+ // is known only once its dialog registers during the first commit: the+ // ref is attached to it in that same commit (below), and the rendered+ // `id` follows in the synchronous re-render that commit schedules, before+ // the first paint. Server markup therefore carries the `id` on no element.+ const presentedHostSheet = presentedActiveSheet ?? presentedRetainedSheet;+ if (presentedHostSheet != null && presentedHostSheet !== lastHostSheet) {+ setLastHostSheet(presentedHostSheet);+ }+ const restingHostSheet =+ lastHostSheet != null && sheetOrder.includes(lastHostSheet)+ ? lastHostSheet+ : (sheetOrder[0] ?? null);+ const hostSheet = presentedHostSheet ?? restingHostSheet;+ // The dialog whose backdrop paints the flow's one scrim. A retained sheet+ // keeps it through a handoff so the entering dialog, presented above it in+ // the top layer, does not dim the previous panel beneath its own backdrop.+ const scrimOwnerSheet = presentedRetainedSheet ?? presentedActiveSheet;+ const isFlowClosing = isFlowVisible && activeSheet == null;const activeSheetPurpose =(activeSheet == null ? null : sheetPurposes.get(activeSheet)) ?? 'info';const allowsEscapeDismiss = activeSheetPurpose !== 'required';@@ -299,59 +378,102 @@ export function BottomSheetSwitcher({onActiveSheetChange(null);}}, [allowsLightDismiss, onActiveSheetChange]);- const {containerRef} = useFocusTrap<HTMLDialogElement>({- isActive: isModal,- });- // Before the shared dismissal stack, this modal trap supplied `onEscape`, so- // the released compatibility shim reported it as active. Keep that signal- // without registering the switcher twice in the one shared stack.+ // Focus containment is the native modal dialog's: showModal() makes the+ // page inert, so Tab cannot leave the active sheet. The released read-only+ // `hasActiveFocusTrapEscape()` signal still reports a modal flow as a trap,+ // as it did when a JavaScript trap backed it.useFocusTrapEscapeCompatibilitySignal(isModal);+ // One lock for the whole modal flow, as on a shared dialog: `isModal` stays+ // true through a handoff (two dialogs open) and through the exit motion, so+ // the shared counter is taken once and given back once.+ useScrollLock(isModal);const {shouldDismissOnCloseRequest} = useLayerDismissal({isActive: isFlowVisible,escapeBehavior: allowsEscapeDismiss ? 'close' : 'block',onDismiss: dismissOnEscape,- getContainer: () => dialogRef.current,- isPresent: () => dialogRef.current?.open ?? false,+ getContainer: () => hostDialogRef.current,+ isPresent: () => hostDialogRef.current?.open ?? false,});- useScrollLock(isModal);- // Open one shared shell for the complete flow. Modal flows enter the native- // top layer once; handoffs only swap panels inside it. The final panel owns- // the exit timing, so isFlowVisible becomes false only when it is safe to- // close the dialog and restore focus.+ // Point the consumer ref and the dismissal registration at the host dialog.+ // Sheet hosts register their dialogs during commit, so by the time this+ // layout effect runs the map already names the dialog for `hostSheet` --+ // and, in the first commit of a flow that mounts closed, the first+ // registered dialog before `sheetOrder` has caught up, so a parent's own+ // mount effects already find the ref resolved. The ref is attached the way+ // React attaches one: a callback ref's returned cleanup runs on detach, and+ // only a ref without one receives null. Attachment follows the resolved+ // element, not the render that resolved it: the re-render that catches+ // `sheetOrder` up resolves the same dialog and leaves the ref alone.+ const attachedRef = useRef<{+ ref: React.Ref<HTMLDialogElement> | undefined;+ host: HTMLDialogElement;+ detach: (() => void) | undefined;+ } | null>(null);useLayoutEffect(() => {- const dialog = dialogRef.current;- if (dialog == null) {+ const host =+ hostSheet == null+ ? (sheetDialogsRef.current.values().next().value ?? null)+ : (sheetDialogsRef.current.get(hostSheet) ?? null);+ hostDialogRef.current = host;+ const attached = attachedRef.current;+ if (attached?.host === host && attached.ref === ref) {return;}+ attached?.detach?.();+ if (host == null) {+ attachedRef.current = null;+ return;+ }+ const detach = mergeRefs(ref)(host);+ attachedRef.current = {+ ref,+ host,+ detach: typeof detach === 'function' ? detach : undefined,+ };+ }, [hostSheet, ref, sheetOrder]);+ useLayoutEffect(+ () => () => {+ hostDialogRef.current = null;+ attachedRef.current?.detach?.();+ attachedRef.current = null;+ },+ [],+ );+ // Focus return is native per dialog: each showModal() records the focused+ // element and close() focuses it again. That serves a one-sheet flow, but+ // the second sheet of a flow records a control inside the first, which is+ // hidden by the time the flow ends, so the browser's return lands nowhere.+ // The flow therefore remembers its own opener -- the page element focused+ // before the first modal present -- and focuses it after the last dialog+ // closes. Sheet hosts ask before presenting modally, so the capture sees+ // the page element; hosts present in their own layout effects, which run+ // before the one below, so the restore follows the last dialog's close.+ const onBeforeSheetPresent = useCallback((sheetId: string) => {+ if (triggerRef.current == null) {+ triggerRef.current = document.activeElement as HTMLElement | null;+ }+ modalFlowRef.current = true;+ presentationCounterRef.current += 1;+ presentationOrderRef.current.set(sheetId, presentationCounterRef.current);+ }, []);+ useLayoutEffect(() => {if (isFlowVisible) {- const nextMode = hasScrim ? 'modal' : 'non-modal';- if (dialog.open && dialogModeRef.current !== nextMode) {- dialog.close();+ if (!hasScrim) {+ modalFlowRef.current = false;}- if (!dialog.open) {- if (hasScrim && triggerRef.current == null) {- triggerRef.current = document.activeElement as HTMLElement | null;- }- if (hasScrim) {- dialog.showModal();- } else {- dialog.show();- }- }- dialogModeRef.current = nextMode;return;}-- if (dialog.open) {- dialog.close();- }- if (dialogModeRef.current === 'modal') {- triggerRef.current?.focus();+ if (modalFlowRef.current) {+ // Like the browser's own return on close(), without scrolling: the+ // page kept its scroll offset under the lock, and an opener scrolled+ // out of view must not drag the page back to itself.+ triggerRef.current?.focus({preventScroll: true});}triggerRef.current = null;- dialogModeRef.current = null;+ modalFlowRef.current = false;+ presentationOrderRef.current.clear();}, [hasScrim, isFlowVisible]);const getSheetPhase = useCallback(@@ -377,6 +499,11 @@ export function BottomSheetSwitcher({[visibleTransition],);+ const isScrimOwner = useCallback(+ (sheetId: string) => sheetId === scrimOwnerSheet,+ [scrimOwnerSheet],+ );+const registerSheetElement = useCallback((sheetId: string, element: HTMLElement | null) => {if (element == null) {@@ -407,28 +534,44 @@ export function BottomSheetSwitcher({[],);- const registerSheetLabel = useCallback(- (sheetId: string, label: string | null) => {- setSheetLabels(current => {- if (label == null) {- if (!current.has(sheetId)) {- return current;- }- const next = new Map(current);- next.delete(sheetId);- return next;- }- if (current.get(sheetId) === label) {- return current;- }- const next = new Map(current);- next.set(sheetId, label);- return next;- });+ const registerSheetDialog = useCallback(+ (sheetId: string, dialog: HTMLDialogElement | null) => {+ if (dialog == null) {+ sheetDialogsRef.current.delete(sheetId);+ presentationOrderRef.current.delete(sheetId);+ setSheetOrder(current =>+ current.includes(sheetId)+ ? current.filter(id => id !== sheetId)+ : current,+ );+ } else {+ sheetDialogsRef.current.set(sheetId, dialog);+ setSheetOrder(current =>+ current.includes(sheetId) ? current : [...current, sheetId],+ );+ }},[],);+ const isCoveredInTopLayer = useCallback((sheetId: string) => {+ const order = presentationOrderRef.current;+ const own = order.get(sheetId);+ if (own == null) {+ return false;+ }+ for (const [otherId, stamp] of order) {+ if (+ otherId !== sheetId &&+ stamp > own &&+ sheetDialogsRef.current.get(otherId)?.open+ ) {+ return true;+ }+ }+ return false;+ }, []);+const registerSheetPurpose = useCallback((sheetId: string, purpose: DialogPurpose | null) => {setSheetPurposes(current => {@@ -533,67 +676,64 @@ export function BottomSheetSwitcher({[],);- const setScrimOpacity = useCallback((opacity: number) => {- dialogRef.current?.style.setProperty(- '--_sheet-scrim-opacity',- String(opacity),- );- }, []);+ // One scrim for the flow. Only the owning dialog's backdrop carries the+ // current opacity; every other presented dialog keeps its backdrop clear.+ // When ownership moves — the retained dialog has faded and closes, or a+ // rapid replacement hides it — the new owner takes the value without a+ // fade, in the same layout pass that closes the old one.+ const applyScrimOpacity = useCallback(() => {+ const owner =+ scrimOwnerSheet == null+ ? null+ : (sheetDialogsRef.current.get(scrimOwnerSheet) ?? null);+ // A fresh open keeps the backdrop's @starting-style fade; only a hand+ // from one presented dialog to another swaps without one.+ const ownerChanged =+ scrimOwnerRef.current != null &&+ scrimOwnerRef.current !== scrimOwnerSheet;+ scrimOwnerRef.current = scrimOwnerSheet;+ for (const [sheetId, dialog] of sheetDialogsRef.current) {+ if (dialog === owner) {+ if (ownerChanged && dialog.open) {+ takeOverScrim(dialog, scrimOpacityRef.current);+ } else {+ dialog.style.setProperty(+ '--_sheet-scrim-opacity',+ String(scrimOpacityRef.current),+ );+ }+ } else if (sheetId !== scrimOwnerSheet) {+ dialog.style.setProperty('--_sheet-scrim-opacity', '0');+ }+ }+ }, [scrimOwnerSheet]);const onSheetScrimOpacityChange = useCallback((sheetId: string, opacity: number) => {// A pointer captured by the outgoing sheet can keep delivering gesture// events after a handoff. Only the currently committed sheet owns the- // shared backdrop, so stale gesture updates must not reach the dialog.+ // flow's scrim value, so stale gesture updates must not reach it.if (sheetId !== committedActiveSheetRef.current) {return;}- setScrimOpacity(opacity);+ scrimOpacityRef.current = opacity;+ applyScrimOpacity();},- [setScrimOpacity],+ [applyScrimOpacity],);+ // A committed selection resets the flow's scrim value -- 1 while a sheet+ // is active, 0 for the exit fade -- and writes it to the owning backdrop in+ // the same effect; a gesture then adjusts the value through+ // `onSheetScrimOpacityChange` until the next selection.useLayoutEffect(() => {- setScrimOpacity(activeSheet == null ? 0 : 1);- }, [activeSheet, setScrimOpacity]);-- const contextValue = useMemo<BottomSheetSwitcherContextValue>(- () => ({- activeSheet,- hasScrim,- onActiveSheetChange,- getSheetPhase,- getSheetAlignmentOffset,- registerSheetElement,- registerSheetLabel,- registerSheetPurpose,- onSheetEnterStart,- onSheetTransitionComplete,- onSheetScrimOpacityChange,- }),- [- activeSheet,- getSheetAlignmentOffset,- getSheetPhase,- hasScrim,- onActiveSheetChange,- onSheetEnterStart,- onSheetScrimOpacityChange,- onSheetTransitionComplete,- registerSheetElement,- registerSheetLabel,- registerSheetPurpose,- ],- );-- const activeLabel =- (activeSheet == null ? null : sheetLabels.get(activeSheet)) ??- (visibleTransition.retainedSheet == null- ? undefined- : sheetLabels.get(visibleTransition.retainedSheet));-- // A `cancel` that bubbles up from a step is not a close request for the- // flow: a file input fires one when its picker is dismissed, and a step- // renders no dialog of its own, so it lands here. It is left alone.+ scrimOpacityRef.current = activeSheet == null ? 0 : 1;+ applyScrimOpacity();+ }, [applyScrimOpacity, activeSheet, hasScrim, isFlowVisible]);++ // A `cancel` that bubbles up from inside a step is not a close request for+ // the flow: a file input fires one when its picker is dismissed, and it+ // reaches the step's dialog. Only a `cancel` fired at a sheet dialog itself+ // dismisses; the bubbled one is left alone.const handleCancel = useCallback((event: SyntheticEvent<HTMLDialogElement>) => {if (event.target !== event.currentTarget) {@@ -618,47 +758,88 @@ export function BottomSheetSwitcher({);const handleClick = useCallback((event: ReactMouseEvent<HTMLDialogElement>) => {- if (hasScrim && event.target === event.currentTarget) {+ // A `::backdrop` click targets its dialog element. Only the active+ // sheet's backdrop is the flow's scrim; a retained dialog is inert and+ // a hidden one closed, so neither can be clicked, but be explicit.+ if (+ hasScrim &&+ event.target === event.currentTarget &&+ event.currentTarget === hostDialogRef.current+ ) {dismissOnLightInteraction();}},[dismissOnLightInteraction, hasScrim],);-- const dialogStyleProps = stylex.props(- styles.dialog,- isFlowVisible && styles.dialogOpen,- hasScrim && styles.scrim,- hasScrim && isFlowVisible && activeSheet == null && styles.scrimClosing,- !hasScrim && styles.dialogNonModal,- xstyle,+ const onDialogCancel = useMemo(+ () => composeEventHandlers(onCancel, handleCancel),+ [handleCancel, onCancel],);- const dialogPresentationProps = mergeProps(- dialogStyleProps,- className,- style,+ const onDialogClick = useMemo(+ () => composeEventHandlers(onClick, handleClick),+ [handleClick, onClick],+ );+ const onDialogKeyDown = useMemo(+ () => composeEventHandlers(onKeyDown, handleKeyDown),+ [handleKeyDown, onKeyDown],+ );++ const contextValue = useMemo<BottomSheetSwitcherContextValue>(+ () => ({+ activeSheet,+ hasScrim,+ onActiveSheetChange,+ getSheetPhase,+ getSheetAlignmentOffset,+ hostSheet,+ isScrimOwner,+ isFlowClosing,+ registerSheetElement,+ registerSheetDialog,+ registerSheetPurpose,+ onBeforeSheetPresent,+ isCoveredInTopLayer,+ onSheetEnterStart,+ onSheetTransitionComplete,+ onSheetScrimOpacityChange,+ dialogProps,+ onDialogCancel,+ onDialogClick,+ onDialogKeyDown,+ }),+ [+ activeSheet,+ dialogProps,+ getSheetAlignmentOffset,+ getSheetPhase,+ hasScrim,+ hostSheet,+ isCoveredInTopLayer,+ isFlowClosing,+ isScrimOwner,+ onActiveSheetChange,+ onBeforeSheetPresent,+ onDialogCancel,+ onDialogClick,+ onDialogKeyDown,+ onSheetEnterStart,+ onSheetScrimOpacityChange,+ onSheetTransitionComplete,+ registerSheetDialog,+ registerSheetElement,+ registerSheetPurpose,+ ],);- const ariaLabel =- props['aria-label'] ??- (props['aria-labelledby'] == null ? activeLabel : undefined);return (<BottomSheetSwitcherContext value={contextValue}>- <dialog- {...props}- {...dialogPresentationProps}- ref={useMergedRefs(ref, dialogRef, containerRef)}- aria-label={ariaLabel}- aria-modal={isModal ? 'true' : undefined}- onCancel={composeEventHandlers(onCancel, handleCancel)}- onClick={composeEventHandlers(onClick, handleClick)}- onKeyDown={composeEventHandlers(onKeyDown, handleKeyDown)}- {...(activeSheetPurpose === 'required'- ? {role: 'alertdialog'}- : undefined)}>- <LayerDepthProvider>{children}</LayerDepthProvider>- <BottomSheetEdgeTint />- </dialog>+ <div+ {...stylex.props(+ styles.flow,+ !hasScrim && isFlowVisible && styles.flowNonModal,+ )}>+ {children}+ </div></BottomSheetSwitcherContext>);}diff --git a/packages/core/src/BottomSheet/BottomSheetSwitcherContext.ts b/packages/core/src/BottomSheet/BottomSheetSwitcherContext.tsindex e34f3c910d..ae64dedeb0 100644--- a/packages/core/src/BottomSheet/BottomSheetSwitcherContext.ts+++ b/packages/core/src/BottomSheet/BottomSheetSwitcherContext.ts@@ -5,11 +5,22 @@/*** @file BottomSheetSwitcherContext.ts* @input Uses React context- * @output Internal phase and lifecycle context shared by BottomSheetSwitcher and BottomSheet+ * @output Internal phase, lifecycle, and host-dialog context shared by BottomSheetSwitcher and BottomSheet* @position Private coordination layer for mutually exclusive BottomSheets+ *+ * Every child sheet renders its own native `<dialog>`; the switcher's only+ * element is a flow wrapper. This context carries the phase machine, the+ * host-dialog selection, and the switcher's dialog-level props and handlers+ * down to those sheet hosts.*/+import type {+ KeyboardEvent as ReactKeyboardEvent,+ MouseEvent as ReactMouseEvent,+ SyntheticEvent,+} from 'react';import {createContext} from 'react';+import type {BaseProps} from '../BaseProps';import type {DialogPurpose} from '../Dialog';export type BottomSheetSwitcherPhase =@@ -26,23 +37,67 @@ export interface BottomSheetSwitcherTransitionEvent {phase: 'entering' | 'aligning' | 'fading' | 'exiting';}+/**+ * The switcher's own dialog surface, applied by every sheet host. `ref` is not+ * part of it: the switcher resolves its ref to the host sheet's dialog, and+ * the single-instance attributes (`id`, `data-testid`) render there only.+ */+export type BottomSheetSwitcherDialogProps = Omit<+ BaseProps<HTMLDialogElement>,+ 'onClick' | 'onKeyDown'+>;+export interface BottomSheetSwitcherContextValue {activeSheet: string | null;hasScrim: boolean;onActiveSheetChange: (sheetId: string | null) => void;getSheetPhase: (sheetId: string) => BottomSheetSwitcherPhase;getSheetAlignmentOffset: (sheetId: string) => number;+ /**+ * The sheet whose dialog hosts the flow: the active sheet, the exiting+ * sheet through its exit, and the last host (or the first mounted sheet)+ * while the flow is closed. The switcher's ref and its single-instance+ * attributes resolve to this sheet's dialog.+ */+ hostSheet: string | null;+ /**+ * Whether this sheet's dialog paints the flow's one scrim right now. During+ * a handoff the retained sheet keeps it, so the entering dialog's backdrop+ * stays transparent above the still-visible previous panel.+ */+ isScrimOwner: (sheetId: string) => boolean;+ /** The flow is closing: the owning backdrop fades out on the exit curve. */+ isFlowClosing: boolean;registerSheetElement: (sheetId: string, element: HTMLElement | null) => void;- registerSheetLabel: (sheetId: string, label: string | null) => void;+ registerSheetDialog: (+ sheetId: string,+ dialog: HTMLDialogElement | null,+ ) => void;registerSheetPurpose: (sheetId: string,purpose: DialogPurpose | null,) => void;+ /**+ * Called by a sheet host just before it presents its dialog modally, so the+ * switcher can remember the page element that opened the flow.+ */+ onBeforeSheetPresent: (sheetId: string) => void;+ /**+ * Whether a modal sheet dialog that is already open sits beneath another+ * open sheet dialog in the top layer, so it must re-present to become the+ * topmost layer again.+ */+ isCoveredInTopLayer: (sheetId: string) => boolean;onSheetEnterStart: (sheetId: string) => void;onSheetTransitionComplete: (event: BottomSheetSwitcherTransitionEvent,) => void;onSheetScrimOpacityChange: (sheetId: string, opacity: number) => void;+ /** Consumer dialog props the switcher forwards to every sheet dialog. */+ dialogProps: BottomSheetSwitcherDialogProps;+ onDialogCancel: (event: SyntheticEvent<HTMLDialogElement>) => void;+ onDialogClick: (event: ReactMouseEvent<HTMLDialogElement>) => void;+ onDialogKeyDown: (event: ReactKeyboardEvent<HTMLDialogElement>) => void;}export const BottomSheetSwitcherContext =