Skip to content

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

TypeScript

feat(core): BottomSheet stacks by open order, replaces on a same-update switch, and BottomSheetSwitcher is deprecated (#7648)

Xinzi Zhou2a162e1b6bd4
diff --git a/.changeset/bottom-sheet-open-order-stacking.md b/.changeset/bottom-sheet-open-order-stacking.md
new file mode 100644
index 0000000000..169d5b3748
--- /dev/null
+++ b/.changeset/bottom-sheet-open-order-stacking.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] `BottomSheet` stacks by open order. A modal sheet opened while another modal sheet is open now stacks on top of it instead of presenting as a second, unrelated dialog: the covered sheet stays mounted with its state, recedes behind the top sheet (0.96 / −8px at depth 1, 0.92 / −16px from depth 2), and is blocked from pointer, keyboard, and assistive technology; only the bottom sheet's backdrop dims the page, so a stack no longer darkens per level; and Escape, a scrim tap, a swipe, and a platform close request pop only the top sheet, through that sheet's own `onOpenChange` and honouring its `purpose`. The top sheet is the most recently opened one still open, wherever the sheets are written — siblings, separate components, inside another sheet's content, or inside a `BottomSheetSwitcher` step; a whole switcher is one level, and switching its step keeps its place. When several sheets open in one update (a deep link), tree order decides and the first painted frame is already right: a sheet nested in another sheet's content no longer opens beneath its parent. Closing the top sheet returns focus into the sheet it reveals; closing every sheet of a stack in one update returns focus once, to the bottom sheet's `finalFocusRef` or opener, after the last dialog has closed (each sheet's own return used to be refused while the others were still modal). A sheet rendered inside a closing sheet's content now leaves with it instead of staying open invisibly, and comes back with the host if its own `isOpen` is still true (its state is never written for it); sheets above it that are not in its content stay open. Sheets with `hasScrim={false}` never stack and are never stacked on. No prop, type, or export changes; a modal sheet on its own behaves exactly as before (apart from the reduced-motion fix released alongside).
+
+@imdreamrunner
diff --git a/.changeset/bottom-sheet-reduced-motion-cross-fade.md b/.changeset/bottom-sheet-reduced-motion-cross-fade.md
new file mode 100644
index 0000000000..5b6396e136
--- /dev/null
+++ b/.changeset/bottom-sheet-reduced-motion-cross-fade.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] BottomSheet follows the reduced-motion design rule. With `prefers-reduced-motion: reduce`, a sheet's entrance, exit, recede and replace handoff — a `BottomSheetSwitcher` step's too — no longer travel or scale: on a touch screen (`pointer: coarse`) the entering sheet fades in at its resting place and the leaving or retained sheet fades out where it is, opacity only, within 200 ms; with a mouse, trackpad or keyboard the change is immediate, except that a swipe dismissal — a transition a touch drag's release started — fades out in place on every pointer. Before, the motions ran shortened transforms on every pointer and nothing cross-faded.
+
+@imdreamrunner
diff --git a/.changeset/bottom-sheet-replace-handoff.md b/.changeset/bottom-sheet-replace-handoff.md
new file mode 100644
index 0000000000..f16448f347
--- /dev/null
+++ b/.changeset/bottom-sheet-replace-handoff.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] `BottomSheet` replaces a sheet that closes in the same update another opens. When the top sheet of a stack closes and exactly one other sheet opens in the same update (one state value naming the open step does this), the new sheet replaces it instead of stacking on it: it rises above the replaced sheet, a taller replaced sheet moves down to meet its top edge at the same time, the replaced sheet fades only after both motions finish and is inert and hidden from assistive technology from the start, the scrim holds steady with no dip, focus moves into the new sheet, and closing the flow later returns focus to the element that opened its first sheet. This is the handoff `BottomSheetSwitcher` runs between its steps, now available to standalone sheets; a multi-step flow can be written as one `BottomSheet` per step with no switcher. A covered sheet closing while a sheet opens, several sheets changing at once, or a close and an open in different updates keep the ordinary push and pop motion, and existing stacking behaviour is unchanged. A replace is recognised only when the move was made from inside the closing sheet: the control last pressed (or, with no recent press, the focused element) was in it, as a step's own Continue or Back button is; a close and an open driven from a control outside it, by two unrelated owners, stay a pop and a push with their own focus return. Non-modal sheets (`hasScrim={false}`) replace each other the same way: they are now hosted in the browser top layer as manual popovers, with no scrim, focus trap or scroll lock as before, so a non-modal step orders above the one it replaces, and the toast viewport re-enters the top layer above a non-modal sheet as it does above a modal. The non-modal sheet's page-level `z-index` is gone with the move (AST-027); below the Popover API support floor the sheet falls back to `show()` in page stacking order, usable but with no promise over later page content (the reduced fallback AST-003 describes). They still never stack. A non-modal sheet now also returns focus to its opener when it closes while the person is still in it (a modal sheet always did); focus the person took elsewhere on the live page stays there. The private stack registry now keeps one state per page shared by every copy of the package on it that speaks the same stack protocol version (a copy on another version keeps its own stack), and one stack per document. No prop, type, or export changes; a modal sheet on its own behaves exactly as before (apart from the reduced-motion fix released alongside). A non-modal sheet on its own changes in three ways with its new host: it is in the top layer (a manual popover) instead of page stacking order, its page-level `z-index` is gone, and it returns focus to its opener on close while focus is still inside it; its scrim-less, scroll-free, page-interactive contract is unchanged.
+
+@imdreamrunner
diff --git a/.changeset/bottom-sheet-switcher-deprecated.md b/.changeset/bottom-sheet-switcher-deprecated.md
new file mode 100644
index 0000000000..fbb0963baa
--- /dev/null
+++ b/.changeset/bottom-sheet-switcher-deprecated.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] `BottomSheetSwitcher` and the `sheetId` prop of `BottomSheet` are deprecated. The replacement is already in this release: write each step of a multi-step flow as its own standalone `BottomSheet` with `isOpen`, driven by one state value that names the open step; closing the top sheet and opening the next in the same update runs the same replace handoff the switcher ran (entering step above, a taller retained step aligns down and fades after both motions, one steady scrim, focus into the new step and back to the flow's opener on close). Migration, per flow: (1) replace the `activeSheet` / `onActiveSheetChange` pair with one `step` state value; (2) give each step `isOpen={step === 'id'}` and `onOpenChange={isOpen => !isOpen && setStep(current => (current === 'id' ? null : current))}` in place of `sheetId="id"` (the guard keeps a step that is being replaced from clearing the step the person just chose); (3) remove the `BottomSheetSwitcher` wrapper, moving its `hasScrim` onto every step; (4) keep the step buttons as they were (`setStep('next')`). The handoff runs when the move is made from inside the open step (a step's own Continue or Back, or code while focus is in it); a step changed from a control outside the flow's sheets — a page control beside a `hasScrim={false}` flow, or code after focus has left the step — closes and opens with the sheets' own push and pop motion, where the switcher handed off on any `activeSheet` change. The switcher's other props map as follows: `onCancel` becomes a guarded `onOpenChange` on each step (one that ignores `false` while the flow must stay open), which keeps the step's dialog role — a standalone sheet reports Escape, the platform close, the scrim tap and the swipe all as `onOpenChange(false)` with no reason, so the guard holds the step open against all of them while it applies, where `onCancel` vetoed only the cancel request; a veto of Escape alone has no equivalent, and the only per-path lever is `purpose` (`form` keeps Escape and blocks the scrim tap and the swipe; `required` blocks all three and exposes the step as an `alertdialog`). A consumer `aria-label` / `aria-labelledby` becomes each step's `label`, which names its dialog. `ref`, `id`, `data-testid`, `className`, `style`, `xstyle` and the other dialog props have no dialog-level equivalent — a standalone sheet's `ref` and base props reach its panel `<div>` and its dialog is implementation — so a test or an anchor that needs the dialog queries the panel's `closest('dialog')`, and dialog-level styling is dropped. Flows that keep using the switcher keep working: a switcher flow used on its own behaves as released — with two fixes released alongside: a toast raised from a step now renders above the flow and can be pressed, and under reduced motion its steps' entrance, exit and handoff follow the reduced-motion rule (no travel; a cross-fade on touch, immediate otherwise) — and when it is stacked with other sheets the stacking behaviour of this release applies to it as one level (it recedes and is blocked when covered, shares the one scrim, stands down from dismissal while covered, and returns focus by the stacking rules). Its declarations and docs are marked `@deprecated` and its docs, templates and stories show only the replacement, until a future minor release removes it. Non-modal flows (`hasScrim={false}`) migrate the same way: non-modal sheets replace each other too.
+
+@imdreamrunner
diff --git a/.changeset/bottom-sheet-switcher-toast-outlet.md b/.changeset/bottom-sheet-switcher-toast-outlet.md
new file mode 100644
index 0000000000..6092074d8e
--- /dev/null
+++ b/.changeset/bottom-sheet-switcher-toast-outlet.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Toasts raised from a `BottomSheetSwitcher` step stay visible and clickable above the flow. A modal switcher flow now supplies its active step's dialog as the toast viewport's host, as a standalone scrim `BottomSheet` and a `Dialog` do; the host follows each handoff to the entering step, and the flow hands the viewport back when it closes. Before, the viewport stayed behind the flow's dialogs, so a toast raised from a step was covered by the step and a press on it landed on the step. A `hasScrim={false}` flow is not modal and leaves the viewport in place.
+
+@imdreamrunner
diff --git a/.changeset/cli-bottom-sheet-templates-standalone-steps.md b/.changeset/cli-bottom-sheet-templates-standalone-steps.md
new file mode 100644
index 0000000000..f14e3f3727
--- /dev/null
+++ b/.changeset/cli-bottom-sheet-templates-standalone-steps.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] The two Bottom Sheet flow block templates (`BottomSheetSwitcherShowcase`, `BottomSheetSwitcherReviewFlow`) now teach the replacement for the deprecated `BottomSheetSwitcher`: each step is a standalone `BottomSheet` driven by one state value, and moving on replaces the open step in place. Both stay examples of `BottomSheetSwitcher` (the showcase remains that page's hero) and are now also listed under `BottomSheet`. Template ids, files and their published registry identities keep their names, so `template <name>`, the released JSON ids and the ShadCN routes are unchanged.
+
+@imdreamrunner
diff --git a/apps/storybook/stories/BottomSheet.stories.tsx b/apps/storybook/stories/BottomSheet.stories.tsx
index dea4a225ca..49d03d93b3 100644
--- a/apps/storybook/stories/BottomSheet.stories.tsx
+++ b/apps/storybook/stories/BottomSheet.stories.tsx
@@ -844,3 +844,72 @@ export const NestedPopover: Story = {
);
},
};
+
+/**
+ * A no-scrim sheet with a `data-autofocus` field: focus on open follows the
+ * native host, which lands on the panel; the field is not focused.
+ */
+export const NoScrimAutofocus: Story = {
+ name: 'No scrim with a data-autofocus field',
+ render: () => {
+ const [isOpen, setIsOpen] = useState(false);
+ const [value, setValue] = useState('');
+ return (
+ <>
+ <Button label="Open sheet" onClick={() => setIsOpen(true)} />
+ <BottomSheet
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ label="Filter places"
+ hasScrim={false}
+ height="hug">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <TextInput
+ label="Search"
+ value={value}
+ onChange={setValue}
+ hasAutoFocus
+ />
+ <Button label="Done" onClick={() => setIsOpen(false)} />
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </>
+ );
+ },
+};
+
+/**
+ * A modal sheet with a `data-autofocus` field (a TextInput with hasAutoFocus):
+ * what focus lands on when the sheet opens.
+ */
+export const ModalAutofocus: Story = {
+ name: 'Modal with a data-autofocus field',
+ render: () => {
+ const [isOpen, setIsOpen] = useState(false);
+ const [value, setValue] = useState('');
+ return (
+ <>
+ <Button label="Open sheet" onClick={() => setIsOpen(true)} />
+ <BottomSheet
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ label="Edit note"
+ height="hug">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <TextInput
+ label="Note"
+ value={value}
+ onChange={setValue}
+ hasAutoFocus
+ />
+ <Button label="Done" onClick={() => setIsOpen(false)} />
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </>
+ );
+ },
+};
diff --git a/apps/storybook/stories/BottomSheetReplace.stories.tsx b/apps/storybook/stories/BottomSheetReplace.stories.tsx
new file mode 100644
index 0000000000..45d8367b21
--- /dev/null
+++ b/apps/storybook/stories/BottomSheetReplace.stories.tsx
@@ -0,0 +1,682 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {useEffect, useState} from 'react';
+import {BottomSheet} from '@astryxdesign/core/BottomSheet';
+import {Button} from '@astryxdesign/core/Button';
+import {CheckboxInput} from '@astryxdesign/core/CheckboxInput';
+import {Divider} from '@astryxdesign/core/Divider';
+import {Heading} from '@astryxdesign/core/Heading';
+import {Section} from '@astryxdesign/core/Section';
+import {HStack, VStack} from '@astryxdesign/core/Stack';
+import {Text} from '@astryxdesign/core/Text';
+import {TextInput} from '@astryxdesign/core/TextInput';
+import {RadioList, RadioListItem} from '@astryxdesign/core/RadioList';
+import {Popover} from '@astryxdesign/core/Popover';
+import {Tooltip} from '@astryxdesign/core/Tooltip';
+import {useToast} from '@astryxdesign/core/Toast';
+
+/**
+ * The BottomSheetSwitcher stories rebuilt with standalone sheets only: one
+ * `isOpen` per step, no `BottomSheetSwitcher` and no `sheetId`. Each story
+ * mirrors the switcher story of the same name (content, labels, heights,
+ * steps) so the two can be compared one to one. Moving from one step to the
+ * next closes one sheet and opens the next in the same update, which the
+ * sheets run as a replace handoff.
+ */
+const meta: Meta<typeof BottomSheet> = {
+ title: 'Core/BottomSheetReplace',
+ component: BottomSheet,
+ tags: ['autodocs'],
+ parameters: {
+ layout: 'fullscreen',
+ docs: {
+ story: {inline: false, height: '560px'},
+ },
+ },
+ argTypes: {
+ ref: {control: false},
+ },
+ decorators: [
+ Story => (
+ <div style={{minHeight: 480, padding: 32}}>
+ <Story />
+ </div>
+ ),
+ ],
+};
+
+export default meta;
+type Story = StoryObj<typeof BottomSheet>;
+type NotificationSheetHeight = 'hug' | 'capped';
+type NotificationStep = 'overview' | 'frequency' | 'channels';
+
+interface NotificationStepSheetProps {
+ isOpen: boolean;
+ /** Called with false when the step requests dismissal (Escape, scrim, swipe). */
+ onOpenChange: (isOpen: boolean) => void;
+ hasScrim: boolean;
+}
+
+interface NotificationOverviewSheetProps extends NotificationStepSheetProps {
+ height: NotificationSheetHeight;
+ onCancel: () => void;
+ onContinue: () => void;
+}
+
+function NotificationOverviewSheet({
+ isOpen,
+ onOpenChange,
+ hasScrim,
+ height,
+ onCancel,
+ onContinue,
+}: NotificationOverviewSheetProps) {
+ return (
+ <BottomSheet
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ hasScrim={hasScrim}
+ label="Set up notifications"
+ height={height}>
+ <Section padding={4}>
+ <VStack gap={4}>
+ <VStack gap={1}>
+ <Heading level={3}>Set up notifications</Heading>
+ <Text type="supporting" color="secondary">
+ Step 1 of 3
+ </Text>
+ </VStack>
+ <Divider />
+ <Text type="supporting" color="secondary">
+ Stay informed about activity that matters without checking back
+ throughout the day.
+ </Text>
+ <VStack gap={3}>
+ <VStack gap={1}>
+ <Text type="label">Important activity</Text>
+ <Text type="supporting" color="secondary">
+ Know when someone mentions you or needs your attention.
+ </Text>
+ </VStack>
+ <VStack gap={1}>
+ <Text type="label">Timely reminders</Text>
+ <Text type="supporting" color="secondary">
+ Get a reminder before work reaches its due date.
+ </Text>
+ </VStack>
+ <VStack gap={1}>
+ <Text type="label">Useful summaries</Text>
+ <Text type="supporting" color="secondary">
+ Catch up on anything you may have missed.
+ </Text>
+ </VStack>
+ </VStack>
+ <HStack gap={2} hAlign="end">
+ <Button label="Cancel" variant="secondary" onClick={onCancel} />
+ <Button label="Continue" onClick={onContinue} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ );
+}
+
+interface NotificationFrequencySheetProps extends NotificationStepSheetProps {
+ height: NotificationSheetHeight;
+ onBack: () => void;
+ onContinue: () => void;
+}
+
+function NotificationFrequencySheet({
+ isOpen,
+ onOpenChange,
+ hasScrim,
+ height,
+ onBack,
+ onContinue,
+}: NotificationFrequencySheetProps) {
+ const [frequency, setFrequency] = useState('daily');
+
+ return (
+ <BottomSheet
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ hasScrim={hasScrim}
+ label="Notification frequency"
+ height={height}>
+ <Section padding={4}>
+ <VStack gap={4}>
+ <VStack gap={1}>
+ <Heading level={3}>How often?</Heading>
+ <Text type="supporting" color="secondary">
+ Step 2 of 3
+ </Text>
+ </VStack>
+ <Divider />
+ <RadioList
+ label="Notification frequency"
+ isLabelHidden
+ value={frequency}
+ onChange={setFrequency}>
+ <RadioListItem label="Immediately" value="immediately" />
+ <RadioListItem label="Daily" value="daily" />
+ <RadioListItem label="Weekly" value="weekly" />
+ </RadioList>
+ <HStack gap={2} hAlign="end">
+ <Button label="Back" variant="secondary" onClick={onBack} />
+ <Button label="Continue" onClick={onContinue} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ );
+}
+
+interface NotificationChannelsSheetProps extends NotificationStepSheetProps {
+ height: NotificationSheetHeight;
+ onBack: () => void;
+ onFinish: () => void;
+}
+
+function NotificationChannelsSheet({
+ isOpen,
+ onOpenChange,
+ hasScrim,
+ height,
+ onBack,
+ onFinish,
+}: NotificationChannelsSheetProps) {
+ const [email, setEmail] = useState(true);
+ const [pushNotifications, setPushNotifications] = useState(true);
+ const [textMessages, setTextMessages] = useState(false);
+
+ return (
+ <BottomSheet
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ hasScrim={hasScrim}
+ label="Notification channels"
+ height={height}>
+ <Section padding={4}>
+ <VStack gap={4}>
+ <VStack gap={1}>
+ <Heading level={3}>Where should we notify you?</Heading>
+ <Text type="supporting" color="secondary">
+ Step 3 of 3
+ </Text>
+ </VStack>
+ <Divider />
+ <Text type="supporting" color="secondary">
+ Choose any combination. You can change these preferences later.
+ </Text>
+ <VStack gap={2}>
+ <CheckboxInput label="Email" value={email} onChange={setEmail} />
+ <CheckboxInput
+ label="Push notifications"
+ value={pushNotifications}
+ onChange={setPushNotifications}
+ />
+ <CheckboxInput
+ label="Text messages"
+ value={textMessages}
+ onChange={setTextMessages}
+ />
+ </VStack>
+ <HStack gap={2} hAlign="end">
+ <Button label="Back" variant="secondary" onClick={onBack} />
+ <Button label="Finish" onClick={onFinish} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ );
+}
+
+interface MultiStepReplaceExampleProps {
+ height: NotificationSheetHeight;
+ hasScrim?: boolean;
+}
+
+function MultiStepReplaceExample({
+ height,
+ hasScrim = true,
+}: MultiStepReplaceExampleProps) {
+ // One value names the open step, so moving on closes one sheet and opens
+ // the next in the same update. A step that is dismissed closes the flow.
+ const [step, setStep] = useState<NotificationStep | null>(null);
+ const stepProps = (own: NotificationStep): NotificationStepSheetProps => ({
+ isOpen: step === own,
+ onOpenChange: isOpen => {
+ if (!isOpen) {
+ setStep(current => (current === own ? null : current));
+ }
+ },
+ hasScrim,
+ });
+
+ return (
+ <>
+ <Button
+ label="Set up notifications"
+ onClick={() => setStep('overview')}
+ />
+ <NotificationOverviewSheet
+ {...stepProps('overview')}
+ height={height}
+ onCancel={() => setStep(null)}
+ onContinue={() => setStep('frequency')}
+ />
+ <NotificationFrequencySheet
+ {...stepProps('frequency')}
+ height={height}
+ onBack={() => setStep('overview')}
+ onContinue={() => setStep('channels')}
+ />
+ <NotificationChannelsSheet
+ {...stepProps('channels')}
+ height={height}
+ onBack={() => setStep('frequency')}
+ onFinish={() => setStep(null)}
+ />
+ </>
+ );
+}
+
+const openFlow: NonNullable<Story['play']> = async ({canvasElement}) => {
+ const trigger = canvasElement.querySelector('button');
+ if (trigger instanceof HTMLElement) {
+ trigger.click();
+ await new Promise(resolve => setTimeout(resolve, 500));
+ }
+};
+
+export const HugContent: Story = {
+ name: 'Hug content',
+ render: () => <MultiStepReplaceExample height="hug" />,
+ play: openFlow,
+};
+
+export const Capped: Story = {
+ render: () => <MultiStepReplaceExample height="capped" />,
+ play: openFlow,
+};
+
+export const NoScrim: Story = {
+ name: 'No scrim',
+ render: () => <MultiStepReplaceExample height="hug" hasScrim={false} />,
+ play: openFlow,
+};
+
+export const NarrowViewport: Story = {
+ name: 'Narrow viewport',
+ parameters: {viewport: {defaultViewport: 'mobile1'}},
+ render: () => <MultiStepReplaceExample height="hug" />,
+ play: openFlow,
+};
+
+// ---------------------------------------------------------------------------
+// Non-modal sheet over a live page: toasts, tooltips and popovers stay above
+// ---------------------------------------------------------------------------
+
+function NonModalOverPage() {
+ const [step, setStep] = useState<'one' | 'two' | null>(null);
+ const toast = useToast();
+ const raise = (where: string) =>
+ toast({body: `Toast from the ${where}`, isAutoHide: false});
+ const stepProps = (id: 'one' | 'two') => ({
+ isOpen: step === id,
+ onOpenChange: (isOpen: boolean) => {
+ if (!isOpen) {
+ setStep(current => (current === id ? null : current));
+ }
+ },
+ hasScrim: false as const,
+ });
+ return (
+ <VStack gap={3}>
+ <Heading level={2}>Non-modal sheet over a live page</Heading>
+ <Text type="supporting" color="secondary">
+ The page stays interactive under a no-scrim sheet. A toast raised from
+ the page or from the sheet paints above the sheet; a tooltip or popover
+ opened from the sheet paints above it too.
+ </Text>
+ <HStack gap={2}>
+ <Button label="Open sheet" onClick={() => setStep('one')} />
+ <Button
+ label="Toast from page"
+ variant="secondary"
+ onClick={() => raise('page')}
+ />
+ </HStack>
+ <BottomSheet {...stepProps('one')} label="Step one" height="hug">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Step one</Heading>
+ <HStack gap={2}>
+ <Button
+ label="Toast from sheet"
+ variant="secondary"
+ onClick={() => raise('sheet')}
+ />
+ <Tooltip content="A tip above the sheet">
+ <Button label="Hover me" variant="secondary" />
+ </Tooltip>
+ <Popover
+ label="Options"
+ content={<Text type="body">A popover above the sheet</Text>}>
+ <Button label="Options" variant="secondary" />
+ </Popover>
+ </HStack>
+ <HStack gap={2} hAlign="end">
+ <Button label="Continue" onClick={() => setStep('two')} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ <BottomSheet {...stepProps('two')} label="Step two" height="hug">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Step two</Heading>
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Back"
+ variant="secondary"
+ onClick={() => setStep('one')}
+ />
+ <Button label="Done" onClick={() => setStep(null)} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </VStack>
+ );
+}
+
+export const NonModalOverLivePage: Story = {
+ name: 'Non-modal over a live page',
+ render: () => <NonModalOverPage />,
+};
+
+// ---------------------------------------------------------------------------
+// Several sheets changing in one update: not a replace
+// ---------------------------------------------------------------------------
+
+/**
+ * A list sheet opens a detail sheet; "Finish" in the detail closes both and
+ * opens a confirmation in the same update. Two closes and one open is not a
+ * step flow's handoff: the two sheets pop with their own motion and the
+ * confirmation is a fresh push, whichever order the sheets are written in.
+ * The sheets here are written confirmation first, so a registry that paired
+ * on the first two flips it heard would wrongly replace the detail.
+ */
+function FinishToConfirmation() {
+ const [isListOpen, setIsListOpen] = useState(false);
+ const [isDetailOpen, setIsDetailOpen] = useState(false);
+ const [isDoneOpen, setIsDoneOpen] = useState(false);
+ return (
+ <>
+ <Button label="Open list" onClick={() => setIsListOpen(true)} />
+ <BottomSheet
+ isOpen={isDoneOpen}
+ onOpenChange={setIsDoneOpen}
+ label="Saved"
+ height="hug">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Saved</Heading>
+ <Text>The list and the detail closed together; this is new.</Text>
+ <HStack gap={2} hAlign="end">
+ <Button label="Close" onClick={() => setIsDoneOpen(false)} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={isDetailOpen}
+ onOpenChange={setIsDetailOpen}
+ label="Detail"
+ height="hug">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Detail</Heading>
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Back"
+ variant="secondary"
+ onClick={() => setIsDetailOpen(false)}
+ />
+ <Button
+ label="Finish"
+ onClick={() => {
+ setIsListOpen(false);
+ setIsDetailOpen(false);
+ setIsDoneOpen(true);
+ }}
+ />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={isListOpen}
+ onOpenChange={setIsListOpen}
+ label="List"
+ height="capped">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>List</Heading>
+ <Button label="Open detail" onClick={() => setIsDetailOpen(true)} />
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </>
+ );
+}
+
+/**
+ * A modal two-step flow whose steps can raise a toast. A reversal (Back
+ * pressed during the Continue handoff) re-shows the first step's dialog; the
+ * toast raised from it afterwards must still land in it and stay pressable.
+ */
+function ModalFlowWithToasts() {
+ const [step, setStep] = useState<'one' | 'two' | null>(null);
+ const toast = useToast();
+ const close = (own: 'one' | 'two') => (isOpen: boolean) => {
+ if (!isOpen) {
+ setStep(current => (current === own ? null : current));
+ }
+ };
+ return (
+ <>
+ <Button label="Open flow" onClick={() => setStep('one')} />
+ <BottomSheet
+ isOpen={step === 'one'}
+ onOpenChange={close('one')}
+ label="Step one"
+ height="hug">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Step one</Heading>
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Toast from step one"
+ variant="secondary"
+ onClick={() =>
+ toast({body: 'Toast from step one', isAutoHide: false})
+ }
+ />
+ <Button label="Continue" onClick={() => setStep('two')} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={step === 'two'}
+ onOpenChange={close('two')}
+ label="Step two"
+ height="hug">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Step two</Heading>
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Back"
+ variant="secondary"
+ onClick={() => setStep('one')}
+ />
+ <Button label="Done" onClick={() => setStep(null)} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </>
+ );
+}
+
+export const ModalFlowToasts: Story = {
+ name: 'Modal flow with toasts (reversal keeps the outlet)',
+ render: () => <ModalFlowWithToasts />,
+};
+
+/**
+ * A two-step flow whose second step carries an autofocused field. Entering
+ * by a replace focuses that field (AR4); a lone open would focus the panel.
+ */
+function AutofocusReplaceFlow({hasScrim}: {hasScrim: boolean}) {
+ const [step, setStep] = useState<'one' | 'two' | null>(null);
+ const [name, setName] = useState('');
+ const close = (own: 'one' | 'two') => (isOpen: boolean) => {
+ if (!isOpen) {
+ setStep(current => (current === own ? null : current));
+ }
+ };
+ return (
+ <>
+ <Button label="Open flow" onClick={() => setStep('one')} />
+ <BottomSheet
+ isOpen={step === 'one'}
+ onOpenChange={close('one')}
+ label="Step one"
+ hasScrim={hasScrim}
+ height="hug">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Step one</Heading>
+ <HStack gap={2} hAlign="end">
+ <Button label="Continue" onClick={() => setStep('two')} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={step === 'two'}
+ onOpenChange={close('two')}
+ label="Step two"
+ hasScrim={hasScrim}
+ height="hug">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Your name</Heading>
+ <TextInput
+ label="Name"
+ value={name}
+ onChange={setName}
+ hasAutoFocus
+ />
+ <HStack gap={2} hAlign="end">
+ <Button label="Done" onClick={() => setStep(null)} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </>
+ );
+}
+
+export const AutofocusReplace: Story = {
+ name: 'Replace entry focuses the autofocus field',
+ render: () => <AutofocusReplaceFlow hasScrim />,
+};
+
+export const AutofocusReplaceNoScrim: Story = {
+ name: 'Replace entry focuses the autofocus field (no scrim)',
+ render: () => <AutofocusReplaceFlow hasScrim={false} />,
+};
+
+/**
+ * A three-step flow whose middle step is an interstitial advanced by code:
+ * Submit opens Processing by press; Processing moves on to Done 300 ms later
+ * on its own. Both moves are handoffs, and closing Done returns focus to the
+ * control that opened the flow.
+ */
+function InterstitialFlow() {
+ const [step, setStep] = useState<'form' | 'processing' | 'done' | null>(null);
+ useEffect(() => {
+ if (step !== 'processing') {
+ return;
+ }
+ const id = setTimeout(() => setStep('done'), 300);
+ return () => clearTimeout(id);
+ }, [step]);
+ const close = (own: 'form' | 'processing' | 'done') => (isOpen: boolean) => {
+ if (!isOpen) {
+ setStep(current => (current === own ? null : current));
+ }
+ };
+ return (
+ <>
+ <Button label="Open form" onClick={() => setStep('form')} />
+ <BottomSheet
+ isOpen={step === 'form'}
+ onOpenChange={close('form')}
+ label="Form"
+ height="hug">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Form</Heading>
+ <HStack gap={2} hAlign="end">
+ <Button label="Submit" onClick={() => setStep('processing')} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={step === 'processing'}
+ onOpenChange={close('processing')}
+ label="Processing"
+ height="hug">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Processing…</Heading>
+ <Text>Saving your changes.</Text>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={step === 'done'}
+ onOpenChange={close('done')}
+ label="Done"
+ height="hug">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Done</Heading>
+ <HStack gap={2} hAlign="end">
+ <Button label="Close" onClick={() => setStep(null)} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </>
+ );
+}
+
+export const Interstitial: Story = {
+ name: 'Interstitial step advanced by code',
+ render: () => <InterstitialFlow />,
+};
+
+export const FinishClosesTwo: Story = {
+ name: 'Finish closes two sheets and opens one',
+ render: () => <FinishToConfirmation />,
+};
diff --git a/apps/storybook/stories/BottomSheetStacking.stories.tsx b/apps/storybook/stories/BottomSheetStacking.stories.tsx
new file mode 100644
index 0000000000..37255c6e12
--- /dev/null
+++ b/apps/storybook/stories/BottomSheetStacking.stories.tsx
@@ -0,0 +1,995 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/**
+ * @file BottomSheetStacking.stories.tsx
+ * @input Uses BottomSheet, each with its own open
+ * state, at phone width
+ * @output Storybook scenarios for stacked bottom sheets: a drill-in with Back
+ * and Close all, a deep link at depth 3, a step flow (standalone steps that
+ * replace each other) at the base with a Help sheet, a step flow on top
+ * (edit → saved), a row-owned detail sheet nested in the
+ * list sheet's content, sheets opened out of tree order, a Dialog over a
+ * sheet and a sheet over that Dialog, and a file browser of unknown depth
+ * @position Core story; stacked bottom sheets (no new component: stacking is
+ * BottomSheet behaviour)
+ */
+import {useState} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import {BottomSheet} from '@astryxdesign/core/BottomSheet';
+import {Button} from '@astryxdesign/core/Button';
+import {Dialog} from '@astryxdesign/core/Dialog';
+import {useToast} from '@astryxdesign/core/Toast';
+import {useAnnounce} from '@astryxdesign/core/hooks';
+import {Divider} from '@astryxdesign/core/Divider';
+import {Heading} from '@astryxdesign/core/Heading';
+import {RadioList, RadioListItem} from '@astryxdesign/core/RadioList';
+import {Section} from '@astryxdesign/core/Section';
+import {HStack, VStack} from '@astryxdesign/core/Stack';
+import {Text} from '@astryxdesign/core/Text';
+import {TextInput} from '@astryxdesign/core/TextInput';
+
+const meta: Meta<typeof BottomSheet> = {
+ title: 'Core/BottomSheetStacking',
+ component: BottomSheet,
+ tags: ['autodocs'],
+ parameters: {
+ layout: 'fullscreen',
+ viewport: {defaultViewport: 'mobile1'},
+ docs: {
+ story: {inline: false, height: '560px'},
+ },
+ },
+ decorators: [
+ Story => (
+ <div style={{minHeight: 480, padding: 16}}>
+ <Story />
+ </div>
+ ),
+ ],
+};
+
+export default meta;
+type Story = StoryObj<typeof BottomSheet>;
+
+// ---------------------------------------------------------------------------
+// Orders: list → order → edit, sibling sheets, with Back and Close all
+// ---------------------------------------------------------------------------
+
+const ORDERS = [
+ {id: '1042', title: 'Trail runners', status: 'Shipped'},
+ {id: '1043', title: 'Rain shell', status: 'Processing'},
+ {id: '1044', title: 'Wool socks ×3', status: 'Delivered'},
+];
+
+/**
+ * A control that announces from where it sits: inside a stacked sheet, the
+ * words follow the sheet's dialog (useAnnounce's modal route) — the top
+ * sheet hears its own, and a covered sheet's words reach the exposed one.
+ */
+function AnnounceButton({label, message}: {label: string; message: string}) {
+ const announce = useAnnounce();
+ return (
+ <Button
+ label={label}
+ variant="ghost"
+ size="sm"
+ onClick={() => announce(message)}
+ />
+ );
+}
+
+function OrdersFlow({deepLink = false}: {deepLink?: boolean}) {
+ const [isListOpen, setIsListOpen] = useState(deepLink);
+ const [orderId, setOrderId] = useState<string | null>(
+ deepLink ? ORDERS[0].id : null,
+ );
+ const [isEditing, setIsEditing] = useState(deepLink);
+ const [note, setNote] = useState('Leave at the side door');
+ const order = ORDERS.find(entry => entry.id === orderId) ?? null;
+
+ const closeAll = () => {
+ setIsListOpen(false);
+ setOrderId(null);
+ setIsEditing(false);
+ };
+
+ return (
+ <VStack gap={3}>
+ <Heading level={2}>Orders</Heading>
+ <Text type="supporting" color="secondary">
+ A drill-in: the list opens an order, the order opens an editor. Three
+ sibling sheets, each with its own state; a sheet opened over another
+ stacks on top of it. Back pops one; Close all closes every sheet in one
+ update.
+ </Text>
+ <Button
+ label={deepLink ? 'Open order 1042 editor' : 'Open orders'}
+ onClick={() => {
+ setIsListOpen(true);
+ if (deepLink) {
+ setOrderId(ORDERS[0].id);
+ setIsEditing(true);
+ }
+ }}
+ />
+ <BottomSheet
+ isOpen={isListOpen}
+ onOpenChange={setIsListOpen}
+ label="Orders"
+ height="hug"
+ data-testid="orders-list">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Your orders</Heading>
+ <Divider />
+ {ORDERS.map(entry => (
+ <HStack key={entry.id} gap={2} vAlign="center">
+ <VStack gap={0.5}>
+ <Text type="label">#{entry.id}</Text>
+ <Text type="supporting" color="secondary">
+ {entry.title} · {entry.status}
+ </Text>
+ </VStack>
+ <Button
+ label="View"
+ variant="secondary"
+ size="sm"
+ onClick={() => setOrderId(entry.id)}
+ />
+ </HStack>
+ ))}
+ <HStack gap={2} hAlign="end">
+ <AnnounceButton
+ label="Announce from Orders"
+ message="Orders refreshed"
+ />
+ <Button label="Close all" variant="ghost" onClick={closeAll} />
+ <Button
+ label="Done"
+ variant="secondary"
+ onClick={() => setIsListOpen(false)}
+ />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={order != null}
+ onOpenChange={open => {
+ if (!open) {
+ setOrderId(null);
+ }
+ }}
+ label={order == null ? 'Order' : `Order ${order.id}`}
+ height="hug"
+ data-testid="orders-detail">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Order #{order?.id ?? ''}</Heading>
+ <Text type="supporting" color="secondary">
+ {order?.title} · {order?.status}
+ </Text>
+ <Divider />
+ <Text type="body">Delivery note: {note}</Text>
+ <HStack gap={2} hAlign="end">
+ <AnnounceButton
+ label="Announce from order"
+ message="Order details loaded"
+ />
+ <Button label="Close all" variant="ghost" onClick={closeAll} />
+ <Button
+ label="Back"
+ variant="secondary"
+ onClick={() => setOrderId(null)}
+ />
+ <Button label="Edit note" onClick={() => setIsEditing(true)} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={isEditing}
+ onOpenChange={setIsEditing}
+ label="Edit delivery note"
+ height="hug"
+ purpose="form"
+ data-testid="orders-edit">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Edit delivery note</Heading>
+ <TextInput
+ label="Delivery note"
+ value={note}
+ onChange={setNote}
+ hasAutoFocus
+ />
+ <HStack gap={2} hAlign="end">
+ <Button label="Close all" variant="ghost" onClick={closeAll} />
+ <Button
+ label="Back"
+ variant="secondary"
+ onClick={() => setIsEditing(false)}
+ />
+ <Button label="Save" onClick={() => setIsEditing(false)} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </VStack>
+ );
+}
+
+export const OrdersDrillIn: Story = {
+ name: 'Orders drill-in (siblings, Back, Close all)',
+ render: () => <OrdersFlow />,
+};
+
+export const DeepLinkDepthThree: Story = {
+ name: 'Deep link at depth 3',
+ render: () => <OrdersFlow deepLink />,
+};
+
+// ---------------------------------------------------------------------------
+// Filters: a step flow at the base (categories → options) with Help on top
+// ---------------------------------------------------------------------------
+
+function FiltersFlow() {
+ const [step, setStep] = useState<string | null>(null);
+ const [isHelpOpen, setIsHelpOpen] = useState(false);
+ const [category, setCategory] = useState('shoes');
+ const [sort, setSort] = useState('newest');
+
+ return (
+ <VStack gap={3}>
+ <Heading level={2}>Filters</Heading>
+ <Text type="supporting" color="secondary">
+ The base is a two-step flow: one state value names the open step, and
+ Next and Back replace one step with the other in place. Help is a
+ standalone sheet that opens over either step; the step recedes.
+ </Text>
+ <Button label="Open filters" onClick={() => setStep('categories')} />
+ <BottomSheet
+ isOpen={step === 'categories'}
+ onOpenChange={isOpen =>
+ !isOpen && setStep(c => (c === 'categories' ? null : c))
+ }
+ label="Categories"
+ height="hug"
+ data-testid="filters-categories">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Category</Heading>
+ <RadioList
+ label="Category"
+ isLabelHidden
+ value={category}
+ onChange={setCategory}>
+ <RadioListItem label="Shoes" value="shoes" />
+ <RadioListItem label="Jackets" value="jackets" />
+ <RadioListItem label="Accessories" value="accessories" />
+ </RadioList>
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Help"
+ variant="ghost"
+ onClick={() => setIsHelpOpen(true)}
+ />
+ <Button label="Next" onClick={() => setStep('options')} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={step === 'options'}
+ onOpenChange={isOpen =>
+ !isOpen && setStep(c => (c === 'options' ? null : c))
+ }
+ label="Options"
+ height="hug"
+ data-testid="filters-options">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Sort</Heading>
+ <RadioList
+ label="Sort"
+ isLabelHidden
+ value={sort}
+ onChange={setSort}>
+ <RadioListItem label="Newest" value="newest" />
+ <RadioListItem label="Price: low to high" value="price" />
+ <RadioListItem label="Top rated" value="rating" />
+ </RadioList>
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Help"
+ variant="ghost"
+ onClick={() => setIsHelpOpen(true)}
+ />
+ <Button
+ label="Back"
+ variant="secondary"
+ onClick={() => setStep('categories')}
+ />
+ <Button label="Apply" onClick={() => setStep(null)} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={isHelpOpen}
+ onOpenChange={setIsHelpOpen}
+ label="Help"
+ height="hug"
+ data-testid="filters-help">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>About filters</Heading>
+ <Text type="body">
+ Pick a category first, then how to sort the results. Your choices
+ are kept until you apply or close the filters.
+ </Text>
+ <HStack gap={2} hAlign="end">
+ <Button label="Got it" onClick={() => setIsHelpOpen(false)} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </VStack>
+ );
+}
+
+export const FiltersSwitcherBase: Story = {
+ name: 'Step flow at the base with a Help sheet',
+ render: () => <FiltersFlow />,
+};
+
+// ---------------------------------------------------------------------------
+// Contacts: a list with a two-step flow on top (edit → saved)
+// ---------------------------------------------------------------------------
+
+const CONTACTS = ['Ada Lovelace', 'Grace Hopper', 'Katherine Johnson'];
+
+function ContactsFlow() {
+ const [isListOpen, setIsListOpen] = useState(false);
+ const [editStep, setEditStep] = useState<string | null>(null);
+ const [contactIndex, setContactIndex] = useState(0);
+ const [names, setNames] = useState(CONTACTS);
+ const [draft, setDraft] = useState('');
+
+ const startEdit = (index: number) => {
+ setContactIndex(index);
+ setDraft(names[index]);
+ setEditStep('edit');
+ };
+ const save = () => {
+ setNames(current =>
+ current.map((name, index) => (index === contactIndex ? draft : name)),
+ );
+ setEditStep('saved');
+ };
+
+ return (
+ <VStack gap={3}>
+ <Heading level={2}>Contacts</Heading>
+ <Text type="supporting" color="secondary">
+ The top level is a two-step flow of standalone sheets: Save replaces the
+ editor with a confirmation in place (one level up the stack; the list
+ beneath stays covered), and Back returns to the list.
+ </Text>
+ <Button label="Open contacts" onClick={() => setIsListOpen(true)} />
+ <BottomSheet
+ isOpen={isListOpen}
+ onOpenChange={setIsListOpen}
+ label="Contacts"
+ height="hug"
+ data-testid="contacts-list">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Contacts</Heading>
+ <Divider />
+ {names.map((name, index) => (
+ <HStack key={CONTACTS[index]} gap={2} vAlign="center">
+ <Text type="body">{name}</Text>
+ <Button
+ label="Edit"
+ variant="secondary"
+ size="sm"
+ onClick={() => startEdit(index)}
+ />
+ </HStack>
+ ))}
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Done"
+ variant="secondary"
+ onClick={() => setIsListOpen(false)}
+ />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={editStep === 'edit'}
+ onOpenChange={isOpen =>
+ !isOpen && setEditStep(c => (c === 'edit' ? null : c))
+ }
+ label="Edit contact"
+ height="hug"
+ purpose="form"
+ data-testid="contacts-edit">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Edit contact</Heading>
+ <TextInput
+ label="Name"
+ value={draft}
+ onChange={setDraft}
+ hasAutoFocus
+ />
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Cancel"
+ variant="secondary"
+ onClick={() => setEditStep(null)}
+ />
+ <Button label="Save" onClick={save} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={editStep === 'saved'}
+ onOpenChange={isOpen =>
+ !isOpen && setEditStep(c => (c === 'saved' ? null : c))
+ }
+ label="Saved"
+ height="hug"
+ data-testid="contacts-saved">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Saved</Heading>
+ <Text type="body">{draft} was updated.</Text>
+ <HStack gap={2} hAlign="end">
+ <Button label="Back" onClick={() => setEditStep(null)} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </VStack>
+ );
+}
+
+export const ContactsSwitcherTop: Story = {
+ name: 'Step flow on top (edit → saved)',
+ render: () => <ContactsFlow />,
+};
+
+// ---------------------------------------------------------------------------
+// Places: each row owns its detail sheet, rendered in the list's content
+// ---------------------------------------------------------------------------
+
+const PLACES = [
+ {id: 'lisbon', name: 'Lisbon', note: 'Tram 28 at dawn'},
+ {id: 'kyoto', name: 'Kyoto', note: 'Philosopher’s Path'},
+ {id: 'oaxaca', name: 'Oaxaca', note: 'Mercado 20 de Noviembre'},
+];
+
+/** Each row owns its detail sheet: nested in the list sheet's content. */
+function PlaceRow({place}: {place: (typeof PLACES)[number]}) {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <HStack gap={2} vAlign="center">
+ <Text type="label">{place.name}</Text>
+ <Button
+ label="Details"
+ variant="secondary"
+ size="sm"
+ onClick={() => setIsOpen(true)}
+ />
+ </HStack>
+ <BottomSheet
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ label={place.name}
+ height="hug"
+ data-testid={`place-${place.id}`}>
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>{place.name}</Heading>
+ <Text type="supporting" color="secondary">
+ {place.note}
+ </Text>
+ <HStack gap={2} hAlign="end">
+ <Button label="Done" onClick={() => setIsOpen(false)} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </>
+ );
+}
+
+function PlacesFlow() {
+ const [isListOpen, setIsListOpen] = useState(false);
+ return (
+ <VStack gap={3}>
+ <Heading level={2}>Places</Heading>
+ <Text type="supporting" color="secondary">
+ Each row renders its own detail sheet right next to the row, inside the
+ list sheet's content. It stacks above the list, leaves with it when the
+ list is closed from code, and comes back with it while still open.
+ </Text>
+ <Button label="Open places" onClick={() => setIsListOpen(true)} />
+ <BottomSheet
+ isOpen={isListOpen}
+ onOpenChange={setIsListOpen}
+ label="Places"
+ height="hug"
+ data-testid="places-list">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Places</Heading>
+ <Divider />
+ {PLACES.map(place => (
+ <PlaceRow key={place.id} place={place} />
+ ))}
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Done"
+ variant="secondary"
+ onClick={() => setIsListOpen(false)}
+ />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </VStack>
+ );
+}
+
+export const RowOwnedDetail: Story = {
+ name: 'Row-owned detail sheet (nested in content)',
+ render: () => <PlacesFlow />,
+};
+
+// ---------------------------------------------------------------------------
+// Out of tree order: the sheet written second is opened first
+// ---------------------------------------------------------------------------
+
+function OutOfTreeOrderFlow() {
+ const [isShippingOpen, setIsShippingOpen] = useState(false);
+ const [isPaymentOpen, setIsPaymentOpen] = useState(false);
+ return (
+ <VStack gap={3}>
+ <Heading level={2}>Checkout</Heading>
+ <Text type="supporting" color="secondary">
+ Shipping is written first in the markup, Payment second. Open Payment
+ first and then Shipping from inside it: Shipping ends up on top. Order
+ is open order, not the order the sheets are written in.
+ </Text>
+ <Button label="Open payment" onClick={() => setIsPaymentOpen(true)} />
+ <BottomSheet
+ isOpen={isShippingOpen}
+ onOpenChange={setIsShippingOpen}
+ label="Shipping"
+ height="hug"
+ data-testid="shipping">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Shipping</Heading>
+ <Text type="body">
+ Written first, opened second: this sheet is on top.
+ </Text>
+ <HStack gap={2} hAlign="end">
+ <Button label="Done" onClick={() => setIsShippingOpen(false)} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={isPaymentOpen}
+ onOpenChange={setIsPaymentOpen}
+ label="Payment"
+ height="hug"
+ data-testid="payment">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Payment</Heading>
+ <Text type="body">
+ Written second, opened first: this sheet recedes when Shipping
+ opens over it.
+ </Text>
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Done"
+ variant="secondary"
+ onClick={() => setIsPaymentOpen(false)}
+ />
+ <Button
+ label="Change shipping"
+ onClick={() => setIsShippingOpen(true)}
+ />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </VStack>
+ );
+}
+
+export const OutOfTreeOrder: Story = {
+ name: 'Opening out of tree order (open order wins)',
+ render: () => <OutOfTreeOrderFlow />,
+};
+
+// ---------------------------------------------------------------------------
+// Dialog interop: a Dialog over a sheet, then a sheet over the Dialog
+// ---------------------------------------------------------------------------
+
+function DialogInteropFlow() {
+ const [isSheetOpen, setIsSheetOpen] = useState(false);
+ const [isConfirmOpen, setIsConfirmOpen] = useState(false);
+ const [isNoteOpen, setIsNoteOpen] = useState(false);
+ const toast = useToast();
+ return (
+ <VStack gap={3}>
+ <Heading level={2}>Photo</Heading>
+ <Text type="supporting" color="secondary">
+ Remove opens a Core Dialog over the sheet: the sheet does not recede,
+ because only sheets count. Why? opens a sheet from inside the Dialog: it
+ paints above the Dialog, and the first sheet recedes beneath both.
+ </Text>
+ <Button label="Open photo" onClick={() => setIsSheetOpen(true)} />
+ <BottomSheet
+ isOpen={isSheetOpen}
+ onOpenChange={setIsSheetOpen}
+ label="Photo"
+ height="hug"
+ data-testid="photo">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Alps, 2025</Heading>
+ <Text type="supporting" color="secondary">
+ Taken on the way up to the hut.
+ </Text>
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Remove"
+ variant="secondary"
+ onClick={() => setIsConfirmOpen(true)}
+ />
+ <Button label="Done" onClick={() => setIsSheetOpen(false)} />
+ </HStack>
+ </VStack>
+ </Section>
+ <Dialog
+ isOpen={isConfirmOpen}
+ onOpenChange={setIsConfirmOpen}
+ aria-label="Remove photo?"
+ data-testid="confirm-dialog">
+ <VStack gap={3}>
+ <Heading level={3}>Remove this photo?</Heading>
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Toast from dialog"
+ variant="ghost"
+ onClick={() =>
+ toast({body: 'Toast from the dialog', isAutoHide: false})
+ }
+ />
+ <Button
+ label="Why?"
+ variant="secondary"
+ onClick={() => setIsNoteOpen(true)}
+ />
+ <Button label="Keep" onClick={() => setIsConfirmOpen(false)} />
+ </HStack>
+ </VStack>
+ <BottomSheet
+ isOpen={isNoteOpen}
+ onOpenChange={setIsNoteOpen}
+ label="About removing"
+ height="hug"
+ data-testid="dialog-sheet">
+ <Section padding={4}>
+ <VStack gap={2}>
+ <Text type="body">
+ Removing a photo only hides it from this album.
+ </Text>
+ <HStack gap={2} hAlign="end">
+ <Button label="Got it" onClick={() => setIsNoteOpen(false)} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </Dialog>
+ </BottomSheet>
+ </VStack>
+ );
+}
+
+// A no-scrim sheet opened from a modal sheet and rendered outside it
+// ---------------------------------------------------------------------------
+
+/**
+ * A modal sheet opens a `hasScrim={false}` sheet that lives outside it in
+ * the tree. The modal keeps the page — and the no-scrim sheet — inert, so the
+ * no-scrim sheet stays beneath the modal instead of painting above it with
+ * nothing to press. Rendered inside the modal's content it would enter the
+ * top layer as usual.
+ */
+function NonModalOutsideModalFlow() {
+ const [isModalOpen, setIsModalOpen] = useState(false);
+ const [isHintOpen, setIsHintOpen] = useState(false);
+ return (
+ <VStack gap={3}>
+ <Heading level={2}>Hints</Heading>
+ <Text type="supporting" color="secondary">
+ Open settings, then Show hint: the hint sheet is declared outside the
+ modal sheet, so it stays beneath it while the modal is open and enters
+ the top layer — above the page&apos;s fixed tab bar — once the modal
+ closes. Swap to hint, inside settings, closes settings and opens the
+ hint in one update.
+ </Text>
+ <Button label="Open settings" onClick={() => setIsModalOpen(true)} />
+ <nav
+ aria-label="Tabs"
+ style={{
+ position: 'fixed',
+ insetInlineStart: 0,
+ insetInlineEnd: 0,
+ bottom: 0,
+ zIndex: 10,
+ padding: 12,
+ background: 'var(--color-background-secondary, #eee)',
+ display: 'flex',
+ justifyContent: 'space-around',
+ }}>
+ <button type="button">Home</button>
+ <button type="button">Search</button>
+ <button type="button">Profile</button>
+ </nav>
+ <BottomSheet
+ isOpen={isModalOpen}
+ onOpenChange={setIsModalOpen}
+ label="Settings"
+ height="hug">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Settings</Heading>
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Show hint"
+ variant="secondary"
+ onClick={() => setIsHintOpen(true)}
+ />
+ <Button
+ label="Swap to hint"
+ variant="secondary"
+ onClick={() => {
+ setIsModalOpen(false);
+ setIsHintOpen(true);
+ }}
+ />
+ <Button label="Done" onClick={() => setIsModalOpen(false)} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={isHintOpen}
+ onOpenChange={setIsHintOpen}
+ hasScrim={false}
+ label="Hint"
+ height="hug">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>Hint</Heading>
+ <HStack gap={2} hAlign="end">
+ <Button label="Got it" onClick={() => setIsHintOpen(false)} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </VStack>
+ );
+}
+
+export const NonModalOutsideModal: Story = {
+ name: 'A no-scrim sheet opened from a modal sheet, declared outside it',
+ render: () => <NonModalOutsideModalFlow />,
+};
+
+export const DialogInterop: Story = {
+ name: 'Dialog over a sheet, sheet over the Dialog',
+ render: () => <DialogInteropFlow />,
+};
+/**
+ * A `hasScrim={false}` sheet opened while a Dialog is open stays beneath it.
+ * Here the Dialog is conditionally rendered and is *unmounted* while still
+ * open — no `close` event fires — and the sheet must still enter the top
+ * layer, above the fixed tab bar, the moment the Dialog is gone.
+ */
+function NonModalUnderUnmountingDialogFlow() {
+ const [isEditing, setIsEditing] = useState(false);
+ const [isHintOpen, setIsHintOpen] = useState(false);
+ return (
+ <VStack gap={3}>
+ <Heading level={2}>Editor</Heading>
+ <Text type="supporting" color="secondary">
+ Edit opens a Dialog. Inside it, Show hint opens a no-scrim sheet that is
+ declared outside the Dialog, so it stays beneath it; Discard removes the
+ open Dialog from the page without closing it. The hint then rises above
+ the tab bar on its own.
+ </Text>
+ <Button label="Edit" onClick={() => setIsEditing(true)} />
+ <nav
+ aria-label="Tabs"
+ style={{
+ position: 'fixed',
+ insetInlineStart: 0,
+ insetInlineEnd: 0,
+ bottom: 0,
+ zIndex: 10,
+ padding: 12,
+ background: 'var(--color-background-secondary, #eee)',
+ display: 'flex',
+ justifyContent: 'space-around',
+ }}>
+ <button type="button">Home</button>
+ <button type="button">Search</button>
+ <button type="button">Profile</button>
+ </nav>
+ {isEditing && (
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Edit caption">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Text>The caption editor.</Text>
+ <HStack gap={2}>
+ <Button
+ label="Show hint"
+ variant="secondary"
+ onClick={() => setIsHintOpen(true)}
+ />
+ <Button
+ label="Discard"
+ variant="secondary"
+ onClick={() => setIsEditing(false)}
+ />
+ </HStack>
+ <Button label="Save" onClick={() => setIsEditing(false)} />
+ </VStack>
+ </Section>
+ </Dialog>
+ )}
+ <BottomSheet
+ isOpen={isHintOpen}
+ onOpenChange={setIsHintOpen}
+ hasScrim={false}
+ label="Hint"
+ height="hug">
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Text>Captions under 125 characters read best.</Text>
+ <Button label="Got it" onClick={() => setIsHintOpen(false)} />
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </VStack>
+ );
+}
+
+export const NonModalUnderUnmountingDialog: Story = {
+ name: 'A no-scrim sheet beneath a Dialog that unmounts while open',
+ render: () => <NonModalUnderUnmountingDialogFlow />,
+};
+
+// ---------------------------------------------------------------------------
+// File browser: mapped sheets of unknown depth
+// ---------------------------------------------------------------------------
+
+interface Folder {
+ name: string;
+ children: Folder[];
+}
+
+const ROOT: Folder = {
+ name: 'Home',
+ children: [
+ {
+ name: 'Photos',
+ children: [
+ {name: 'Trips', children: [{name: 'Alps', children: []}]},
+ {name: 'Family', children: []},
+ ],
+ },
+ {
+ name: 'Documents',
+ children: [{name: 'Taxes', children: [{name: '2025', children: []}]}],
+ },
+ {name: 'Music', children: []},
+ ],
+};
+
+function FileBrowserFlow() {
+ // `path` is the history of visited folders; `openDepth` says how many of
+ // them are open. Closed entries stay mounted until their exit finishes and
+ // are replaced the next time a folder opens at that depth.
+ const [path, setPath] = useState<Folder[]>([ROOT]);
+ const [openDepth, setOpenDepth] = useState(0);
+
+ const openChild = (level: number, child: Folder) => {
+ setPath([...path.slice(0, level + 1), child]);
+ setOpenDepth(level + 2);
+ };
+
+ return (
+ <VStack gap={3}>
+ <Heading level={2}>Files</Heading>
+ <Text type="supporting" color="secondary">
+ One mapped BottomSheet per visited folder; the depth is whatever the
+ person browses to. Sheets deeper than two steps back share the second
+ recede step.
+ </Text>
+ <Button label="Browse files" onClick={() => setOpenDepth(1)} />
+ {path.map((folder, level) => (
+ <BottomSheet
+ key={`${level}:${folder.name}`}
+ isOpen={level < openDepth}
+ onOpenChange={open => {
+ if (!open) {
+ setOpenDepth(level);
+ }
+ }}
+ label={folder.name}
+ height="hug"
+ data-testid={`folder-${level}`}>
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>{folder.name}</Heading>
+ <Text type="supporting" color="secondary">
+ {path
+ .slice(0, level + 1)
+ .map(entry => entry.name)
+ .join(' / ')}
+ </Text>
+ <Divider />
+ {folder.children.length === 0 ? (
+ <Text type="body">This folder is empty.</Text>
+ ) : (
+ folder.children.map(child => (
+ <HStack key={child.name} gap={2} vAlign="center">
+ <Text type="body">{child.name}</Text>
+ <Button
+ label="Open"
+ variant="secondary"
+ size="sm"
+ onClick={() => openChild(level, child)}
+ />
+ </HStack>
+ ))
+ )}
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Close all"
+ variant="ghost"
+ onClick={() => setOpenDepth(0)}
+ />
+ <Button
+ label={level === 0 ? 'Done' : 'Back'}
+ variant="secondary"
+ onClick={() => setOpenDepth(level)}
+ />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ ))}
+ </VStack>
+ );
+}
+
+export const FileBrowserUnknownDepth: Story = {
+ name: 'File browser (unknown depth)',
+ render: () => <FileBrowserFlow />,
+};
diff --git a/apps/storybook/stories/BottomSheetSwitcher.stories.tsx b/apps/storybook/stories/BottomSheetSwitcher.stories.tsx
index 0297d118d1..19465c2c63 100644
--- a/apps/storybook/stories/BottomSheetSwitcher.stories.tsx
+++ b/apps/storybook/stories/BottomSheetSwitcher.stories.tsx
@@ -13,16 +13,34 @@ import {Layout, LayoutContent, LayoutFooter} from '@astryxdesign/core/Layout';
import {Section} from '@astryxdesign/core/Section';
import {HStack, VStack} from '@astryxdesign/core/Stack';
import {Text} from '@astryxdesign/core/Text';
+import {TextInput} from '@astryxdesign/core/TextInput';
+import {useToast} from '@astryxdesign/core/Toast';
import {RadioList, RadioListItem} from '@astryxdesign/core/RadioList';
+/**
+ * Deprecated. A `BottomSheetSwitcher` flow used on its own behaves as
+ * released, and when it is stacked with other sheets it is one level of the
+ * bottom-sheet stack; a future minor release removes it. These stories stay
+ * as its documentation. New
+ * flows write each step as a standalone `BottomSheet` driven by one state
+ * value — see the `Core/BottomSheetReplace` stories, which mirror these one
+ * to one with the replacement.
+ */
const meta: Meta<typeof BottomSheetSwitcher> = {
- title: 'Core/BottomSheetSwitcher',
+ title: 'Core/BottomSheetSwitcher (deprecated)',
+ // The title carries the lifecycle; the ids stay what the browser specs,
+ // the docs, and existing links use.
+ id: 'core-bottomsheetswitcher',
component: BottomSheetSwitcher,
tags: ['autodocs'],
parameters: {
layout: 'fullscreen',
docs: {
story: {inline: false, height: '560px'},
+ description: {
+ component:
+ 'Deprecated: write each step as its own BottomSheet with isOpen, controlled by one state value that names the open step; the same replace handoff runs between steps. A switcher flow used on its own behaves as released (with two fixes: a toast raised from a step renders above the flow and can be pressed, and under reduced motion its steps follow the reduced-motion rule); stacked with other sheets, it is one level of the stack (it recedes and is blocked when covered and shares the one scrim). A future minor release removes it. The Core/BottomSheetReplace stories show each of these flows rebuilt with the replacement.',
+ },
},
},
argTypes: {
@@ -338,6 +356,250 @@ function MultiStepSwitcherExample({
);
}
+/**
+ * The deprecated switcher stacked with standalone sheets: one level of the
+ * stack, by `component:BottomSheet` FR12. "Over" opens the flow from a
+ * control inside a standalone sheet, so the sheet recedes beneath the flow
+ * and keeps the one scrim; "under" opens a standalone Help sheet from a step,
+ * so the whole flow recedes beneath it and its step backdrops stay clear.
+ */
+function StackedSwitcherExample({flowIsOver}: {flowIsOver: boolean}) {
+ const [isSheetOpen, setIsSheetOpen] = useState(false);
+ const [activeSheet, setActiveSheet] = useState<string | null>(null);
+ const [isHelpOpen, setIsHelpOpen] = useState(false);
+ const toast = useToast();
+ const flow = (
+ <BottomSheetSwitcher
+ activeSheet={activeSheet}
+ onActiveSheetChange={setActiveSheet}>
+ <BottomSheet sheetId="overview" label="Set up notifications" height="hug">
+ <Section padding={4}>
+ <VStack gap={4}>
+ <VStack gap={1}>
+ <Heading level={3}>Set up notifications</Heading>
+ <Text type="supporting" color="secondary">
+ Step 1 of 2
+ </Text>
+ </VStack>
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Toast from step"
+ variant="ghost"
+ onClick={() =>
+ toast({body: 'Toast from the step', isAutoHide: false})
+ }
+ />
+ {!flowIsOver && (
+ <Button
+ label="Help"
+ variant="secondary"
+ onClick={() => setIsHelpOpen(true)}
+ />
+ )}
+ <Button
+ label="Cancel"
+ variant="secondary"
+ onClick={() => setActiveSheet(null)}
+ />
+ <Button
+ label="Continue"
+ onClick={() => setActiveSheet('frequency')}
+ />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ <BottomSheet sheetId="frequency" label="Frequency" height="hug">
+ <Section padding={4}>
+ <VStack gap={4}>
+ <VStack gap={1}>
+ <Heading level={3}>Frequency</Heading>
+ <Text type="supporting" color="secondary">
+ Step 2 of 2
+ </Text>
+ </VStack>
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Back"
+ variant="secondary"
+ onClick={() => setActiveSheet('overview')}
+ />
+ <Button label="Done" onClick={() => setActiveSheet(null)} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </BottomSheetSwitcher>
+ );
+ if (flowIsOver) {
+ return (
+ <>
+ <Button label="Open settings" onClick={() => setIsSheetOpen(true)} />
+ <BottomSheet
+ isOpen={isSheetOpen}
+ onOpenChange={setIsSheetOpen}
+ label="Settings"
+ height="capped">
+ <Section padding={4}>
+ <VStack gap={4}>
+ <Heading level={3}>Settings</Heading>
+ <Text>
+ A standalone sheet. The deprecated flow opened from here stacks
+ on top of it; this sheet recedes and keeps the one scrim.
+ </Text>
+ <HStack gap={2}>
+ <Button
+ label="Set up notifications"
+ onClick={() => setActiveSheet('overview')}
+ />
+ {/* Closes the host. While the flow is open above it, the
+ browser's modal blocking keeps this control out of reach
+ (the flow's dialog is modal), so that scenario — the
+ host closed from code, as a route change would — is
+ driven by the real-browser check; a person reaches it
+ before the flow opens and after a step closes it. */}
+ <Button
+ label="Close settings"
+ variant="secondary"
+ onClick={() => setIsSheetOpen(false)}
+ />
+ </HStack>
+ </VStack>
+ </Section>
+ {flow}
+ </BottomSheet>
+ </>
+ );
+ }
+ return (
+ <>
+ <Button
+ label="Set up notifications"
+ onClick={() => setActiveSheet('overview')}
+ />
+ {flow}
+ <BottomSheet
+ isOpen={isHelpOpen}
+ onOpenChange={setIsHelpOpen}
+ label="Help"
+ height="hug">
+ <Section padding={4}>
+ <VStack gap={4}>
+ <Heading level={3}>Help</Heading>
+ <Text>
+ A standalone sheet opened from a step. The whole deprecated flow
+ recedes beneath it as one level; this sheet's backdrop stays clear
+ because the flow owns the stack's scrim.
+ </Text>
+ <HStack gap={2} hAlign="end">
+ <Button label="Got it" onClick={() => setIsHelpOpen(false)} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </>
+ );
+}
+
+/**
+ * A note sheet with a text field sits over a deprecated flow whose step
+ * advances from code — a timer here, a background completion in an app.
+ * The flow's level becomes a new dialog beneath the note sheet, so the
+ * registry puts the note sheet back on top; the field being typed in keeps
+ * focus through that, and every keystroke lands in it.
+ */
+function TypingOverAdvancingFlowExample() {
+ const [activeSheet, setActiveSheet] = useState<string | null>(null);
+ const [isNoteOpen, setIsNoteOpen] = useState(false);
+ const [note, setNote] = useState('');
+ const [isArmed, setIsArmed] = useState(false);
+ const toast = useToast();
+ return (
+ <>
+ <Button
+ label="Set up notifications"
+ onClick={() => setActiveSheet('overview')}
+ />
+ <BottomSheetSwitcher
+ activeSheet={activeSheet}
+ onActiveSheetChange={setActiveSheet}>
+ <BottomSheet
+ sheetId="overview"
+ label="Set up notifications"
+ height="hug">
+ <Section padding={4}>
+ <VStack gap={4}>
+ <Heading level={3}>Set up notifications</Heading>
+ <Text type="supporting" color="secondary">
+ Step 1 of 2. Add a note, then type: the flow moves to step 2 on
+ its own two seconds after the note opens.
+ </Text>
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Add a note"
+ onClick={() => {
+ setIsNoteOpen(true);
+ if (!isArmed) {
+ setIsArmed(true);
+ setTimeout(() => setActiveSheet('frequency'), 2000);
+ }
+ }}
+ />
+ <Button
+ label="Continue"
+ variant="primary"
+ onClick={() => setActiveSheet('frequency')}
+ />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ <BottomSheet
+ sheetId="frequency"
+ label="Notification frequency"
+ height="hug">
+ <Section padding={4}>
+ <VStack gap={4}>
+ <Heading level={3}>Notification frequency</Heading>
+ <Text type="supporting" color="secondary">
+ Step 2 of 2
+ </Text>
+ <HStack gap={2} hAlign="end">
+ <Button label="Done" onClick={() => setActiveSheet(null)} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </BottomSheetSwitcher>
+ <BottomSheet
+ isOpen={isNoteOpen}
+ onOpenChange={setIsNoteOpen}
+ label="Note"
+ height="hug">
+ <Section padding={4}>
+ <VStack gap={4}>
+ <Heading level={3}>Note</Heading>
+ <TextInput
+ label="Note"
+ value={note}
+ onChange={setNote}
+ hasAutoFocus
+ />
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Toast from note"
+ variant="secondary"
+ onClick={() => toast({body: 'Note toast', isAutoHide: false})}
+ />
+ <Button label="Save" onClick={() => setIsNoteOpen(false)} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </>
+ );
+}
+
const openFlow: NonNullable<Story['play']> = async ({canvasElement}) => {
const trigger = canvasElement.querySelector('button');
if (trigger instanceof HTMLElement) {
@@ -375,3 +637,18 @@ export const NarrowViewport: Story = {
render: () => <MultiStepSwitcherExample height="hug" />,
play: openFlow,
};
+
+export const StackedOverASheet: Story = {
+ name: 'Stacked over a standalone sheet',
+ render: () => <StackedSwitcherExample flowIsOver />,
+};
+
+export const StackedUnderASheet: Story = {
+ name: 'Stacked under a standalone sheet',
+ render: () => <StackedSwitcherExample flowIsOver={false} />,
+};
+
+export const TypingOverAdvancingFlow: Story = {
+ name: 'Typing in a sheet over a flow that advances from code',
+ render: () => <TypingOverAdvancingFlowExample />,
+};
diff --git a/apps/storybook/stories/LayerDismissal.stories.tsx b/apps/storybook/stories/LayerDismissal.stories.tsx
index 451c5f7287..172da11e87 100644
--- a/apps/storybook/stories/LayerDismissal.stories.tsx
+++ b/apps/storybook/stories/LayerDismissal.stories.tsx
@@ -30,7 +30,7 @@ import {
Tooltip,
VStack,
} from '@astryxdesign/core';
-import {BottomSheet, BottomSheetSwitcher} from '@astryxdesign/core/BottomSheet';
+import {BottomSheet} from '@astryxdesign/core/BottomSheet';
import {InfoTip} from '@astryxdesign/lab/InfoTip';
import type {Meta, StoryObj} from '@storybook/react-vite';
@@ -527,31 +527,32 @@ export const MobileNavAlone: Story = {render: () => <MobileNavAloneExample />};
* next Escape closes the sheet.
*/
function SheetWithHoverTipExample() {
- const [activeSheet, setActiveSheet] = useState<string | null>(null);
+ const [isOpen, setIsOpen] = useState(false);
return (
<>
<Button
label="Open sheet"
variant="secondary"
- onClick={() => setActiveSheet('details')}
+ onClick={() => setIsOpen(true)}
/>
- <BottomSheetSwitcher
- activeSheet={activeSheet}
- onActiveSheetChange={setActiveSheet}
- hasScrim={false}>
- <BottomSheet sheetId="details" label="Details" height="hug" padding={0}>
- <VStack gap={3} xstyle={sheetStyles.body}>
- <Text type="body">
- Hover the button to show the tip, then press Escape. The first
- press closes only the tip; the next press closes the sheet.
- </Text>
- <Tooltip content="A hover tip, showing">
- <Button label="Hover me" variant="secondary" />
- </Tooltip>
- </VStack>
- </BottomSheet>
- </BottomSheetSwitcher>
+ <BottomSheet
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ hasScrim={false}
+ label="Details"
+ height="hug"
+ padding={0}>
+ <VStack gap={3} xstyle={sheetStyles.body}>
+ <Text type="body">
+ Hover the button to show the tip, then press Escape. The first press
+ closes only the tip; the next press closes the sheet.
+ </Text>
+ <Tooltip content="A hover tip, showing">
+ <Button label="Hover me" variant="secondary" />
+ </Tooltip>
+ </VStack>
+ </BottomSheet>
</>
);
}
diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.md
index 26c0b8c82d..0fab0e43de 100644
--- a/docs/architecture/layer-runtime.md
+++ b/docs/architecture/layer-runtime.md
@@ -311,7 +311,10 @@ stack. Tooltip and HoverCard report current DOM presence; Popover and
DropdownMenu register through `useFocusTrap`; Dialog, Lightbox, MobileNav,
BottomSheet, BottomSheetSwitcher, and Drawer additionally ask
`shouldDismissOnCloseRequest()` before acting on native platform close
-requests. Other family members still use local Escape handling as listed in
+requests. A BottomSheet covered by, or being replaced by, another sheet of its
+stack reports itself absent to the shared stack while that lasts
+(`component:BottomSheet` FR7): the shared stack stays the one dismissal
+registry, and only the order among sheets is the sheet stack's to state. Other family members still use local Escape handling as listed in
`family:overlay-dismissal`.
Outside interaction is not coordinated by the shared stack. Current paths are
@@ -379,15 +382,42 @@ it.
ToastViewport uses `popover="manual"` for top-layer promotion. Each open modal
Dialog and each open scrim BottomSheet supplies its `<dialog>` as an outlet
-through the private `Layer/modalOutlet.ts` registry. A BottomSheet releases its
+through the private `Layer/modalOutlet.ts` registry (`spec:AST-003` FR18:
+every active native modal supplies one, a covered sheet included); a modal
+BottomSheetSwitcher flow supplies its active step's dialog, following each
+handoff. The registry orders outlets; it mounts nothing (INV14 names the
+mounting the runtime is to own). Which outlet is the latest — the one a
+global host renders into — follows the sheet stack's order among sheets, not
+the order they were supplied in: the top sheet is the latest, so a toast
+lands in the top sheet and never in a covered, inert one, also when the
+covered flow beneath it changes step and supplies its new step's dialog
+(that supply goes beneath the top sheet); when the top sheet closes the
+sheet it reveals is the latest again and takes the host back; a sheet is
+raised only among sheet outlets, so a Dialog opened from a sheet and
+supplied later stays the latest until it closes. A BottomSheet releases its
outlet when it starts closing: its dialog stays modal through the exit
animation, but inert. A top-layer viewport renders into a host element
it owns, moves that host into the latest open outlet, returns it to the
viewport's tree position when no outlet is open, and enters the top layer again
after each move. Toasts therefore paint above the modal and stay operable inside
it. Moving the host does not remount the rows, so entries, timers, and focus
-handoff survive. Toast state lives inside the viewport. A viewport rendered with
-`isTopLayer={false}` stays in place.
+handoff survive. The rule is one of order, not of modality, and it reaches
+the surfaces that tell the registry they entered the top layer: the modal
+outlets, and a non-modal top-layer surface that blocks nothing and announces
+itself — a `hasScrim={false}` BottomSheet in the top layer with no backdrop
+(while a modal that does not contain it is open it stays beneath that modal,
+outside the top layer, and enters — announcing then — once that modal has
+gone). How such a surface is put in the top layer is the component's own
+today, inside the INV14 gap below; the rule here is only that it announces
+its entry through the same registry, and that the viewport then leaves and
+re-enters the top layer in place, keeping focus inside it, so toasts paint
+above it too. A non-modal top-layer surface that does not announce itself is
+outside the rule: a `hasScrim={false}` Drawer (`popover="manual"`,
+`showPopover()`) shown after the viewport covers toasts raised while it is
+open; the rule does not cover it. In a stack of scrim BottomSheets the latest
+outlet is the top sheet, so toasts paint above the whole stack. Toast state
+lives inside the viewport. A viewport rendered with `isTopLayer={false}` stays
+in place.
CommandPalette composes native Dialog. Its normal launcher presentation therefore
uses `showModal()`; its documentation/showcase `isInline` path does not. The
@@ -493,7 +523,7 @@ Current gaps are observable facts, not current target behavior:
- Backdrop, manual outside, touch, and swipe paths do not share the existing
gesture claim or one association model.
- Toast's root and fallback hosts remain behind the other native modals:
- Lightbox, MobileNav, and a scrim BottomSheetSwitcher.
+ Lightbox and MobileNav.
- The reduced browser fallback is not documented as non-equivalent.
- Existing tests simulate Popover `toggle` and DOM nesting; they do not prove
native pointer light dismissal, top-layer/modal ordering, real anchor geometry,
@@ -508,6 +538,10 @@ shared presentation hold, exit copy, runtime backdrop tint, or lift module
exists, and Dialog, Drawer, BottomSheet, Lightbox, MobileNav, ToastViewport,
and Selector each build their own top-layer mounting, exit, or backdrop, and
Popover builds its own presentation hold for its sheet presentation.
+BottomSheet's own includes its sheet stack's mounting — the re-show that
+keeps a document's sheets in open order, a step dialog's modal present, and
+the non-modal sheet's popover host — alongside its scrim; the ordering rules
+above are the stack's, the mounting under them is this gap's.
## Change coupling
diff --git a/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.doc.mjs b/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.doc.mjs
index fbc7974c0e..a7291f7c10 100644
--- a/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.doc.mjs
+++ b/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.doc.mjs
@@ -4,16 +4,18 @@
export const doc = {
type: 'block',
exampleFor: 'BottomSheetSwitcher',
- name: 'Bottom Sheet Switcher — Review flow',
- displayName: 'Bottom Sheet Switcher — Review flow',
+ alsoExampleFor: ['BottomSheet'],
+ // The published registry identity predates the rewrite; keep it.
+ registry: {slug: 'review-flow'},
+ name: 'Bottom Sheet — Review flow',
+ displayName: 'Bottom Sheet — Review flow',
description:
- '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.',
+ 'A two-step form flow of two standalone sheets driven by one state value: Continue replaces the review step with the confirmation in place, and Back returns.',
isReady: true,
isShowcase: false,
aspectRatio: 3 / 4,
componentsUsed: [
'BottomSheet',
- 'BottomSheetSwitcher',
'Button',
'Heading',
'Section',
diff --git a/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.tsx b/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.tsx
index 09cb79db51..c4a67ee8d4 100644
--- a/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.tsx
+++ b/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.tsx
@@ -3,73 +3,79 @@
'use client';
import {useState} from 'react';
-import {BottomSheet, BottomSheetSwitcher} from '@astryxdesign/core/BottomSheet';
+import {BottomSheet} from '@astryxdesign/core/BottomSheet';
import {Button} from '@astryxdesign/core/Button';
import {Heading} from '@astryxdesign/core/Heading';
import {Section} from '@astryxdesign/core/Section';
import {HStack, VStack} from '@astryxdesign/core/Stack';
import {Text} from '@astryxdesign/core/Text';
+type Step = 'review' | 'confirm' | null;
+
export default function BottomSheetSwitcherReviewFlow() {
- const [activeSheet, setActiveSheet] = useState<string | null>(null);
+ // One state value names the open step; Continue and Back close one sheet
+ // and open the other in the same update, which replaces it in place.
+ const [step, setStep] = useState<Step>(null);
+ // Clear the step only if it is still the open one: a step that closes
+ // because the person moved on must not undo the move.
+ const close = (own: Step) => (isOpen: boolean) => {
+ if (!isOpen) {
+ setStep(current => (current === own ? null : current));
+ }
+ };
return (
<>
- <Button
- label="Review settings"
- onClick={() => setActiveSheet('review')}
- />
- <BottomSheetSwitcher
- activeSheet={activeSheet}
- onActiveSheetChange={setActiveSheet}>
- <BottomSheet
- sheetId="review"
- label="Review notification settings"
- height="hug"
- purpose="form">
- <Section padding={4}>
- <VStack gap={4}>
- <VStack gap={1}>
- <Heading level={3}>Review settings</Heading>
- <Text type="supporting" color="secondary">
- Daily summaries will be sent by email.
- </Text>
- </VStack>
- <HStack gap={2} hAlign="end">
- <Button
- label="Cancel"
- variant="secondary"
- onClick={() => setActiveSheet(null)}
- />
- <Button
- label="Continue"
- onClick={() => setActiveSheet('confirm')}
- />
- </HStack>
+ <Button label="Review settings" onClick={() => setStep('review')} />
+ <BottomSheet
+ isOpen={step === 'review'}
+ onOpenChange={close('review')}
+ label="Review notification settings"
+ height="hug"
+ purpose="form">
+ <Section padding={4}>
+ <VStack gap={4}>
+ <VStack gap={1}>
+ <Heading level={3}>Review settings</Heading>
+ <Text type="supporting" color="secondary">
+ Daily summaries will be sent by email.
+ </Text>
</VStack>
- </Section>
- </BottomSheet>
- <BottomSheet sheetId="confirm" label="Confirm settings" height="hug">
- <Section padding={4}>
- <VStack gap={4}>
- <VStack gap={1}>
- <Heading level={3}>Confirm settings</Heading>
- <Text type="supporting" color="secondary">
- Your notification settings are ready to save.
- </Text>
- </VStack>
- <HStack gap={2} hAlign="end">
- <Button
- label="Back"
- variant="secondary"
- onClick={() => setActiveSheet('review')}
- />
- <Button label="Save" onClick={() => setActiveSheet(null)} />
- </HStack>
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Cancel"
+ variant="secondary"
+ onClick={() => setStep(null)}
+ />
+ <Button label="Continue" onClick={() => setStep('confirm')} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={step === 'confirm'}
+ onOpenChange={close('confirm')}
+ label="Confirm settings"
+ height="hug">
+ <Section padding={4}>
+ <VStack gap={4}>
+ <VStack gap={1}>
+ <Heading level={3}>Confirm settings</Heading>
+ <Text type="supporting" color="secondary">
+ Your notification settings are ready to save.
+ </Text>
</VStack>
- </Section>
- </BottomSheet>
- </BottomSheetSwitcher>
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Back"
+ variant="secondary"
+ onClick={() => setStep('review')}
+ />
+ <Button label="Save" onClick={() => setStep(null)} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
</>
);
}
diff --git a/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.doc.mjs b/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.doc.mjs
index 06bd27c387..6174cd9548 100644
--- a/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.doc.mjs
+++ b/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.doc.mjs
@@ -4,16 +4,18 @@
export const doc = {
type: 'block',
exampleFor: 'BottomSheetSwitcher',
- name: 'Bottom Sheet Switcher',
- displayName: 'Bottom Sheet Switcher',
+ alsoExampleFor: ['BottomSheet'],
+ // The published registry identity predates the rewrite; keep it.
+ registry: {slug: 'default'},
+ name: 'Bottom Sheet — Multi-step flow',
+ displayName: 'Bottom Sheet — Multi-step flow',
description:
- '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.',
+ 'A three-step flow of standalone sheets of different heights, driven by one state value: moving on replaces the open step in place. This is the replacement for the deprecated BottomSheetSwitcher.',
isReady: true,
isShowcase: true,
aspectRatio: 3 / 4,
componentsUsed: [
'BottomSheet',
- 'BottomSheetSwitcher',
'Button',
'CheckboxInput',
'Divider',
diff --git a/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.tsx b/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.tsx
index 04ce77ea4a..07a63a88d8 100644
--- a/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.tsx
+++ b/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.tsx
@@ -3,7 +3,7 @@
'use client';
import {useState} from 'react';
-import {BottomSheet, BottomSheetSwitcher} from '@astryxdesign/core/BottomSheet';
+import {BottomSheet} from '@astryxdesign/core/BottomSheet';
import {Button} from '@astryxdesign/core/Button';
import {CheckboxInput} from '@astryxdesign/core/CheckboxInput';
import {Divider} from '@astryxdesign/core/Divider';
@@ -15,20 +15,35 @@ import {RadioList, RadioListItem} from '@astryxdesign/core/RadioList';
type NotificationSheetHeight = 'hug' | 'capped';
-interface NotificationOverviewSheetProps {
+/**
+ * Each step is a standalone sheet. Closing the open step and opening the
+ * next one in the same update (one `step` state value) replaces it in place.
+ */
+interface StepSheetProps {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ hasScrim: boolean;
height: NotificationSheetHeight;
+}
+
+interface NotificationOverviewSheetProps extends StepSheetProps {
onCancel: () => void;
onContinue: () => void;
}
function NotificationOverviewSheet({
+ isOpen,
+ onOpenChange,
+ hasScrim,
height,
onCancel,
onContinue,
}: NotificationOverviewSheetProps) {
return (
<BottomSheet
- sheetId="overview"
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ hasScrim={hasScrim}
label="Set up notifications"
height={height}>
<Section padding={4}>
@@ -74,13 +89,15 @@ function NotificationOverviewSheet({
);
}
-interface NotificationFrequencySheetProps {
- height: NotificationSheetHeight;
+interface NotificationFrequencySheetProps extends StepSheetProps {
onBack: () => void;
onContinue: () => void;
}
function NotificationFrequencySheet({
+ isOpen,
+ onOpenChange,
+ hasScrim,
height,
onBack,
onContinue,
@@ -89,7 +106,9 @@ function NotificationFrequencySheet({
return (
<BottomSheet
- sheetId="frequency"
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ hasScrim={hasScrim}
label="Notification frequency"
height={height}>
<Section padding={4}>
@@ -120,13 +139,15 @@ function NotificationFrequencySheet({
);
}
-interface NotificationChannelsSheetProps {
- height: NotificationSheetHeight;
+interface NotificationChannelsSheetProps extends StepSheetProps {
onBack: () => void;
onFinish: () => void;
}
function NotificationChannelsSheet({
+ isOpen,
+ onOpenChange,
+ hasScrim,
height,
onBack,
onFinish,
@@ -137,7 +158,9 @@ function NotificationChannelsSheet({
return (
<BottomSheet
- sheetId="channels"
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ hasScrim={hasScrim}
label="Notification channels"
height={height}>
<Section padding={4}>
@@ -175,47 +198,55 @@ function NotificationChannelsSheet({
);
}
-interface MultiStepSwitcherExampleProps {
+type Step = 'overview' | 'frequency' | 'channels' | null;
+
+interface MultiStepExampleProps {
height: NotificationSheetHeight;
hasScrim?: boolean;
}
-function MultiStepSwitcherExample({
- height,
- hasScrim = true,
-}: MultiStepSwitcherExampleProps) {
- const [activeSheet, setActiveSheet] = useState<string | null>(null);
+function MultiStepExample({height, hasScrim = true}: MultiStepExampleProps) {
+ // One state value names the open step. Moving on closes one sheet and
+ // opens the next in the same update, which replaces it in place.
+ const [step, setStep] = useState<Step>(null);
+ const stepProps = (id: Step) => ({
+ isOpen: step === id,
+ onOpenChange: (isOpen: boolean) => {
+ // Clear the step only if it is still the open one: a step that closes
+ // because the person moved on must not undo the move.
+ if (!isOpen) {
+ setStep(current => (current === id ? null : current));
+ }
+ },
+ hasScrim,
+ height,
+ });
return (
<>
<Button
label="Set up notifications"
- onClick={() => setActiveSheet('overview')}
+ onClick={() => setStep('overview')}
+ />
+ <NotificationOverviewSheet
+ {...stepProps('overview')}
+ onCancel={() => setStep(null)}
+ onContinue={() => setStep('frequency')}
+ />
+ <NotificationFrequencySheet
+ {...stepProps('frequency')}
+ onBack={() => setStep('overview')}
+ onContinue={() => setStep('channels')}
+ />
+ <NotificationChannelsSheet
+ {...stepProps('channels')}
+ onBack={() => setStep('frequency')}
+ onFinish={() => setStep(null)}
/>
- <BottomSheetSwitcher
- activeSheet={activeSheet}
- onActiveSheetChange={setActiveSheet}
- hasScrim={hasScrim}>
- <NotificationOverviewSheet
- height={height}
- onCancel={() => setActiveSheet(null)}
- onContinue={() => setActiveSheet('frequency')}
- />
- <NotificationFrequencySheet
- height={height}
- onBack={() => setActiveSheet('overview')}
- onContinue={() => setActiveSheet('channels')}
- />
- <NotificationChannelsSheet
- height={height}
- onBack={() => setActiveSheet('frequency')}
- onFinish={() => setActiveSheet(null)}
- />
- </BottomSheetSwitcher>
</>
);
}
export default function BottomSheetSwitcherShowcase() {
- return <MultiStepSwitcherExample height="hug" />;
+ return <MultiStepExample height="hug" />;
}
diff --git a/packages/cli/test/__golden__/no-icon-set/search-close.json b/packages/cli/test/__golden__/no-icon-set/search-close.json
index abf4a4facc..efdd97789c 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-close.json
+++ b/packages/cli/test/__golden__/no-icon-set/search-close.json
@@ -3,7 +3,7 @@
"type": "search",
"data": {
"query": "close",
- "matchCount": 44,
+ "matchCount": 45,
"results": [
{
"domain": "component",
@@ -16,6 +16,17 @@
"command": "astryx component AlertDialog",
"mentions": []
},
+ {
+ "domain": "component",
+ "name": "BottomSheet",
+ "package": "@astryxdesign/core",
+ "score": "<text>",
+ "reason": "<text>",
+ "description": "<text>",
+ "import": "@astryxdesign/core/BottomSheet",
+ "command": "astryx component BottomSheet",
+ "mentions": []
+ },
{
"domain": "component",
"name": "BottomSheetSwitcher",
@@ -230,17 +241,6 @@
"command": "astryx docs styling/styling-advanced compound-components",
"parent": "astryx docs styling/styling-advanced --index",
"mentions": []
- },
- {
- "domain": "component",
- "name": "ComplexSelector",
- "package": "@astryxdesign/core",
- "score": "<text>",
- "reason": "<text>",
- "description": "<text>",
- "import": "@astryxdesign/core/ComplexSelector",
- "command": "astryx component ComplexSelector",
- "mentions": []
}
]
},
diff --git a/packages/cli/test/__golden__/no-icon-set/search-close.txt b/packages/cli/test/__golden__/no-icon-set/search-close.txt
index 57026ef943..414978469e 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-close.txt
+++ b/packages/cli/test/__golden__/no-icon-set/search-close.txt
@@ -1,9 +1,14 @@
-Results for "close" (20 of 44)
+Results for "close" (20 of 45)
name: AlertDialog
domain: component
package: @astryxdesign/core
import: @astryxdesign/core/AlertDialog
command: pnpm exec astryx component AlertDialog
+name: BottomSheet
+domain: component
+package: @astryxdesign/core
+import: @astryxdesign/core/BottomSheet
+command: pnpm exec astryx component BottomSheet
name: BottomSheetSwitcher
domain: component
package: @astryxdesign/core
@@ -100,9 +105,4 @@ section: compound-components
domain: doc
package: @astryxdesign/cli
command: pnpm exec astryx docs styling/styling-advanced compound-components
-parent: pnpm exec astryx docs styling/styling-advanced --index
-name: ComplexSelector
-domain: component
-package: @astryxdesign/core
-import: @astryxdesign/core/ComplexSelector
-command: pnpm exec astryx component ComplexSelector
\ No newline at end of file
+parent: pnpm exec astryx docs styling/styling-advanced --index
\ No newline at end of file
diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon-set.json b/packages/cli/test/__golden__/no-icon-set/search-icon-set.json
index c425d22c35..c931a71b43 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-icon-set.json
+++ b/packages/cli/test/__golden__/no-icon-set/search-icon-set.json
@@ -3,7 +3,7 @@
"type": "search",
"data": {
"query": "icon set",
- "matchCount": 366,
+ "matchCount": 367,
"results": [
{
"domain": "doc",
diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt b/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt
index a3ab6e0709..6e222060b3 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt
+++ b/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt
@@ -1,4 +1,4 @@
-Results for "icon set" (20 of 366)
+Results for "icon set" (20 of 367)
name: authoring/building-blocks/templates/build-the-template/template-assets/template-icons
section: use-astryx-icon
domain: doc
diff --git a/packages/core/src/BottomSheet/BottomSheet.doc.mjs b/packages/core/src/BottomSheet/BottomSheet.doc.mjs
index 00b9e05937..1431c4f4ac 100644
--- a/packages/core/src/BottomSheet/BottomSheet.doc.mjs
+++ b/packages/core/src/BottomSheet/BottomSheet.doc.mjs
@@ -95,25 +95,25 @@ 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 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>.",
+ "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 the deprecated 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>. Sheets stack: a sheet opened while another is open sits on top of it, the covered sheet stays mounted and recedes, and one scrim covers the page. A sheet that closes as another opens in the same update is replaced by it, with the step-to-step handoff a multi-step flow needs.",
props: [
{
name: 'isOpen',
type: 'boolean',
description:
- 'Whether a standalone sheet is open. Fully controlled; pair with onOpenChange. Omit inside BottomSheetSwitcher.',
+ 'Whether a standalone sheet is open. Fully controlled; pair with onOpenChange. Omitted only inside the deprecated BottomSheetSwitcher, which drives its steps itself.',
},
{
name: 'onOpenChange',
type: '(isOpen: boolean) => void',
description:
- 'For a standalone sheet, called when it requests an open-state change. Automatic calls follow purpose: info dismisses on Escape, scrim click, or swipe; form dismisses on Escape only; required never dismisses implicitly. Omit inside BottomSheetSwitcher.',
+ 'For a standalone sheet, called when it requests an open-state change. Automatic calls follow purpose: info dismisses on Escape, scrim click, or swipe; form dismisses on Escape only; required never dismisses implicitly. Omitted only inside the deprecated BottomSheetSwitcher, which drives its steps itself.',
},
{
name: 'finalFocusRef',
type: 'RefObject<HTMLElement | null>',
description:
- 'Optional explicit focus-return target for a standalone sheet. Use when the opener can remount or the active element is not a reliable trigger, such as an adaptive presentation switch. Omit inside BottomSheetSwitcher.',
+ 'Optional explicit focus-return target for a standalone sheet. Use when the opener can remount or the active element is not a reliable trigger, such as an adaptive presentation switch. Always focused when the sheet closes on its own or last; when a modal sheet is still open beneath, focus returns into that sheet (to this element if it is inside it, else the revealed panel). Omitted only inside the deprecated BottomSheetSwitcher, which drives its steps itself.',
},
{
name: 'purpose',
@@ -126,7 +126,7 @@ export const docs = {
name: 'sheetId',
type: 'string',
description:
- 'Unique ID for this sheet inside BottomSheetSwitcher. The switcher opens it when activeSheet matches. Omit isOpen and onOpenChange when sheetId is used.',
+ 'Deprecated with BottomSheetSwitcher: give each step its own standalone sheet with isOpen instead. Still works as released: the unique ID of this sheet inside a BottomSheetSwitcher, which opens it when activeSheet matches; omit isOpen and onOpenChange when sheetId is used.',
},
{
name: 'label',
@@ -165,20 +165,25 @@ 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, 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.",
+ "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. A scrim sheet also takes part in stacking (see Stacking below). false presents the sheet in the top layer as a manual popover (below the Popover API support floor, show() in page stacking order as a reduced fallback) with no scrim, no focus trap and no scroll lock, leaving the page behind interactive and scrollable; a no-scrim sheet neither stacks nor is stacked on, but no-scrim steps replace each other with the same handoff. A no-scrim sheet shown while a modal (a scrim sheet or a Dialog) that does not contain it is open is inert under that modal and stays beneath it (show(), no page-level z-index) until that modal has gone, then enters the top layer; a modal mid-exit counts as gone, and rendered inside the modal the sheet enters the top layer at once. In a multi-step flow, set hasScrim the same on every step.",
default: 'true',
},
],
usage: {
anatomy,
description:
- 'A mobile touch surface for filters, actions, forms, and detail views that should rise from the bottom of the viewport; use BottomSheetSwitcher for multi-step flows.',
+ "A mobile touch surface for filters, actions, forms, and detail views that should rise from the bottom of the viewport. For a multi-step flow, give each step its own sheet and one state value that names the open step (see Replacing a sheet); open a second sheet over the first when a step should stay visible beneath it.\n\nStacking. Every sheet keeps its own isOpen. Open a sheet while another scrim sheet is open and it stacks on top: the sheet beneath stays mounted with its scroll position and inputs, recedes behind the new one (the nearest covered sheet shrinks to 0.96 and lifts 8px, deeper ones to 0.92 and 16px), and is blocked from pointer, keyboard, and assistive technology by the top sheet's modal dialog. The sheets can be siblings, live in separate components, sit inside another sheet's content, or sit inside a BottomSheetSwitcher step; a whole switcher is one level, and switching its step in place does not change its position. Nothing moves in the DOM: each sheet's dialog stays where it is written, and no wrapper component is needed.\n\nOrder is open order. The top sheet is the one presented most recently that is still open; a sheet that closes and reopens comes back on top. When several sheets open in one update (a deep link into a flow), there is no open order between them, so tree order decides: a sheet below the sheets rendered in its content, siblings in the order they are written. That order is right in the first painted frame.\n\nOne scrim. Only the bottom sheet's backdrop dims the page; the backdrops of the sheets above it are transparent, so a stack never darkens per level. The dim holds steady while sheets push and pop, and if the bottom sheet closes while sheets remain above it, the next sheet's backdrop takes over in the same frame.\n\nDismissal. Escape, a tap on the scrim, a downward swipe, and a platform close request (Android back, a close watcher) reach only the top sheet, through that sheet's own onOpenChange, and that sheet's purpose applies: required blocks all of them, form blocks the scrim and the swipe. Nothing closes a whole stack at once; set every sheet closed in one update when a flow is done and they leave together.\n\nClosing a covered sheet from code. Sheets rendered inside the closing sheet's content are part of it: they are presented only while it is open and leave with it. Their isOpen stays yours, as with a Dialog rendered in a closed Dialog: nothing is written to it, and a nested sheet that is still open when its host reopens is presented again, on top. Set it closed yourself when the flow is done. Sheets above the closing sheet that are not in its content stay open and keep their order; the closing sheet slides out from beneath them, and if it owned the scrim, the sheet above takes it over.\n\nReplacing a sheet. Close the top sheet and open another in the same update (one state value that names the open step does this) and the new sheet replaces it instead of stacking on it: the new sheet rises above the one it replaces; if the replaced sheet is taller it moves down to meet the new sheet's top edge at the same time; the replaced sheet fades only after both motions finish, and is inert and hidden from assistive technology from the start. The scrim holds steady throughout, with no dip; focus moves into the new sheet; and when the flow closes, focus returns to the element that opened its first sheet, whichever sheet closed last. This is the handoff the deprecated BottomSheetSwitcher ran between its steps; a multi-step flow needs no switcher: give each step its own BottomSheet and one state value. A replace happens only when exactly one sheet closes and one opens in the update, the closing sheet was the top sheet of its stack, and the move was made from inside it (the control last pressed, or with no recent press the focused element, was in the closing sheet, as a step's own Continue or Back button is); a covered sheet closing while a sheet opens, a close and an open in different updates, or a close and an open driven from a control outside the closing sheet (two unrelated owners acting at once) keep the ordinary push and pop motion and their own focus return. A replace over an open stack runs one level up and leaves the sheets beneath covered. Non-modal sheets (hasScrim={false}) replace each other the same way, with no scrim: they are hosted in the browser top layer as manual popovers, so the entering step orders above the retained one with no page-level z-index, and toasts raised before or while the sheet is open stay above it. Below the Popover API support floor (Tier 2 in the browser support guide) the sheet falls back to show() in page stacking order: usable, but with no promise over later page content. A non-modal sheet returns focus to its opener on close only while focus is still inside it; focus taken elsewhere on the live page stays there.\n\nFocus. Opening a sheet moves focus into it, wherever the engine's native dialog focusing steps land: the panel in Chromium, the first focusable control in Firefox (a data-autofocus field only when it comes first). A step entering as a replacement focuses a data-autofocus descendant first, so a flow that opens on a field keeps the keyboard on it. Closing the top sheet returns focus into the sheet it reveals: to the control that opened it when that control is still there, otherwise to the revealed sheet's panel. When the last sheet closes, the standalone rules apply: finalFocusRef, else the element that opened the sheet, with a focus ring only after keyboard input. When every sheet of a stack closes in one update, focus returns once, to the bottom sheet's finalFocusRef or opener, after the last dialog has closed.\n\nCaveats. A Dialog, AlertDialog, or Popover opened from a sheet paints above the sheet and does not make it recede; a sheet opened from inside that Dialog paints above the Dialog and stacks over the sheet beneath. Sheets with hasScrim={false} stay out of the stack entirely (they replace each other, but never stack, recede, or take the scrim). A sheet React hides (a suspended Suspense boundary, Activity mode=\"hidden\") leaves the stack and closes its dialog; when it is shown again it is presented again, on top. Only sheets rendered in the same document stack; a sheet inside an iframe is its own stack.",
bestPractices: [
{
guidance: true,
description:
'Use for mobile-first surfaces (filters, share sheets, quick actions) where the content should rise from the bottom edge.',
},
+ {
+ guidance: true,
+ description:
+ "For a drill-in, open the next sheet over the current one and keep each sheet's isOpen where its data lives; a detail sheet can sit inside the list sheet that opens it, right next to the row. Close every sheet in one update to close the whole flow.",
+ },
{
guidance: true,
description:
@@ -192,7 +197,12 @@ export const docs = {
{
guidance: false,
description:
- "Don't make the sheet content overly long. Consider breaking it into steps and using Bottom Sheet Switcher.",
+ "Don't make the sheet content overly long. Break it into steps, each its own sheet, with one state value naming the open step; moving on replaces one with the next.",
+ },
+ {
+ guidance: false,
+ description:
+ "Don't stack more than two or three sheets: deeper sheets share the second recede step and the user has to pop them one at a time. Replace steps instead (close one, open the next in one update) when they do not need to stay visible.",
},
],
},
@@ -265,20 +275,87 @@ export const docs = {
</BottomSheet>`,
},
{
- label: 'Multi-step flow (one sheet at a time)',
- code: `const [activeSheet, setActiveSheet] = useState(null);
+ label:
+ 'Multi-step flow (one sheet at a time, each step replaces the last)',
+ code: `// One value names the open step. Moving on closes one sheet and opens the
+// next in the same update: the next step rises above the current one, which
+// fades once it has arrived. A dismissed step closes the flow.
+const [step, setStep] = useState(null);
+const stepProps = own => ({
+ isOpen: step === own,
+ onOpenChange: isOpen => !isOpen && setStep(current => (current === own ? null : current)),
+});
+<>
+ <Button label="Start" onClick={() => setStep('details')} />
+ <BottomSheet {...stepProps('details')} label="Details">
+ <Button label="Continue" onClick={() => setStep('confirm')} />
+ </BottomSheet>
+ <BottomSheet {...stepProps('confirm')} label="Confirm">
+ <Button label="Back" onClick={() => setStep('details')} />
+ <Button label="Done" onClick={() => setStep(null)} />
+ </BottomSheet>
+</>`,
+ },
+ {
+ label: 'Stacked sheets (drill-in: list, order, edit)',
+ code: `const [isListOpen, setIsListOpen] = useState(false);
+const [orderId, setOrderId] = useState(null);
+const [isEditing, setIsEditing] = useState(false);
+const closeAll = () => {
+ setIsListOpen(false);
+ setOrderId(null);
+ setIsEditing(false);
+};
<>
- <Button label="Start" onClick={() => setActiveSheet('details')} />
- <BottomSheetSwitcher
- activeSheet={activeSheet}
- onActiveSheetChange={setActiveSheet}>
- <BottomSheet sheetId="details" label="Details">
- <Button label="Continue" onClick={() => setActiveSheet('confirm')} />
- </BottomSheet>
- <BottomSheet sheetId="confirm" label="Confirm">
- <Button label="Back" onClick={() => setActiveSheet('details')} />
- </BottomSheet>
- </BottomSheetSwitcher>
+ <Button label="Orders" onClick={() => setIsListOpen(true)} />
+ <BottomSheet isOpen={isListOpen} onOpenChange={setIsListOpen} label="Orders">
+ {orders.map(order => (
+ <Button key={order.id} label={order.title} onClick={() => setOrderId(order.id)} />
+ ))}
+ </BottomSheet>
+ {/* Opens over the list; the list recedes and stays mounted. */}
+ <BottomSheet
+ isOpen={orderId != null}
+ onOpenChange={open => !open && setOrderId(null)}
+ label="Order">
+ <Button label="Edit" onClick={() => setIsEditing(true)} />
+ <Button label="Close all" onClick={closeAll} />
+ </BottomSheet>
+ <BottomSheet isOpen={isEditing} onOpenChange={setIsEditing} label="Edit order">
+ <Button label="Save" onClick={() => setIsEditing(false)} />
+ </BottomSheet>
+</>`,
+ },
+ {
+ label: 'Detail sheet inside the list sheet that opens it',
+ code: `function PlaceRow({place}) {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <Button label={place.name} onClick={() => setIsOpen(true)} />
+ {/* Rendered in the list sheet's content: stacks above it, leaves with it, and comes back with it while still open. */}
+ <BottomSheet isOpen={isOpen} onOpenChange={setIsOpen} label={place.name}>
+ <PlaceDetail place={place} />
+ </BottomSheet>
+ </>
+ );
+}
+
+<BottomSheet isOpen={isListOpen} onOpenChange={setIsListOpen} label="Places">
+ {places.map(place => <PlaceRow key={place.id} place={place} />)}
+</BottomSheet>`,
+ },
+ {
+ label: 'Deep link into a stack (several sheets open in one update)',
+ code: `// From a URL: list, order and editor open together. With no open order
+// between them, tree order decides: the list is at the bottom, the editor on top.
+const [isListOpen, setIsListOpen] = useState(() => route.list);
+const [orderId, setOrderId] = useState(() => route.orderId);
+const [isEditing, setIsEditing] = useState(() => route.edit);
+<>
+ <BottomSheet isOpen={isListOpen} onOpenChange={setIsListOpen} label="Orders">…</BottomSheet>
+ <BottomSheet isOpen={orderId != null} onOpenChange={open => !open && setOrderId(null)} label="Order">…</BottomSheet>
+ <BottomSheet isOpen={isEditing} onOpenChange={setIsEditing} label="Edit order">…</BottomSheet>
</>`,
},
{
@@ -320,11 +397,11 @@ export const docs = {
/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */
export const docsDense = {
description:
- 'mobile touch sheet rising from the bottom edge (native <dialog>): grab handle, opt-in transform-based drag-to-resize snap points (snapPoints: viewport fraction, percent or px length), scrolling area resizes to the snapped visible height on release (a peek stop, a quarter of the sheet or less, keeps the full height and slides instead), Dialog-aligned dismissal purpose (info/form/required), purpose-gated swipe-to-dismiss, fully-expanded Tall visual-viewport mobile-keyboard handling, named height scale, Dialog-like container padding (padding prop, theme bottom-sheet padding, default --spacing-4), modal (default) or non-modal (hasScrim={false}) presentation',
+ 'mobile touch sheet rising from the bottom edge (native <dialog>): grab handle, opt-in transform-based drag-to-resize snap points (snapPoints: viewport fraction, percent or px length), scrolling area resizes to the snapped visible height on release (a peek stop, a quarter of the sheet or less, keeps the full height and slides instead), Dialog-aligned dismissal purpose (info/form/required), purpose-gated swipe-to-dismiss, fully-expanded Tall visual-viewport mobile-keyboard handling, named height scale, Dialog-like container padding (padding prop, theme bottom-sheet padding, default --spacing-4), modal (default) or non-modal (hasScrim={false}) presentation; modal sheets stack in open order (covered sheet stays mounted, recedes 0.96/−8px then 0.92/−16px, blocked; one scrim; same-update opens ordered by tree; Escape/scrim/swipe pop the top sheet only; a sheet inside a closing sheet leaves with it and returns with it while still open)',
usage: {
anatomy,
description:
- 'Mobile touch surface for filters, actions, forms, and detail views that should rise from the bottom of the viewport; use BottomSheetSwitcher for multi-step flows.',
+ "Mobile touch surface for filters, actions, forms, and detail views that should rise from the bottom of the viewport; for a multi-step flow give each step its own sheet and one state value naming the open step: a same-update close and open is a replace handoff (entering sheet above, retained sheet aligns then fades, one steady scrim, focus back to the flow's opener on close). Open a sheet over another to stack: each sheet keeps its own isOpen, the top sheet is the most recently opened one, the covered sheet recedes and is blocked, one scrim dims the page, and dismissal pops only the top sheet. Sheets rendered in a closing sheet's content leave with it (their isOpen stays yours; they return with the host while still open); siblings above it stay open.",
bestPractices: [
{
guidance: true,
@@ -344,7 +421,12 @@ export const docsDense = {
{
guidance: false,
description:
- "Don't make the sheet content overly long. Consider breaking it into steps and using Bottom Sheet Switcher.",
+ "Don't make the sheet content overly long. Break it into steps, each its own sheet, with one state value naming the open step; moving on replaces one with the next.",
+ },
+ {
+ guidance: false,
+ description:
+ "Don't stack more than two or three sheets; replace steps (close one, open the next in one update) when they need not stay visible.",
},
],
},
diff --git a/packages/core/src/BottomSheet/BottomSheet.spec.md b/packages/core/src/BottomSheet/BottomSheet.spec.md
index be949fa553..382c1a90c7 100644
--- a/packages/core/src/BottomSheet/BottomSheet.spec.md
+++ b/packages/core/src/BottomSheet/BottomSheet.spec.md
@@ -15,6 +15,9 @@ verified_by:
packages/core/src/BottomSheet/BottomSheet.test.tsx,
packages/core/src/BottomSheet/BottomSheetPanel.test.tsx,
packages/core/src/BottomSheet/BottomSheetKeyboard.test.tsx,
+ packages/core/src/BottomSheet/BottomSheetStacking.test.tsx,
+ packages/core/src/BottomSheet/BottomSheetReplace.test.tsx,
+ packages/core/src/Toast/ToastViewport.modalHost.test.tsx,
packages/core/src/BottomSheet/__tests__/BottomSheetNativeModal.a11y.browser.spec.ts,
packages/core/src/BottomSheet/__tests__/BottomSheetKeyboard.a11y.browser.spec.ts,
apps/storybook/stories/BottomSheet.stories.tsx,
@@ -142,23 +145,23 @@ remain documented in `BottomSheet.doc.mjs`.
## Behavioral and layout contract
-| ID | Invariant | Basis |
-| ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
-| FR1 | The current presented sheet contains one Sheet panel, one scrolling Content area, and one decorative Handle; a Scrim is present only in scrim-backed presentation. | Current source, docs, and tests |
-| FR2 | The Sheet panel carries `bottom-sheet`; Content area, Handle, and Scrim carry no BottomSheet public target. | Current source, docs, and tests |
-| FR3 | Content renders in one real observed content box. Effective overflow, containment, and keyboard access come from `useScrollableArea`; the named overflowing body delegates forward Tab entry to a safe first sequential native link/button. | `spec:AST-025`; tests |
-| FR4 | The Content area pads caller content by the sheet's container inset and publishes the applied inset to descendants as a container publisher. | `architecture:container-padding` |
-| FR5 | Modal sheets presented in one document form one stack ordered by open order: the sheet opened most recently is on top; sheets opening in one update are ordered by tree order (a sheet before the sheets rendered in its content, siblings in source order), and the first painted frame already shows that order. Only sheets of one document stack. Implementation gap: on current `main` two open modal sheets are unrelated native dialogs ordered by effect timing, and a deep link that opens a sheet and a sheet in its content in one update paints the inner sheet beneath its parent. | DEC-2 |
-| FR6 | A covered modal sheet stays mounted with its state, recedes behind the top sheet, and is blocked: the browser's modal rules block it, and when it contains no presented sheet it is also `inert` and `aria-hidden`. Exactly one backdrop is visible for a stack — the bottom open sheet's — and a change of scrim owner lands with no transition, so the page dim is constant through a push, a pop, and a handoff. Implementation gap: on current `main` every open modal sheet paints its own backdrop and nothing recedes. | DEC-2 |
-| FR7 | Escape, a scrim tap, a swipe, and a platform close request reach only the top sheet of a stack, through that sheet's own `onOpenChange` and `purpose`; a covered sheet, and a replaced sheet during its handoff, report themselves absent to the shared `family:overlay-dismissal` stack while that lasts, so the order among sheets is the sheet stack's and the shared stack stays one registry. Implementation gap: on current `main` a covered sheet reports itself present (its dialog is open) and the shared dismissal stack ranks tree depth first, so a covered sheet nested in another sheet's content receives Escape ahead of a later sheet opened outside it. | DEC-2; `family:overlay-dismissal/FR2`, `/FR3` |
-| FR8 | A sheet rendered in another sheet's content is presented only while its host is open: it leaves the top layer with its host and is presented again, on top, if its own `isOpen` is still true when the host reopens. Its `isOpen` is never written by the host. Implementation gap: on current `main` a nested sheet stays open in the top layer with no visible box when its host closes from code. | DEC-2 |
-| FR9 | Closing the top sheet returns focus into the sheet it reveals: to the element that opened the closing sheet when that element is inside the revealed sheet, else to the revealed sheet's panel; an explicit `finalFocusRef` outside the revealed sheet yields to its panel in the same way. The last sheet of a stack keeps the standalone rule: `finalFocusRef`, else the opener. Closing every sheet of a stack in one update returns focus once, to the bottom sheet's `finalFocusRef` or opener, after the last dialog has closed. A close driven by the stack itself never moves focus. Implementation gap: on current `main` closing several sheets in one update leaves focus on `body`. | DEC-2 |
-| FR10 | When exactly one standalone sheet closes and exactly one opens in the same update, both of one document and one modality, the closing sheet was the top sheet of its group — its document's modal stack, or, for non-modal sheets, the one open non-modal sheet (FR11) — with the opening sheet set aside, neither dialog contains the other, and the actor — the control last pressed, or, with no fresh press, the element focused when the update began — is inside the closing sheet's dialog or is none (no fresh press, and nothing or only the document body focused, as when code changes the step while focus has fallen to the body), the opening sheet replaces the closing one: it enters above the retained sheet; a retained sheet whose top edge is above the entering sheet's resting top edge moves down to meet it at the same time; the retained sheet fades only after both motions complete; it is `inert` and `aria-hidden` from the first frame and takes no dismissal request; the scrim owner is FR6's, the bottom open sheet: when the retained sheet is that owner (a replace at the bottom of the stack) its backdrop keeps the one visible scrim until it leaves and the entering sheet's backdrop takes over with no transition, and when the replace runs above a covered sheet that sheet stays the owner and the retained sheet's backdrop is transparent throughout, so it only fades; focus moves into the entering sheet; and the entering sheet adopts the retained sheet's focus-return target, so closing the flow returns focus to its first opener. A close and an open that fail any condition — different updates, a covered sheet closing, several sheets changing, a sheet closing with its host, or a control outside the closing sheet acting — keep the ordinary push and pop motion and their own focus return. Implementation gap: on current `main` a same-update close and open is a pop beneath a push. | DEC-2 |
-| FR11 | A non-modal sheet (`hasScrim={false}`) is presented in the browser's top layer as a manual popover with no backdrop, no scroll lock, and no focus trap, and carries no page-level `z-index`; where the Popover API is absent it is presented with `show()` in page stacking order as a reduced fallback. A non-modal sheet shown while a modal dialog that does not contain it is open (a modal sheet, a `Dialog`) is inert under that modal, so it does not enter the top layer yet — there it would paint above the modal while a press on it lands on the modal — and is presented with `show()` beneath the modal, with no page-level `z-index`; a modal on its way out (inert, hidden) counts as gone. Once no such modal is open the sheet enters the top layer as a manual popover, a top-layer toast viewport re-entering above it (FR14), so page content never paints over an interactive non-modal sheet (`spec:AST-027` FR8). A non-modal sheet rendered inside the modal's content is not inert and enters the top layer at once. Non-modal sheets never stack, recede, or own a scrim, and never pair with a modal sheet; because they never stack, the one open non-modal sheet of a document is always the top of its own group, so two non-modal sheets replace each other under FR10 — the closing one being that top — with no backdrop. On a lone open, focus goes where the engine's own `show()` focusing steps would put it when they enter the sheet, and no `data-autofocus` preference is added over them (the released behavior, kept, and the same rule as a modal sheet's `showModal()`): in Chromium the panel, whose focusing steps take the first focusable area including a `tabindex="-1"` container; in Firefox the first focusable control in the content, which is the `data-autofocus` field only when it comes first; in WebKit wherever its `show()` lands. Where the manual-popover host's own focusing steps would land elsewhere than that engine's `show()` (Chromium's `showPopover()` lands on the first control), focus arrives where `show()` would have put it without passing through any control — no control receives a focus or a blur on the way, so a field validating on blur does not fire on open; when the sheet is replacing the sheet the person was in, it takes focus, and a `data-autofocus` descendant then wins (AR4). On close an explicit `finalFocusRef` is focused wherever focus is, and otherwise the element focused when the sheet was shown is focused again only while focus is still inside the sheet — the native dialog's own return rule, kept. Implementation gap: on current `main` a non-modal sheet is presented with `show()` and a page-level `z-index: 1000`; its focus on open (the engine's `show()` focusing steps, which land on the panel in Chromium and on the first control in Firefox) and its focus return (`finalFocusRef` after every exit, the native return to the element focused at `show()` while focus is inside) already match this row. | DEC-2; `spec:AST-027/FR8`; `architecture:layer-runtime` |
-| FR12 | A modal `BottomSheetSwitcher` flow is one level of the stack: the dialog of its active step is the flow's level, keeps the flow's rank across the flow's own handoffs, recedes and is blocked when covered, yields its backdrop to the stack's scrim owner, stands down from dismissal while covered, and returns focus by FR9. A standalone sheet rendered in a step's content stacks above the flow and leaves with the step (FR8). A switcher step is never paired under FR10. Implementation gap: on current `main` a switcher flow and a standalone sheet open together are unrelated dialogs. | DEC-2; `component:BottomSheetSwitcher/DEC-1` |
-| FR13 | Every open scrim sheet supplies its dialog as a passive global outlet for app-global surfaces such as toasts (`spec:AST-003` FR18: each active native modal, a covered sheet included), and a modal `BottomSheetSwitcher` flow supplies its active step's dialog — the one its host dialog resolves to, following each handoff; the retained step's dialog, inert and fading, never hosts. Among sheets, the latest outlet — the one a global host renders into — follows the stack's order, not the order the sheets were supplied in: the top sheet is the latest, so a toast lands in the top sheet and never in a covered, inert one, and when the top sheet closes the sheet it reveals is the latest again and takes the host back. A sheet is raised only among sheet outlets: an outlet supplied later by another modal (a `Dialog` opened from a sheet) stays above every sheet until it closes. A sheet, or a flow, stops supplying as soon as it starts closing, and a native `close` event that fires while its dialog is open again (the stack re-showing it, or a reopen during its exit) does not take its outlet away. Implementation gap: on current `main` the latest outlet is the one supplied last, so a sheet re-shown or revealed by its stack is not it, and a switcher flow supplies no outlet, so a toast raised from a step lands behind the flow. | DEC-2; `spec:AST-003/FR16`, `/FR18`; `architecture:layer-runtime`; `component:BottomSheetSwitcher/FR10` |
-| FR14 | When a non-modal sheet enters the top layer, a top-layer toast viewport shown before it leaves and re-enters the top layer in place, keeping focus inside it, so toasts paint above the sheet. Implementation gap: on current `main` a non-modal sheet is not a top-layer surface (`show()` under a page-level `z-index`, beneath the popover viewport), so the toast viewport's re-entry above a non-modal sheet has nothing to answer. | DEC-2; `architecture:layer-runtime` |
-| FR15 | Under `prefers-reduced-motion: reduce` the recede, the return from receded, a push's entrance, a pop's exit and the replace handoff — and a `BottomSheetSwitcher` step's, which shares the sheet panel's motion — follow `design:reduced-motion`, keyed on its queries (`prefers-reduced-motion: reduce`, with `pointer: coarse` for the cross-fade): no transform motion runs (DR1) — a covered sheet appears in its receded place and size the frame the push lands and returns the same way, the entering sheet appears in its final place, the retained sheet does not align down; on a coarse pointer the entering sheet fades in and the leaving or retained sheet fades out where it is, opacity only, in 200 ms or less (DR2); a dismissal the release of a touch drag started (a swipe past the dismiss line) fades out in place the same way on every pointer (DR2's drag-release clause); on any other pointer every other change is immediate (DR3); the handoff's steps run in the released order, so the retained sheet is hidden and its dialog closed once its fade ends. The constant page dim through a push, a pop and a handoff (FR6) holds as it does with motion. Implementation gap: on current `main` there is no recede or handoff between standalone sheets, and the shipped sheet's own entrance and exit under reduced motion run their transforms shortened on every pointer and do not cross-fade on a coarse pointer. | DEC-2; `design:reduced-motion` |
+| ID | Invariant | Basis |
+| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
+| FR1 | The current presented sheet contains one Sheet panel, one scrolling Content area, and one decorative Handle; a Scrim is present only in scrim-backed presentation. | Current source, docs, and tests |
+| FR2 | The Sheet panel carries `bottom-sheet`; Content area, Handle, and Scrim carry no BottomSheet public target. | Current source, docs, and tests |
+| FR3 | Content renders in one real observed content box. Effective overflow, containment, and keyboard access come from `useScrollableArea`; the named overflowing body delegates forward Tab entry to a safe first sequential native link/button. | `spec:AST-025`; tests |
+| FR4 | The Content area pads caller content by the sheet's container inset and publishes the applied inset to descendants as a container publisher. | `architecture:container-padding` |
+| FR5 | Modal sheets presented in one document form one stack ordered by open order: the sheet opened most recently is on top; sheets opening in one update are ordered by tree order (a sheet before the sheets rendered in its content, siblings in source order), and the first painted frame already shows that order. Only sheets of one document stack. | DEC-2 |
+| FR6 | A covered modal sheet stays mounted with its state, recedes behind the top sheet, and is blocked: the browser's modal rules block it, and when it contains no presented sheet it is also `inert` and `aria-hidden`. Exactly one backdrop is visible for a stack — the bottom open sheet's — and a change of scrim owner lands with no transition, so the page dim is constant through a push, a pop, and a handoff. | DEC-2 |
+| FR7 | Escape, a scrim tap, a swipe, and a platform close request reach only the top sheet of a stack, through that sheet's own `onOpenChange` and `purpose`; a covered sheet, and a replaced sheet during its handoff, report themselves absent to the shared `family:overlay-dismissal` stack while that lasts, so the order among sheets is the sheet stack's and the shared stack stays one registry. | DEC-2; `family:overlay-dismissal/FR2`, `/FR3` |
+| FR8 | A sheet rendered in another sheet's content is presented only while its host is open: it leaves the top layer with its host and is presented again, on top, if its own `isOpen` is still true when the host reopens. Its `isOpen` is never written by the host. | DEC-2 |
+| FR9 | Closing the top sheet returns focus into the sheet it reveals: to the element that opened the closing sheet when that element is inside the revealed sheet, else to the revealed sheet's panel; an explicit `finalFocusRef` outside the revealed sheet yields to its panel in the same way. The last sheet of a stack keeps the standalone rule: `finalFocusRef`, else the opener. Closing every sheet of a stack in one update returns focus once, to the bottom sheet's `finalFocusRef` or opener, after the last dialog has closed. A close driven by the stack itself never moves focus. | DEC-2 |
+| FR10 | When exactly one standalone sheet closes and exactly one opens in the same update, both of one document and one modality, the closing sheet was the top sheet of its group — its document's modal stack, or, for non-modal sheets, the one open non-modal sheet (FR11) — with the opening sheet set aside, neither dialog contains the other, and the actor — the control last pressed, or, with no fresh press, the element focused when the update began — is inside the closing sheet's dialog or is none (no fresh press, and nothing or only the document body focused, as when code changes the step while focus has fallen to the body), the opening sheet replaces the closing one: it enters above the retained sheet; a retained sheet whose top edge is above the entering sheet's resting top edge moves down to meet it at the same time; the retained sheet fades only after both motions complete; it is `inert` and `aria-hidden` from the first frame and takes no dismissal request; the scrim owner is FR6's, the bottom open sheet: when the retained sheet is that owner (a replace at the bottom of the stack) its backdrop keeps the one visible scrim until it leaves and the entering sheet's backdrop takes over with no transition, and when the replace runs above a covered sheet that sheet stays the owner and the retained sheet's backdrop is transparent throughout, so it only fades; focus moves into the entering sheet; and the entering sheet adopts the retained sheet's focus-return target, so closing the flow returns focus to its first opener. A close and an open that fail any condition — different updates, a covered sheet closing, several sheets changing, a sheet closing with its host, or a control outside the closing sheet acting — keep the ordinary push and pop motion and their own focus return. | DEC-2 |
+| FR11 | A non-modal sheet (`hasScrim={false}`) is presented in the browser's top layer as a manual popover with no backdrop, no scroll lock, and no focus trap, and carries no page-level `z-index`; where the Popover API is absent it is presented with `show()` in page stacking order as a reduced fallback. A non-modal sheet shown while a modal dialog that does not contain it is open (a modal sheet, a `Dialog`) is inert under that modal, so it does not enter the top layer yet — there it would paint above the modal while a press on it lands on the modal — and is presented with `show()` beneath the modal, with no page-level `z-index`; a modal on its way out (inert, hidden) counts as gone. Once no such modal is open the sheet enters the top layer as a manual popover, a top-layer toast viewport re-entering above it (FR14), so page content never paints over an interactive non-modal sheet (`spec:AST-027` FR8). A non-modal sheet rendered inside the modal's content is not inert and enters the top layer at once. Non-modal sheets never stack, recede, or own a scrim, and never pair with a modal sheet; because they never stack, the one open non-modal sheet of a document is always the top of its own group, so two non-modal sheets replace each other under FR10 — the closing one being that top — with no backdrop. On a lone open, focus goes where the engine's own `show()` focusing steps would put it when they enter the sheet, and no `data-autofocus` preference is added over them (the released behavior, kept, and the same rule as a modal sheet's `showModal()`): in Chromium the panel, whose focusing steps take the first focusable area including a `tabindex="-1"` container; in Firefox the first focusable control in the content, which is the `data-autofocus` field only when it comes first; in WebKit wherever its `show()` lands. Where the manual-popover host's own focusing steps would land elsewhere than that engine's `show()` (Chromium's `showPopover()` lands on the first control), focus arrives where `show()` would have put it without passing through any control — no control receives a focus or a blur on the way, so a field validating on blur does not fire on open; when the sheet is replacing the sheet the person was in, it takes focus, and a `data-autofocus` descendant then wins (AR4). On close an explicit `finalFocusRef` is focused wherever focus is, and otherwise the element focused when the sheet was shown is focused again only while focus is still inside the sheet — the native dialog's own return rule, kept. | DEC-2; `spec:AST-027/FR8`; `architecture:layer-runtime` |
+| FR12 | A modal `BottomSheetSwitcher` flow is one level of the stack: the dialog of its active step is the flow's level, keeps the flow's rank across the flow's own handoffs, recedes and is blocked when covered, yields its backdrop to the stack's scrim owner, stands down from dismissal while covered, and returns focus by FR9. A standalone sheet rendered in a step's content stacks above the flow and leaves with the step (FR8). A switcher step is never paired under FR10. | DEC-2; `component:BottomSheetSwitcher/DEC-1` |
+| FR13 | Every open scrim sheet supplies its dialog as a passive global outlet for app-global surfaces such as toasts (`spec:AST-003` FR18: each active native modal, a covered sheet included), and a modal `BottomSheetSwitcher` flow supplies its active step's dialog — the one its host dialog resolves to, following each handoff; the retained step's dialog, inert and fading, never hosts. Among sheets, the latest outlet — the one a global host renders into — follows the stack's order, not the order the sheets were supplied in: the top sheet is the latest, so a toast lands in the top sheet and never in a covered, inert one, and when the top sheet closes the sheet it reveals is the latest again and takes the host back. A sheet is raised only among sheet outlets: an outlet supplied later by another modal (a `Dialog` opened from a sheet) stays above every sheet until it closes. A sheet, or a flow, stops supplying as soon as it starts closing, and a native `close` event that fires while its dialog is open again (the stack re-showing it, or a reopen during its exit) does not take its outlet away. | DEC-2; `spec:AST-003/FR16`, `/FR18`; `architecture:layer-runtime`; `component:BottomSheetSwitcher/FR10` |
+| FR14 | When a non-modal sheet enters the top layer, a top-layer toast viewport shown before it leaves and re-enters the top layer in place, keeping focus inside it, so toasts paint above the sheet. | DEC-2; `architecture:layer-runtime` |
+| FR15 | Under `prefers-reduced-motion: reduce` the recede, the return from receded, a push's entrance, a pop's exit and the replace handoff — and a `BottomSheetSwitcher` step's, which shares the sheet panel's motion — follow `design:reduced-motion`, keyed on its queries (`prefers-reduced-motion: reduce`, with `pointer: coarse` for the cross-fade): no transform motion runs (DR1) — a covered sheet appears in its receded place and size the frame the push lands and returns the same way, the entering sheet appears in its final place, the retained sheet does not align down; on a coarse pointer the entering sheet fades in and the leaving or retained sheet fades out where it is, opacity only, in 200 ms or less (DR2); a dismissal the release of a touch drag started (a swipe past the dismiss line) fades out in place the same way on every pointer (DR2's drag-release clause); on any other pointer every other change is immediate (DR3); the handoff's steps run in the released order, so the retained sheet is hidden and its dialog closed once its fade ends. The constant page dim through a push, a pop and a handoff (FR6) holds as it does with motion. | DEC-2; `design:reduced-motion` |
### Allowed variation
@@ -214,7 +217,7 @@ remain documented in `BottomSheet.doc.mjs`.
has these elements, each with one job:
- the dialog carries the sheet's dialog role, modality and the top layer
when the sheet is modal, and holds the panel at the block end with its
- own grid;
+ own grid; a covered sheet's recede (FR6) is this element's transform;
- the panel paints the `bottom-sheet` target;
- the grabber bar is the drag handle, and its `::before` draws the handle;
- the body is the scroll area;
@@ -232,9 +235,13 @@ remain documented in `BottomSheet.doc.mjs`.
- Elements a presenting component adds beyond this frame are its own to
justify.
- **PR1 — One stack per document.** Sheets rendered by every copy of the
- package loaded on a page, and by every React root on it, form one stack per
- document: their order is their open order, whichever copy or root rendered
- them. No public API reaches the ordering.
+ package loaded on a page that shares the stack protocol, and by every React
+ root on it, form one stack per document: their order is their open order,
+ whichever copy or root rendered them. The protocol version is part of the
+ document-global key the copies meet under; a copy on another protocol
+ version keeps a stack of its own, ordering only the sheets it renders, so
+ two copies of different versions on one page are two independent stacks
+ and neither reads the other's state. No public API reaches the ordering.
- **PR2 — No per-level backdrop cost.** A stack paints one visible backdrop
whatever its depth — the scrim owner's, the bottom open sheet's under FR6 —
and every other backdrop in the stack, a covered sheet's or a sheet's above
@@ -257,8 +264,7 @@ remain documented in `BottomSheet.doc.mjs`.
exposed dialog. A covered sheet that contains the top sheet is left alone,
because the top sheet's modality already excludes it (FR6, FR10). Each
sheet keeps its own role and accessible name; a non-modal sheet's manual
- popover host changes neither. Implementation gap: on current `main` a
- covered sheet is exposed as an open dialog.
+ popover host changes neither.
- **AR4 — Focus follows the person through a stack.** Opening the top sheet
moves focus into it; a replace moves focus into the entering step whatever
the native host did; a pop returns focus into the revealed sheet; the last
@@ -272,9 +278,7 @@ remain documented in `BottomSheet.doc.mjs`.
exception is a sheet entering as a replacement (FR10), whose focus is
placed after the native focusing steps because they may have left it in the
replaced sheet, or on the entering panel: there a `data-autofocus` descendant is focused first, else
- the panel, so a step flow that opens on a field keeps the keyboard on it. Implementation gap: on current `main` a pop returns focus to the
- element the closing dialog recorded, which may be inside a sheet that is
- itself closing.
+ the panel, so a step flow that opens on a field keeps the keyboard on it.
- **AR5 — What assistive technology perceives of a push, a pop, and a
replace.** The stack adds no announcement of its own to a push or a pop:
@@ -288,9 +292,7 @@ remain documented in `BottomSheet.doc.mjs`.
field or else its panel (AR4), so the entering dialog's accessible name is
announced as focus enters it, and the retained step is hidden from the
first frame of the handoff (AR3); the stack announces nothing of the
- retained step's leaving. Implementation gap: on current `main` a covered sheet stays
- exposed and a flow's steps are not standalone sheets, so a push is
- perceived as a second open dialog.
+ retained step's leaving.
## Design relationships
@@ -365,18 +367,18 @@ a decision that they must remain unthemeable.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------- |
-| FR1 | `BottomSheet.test.tsx` render, content, Handle, and scrim behavior suites | Modal, non-modal, and switcher presentations | Removing a documented part fails existing content, structure, or dismissal assertions. | `audit:BottomSheet/anatomy` |
-| FR2 | Panel target assertion, source inspection, and theming target inventories | Sheet panel, Content area, Handle, and Scrim | Removing the panel target or documenting an unshipped child target fails evidence or inventory. | `audit:BottomSheet/theming` |
-| FR3, AR1–AR2 | `BottomSheetKeyboard.test.tsx`; `BottomSheetKeyboard.a11y.browser.spec.ts`; open Storybook stories | fitting/overflow, plain text, usable/unusable/dynamic descendants, focus | Missing/duplicate keyboard access, stale ownership, focus movement, or broken content-box layout fails. | `audit:BottomSheet/accessibility` |
-| Layout evidence | `BottomSheetPanel.test.tsx` | Floating Handle and scrolling Content area | Reordering or merging the stable parts fails existing panel structure and style assertions. | `audit:BottomSheet/anatomy` |
-| FR4 | `BottomSheetPanel.test.tsx` container padding tests; `derivedVarRegistry.test.ts` | default, `padding` prop, theme `padding`, lone padded Section child | The published inset differs from the applied padding, or a lone padded Section changes geometry. | `audit:BottomSheet/anatomy` |
-| Element jobs | Open-sheet element count test against the named job list | modal and non-modal sheet, scrim and no scrim | An element in the open sheet's frame with no named job, or a named job with no element | |
-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target inventory | Missing, extra, prefixed, stale, or multiply assigned mappings fail repository validation. | `audit:BottomSheet/theming` |
-| FR5–FR9, FR12–FR15, AR3–AR5 | Stacking unit suite (jsdom, native dialog methods stubbed); real-browser per-frame sampling of transforms, backdrop opacity, hit-testing, and focus on the stacking stories in Chromium, WebKit, and real Safari; a real-browser accessibility-tree check (`spec:AST-020`, `spec:AST-009` FR3) that a lone sheet, a stack of two and three, and a replace handoff expose exactly one `dialog`, the top or entering sheet, with its name, while covered and replaced sheets are hidden, that the stack renders no live region of its own, and that focus enters the entering step's `data-autofocus` field or panel on a replace; a real-browser run with reduced motion emulated on a fine and on a coarse pointer, sampling per frame that no transform animates, that the covered sheet is in its receded place from the frame the push lands, that on a coarse pointer the entering and leaving sheets change opacity only within 200 ms and on a fine pointer at once, that a swipe dismissal fades out in place on a fine pointer, that the dim is constant and that the handoff still completes | siblings, separate components, nested in content, inside a switcher step, a switcher flow as a level, out-of-tree-order opens, same-update deep link, depth 1–3, Escape/scrim/swipe/platform close, covered close, close of the whole stack, focus after each pop, two package copies, a second document | A covered or replaced sheet is exposed in the accessibility tree, the top sheet is exposed without role `dialog` or its name, a covered sheet stays interactive, a second backdrop paints, the dim dips or doubles on a handoff, a dismissal reaches a covered sheet, a nested sheet's state is written or it stays open invisibly, or focus lands on `body` after a pop or a close of the whole stack. Implementation gap: the suite does not exist on current `main`. | `audit:BottomSheet/behavior` |
-| FR10–FR11 | Replace unit suite (jsdom); real-browser parity of the standalone flow against the switcher's handoff — per-frame transforms, opacity, page dim, focus, settled pixels — in Chromium and WebKit, and real Safari for hosting, dim, toast order, and focus; a per-engine lone-open focus probe in Chromium, Firefox and WebKit comparing the sheet's focus on open against that engine's bare `show()` and `showModal()` on the same markup, and recording the focus and blur events the sheet's first control receives on open (none) | push, pop, different updates, covered close, nested, a replace above a covered sheet (the bottom sheet keeps the scrim, the retained sheet only fades), switcher flow, a lone sheet; handoff in both completion orders; reversal mid-handoff in both directions and both tree orders; unrelated owners from a page control; non-modal replace, reversal, `show()` fallback; a non-modal sheet opened from a modal sheet or a `Dialog` and rendered outside it (while the modal is open, and once it has closed, with positioned page content), one opened in the update that closes a modal sheet, and one rendered inside the modal's content | A replace is recognized for unrelated owners or missed for a real step flow, the retained sheet is exposed or dismissable, the scrim dips, the replaced step stays on screen after a reversal, focus does not enter the step or return to the flow's opener, a non-modal sheet carries a page-level `z-index`, a toast paints under a non-modal sheet, or a lone sheet's focus on open, modal or not, differs from where that engine's released native host (`showModal()`, or `show()` for a non-modal sheet) puts it — in Chromium the panel, with a ring only after keyboard input and a `data-autofocus` field left unfocused; in Firefox the first focusable control — a control inside the sheet receives a focus or a blur on a lone open that `show()` would not have given it, or a replacement entry fails to focus its `data-autofocus` field. A non-modal sheet rendered outside an open modal paints above it while a press lands on the modal, or stays beneath page content once that modal has gone. Implementation gap: the suite does not exist on current `main`. | `audit:BottomSheet/behavior` |
-| FR13–FR14 | Toast viewport hosting suite (jsdom, native dialog methods and popover state stubbed); real-browser hit-testing of a toast raised from the top sheet, from a Dialog opened from a sheet after an inner sheet closed, from a sheet re-shown by a reversal, and over a non-modal sheet | a lone sheet; a stack of two; sheet → Dialog → sheet → close the inner sheet; a reversal and a reopen during exit, with the stale native `close`; a non-modal sheet shown after the viewport; a modal switcher flow alone, through a handoff and its close; a flow stacked over a standalone sheet and a standalone sheet over a flow; a non-modal flow | A toast renders in a covered or inert sheet, a Dialog opened from a sheet loses the toast to the sheet beneath it, a re-shown sheet loses its outlet to the stale `close`, a toast raised from a switcher step lands behind the flow or in its retained step, or a toast paints beneath a non-modal sheet. Implementation gap: on current `main` the suite covers the lone sheet and Dialogs only. | `audit:BottomSheet/behavior` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
+| FR1 | `BottomSheet.test.tsx` render, content, Handle, and scrim behavior suites | Modal, non-modal, and switcher presentations | Removing a documented part fails existing content, structure, or dismissal assertions. | `audit:BottomSheet/anatomy` |
+| FR2 | Panel target assertion, source inspection, and theming target inventories | Sheet panel, Content area, Handle, and Scrim | Removing the panel target or documenting an unshipped child target fails evidence or inventory. | `audit:BottomSheet/theming` |
+| FR3, AR1–AR2 | `BottomSheetKeyboard.test.tsx`; `BottomSheetKeyboard.a11y.browser.spec.ts`; open Storybook stories | fitting/overflow, plain text, usable/unusable/dynamic descendants, focus | Missing/duplicate keyboard access, stale ownership, focus movement, or broken content-box layout fails. | `audit:BottomSheet/accessibility` |
+| Layout evidence | `BottomSheetPanel.test.tsx` | Floating Handle and scrolling Content area | Reordering or merging the stable parts fails existing panel structure and style assertions. | `audit:BottomSheet/anatomy` |
+| FR4 | `BottomSheetPanel.test.tsx` container padding tests; `derivedVarRegistry.test.ts` | default, `padding` prop, theme `padding`, lone padded Section child | The published inset differs from the applied padding, or a lone padded Section changes geometry. | `audit:BottomSheet/anatomy` |
+| Element jobs | Open-sheet element count test against the named job list | modal and non-modal sheet, scrim and no scrim | An element in the open sheet's frame with no named job, or a named job with no element | |
+| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target inventory | Missing, extra, prefixed, stale, or multiply assigned mappings fail repository validation. | `audit:BottomSheet/theming` |
+| FR5–FR9, FR12–FR15, AR3–AR5 | Stacking unit suite (jsdom, native dialog methods stubbed); real-browser per-frame sampling of transforms, backdrop opacity, hit-testing, and focus on the stacking stories in Chromium, WebKit, and real Safari; a real-browser accessibility-tree check (`spec:AST-020`, `spec:AST-009` FR3) that a lone sheet, a stack of two and three, and a replace handoff expose exactly one `dialog`, the top or entering sheet, with its name, while covered and replaced sheets are hidden, that the stack renders no live region of its own, and that focus enters the entering step's `data-autofocus` field or panel on a replace; a real-browser run with reduced motion emulated on a fine and on a coarse pointer, sampling per frame that no transform animates, that the covered sheet is in its receded place from the frame the push lands, that on a coarse pointer the entering and leaving sheets change opacity only within 200 ms and on a fine pointer at once, that a swipe dismissal fades out in place on a fine pointer, that the dim is constant and that the handoff still completes | siblings, separate components, nested in content, inside a switcher step, a switcher flow as a level, out-of-tree-order opens, same-update deep link, depth 1–3, Escape/scrim/swipe/platform close, covered close, close of the whole stack, focus after each pop, two package copies, a second document | A covered or replaced sheet is exposed in the accessibility tree, the top sheet is exposed without role `dialog` or its name, a covered sheet stays interactive, a second backdrop paints, the dim dips or doubles on a handoff, a dismissal reaches a covered sheet, a nested sheet's state is written or it stays open invisibly, or focus lands on `body` after a pop or a close of the whole stack. | `audit:BottomSheet/behavior` |
+| FR10–FR11 | Replace unit suite (jsdom); real-browser parity of the standalone flow against the switcher's handoff — per-frame transforms, opacity, page dim, focus, settled pixels — in Chromium and WebKit, and real Safari for hosting, dim, toast order, and focus; a per-engine lone-open focus probe in Chromium, Firefox and WebKit comparing the sheet's focus on open against that engine's bare `show()` and `showModal()` on the same markup, and recording the focus and blur events the sheet's first control receives on open (none) | push, pop, different updates, covered close, nested, a replace above a covered sheet (the bottom sheet keeps the scrim, the retained sheet only fades), switcher flow, a lone sheet; handoff in both completion orders; reversal mid-handoff in both directions and both tree orders; unrelated owners from a page control; non-modal replace, reversal, `show()` fallback; a non-modal sheet opened from a modal sheet or a `Dialog` and rendered outside it (while the modal is open, and once it has closed, with positioned page content), one opened in the update that closes a modal sheet, and one rendered inside the modal's content | A replace is recognized for unrelated owners or missed for a real step flow, the retained sheet is exposed or dismissable, the scrim dips, the replaced step stays on screen after a reversal, focus does not enter the step or return to the flow's opener, a non-modal sheet carries a page-level `z-index`, a toast paints under a non-modal sheet, or a lone sheet's focus on open, modal or not, differs from where that engine's released native host (`showModal()`, or `show()` for a non-modal sheet) puts it — in Chromium the panel, with a ring only after keyboard input and a `data-autofocus` field left unfocused; in Firefox the first focusable control — a control inside the sheet receives a focus or a blur on a lone open that `show()` would not have given it, or a replacement entry fails to focus its `data-autofocus` field. A non-modal sheet rendered outside an open modal paints above it while a press lands on the modal, or stays beneath page content once that modal has gone. | `audit:BottomSheet/behavior` |
+| FR13–FR14 | Toast viewport hosting suite (jsdom, native dialog methods and popover state stubbed); real-browser hit-testing of a toast raised from the top sheet, from a Dialog opened from a sheet after an inner sheet closed, from a sheet re-shown by a reversal, and over a non-modal sheet | a lone sheet; a stack of two; sheet → Dialog → sheet → close the inner sheet; a reversal and a reopen during exit, with the stale native `close`; a non-modal sheet shown after the viewport; a modal switcher flow alone, through a handoff and its close; a flow stacked over a standalone sheet and a standalone sheet over a flow; a non-modal flow | A toast renders in a covered or inert sheet, a Dialog opened from a sheet loses the toast to the sheet beneath it, a re-shown sheet loses its outlet to the stale `close`, a toast raised from a switcher step lands behind the flow or in its retained step, or a toast paints beneath a non-modal sheet. | `audit:BottomSheet/behavior` |
Existing tests directly assert the Sheet panel target, Content area placement,
Handle structure, and scrim behavior. Source and public target metadata confirm
@@ -421,9 +423,11 @@ flow's close — so a multi-step flow is one standalone sheet per step and one
state value (FR10). Non-modal sheets are hosted in the top layer as manual
popovers, never stack, and replace each other the same way (FR11). A
`BottomSheetSwitcher` flow is one level (FR12). The ordering is one per
-document across package copies and React roots (PR1), because the coordinated
-thing — a document's top layer — is wider than any React tree. Nothing here is
-public API; a lone modal sheet never notices the stack.
+document across React roots and across the package copies that share the
+stack protocol (PR1; a copy on another protocol version keeps its own stack),
+because the coordinated thing — a document's top layer — is wider than any
+React tree. Nothing here is public API; a lone modal sheet never notices the
+stack.
Rejected: an ordered list of steps on the switcher (`activeSheets`), because
it changes the switcher's public contract, requires every level of a flow to
live under one switcher, and cannot order a sheet opened from elsewhere.
diff --git a/packages/core/src/BottomSheet/BottomSheet.test.tsx b/packages/core/src/BottomSheet/BottomSheet.test.tsx
index 32b8dc8dad..2cc246afa3 100644
--- a/packages/core/src/BottomSheet/BottomSheet.test.tsx
+++ b/packages/core/src/BottomSheet/BottomSheet.test.tsx
@@ -14,6 +14,7 @@ import {act, render, screen, fireEvent} from '@testing-library/react';
import {createRef, useState} from 'react';
import {BottomSheet} from './BottomSheet';
import {BottomSheetEscapeContext} from './bottomSheetEscape';
+import {resetBottomSheetStackForTests} from './bottomSheetStack';
import {BottomSheetSwitcher} from './BottomSheetSwitcher';
import {__resetInteractionModalityForTest} from '../utils/interactionModality';
@@ -25,6 +26,7 @@ const SNAP_POINTS: ReadonlyArray<number> = [0.14, 0.5, 0.92];
// jsdom doesn't implement <dialog> open/close or pointer capture; stub them.
beforeEach(() => {
+ resetBottomSheetStackForTests();
HTMLDialogElement.prototype.showModal = vi.fn(function (
this: HTMLDialogElement,
) {
@@ -33,6 +35,14 @@ beforeEach(() => {
HTMLDialogElement.prototype.show = vi.fn(function (this: HTMLDialogElement) {
this.setAttribute('open', '');
});
+ // A non-modal sheet is a manual popover; jsdom's stand-ins keep the same
+ // `open` marker the dialog paths use (the Drawer tests do the same).
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ this.setAttribute('open', '');
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ this.removeAttribute('open');
+ });
HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
this.removeAttribute('open');
});
@@ -219,19 +229,24 @@ function getHandle(): HTMLElement {
// Drive a pointer drag on the grab handle. jsdom PointerEvents don't carry
// clientY, so dispatch plain events with the coords the handlers read.
-function drag(handle: HTMLElement, points: {y: number}[]) {
+function drag(
+ handle: HTMLElement,
+ points: {y: number}[],
+ pointerType: 'mouse' | 'touch' | 'pen' = 'mouse',
+) {
const [down, ...rest] = points;
fireEvent.pointerDown(handle, {
pointerId: 1,
clientY: down.y,
button: 0,
isPrimary: true,
+ pointerType,
});
for (const p of rest) {
- fireEvent.pointerMove(handle, {pointerId: 1, clientY: p.y});
+ fireEvent.pointerMove(handle, {pointerId: 1, clientY: p.y, pointerType});
}
const last = points[points.length - 1];
- fireEvent.pointerUp(handle, {pointerId: 1, clientY: last.y});
+ fireEvent.pointerUp(handle, {pointerId: 1, clientY: last.y, pointerType});
}
function fireTimedPointer(
@@ -583,7 +598,7 @@ describe('BottomSheet', () => {
});
describe('hasScrim={false} (non-modal)', () => {
- it('opens non-modally: show() instead of showModal(), no aria-modal', () => {
+ it('opens non-modally: a manual popover instead of showModal(), no aria-modal', () => {
render(
<BottomSheet
isOpen
@@ -593,11 +608,315 @@ describe('BottomSheet', () => {
Content
</BottomSheet>,
);
- expect(HTMLDialogElement.prototype.show).toHaveBeenCalled();
+ // In the top layer as a manual popover (no light dismiss, no backdrop)
+ // so sheets order by presentation without a page-level z-index.
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();
+ expect(HTMLDialogElement.prototype.show).not.toHaveBeenCalled();
expect(HTMLDialogElement.prototype.showModal).not.toHaveBeenCalled();
+ expect(screen.getByRole('dialog')).toHaveAttribute('popover', 'manual');
expect(screen.getByRole('dialog')).not.toHaveAttribute('aria-modal');
});
+ it('focuses the panel, as show() did, when the browser focuses the popover on show (an engine whose show() lands on the panel container)', () => {
+ // Chromium's `show()` focusing steps land on the panel (tabindex -1,
+ // no ring); `showPopover()` lands on the first control and draws a
+ // ring. The sheet puts focus on the panel so a lone non-modal sheet
+ // focuses exactly as it did. The engine is told apart by what its
+ // `show()` does: here it focuses the tabindex -1 container.
+ const show = HTMLDialogElement.prototype.show;
+ HTMLDialogElement.prototype.show = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ this.querySelector<HTMLElement>('[tabindex="-1"]')?.focus();
+ });
+ const showPopover = HTMLElement.prototype.showPopover;
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ this.setAttribute('open', '');
+ // The popover focusing steps: the autofocus delegate when there is
+ // one, else (as Chromium does) the first control.
+ (
+ this.querySelector<HTMLElement>('[autofocus]') ??
+ this.querySelector<HTMLElement>('button')
+ )?.focus();
+ });
+ try {
+ const opener = document.createElement('button');
+ document.body.appendChild(opener);
+ opener.focus();
+ const events: string[] = [];
+ render(
+ <BottomSheet
+ isOpen
+ onOpenChange={() => {}}
+ label="Filters"
+ hasScrim={false}>
+ <button
+ type="button"
+ onFocus={() => events.push('focus')}
+ onBlur={() => events.push('blur')}>
+ First action
+ </button>
+ </BottomSheet>,
+ );
+ expect(document.activeElement).toBe(getSheet());
+ // The control is never focused on the way to the panel, so a field
+ // validating on blur would not fire.
+ expect(events).toEqual([]);
+ expect(getSheet()).not.toHaveAttribute('autofocus');
+ opener.remove();
+ } finally {
+ HTMLElement.prototype.showPopover = showPopover;
+ HTMLDialogElement.prototype.show = show;
+ }
+ });
+
+ it('measures the engine inside its own dialog, so a first non-modal sheet opened inside an open modal does not cache the wrong answer', () => {
+ // A browser moves no focus into a dialog that sits under an open
+ // modal's inertness. The stub models that for `show()`: a dialog
+ // appended to the body while a modal outside it is open focuses
+ // nothing; one inside the modal (or with no modal open) focuses its
+ // tabindex -1 container, as Chromium's show() does.
+ const show = HTMLDialogElement.prototype.show;
+ HTMLDialogElement.prototype.show = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ const modal = Array.from(
+ document.querySelectorAll<HTMLDialogElement>(
+ 'dialog[open][aria-modal="true"]',
+ ),
+ ).find(d => !d.contains(this));
+ if (modal != null) {
+ return;
+ }
+ this.querySelector<HTMLElement>('[tabindex="-1"]')?.focus();
+ });
+ const showPopover = HTMLElement.prototype.showPopover;
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ this.setAttribute('open', '');
+ (
+ this.querySelector<HTMLElement>('[autofocus]') ??
+ this.querySelector<HTMLElement>('button')
+ )?.focus();
+ });
+ function App() {
+ const [isModalOpen, setIsModalOpen] = useState(true);
+ const [isHintOpen, setIsHintOpen] = useState(false);
+ const [isLoneOpen, setIsLoneOpen] = useState(false);
+ return (
+ <>
+ <BottomSheet
+ isOpen={isModalOpen}
+ onOpenChange={setIsModalOpen}
+ label="Settings">
+ <button type="button" onClick={() => setIsHintOpen(true)}>
+ Show hint
+ </button>
+ <button type="button" onClick={() => setIsModalOpen(false)}>
+ Done
+ </button>
+ <BottomSheet
+ isOpen={isHintOpen}
+ onOpenChange={setIsHintOpen}
+ hasScrim={false}
+ label="Hint">
+ <button type="button">Got it</button>
+ </BottomSheet>
+ </BottomSheet>
+ <button type="button" onClick={() => setIsLoneOpen(true)}>
+ Open filters
+ </button>
+ <BottomSheet
+ isOpen={isLoneOpen}
+ onOpenChange={setIsLoneOpen}
+ hasScrim={false}
+ label="Filters">
+ <button type="button">First action</button>
+ </BottomSheet>
+ </>
+ );
+ }
+ try {
+ render(<App />);
+ // The first non-modal sheet of the page opens inside the open modal:
+ // the engine is measured there, where show() can move focus.
+ fireEvent.click(screen.getByRole('button', {name: 'Show hint'}));
+ const hint = screen.getByRole('dialog', {name: 'Hint'});
+ expect(document.activeElement).toBe(
+ hint.querySelector('.astryx-bottom-sheet'),
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Done'}));
+ // A later lone non-modal sheet focuses as show() would: the panel.
+ fireEvent.click(screen.getByRole('button', {name: 'Open filters'}));
+ const filters = screen.getByRole('dialog', {name: 'Filters'});
+ expect(document.activeElement).toBe(
+ filters.querySelector('.astryx-bottom-sheet'),
+ );
+ } finally {
+ HTMLElement.prototype.showPopover = showPopover;
+ HTMLDialogElement.prototype.show = show;
+ }
+ });
+
+ it('leaves focus on the first control, as show() did, in an engine whose show() skips the panel container', () => {
+ // Firefox's `show()` and `showPopover()` both land on the first
+ // control in the sheet. Nothing is re-targeted, so a lone non-modal
+ // sheet focuses as it did with `show()` there too.
+ const show = HTMLDialogElement.prototype.show;
+ HTMLDialogElement.prototype.show = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ this.querySelector<HTMLElement>('button')?.focus();
+ });
+ const showPopover = HTMLElement.prototype.showPopover;
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ this.setAttribute('open', '');
+ (
+ this.querySelector<HTMLElement>('[autofocus]') ??
+ this.querySelector<HTMLElement>('button')
+ )?.focus();
+ });
+ try {
+ const opener = document.createElement('button');
+ document.body.appendChild(opener);
+ opener.focus();
+ render(
+ <BottomSheet
+ isOpen
+ onOpenChange={() => {}}
+ label="Filters"
+ hasScrim={false}>
+ <button type="button">First action</button>
+ </BottomSheet>,
+ );
+ expect(document.activeElement).toBe(
+ screen.getByRole('button', {name: 'First action'}),
+ );
+ expect(getSheet()).not.toHaveAttribute('autofocus');
+ opener.remove();
+ } finally {
+ HTMLElement.prototype.showPopover = showPopover;
+ HTMLDialogElement.prototype.show = show;
+ }
+ });
+
+ it('returns focus to its opener on close when the person was still in the sheet', () => {
+ const opener = document.createElement('button');
+ opener.textContent = 'Open';
+ document.body.appendChild(opener);
+ opener.focus();
+ try {
+ render(<ExitHarness hasScrim={false} />);
+ // The person moved into the sheet (e.g. tabbed to its control).
+ screen.getByRole('button', {name: 'Close sheet'}).focus();
+ fireEvent.keyDown(screen.getByRole('dialog'), {key: 'Escape'});
+ finishSheetExit();
+ expect(screen.getByRole('dialog', {hidden: true})).not.toHaveAttribute(
+ 'open',
+ );
+ expect(document.activeElement).toBe(opener);
+ } finally {
+ opener.remove();
+ }
+ });
+
+ it('always focuses finalFocusRef on close, even when focus had left the sheet', () => {
+ const elsewhere = document.createElement('input');
+ const target = document.createElement('button');
+ target.textContent = 'Target';
+ document.body.append(elsewhere, target);
+ const finalFocusRef = {current: target as HTMLElement | null};
+ function Harness() {
+ const [isOpen, setIsOpen] = useState(true);
+ return (
+ <>
+ <button type="button" onClick={() => setIsOpen(false)}>
+ Close from page
+ </button>
+ <BottomSheet
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ hasScrim={false}
+ finalFocusRef={finalFocusRef}
+ label="Filters">
+ Content
+ </BottomSheet>
+ </>
+ );
+ }
+ try {
+ render(<Harness />);
+ // The page stayed live: the person moved on, then a page control
+ // closed the sheet. The explicit target still receives focus.
+ elsewhere.focus();
+ fireEvent.click(screen.getByRole('button', {name: 'Close from page'}));
+ finishSheetExit();
+ expect(document.activeElement).toBe(target);
+ } finally {
+ elsewhere.remove();
+ target.remove();
+ }
+ });
+
+ it('leaves focus where the person took it when the sheet closes from the page', () => {
+ const opener = document.createElement('button');
+ const elsewhere = document.createElement('input');
+ document.body.append(opener, elsewhere);
+ opener.focus();
+ try {
+ render(<ExitHarness hasScrim={false} />);
+ // The page stayed live: the person moved on, then the sheet closed
+ // (a timer, a page control).
+ elsewhere.focus();
+ fireEvent.click(screen.getByRole('button', {name: 'Close sheet'}));
+ finishSheetExit();
+ expect(document.activeElement).toBe(elsewhere);
+ } finally {
+ opener.remove();
+ elsewhere.remove();
+ }
+ });
+
+ it('leaves focus alone when the browser does not move it on show', () => {
+ const opener = document.createElement('button');
+ document.body.appendChild(opener);
+ opener.focus();
+ render(
+ <BottomSheet
+ isOpen
+ onOpenChange={() => {}}
+ label="Filters"
+ hasScrim={false}>
+ <button type="button">First action</button>
+ </BottomSheet>,
+ );
+ expect(document.activeElement).toBe(opener);
+ opener.remove();
+ });
+
+ it('falls back to show() below the Popover API support floor', () => {
+ const showPopover = HTMLElement.prototype.showPopover;
+ // @ts-expect-error -- emulate a browser without the Popover API
+ delete HTMLElement.prototype.showPopover;
+ try {
+ render(
+ <BottomSheet
+ isOpen
+ onOpenChange={() => {}}
+ label="Filters"
+ hasScrim={false}>
+ Content
+ </BottomSheet>,
+ );
+ expect(HTMLDialogElement.prototype.show).toHaveBeenCalled();
+ expect(HTMLDialogElement.prototype.showModal).not.toHaveBeenCalled();
+ } finally {
+ HTMLElement.prototype.showPopover = showPopover;
+ }
+ });
+
it('does not dismiss when the shell (dialog element itself) is clicked', () => {
// No scrim: a tap on the transparent shell must pass through to the page,
// not dismiss the sheet.
@@ -2582,6 +2901,150 @@ describe('BottomSheet', () => {
);
expect(screen.getByRole('dialog')).toBeInTheDocument();
});
+
+ function stubReducedMotion(coarse: boolean) {
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn((query: string) => ({
+ matches:
+ query === '(prefers-reduced-motion: reduce)' ||
+ (coarse &&
+ query ===
+ '(prefers-reduced-motion: reduce) and (pointer: coarse)'),
+ media: query,
+ onchange: null,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ })),
+ );
+ }
+
+ function Controlled() {
+ const [isOpen, setIsOpen] = useState(true);
+ return (
+ <BottomSheet isOpen={isOpen} onOpenChange={setIsOpen} label="Filters">
+ <button type="button" onClick={() => setIsOpen(false)}>
+ Close
+ </button>
+ </BottomSheet>
+ );
+ }
+
+ it("a touch swipe dismissal under reduced motion fades out in place on a fine pointer (design:reduced-motion DR2, a touch drag's release)", () => {
+ stubReducedMotion(false);
+ render(<Controlled />);
+ const dialog = screen.getByRole('dialog');
+ drag(getHandle(), [{y: 0}, {y: 40}, {y: 120}], 'touch');
+ // Exiting: a transform end does not close the dialog, the fade does.
+ fireEvent.transitionEnd(getSheet(), {propertyName: 'transform'});
+ expect(dialog).toHaveAttribute('open');
+ fireEvent.transitionEnd(getSheet(), {propertyName: 'opacity'});
+ expect(dialog).not.toHaveAttribute('open');
+ });
+
+ it('a touch swipe dismissal does not outlive the sheet: reopened and closed from a control, it leaves at once again', () => {
+ stubReducedMotion(false);
+ function Reopenable() {
+ const [isOpen, setIsOpen] = useState(true);
+ return (
+ <>
+ <button type="button" onClick={() => setIsOpen(true)}>
+ Open
+ </button>
+ <BottomSheet
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ label="Filters">
+ <button type="button" onClick={() => setIsOpen(false)}>
+ Close
+ </button>
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<Reopenable />);
+ const dialog = screen.getByRole('dialog');
+ drag(getHandle(), [{y: 0}, {y: 40}, {y: 120}], 'touch');
+ fireEvent.transitionEnd(getSheet(), {propertyName: 'opacity'});
+ expect(dialog).not.toHaveAttribute('open');
+ fireEvent.click(screen.getByRole('button', {name: 'Open'}));
+ expect(dialog).toHaveAttribute('open');
+ fireEvent.click(screen.getByRole('button', {name: 'Close'}));
+ // A control dismissal: its collapsed transform end closes the dialog.
+ fireEvent.transitionEnd(getSheet(), {propertyName: 'transform'});
+ expect(dialog).not.toHaveAttribute('open');
+ });
+
+ it('a refused touch swipe spends its request: a guarded onOpenChange keeps the sheet open, and the next close from a control leaves at once', () => {
+ stubReducedMotion(false);
+ function Guarded() {
+ const [isOpen, setIsOpen] = useState(true);
+ const [isGuarded, setIsGuarded] = useState(true);
+ return (
+ <BottomSheet
+ isOpen={isOpen}
+ // The documented replacement for the switcher's onCancel: ignore
+ // implicit closes while the step must stay open.
+ onOpenChange={next => {
+ if (!next && isGuarded) {
+ return;
+ }
+ setIsOpen(next);
+ }}
+ label="Filters">
+ <button type="button" onClick={() => setIsGuarded(false)}>
+ Unlock
+ </button>
+ <button type="button" onClick={() => setIsOpen(false)}>
+ Close
+ </button>
+ </BottomSheet>
+ );
+ }
+ render(<Guarded />);
+ const dialog = screen.getByRole('dialog');
+ drag(getHandle(), [{y: 0}, {y: 40}, {y: 120}], 'touch');
+ // Refused: the sheet stays open.
+ expect(dialog).toHaveAttribute('open');
+ fireEvent.click(screen.getByRole('button', {name: 'Unlock'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Close'}));
+ // A control close: its collapsed transform end closes the dialog; the
+ // spent swipe request does not turn it into a cross-fade.
+ fireEvent.transitionEnd(getSheet(), {propertyName: 'transform'});
+ expect(dialog).not.toHaveAttribute('open');
+ });
+
+ it('a mouse drag dismissal under reduced motion on a fine pointer leaves at once (DR3): a mouse or pen drag is not a touch drag', () => {
+ stubReducedMotion(false);
+ render(<Controlled />);
+ const dialog = screen.getByRole('dialog');
+ drag(getHandle(), [{y: 0}, {y: 40}, {y: 120}], 'mouse');
+ fireEvent.transitionEnd(getSheet(), {propertyName: 'transform'});
+ expect(dialog).not.toHaveAttribute('open');
+ });
+
+ it('a dismissal from a control under reduced motion on a fine pointer leaves at once (DR3): its (collapsed) transform end closes the dialog', () => {
+ stubReducedMotion(false);
+ render(<Controlled />);
+ const dialog = screen.getByRole('dialog');
+ fireEvent.click(screen.getByRole('button', {name: 'Close'}));
+ fireEvent.transitionEnd(getSheet(), {propertyName: 'transform'});
+ expect(dialog).not.toHaveAttribute('open');
+ });
+
+ it('a dismissal from a control under reduced motion on a coarse pointer fades out (DR2)', () => {
+ stubReducedMotion(true);
+ render(<Controlled />);
+ const dialog = screen.getByRole('dialog');
+ fireEvent.click(screen.getByRole('button', {name: 'Close'}));
+ fireEvent.transitionEnd(getSheet(), {propertyName: 'transform'});
+ expect(dialog).toHaveAttribute('open');
+ fireEvent.transitionEnd(getSheet(), {propertyName: 'opacity'});
+ expect(dialog).not.toHaveAttribute('open');
+ });
});
describe('container padding isolation', () => {
diff --git a/packages/core/src/BottomSheet/BottomSheet.tsx b/packages/core/src/BottomSheet/BottomSheet.tsx
index 4e702d0c34..d7c2911a88 100644
--- a/packages/core/src/BottomSheet/BottomSheet.tsx
+++ b/packages/core/src/BottomSheet/BottomSheet.tsx
@@ -4,7 +4,7 @@
/**
* @file BottomSheet.tsx
- * @input Uses React, StyleX, core hooks, shared layer dismissal, the modal outlet registry, the shared interaction modality, named BottomSheetPanel, BottomSheetSwitcherContext
+ * @input Uses React, StyleX, core hooks, shared layer dismissal, the modal outlet registry, the shared interaction modality, named BottomSheetPanel, BottomSheetSwitcherContext, BottomSheetHostContext, the private bottom-sheet stack registry
* @output Exports BottomSheet component and BottomSheetProps
* @position Public BottomSheet router plus private standalone/switcher hosts
*
@@ -23,24 +23,57 @@
* 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.
+ * decide: gating `cancel` by `purpose` and the shared dismissal stack, the
+ * stack of sheets below, and, in a switcher, handing one scrim between two
+ * dialogs and keeping focus in the active sheet when a retained dialog
+ * closes.
*
- * While a standalone modal sheet is open, its dialog is the outlet that
- * app-global surfaces (toasts) render into (Layer/modalOutlet.ts).
+ * A standalone sheet also joins the private bottom-sheet stack
+ * (bottomSheetStack.ts) while it is presented. The stack is behaviour, not
+ * API: a modal sheet opened while another modal sheet is open stacks on top
+ * of it, the covered sheet recedes and is blocked, one scrim stays visible,
+ * and the native top layer is kept in open order even when several sheets
+ * open in one commit. A sheet rendered in another sheet's content leaves
+ * with its host and returns with it while its own `isOpen` is still true;
+ * its state is never written for it. A modal sheet on its own never
+ * notices the stack; when every sheet of a stack closes in one update, the
+ * registry returns focus once, to the bottom sheet's target, after the last
+ * dialog has closed.
+ *
+ * A standalone sheet closing in the same update as another standalone sheet
+ * opens, at the same level and from a control inside the closing sheet, is
+ * replaced by it: the two run the handoff a BottomSheetSwitcher runs between
+ * its steps (entering sheet above, retained sheet aligning down then fading,
+ * one steady scrim, focus into the new sheet and back to the flow's opener
+ * on close). The registry pairs them and drives the handoff; this host
+ * renders the retained panel state it reports, and reports its panel's
+ * motions back. Non-modal sheets (`hasScrim={false}`) are hosted as manual
+ * popovers so the top layer orders them, with `show()` below the Popover API
+ * floor; they never stack, but they replace each other the same way, and
+ * return focus to their opener on close only while the person is still in
+ * them.
+ *
+ * Every open standalone modal sheet supplies its dialog as an outlet for
+ * app-global surfaces (toasts) (Layer/modalOutlet.ts); the latest outlet,
+ * the one they render into, follows the sheet stack's order, so toasts land
+ * in the top sheet and return to the sheet beneath when it closes.
*
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/BottomSheet/BottomSheetPanel.tsx
* - /packages/core/src/BottomSheet/BottomSheetEdgeTint.tsx
+ * - /packages/core/src/BottomSheet/BottomSheetHostContext.ts
+ * - /packages/core/src/BottomSheet/bottomSheetStack.ts
* - /packages/core/src/BottomSheet/BottomSheet.doc.mjs
* - /packages/core/src/BottomSheet/BottomSheet.test.tsx
+ * - /packages/core/src/BottomSheet/BottomSheetStacking.test.tsx
* - /packages/core/src/BottomSheet/BottomSheetSwitcher.tsx
* - /packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx
* - /packages/core/src/Layer/layerDismissalFamilies.test.tsx
* - /packages/core/src/Layer/layerDismissalInvariants.test.tsx
* - /packages/core/src/Toast/ToastViewport.modalHost.test.tsx
* - /apps/storybook/stories/BottomSheet.stories.tsx
+ * - /apps/storybook/stories/BottomSheetStacking.stories.tsx
+ * - /apps/storybook/stories/BottomSheetReplace.stories.tsx
* - /packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetShowcase.tsx
*/
@@ -58,7 +91,12 @@ import * as stylex from '@stylexjs/stylex';
import type {BaseProps} from '../BaseProps';
import type {DialogPurpose} from '../Dialog';
import type {SpacingStep} from '../utils/types';
-import {colorVars, durationVars, easeVars} from '../theme/tokens.stylex';
+import {
+ colorVars,
+ durationVars,
+ easeVars,
+ spacingVars,
+} from '../theme/tokens.stylex';
import {useDevWarning, useScrollLock} from '../hooks';
import {mergeProps} from '../utils';
import {LayerDepthProvider} from '../Layer/LayerDepthContext';
@@ -73,6 +111,32 @@ import {
type BottomSheetPanelState,
} from './BottomSheetPanel';
import {BottomSheetEdgeTint} from './BottomSheetEdgeTint';
+import {
+ BottomSheetHostContext,
+ CLOSED_BOTTOM_SHEET_HOST,
+ OPEN_BOTTOM_SHEET_HOST,
+} from './BottomSheetHostContext';
+import {
+ BOTTOM_SHEET_STACK_DEFAULT_VIEW,
+ cancelScrimWrite,
+ closeDialogKeepingFocus,
+ focusSheetPanel,
+ getBottomSheetBeneath,
+ hideSheetHost,
+ isClosingTogether,
+ isSheetHostPresented,
+ presentStepModally,
+ presentWithClearScrim,
+ registerBottomSheet,
+ reportBottomSheetMotion,
+ reportClosedTogether,
+ sealBottomSheetBatch,
+ setBottomSheetOpen,
+ showSheetHostNonModal,
+ writeScrimOpacity,
+ type BottomSheetScrimWrite,
+ type BottomSheetStackView,
+} from './bottomSheetStack';
import {
BottomSheetSwitcherContext,
type BottomSheetSwitcherContextValue,
@@ -106,18 +170,31 @@ const styles = stylex.create({
// An open standalone dialog is its panel's positioner: the panel sits at its
// block end, centred, with no wrapper between them
// (architecture:component-style-authoring INV7). A tap beside a narrower
- // panel lands on the dialog itself, which light dismiss reads.
+ // panel lands on the dialog itself, which light dismiss reads. The stack's
+ // recede (stackPositionerStyles) is applied to this dialog too, so a
+ // covered standalone sheet shrinks and lifts as one, panel and all.
dialogPanelHost: {
display: 'grid',
alignContent: 'end',
justifyItems: 'center',
},
+ // A non-modal sheet is hosted in the top layer (manual popover), so it
+ // carries no page-level z-index (spec:AST-027). Below the Popover API
+ // floor `show()` leaves it in page stacking order as a reduced fallback:
+ // usable, but with no promise over later page content.
dialogNonModal: {
pointerEvents: 'none',
- zIndex: 1000,
width: '100%',
height: '100%',
},
+ dialogNonModalItem: {
+ pointerEvents: 'none',
+ width: '100%',
+ height: '100%',
+ },
+ dialogNonModalItemTop: {
+ zIndex: 1,
+ },
scrim: {
'::backdrop': {
backgroundColor: colorVars['--color-overlay'],
@@ -126,31 +203,17 @@ const styles = stylex.create({
'@starting-style': 0,
},
transitionProperty: 'opacity, display',
- // 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.
+ // The scrim changes hands between stacked sheets with no fade at all:
+ // the host pins this to 0s inline for the frame the change lands in
+ // (see `writeScrimOpacity`). Reduced motion keeps the pin too.
transitionDuration: `var(--_sheet-scrim-duration, ${durationVars['--duration-medium']})`,
transitionTimingFunction: easeVars['--ease-standard'],
transitionBehavior: 'allow-discrete',
'@media (prefers-reduced-motion: reduce)': {
- // 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.
*
@@ -179,8 +242,58 @@ const styles = stylex.create({
positionerTop: {
zIndex: 1,
},
+ // A sheet in a stack recedes and returns with CSS motion only; the style
+ // stays on while another sheet is presented so the return animates too.
+ // On a standalone sheet these apply to the dialog itself (its panel's
+ // positioner); on a switcher step, to the step's positioner.
+ positionerStackMotion: {
+ transformOrigin: '50% 0',
+ transitionProperty: 'transform',
+ transitionDuration: durationVars['--duration-medium'],
+ transitionTimingFunction: easeVars['--ease-standard'],
+ '@media (prefers-reduced-motion: reduce)': {
+ transitionDuration: '0.01s',
+ },
+ },
+ // Covered sheets recede behind the top sheet: the nearest shrinks a step
+ // about its top edge and lifts, the next shrinks a second step; deeper
+ // sheets share that second step. Only sheets count toward the depth.
+ positionerReceded1: {
+ transform: `translateY(calc(-1 * ${spacingVars['--spacing-2']})) scale(0.96)`,
+ },
+ positionerReceded2: {
+ transform: `translateY(calc(-2 * ${spacingVars['--spacing-2']})) scale(0.92)`,
+ },
});
+/** Positioner styles for a sheet's place in the stack; the switcher items share them. */
+function stackPositionerStyles(view: BottomSheetStackView) {
+ return [
+ view.isStacked && styles.positionerStackMotion,
+ view.depth === 1 && styles.positionerReceded1,
+ view.depth >= 2 && styles.positionerReceded2,
+ ] as const;
+}
+
+/** The `data-sheet-stack` value for a host: only set while sheets stack. */
+function stackStateAttribute(
+ view: BottomSheetStackView,
+ isOpen: boolean,
+): 'top' | 'covered' | 'exiting' | 'replaced' | undefined {
+ if (!view.isStacked) {
+ return undefined;
+ }
+ if (!isOpen) {
+ return view.replacedMotion != null ? 'replaced' : 'exiting';
+ }
+ return view.isTop ? 'top' : 'covered';
+}
+
+/** Scrim opacity for an open modal sheet: one visible backdrop per stack. */
+function scrimOpacityForView(view: BottomSheetStackView): '0' | '1' {
+ return view.isStacked && !view.ownsScrim ? '0' : '1';
+}
+
interface BottomSheetSharedProps extends BaseProps<HTMLDivElement> {
/** Ref forwarded to the visual sheet panel <div>. */
ref?: React.Ref<HTMLDivElement>;
@@ -229,12 +342,23 @@ interface StandaloneBottomSheetProps extends BottomSheetSharedProps {
isOpen: boolean;
onOpenChange: (isOpen: boolean) => void;
hasScrim?: boolean;
- /** Element that receives focus after the sheet closes. */
+ /**
+ * Element that receives focus after the sheet closes. For a sheet on its
+ * own, or the last sheet of a stack, it is always focused, wherever focus
+ * was. When the sheet closes with a modal sheet still open beneath it,
+ * focus returns into that sheet instead (to this element if it is inside
+ * it, else the revealed sheet's panel), because the page is still inert.
+ */
finalFocusRef?: RefObject<HTMLElement | null>;
sheetId?: never;
}
interface SwitcherBottomSheetProps extends BottomSheetSharedProps {
+ /**
+ * @deprecated `BottomSheetSwitcher` is deprecated; give each step its own
+ * standalone sheet with `isOpen` instead. Keeps working until a future
+ * minor release removes the switcher.
+ */
sheetId: string;
isOpen?: never;
onOpenChange?: never;
@@ -264,63 +388,13 @@ function panelStateForSwitcherPhase(
}
}
-// preventScroll on both: presenting a sheet must not scroll the page to reveal
-// what it just focused. For an autofocused field that reveal is the mobile
-// keyboard's, and it moves the document under a fixed sheet; useMobileKeyboard
-// brings the field into view within the sheet instead.
function focusPanel(panel: HTMLElement | null, isModal: boolean): void {
- const activeElement = document.activeElement;
- if (activeElement != null && panel?.contains(activeElement)) {
- return;
- }
- const autofocus = panel?.querySelector<HTMLElement>('[data-autofocus]');
- if (autofocus != null) {
- autofocus.focus({preventScroll: true});
- } else if (isModal) {
- panel?.focus({preventScroll: true});
- }
-}
-
-/**
- * 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');
+ focusSheetPanel(panel, 'open', isModal);
}
function StandaloneBottomSheet({
ref,
- isOpen,
+ isOpen: isOpenProp,
onOpenChange,
label,
children,
@@ -335,13 +409,68 @@ function StandaloneBottomSheet({
const dialogRef = useRef<HTMLDialogElement | null>(null);
const panelRef = useRef<HTMLDivElement | null>(null);
const triggerRef = useRef<HTMLElement | null>(null);
+ // Whether focus was inside this sheet when its close began. A non-modal
+ // sheet leaves the page interactive, so it returns focus to its opener
+ // only if the person was still in the sheet; a modal sheet always does.
+ const hadFocusAtCloseRef = useRef(false);
+ const finalFocusRefRef = useRef(finalFocusRef);
+ finalFocusRefRef.current = finalFocusRef;
+ // A sheet rendered in another sheet's content is presented only while that
+ // sheet is open: it leaves with its host and, if its own state is still
+ // open, comes back when the host does (see BottomSheetHostContext). Its
+ // state stays the consumer's; nothing here writes it.
+ const host = use(BottomSheetHostContext);
+ const isHostOpen = host?.isOpen ?? true;
+ const isOpen = isOpenProp && isHostOpen;
+ // Presentation outlives the controlled prop: a closing sheet stays mounted
+ // and in its native host through its exit, and only its motion completion
+ // (or a replace finishing) clears it. The open flip is derived during
+ // render; the close flip is the host's own event.
const [isPresented, setIsPresented] = useState(isOpen);
+ if (isOpen && !isPresented) {
+ setIsPresented(true);
+ }
const shouldPresent = isOpen || isPresented;
+
+ // The sheet's place in the stack of presented modal sheets. Default until
+ // the stack reports otherwise, which it does in the commit that presents
+ // the sheet, so the first painted frame already shows it.
+ const stackKeyRef = useRef<object>({});
+ const [stackView, setStackView] = useState<BottomSheetStackView>(
+ BOTTOM_SHEET_STACK_DEFAULT_VIEW,
+ );
+ const isOpenRef = useRef(isOpen);
+ isOpenRef.current = isOpen;
+ // Closed and being replaced by the sheet that opened in the same update:
+ // the panel is retained (stays, aligns, fades) instead of sliding out.
+ const isReplaced = !isOpen && isPresented && stackView.replacedMotion != null;
+ // Whether a replace pairs this close is known only once every sheet of the
+ // commit has reported to the registry, in the layout phase. Until the
+ // registry has answered (a synchronous re-render later, before paint) the
+ // panel holds its open pose: an exit pose rendered first and read back by
+ // the panel's own style query would start the exit transition, and the
+ // reversal into the retained pose would then snap the panel to rest. The
+ // flag is keyed to the close it settles: every change of `isOpen` starts
+ // it over, during render, and the layout effect below settles a close.
+ const [isCloseSettled, setIsCloseSettled] = useState(false);
+ const [settledIsOpen, setSettledIsOpen] = useState(isOpen);
+ if (settledIsOpen !== isOpen) {
+ setSettledIsOpen(isOpen);
+ setIsCloseSettled(false);
+ }
const panelState: BottomSheetPanelState = isOpen
- ? {kind: 'open', entering: false}
- : isPresented
- ? {kind: 'exiting'}
- : {kind: 'hidden'};
+ ? {kind: 'open', entering: stackView.isReplacing}
+ : isReplaced
+ ? {
+ kind: 'retained',
+ motion: stackView.replacedMotion ?? 'covered',
+ alignmentOffset: stackView.alignmentOffset,
+ }
+ : isPresented
+ ? isCloseSettled
+ ? {kind: 'exiting'}
+ : {kind: 'open', entering: false}
+ : {kind: 'hidden'};
// Popover's sheet may turn Escape off on its own (bottomSheetEscape.ts).
const isEscapeAllowed = use(BottomSheetEscapeContext);
@@ -361,69 +490,224 @@ function StandaloneBottomSheet({
},
[],
);
+ const stackViewRef = useRef(stackView);
+ stackViewRef.current = stackView;
+ const scrimWriteRef = useRef<BottomSheetScrimWrite>({frame: null});
+ useEffect(() => () => cancelScrimWrite(scrimWriteRef.current), []);
+ const writeScrim = useCallback(
+ (opacity: '0' | '1') =>
+ writeScrimOpacity(dialogRef.current, opacity, scrimWriteRef.current),
+ [],
+ );
const handleScrimOpacity = useCallback((opacity: number) => {
+ // Only the sheet whose backdrop is the visible scrim thins it; a sheet
+ // stacked above it has a transparent backdrop that a drag must not reveal.
+ const view = stackViewRef.current;
+ if (view.isStacked && !view.ownsScrim) {
+ return;
+ }
dialogRef.current?.style.setProperty(
'--_sheet-scrim-opacity',
String(opacity),
);
}, []);
- useEffect(() => {
- const dialog = dialogRef.current;
- if (dialog == null || !isOpen) {
+ // A sheet joins the registry for as long as it is presented. For a modal
+ // sheet the registry shows the dialog (in open order, repairing same-commit
+ // ties before paint), moves focus into it when it lands on top, and reports
+ // the sheet's view. A non-modal sheet is a group of its own: it is shown as
+ // a manual popover (or by `show()` below the Popover API floor), never
+ // stacks or recedes, and only replaces other non-modal sheets.
+ useLayoutEffect(() => {
+ if (!shouldPresent) {
return;
}
-
- // The controlled prop opens an already-mounted dialog; presentation state
- // must latch here so a later close can keep it mounted through its exit.
- // eslint-disable-next-line @eslint-react/set-state-in-effect -- latches controlled open state for exit animation
- setIsPresented(true);
- dialog.style.setProperty('--_sheet-scrim-opacity', '1');
- const wasOpen = dialog.open;
- if (!wasOpen) {
- if (hasScrim) {
- triggerRef.current = document.activeElement as HTMLElement | null;
- dialog.showModal();
- } else {
- dialog.show();
- }
- focusPanel(panelRef.current, hasScrim);
+ const key = stackKeyRef.current;
+ return registerBottomSheet(
+ {
+ key,
+ getElement: () => dialogRef.current,
+ show: () => {
+ const dialog = dialogRef.current;
+ if (dialog == null || isSheetHostPresented(dialog)) {
+ return;
+ }
+ if (triggerRef.current == null) {
+ triggerRef.current = document.activeElement as HTMLElement | null;
+ }
+ if (!hasScrim) {
+ showSheetHostNonModal(dialog, panelRef.current);
+ return;
+ }
+ dialog.style.setProperty(
+ '--_sheet-scrim-opacity',
+ scrimOpacityForView(stackViewRef.current),
+ );
+ dialog.showModal();
+ },
+ hide: () => closeDialogKeepingFocus(dialogRef.current),
+ focus: reason => focusSheetPanel(panelRef.current, reason, hasScrim),
+ getReturnTarget: () =>
+ finalFocusRefRef.current?.current ?? triggerRef.current,
+ onView: view => {
+ stackViewRef.current = view;
+ setStackView(view);
+ // Who owns the scrim is the stack's decision; a change of owner
+ // lands with no fade (see writeScrimOpacity). A replaced sheet
+ // keeps the scrim it owns until the sheet replacing it takes it
+ // over; a closing sheet whose scrim an open sheet took over drops
+ // its backdrop the same way; a closing sheet that owned the scrim
+ // alone fades it out.
+ if (isOpenRef.current || view.replacedMotion != null) {
+ writeScrim(scrimOpacityForView(view));
+ } else if (view.isScrimTakenOver) {
+ writeScrim('0');
+ }
+ },
+ replaceable: {
+ getPanel: () => panelRef.current,
+ getOpener: () => triggerRef.current,
+ setOpener: opener => {
+ triggerRef.current = opener;
+ },
+ finish: () => {
+ // The registry has closed the dialog; focus stayed in the sheet
+ // that replaced this one, and so did the flow's opener.
+ triggerRef.current = null;
+ setIsPresented(false);
+ },
+ },
+ },
+ isOpenRef.current,
+ hasScrim,
+ );
+ }, [hasScrim, shouldPresent, writeScrim]);
+ useLayoutEffect(() => {
+ if (!isOpen) {
+ // Read before the browser's focus fixup for the exiting sheet's
+ // `inert` runs (at the next rendering opportunity), so this is where
+ // focus was when the person closed the sheet.
+ const dialog = dialogRef.current;
+ hadFocusAtCloseRef.current =
+ dialog != null && dialog.contains(dialog.ownerDocument.activeElement);
+ }
+ if (shouldPresent) {
+ setBottomSheetOpen(stackKeyRef.current, isOpen);
+ }
+ if (!isOpen) {
+ // The registry has had every sheet's report for this commit; a close
+ // that was not paired as a replace is an exit from here on.
+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- settles the close once the registry has answered
+ setIsCloseSettled(true);
}
- }, [hasScrim, isOpen]);
+ }, [hasScrim, isOpen, shouldPresent]);
// Host app-global surfaces (toasts) inside this sheet while it is an open
- // modal, so they stay visible and operable above it. A closing sheet stays
- // modal through its exit animation, but inert and hidden, so it hands them
- // back as soon as it starts closing.
- useModalOutlet(dialogRef, isOpen && hasScrim);
-
+ // modal, so they stay visible and operable above it. Every open scrim sheet
+ // supplies an outlet (each is an active native modal); the latest outlet —
+ // the one global hosts render into — follows the sheet stack's order among
+ // sheets rather than the order the sheets were supplied in, so a toast lands
+ // in the top sheet, and when that sheet closes the sheet it reveals becomes
+ // the latest sheet again and takes the toasts back; a Dialog opened from a
+ // sheet is supplied later and stays above every sheet. A closing sheet stays modal through its
+ // exit animation, but inert and hidden, so it stops supplying as soon as it
+ // starts closing. The registry reports a lone open sheet as the top one.
+ // Passive: it runs after the layout effects that present.
+ useModalOutlet(
+ dialogRef,
+ isOpen && hasScrim,
+ stackView.isTop,
+ 'bottom-sheet',
+ );
+ // Closes a batch of same-commit opens; see sealBottomSheetBatch.
useEffect(() => {
- if (!isOpen && isPresented && hasScrim) {
- handleScrimOpacity(0);
+ sealBottomSheetBatch();
+ });
+
+ // The scrim at rest: one visible backdrop per stack while open (a sheet
+ // stacked above the owner keeps its own backdrop transparent, and a reopen
+ // during the exit brings the owner's back), fading out through the exit.
+ useLayoutEffect(() => {
+ const dialog = dialogRef.current;
+ if (dialog == null || !hasScrim) {
+ return;
+ }
+ // A replaced sheet keeps the scrim it owns until the sheet replacing it
+ // takes it over; see bottomSheetStack.
+ if (isOpen || isReplaced) {
+ dialog.style.setProperty(
+ '--_sheet-scrim-opacity',
+ scrimOpacityForView(stackViewRef.current),
+ );
+ } else if (isPresented) {
+ dialog.style.setProperty('--_sheet-scrim-opacity', '0');
}
- }, [handleScrimOpacity, hasScrim, isOpen, isPresented]);
+ }, [hasScrim, isOpen, isPresented, isReplaced]);
+ const handleMotionStart = useCallback((motion: BottomSheetPanelMotion) => {
+ reportBottomSheetMotion(stackKeyRef.current, 'start', motion);
+ }, []);
const handleMotionComplete = useCallback(
(motion: BottomSheetPanelMotion) => {
+ // The replace handoff's motions (entering as a replacer, aligning and
+ // fading as the replaced sheet) are the registry's to sequence.
+ reportBottomSheetMotion(stackKeyRef.current, 'complete', motion);
if (motion !== 'exiting' || isOpen) {
return;
}
+ // A sheet closing from code beneath open sheets leaves focus where it
+ // is: in the sheet on top. Its own close must not pull focus back to
+ // the element its dialog recorded, nor does it move it anywhere else.
+ if (hasScrim && stackViewRef.current.depth > 0) {
+ closeDialogKeepingFocus(dialogRef.current);
+ setIsPresented(false);
+ triggerRef.current = null;
+ return;
+ }
+ // Closing together with the other sheets of its stack ("Close all"):
+ // the registry returns focus once, after the last dialog has left.
+ if (hasScrim && isClosingTogether(stackKeyRef.current)) {
+ closeDialogKeepingFocus(dialogRef.current);
+ setIsPresented(false);
+ triggerRef.current = null;
+ reportClosedTogether(stackKeyRef.current);
+ return;
+ }
const dialog = dialogRef.current;
- if (dialog?.open) {
- dialog.close();
+ if (dialog != null) {
+ hideSheetHost(dialog);
}
setIsPresented(false);
// The returned focus shows the focus-visible ring only after keyboard
// input (`architecture:interaction-modality` INV1). The native close
// may already have restored focus to the target with a ring; the helper
// clears it first.
- const returnTarget = finalFocusRef?.current ?? triggerRef.current;
- if (returnTarget != null) {
+ //
+ // With a sheet still open beneath this one, focus returns into that
+ // sheet: to the opener when it is there, else to the sheet's panel.
+ //
+ // An explicit `finalFocusRef` always receives focus, as released. The
+ // recorded opener of a non-modal sheet does so only if the person was
+ // still in the sheet when it closed (`hidePopover()` never moves
+ // focus, and the page behind it was live, so focus the person took
+ // elsewhere stays there).
+ const revealed = hasScrim
+ ? getBottomSheetBeneath(stackKeyRef.current)
+ : null;
+ const returnTarget =
+ finalFocusRef?.current ??
+ (hasScrim || hadFocusAtCloseRef.current ? triggerRef.current : null);
+ if (
+ revealed != null &&
+ (returnTarget == null || !revealed.element.contains(returnTarget))
+ ) {
+ revealed.focus();
+ } else if (returnTarget != null) {
focusForLastInput(returnTarget);
}
triggerRef.current = null;
},
- [finalFocusRef, isOpen],
+ [finalFocusRef, hasScrim, isOpen],
);
useInteractionModalityTracking();
@@ -449,17 +733,28 @@ function StandaloneBottomSheet({
isOpen && purpose !== 'required' && isEscapeAllowed ? 'close' : 'block',
onDismiss: dismissOnEscape,
getContainer: () => dialogRef.current,
- isPresent: () => dialogRef.current?.open ?? false,
+ // A covered sheet is on screen but never the one a press is for: the
+ // dismissal stack ranks by tree nesting first, which would hand Escape to
+ // a covered sheet nested in another sheet's content ahead of a top sheet
+ // written outside it. Standing down while covered keeps Escape and the
+ // platform close request with the top sheet, as the sheet stack orders.
+ // A replaced sheet stands down the same way: the sheet that replaced it,
+ // registered before or after it, takes the press.
+ isPresent: () =>
+ isSheetHostPresented(dialogRef.current) &&
+ !stackViewRef.current.isCovered &&
+ stackViewRef.current.replacedMotion == null,
});
// The native `cancel` event is a close request the stack never saw a press
- // for (Android back, the platform close watcher). One that bubbles up from
- // inside is not: a file input fires it when its picker is dismissed, so it is
- // left alone. Otherwise always preventDefault so the browser cannot close the
- // controlled <dialog>, then answer with the stack's rules: only the top-most
- // layer dismisses, and nothing dismisses during an IME composition.
+ // for (Android back, the platform close watcher). Always preventDefault so
+ // the browser cannot close the controlled <dialog>, then answer with the
+ // stack's rules: only the top-most layer dismisses, and nothing dismisses
+ // during an IME composition.
const handleCancel = useCallback(
(event: React.SyntheticEvent<HTMLDialogElement>) => {
+ // A `cancel` that bubbles up from inside is not a close request: a
+ // file input fires it when its picker is dismissed, so it is left alone.
if (event.target !== event.currentTarget) {
return;
}
@@ -479,28 +774,53 @@ function StandaloneBottomSheet({
[dismissOnLightInteraction, hasScrim],
);
+ const isExiting = !isOpen && isPresented;
+ // A covered sheet is blocked by the browser: the top sheet's modal dialog
+ // makes everything outside it inert, this dialog included. A covered sheet
+ // that contains no presented sheet is marked inert and hidden as well, so
+ // the state is explicit; one that does contain the top sheet is left alone,
+ // because inert on it would reach the top sheet too.
+ const isInert = isExiting || stackView.isBlocked;
+
return (
<dialog
{...stylex.props(
styles.dialog,
shouldPresent && styles.dialogOpen,
shouldPresent && styles.dialogPanelHost,
+ // The dialog is the panel's positioner, so the stack's recede
+ // transforms the dialog: panel, grabber and all shrink and lift as
+ // one. The backdrop is not a descendant and stays put.
+ ...stackPositionerStyles(stackView),
hasScrim && styles.scrim,
- hasScrim && !isOpen && isPresented && styles.scrimClosing,
+ hasScrim && isExiting && styles.scrimClosing,
!hasScrim && styles.dialogNonModal,
)}
ref={dialogRef}
+ // A non-modal sheet is hosted in the top layer as a manual popover
+ // (no light dismiss, no backdrop), so sheets order by presentation
+ // without a page-level z-index. Below the Popover API floor the
+ // attribute is inert and the sheet falls back to show(), in page
+ // stacking order (the documented reduced fallback).
+ popover={hasScrim ? undefined : 'manual'}
aria-label={label}
- aria-hidden={!isOpen && isPresented ? 'true' : undefined}
+ aria-hidden={isInert ? 'true' : undefined}
aria-modal={hasScrim && isOpen ? 'true' : undefined}
role={purpose === 'required' ? 'alertdialog' : undefined}
- inert={!isOpen && isPresented ? true : undefined}
+ inert={isInert ? true : undefined}
+ data-sheet-stack={
+ hasScrim ? stackStateAttribute(stackView, isOpen) : undefined
+ }
+ data-sheet-stack-depth={
+ hasScrim && stackView.depth > 0 ? stackView.depth : undefined
+ }
onCancel={handleCancel}
onClick={handleClick}>
<BottomSheetPanel
{...props}
ref={ref}
state={panelState}
+ isOpenRequested={isOpen}
height={height}
label={label}
snapPoints={snapPoints}
@@ -510,6 +830,7 @@ function StandaloneBottomSheet({
onDismiss={dismissOnLightInteraction}
onScrimOpacity={handleScrimOpacity}
onElementChange={handlePanelElementChange}
+ onMotionStart={handleMotionStart}
onMotionComplete={handleMotionComplete}>
<ModalAnnounceProvider
dialogRef={dialogRef}
@@ -517,7 +838,12 @@ function StandaloneBottomSheet({
<LayerDepthProvider>
{/* A sheet opened inside this one starts from Escape on. */}
<BottomSheetEscapeContext value>
- {children}
+ <BottomSheetHostContext
+ value={
+ isOpen ? OPEN_BOTTOM_SHEET_HOST : CLOSED_BOTTOM_SHEET_HOST
+ }>
+ {children}
+ </BottomSheetHostContext>
</BottomSheetEscapeContext>
</LayerDepthProvider>
</ModalAnnounceProvider>
@@ -563,6 +889,7 @@ function SwitcherBottomSheetItem({
onSheetEnterStart,
onSheetTransitionComplete,
onSheetScrimOpacityChange,
+ stackView,
dialogProps,
onDialogCancel,
onDialogClick,
@@ -583,6 +910,10 @@ function SwitcherBottomSheetItem({
const isPresented = phase !== 'hidden';
const isTopSheet = phase === 'active' || phase === 'entering';
const ownsScrim = hasValidSheetId && isScrimOwner(sheetId);
+ // The flow is one level of the bottom-sheet stack; a sheet outside the flow
+ // covering it blocks every step dialog, the way a covered standalone sheet
+ // is blocked. A step is also inactive on its own terms during a handoff.
+ const isBlocked = isInactive || (hasScrim && stackView.isBlocked);
const isHostSheet = hasValidSheetId && hostSheet === sheetId;
const dialogRef = useRef<HTMLDialogElement | null>(null);
const dialogModeRef = useRef<'modal' | 'non-modal' | null>(null);
@@ -796,8 +1127,18 @@ function SwitcherBottomSheetItem({
}
aria-labelledby={switcherAriaLabelledBy}
aria-modal={hasScrim && isInteractive ? 'true' : undefined}
- aria-hidden={isInactive ? 'true' : undefined}
- inert={isInactive ? true : undefined}
+ aria-hidden={isBlocked ? 'true' : undefined}
+ inert={isBlocked ? true : undefined}
+ data-sheet-stack={
+ hasScrim && isPresented
+ ? stackStateAttribute(stackView, activeSheet != null)
+ : undefined
+ }
+ data-sheet-stack-depth={
+ hasScrim && isPresented && stackView.depth > 0
+ ? stackView.depth
+ : undefined
+ }
role={purpose === 'required' ? 'alertdialog' : switcherDialogProps.role}
onCancel={onDialogCancel}
onClick={onDialogClick}
@@ -807,14 +1148,16 @@ function SwitcherBottomSheetItem({
styles.positioner,
!isPresented && styles.positionerHidden,
isTopSheet && styles.positionerTop,
+ ...(hasScrim ? stackPositionerStyles(stackView) : []),
)}
hidden={!isPresented}
- aria-hidden={isInactive ? 'true' : undefined}
- inert={isInactive ? true : undefined}>
+ aria-hidden={isBlocked ? 'true' : undefined}
+ inert={isBlocked ? true : undefined}>
<BottomSheetPanel
{...props}
ref={ref}
state={panelState}
+ isOpenRequested={hasValidSheetId && activeSheet === sheetId}
height={height}
label={label}
snapPoints={snapPoints}
@@ -828,7 +1171,10 @@ function SwitcherBottomSheetItem({
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. */}
+ it establishes a nested BottomSheetSwitcher of its own. A
+ standalone sheet in this step's content is presented only while
+ the step is the interactive one: it leaves when the step is left,
+ keeps its own isOpen, and returns with the step while still open. */}
<BottomSheetSwitcherContext value={null}>
<ModalAnnounceProvider
dialogRef={dialogRef}
@@ -836,7 +1182,14 @@ function SwitcherBottomSheetItem({
<LayerDepthProvider>
{/* A sheet opened inside this one starts from Escape on. */}
<BottomSheetEscapeContext value>
- {children}
+ <BottomSheetHostContext
+ value={
+ isInteractive
+ ? OPEN_BOTTOM_SHEET_HOST
+ : CLOSED_BOTTOM_SHEET_HOST
+ }>
+ {children}
+ </BottomSheetHostContext>
</BottomSheetEscapeContext>
</LayerDepthProvider>
</ModalAnnounceProvider>
diff --git a/packages/core/src/BottomSheet/BottomSheetHostContext.ts b/packages/core/src/BottomSheet/BottomSheetHostContext.ts
new file mode 100644
index 0000000000..150ce043ec
--- /dev/null
+++ b/packages/core/src/BottomSheet/BottomSheetHostContext.ts
@@ -0,0 +1,44 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file BottomSheetHostContext.ts
+ * @input React context
+ * @output Exports BottomSheetHostContext and its value type
+ * @position Internal to BottomSheet; how a sheet rendered inside another
+ * sheet's content learns whether that sheet is open
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/BottomSheet/BottomSheet.tsx
+ * - /packages/core/src/BottomSheet/BottomSheetSwitcher.tsx
+ * - /packages/core/src/BottomSheet/BottomSheetStacking.test.tsx
+ *
+ * A sheet rendered in another sheet's content is part of that sheet: it is
+ * presented only while its host is open, leaves with it, and comes back with
+ * it if its own `isOpen` is still true. Without this a host closing from code
+ * would leave the inner dialog open in the top layer with no box to paint —
+ * an invisible modal blocking the page. The inner sheet's state is never
+ * written by the host: it stays the consumer's, as with a Dialog rendered in
+ * a closed Dialog. The context is provided by every host (standalone, modal
+ * or not, and each switcher step) and read by every standalone sheet and
+ * every switcher flow; at the root it is null, which reads as "open".
+ */
+
+import {createContext} from 'react';
+
+export interface BottomSheetHostContextValue {
+ /** Whether the host sheet is open; a closing host reads false at once. */
+ isOpen: boolean;
+}
+
+export const BottomSheetHostContext =
+ createContext<BottomSheetHostContextValue | null>(null);
+BottomSheetHostContext.displayName = 'BottomSheetHostContext';
+
+export const OPEN_BOTTOM_SHEET_HOST: BottomSheetHostContextValue = {
+ isOpen: true,
+};
+export const CLOSED_BOTTOM_SHEET_HOST: BottomSheetHostContextValue = {
+ isOpen: false,
+};
diff --git a/packages/core/src/BottomSheet/BottomSheetPanel.test.tsx b/packages/core/src/BottomSheet/BottomSheetPanel.test.tsx
index 197b9e8e05..900f34051e 100644
--- a/packages/core/src/BottomSheet/BottomSheetPanel.test.tsx
+++ b/packages/core/src/BottomSheet/BottomSheetPanel.test.tsx
@@ -158,16 +158,26 @@ describe('BottomSheetPanel', () => {
});
it('completes immediately when the rendered transition is disabled', () => {
- vi.mocked(matchMedia).mockReturnValue({
- matches: true,
- media: '(prefers-reduced-motion: reduce)',
- onchange: null,
- addEventListener: vi.fn(),
- removeEventListener: vi.fn(),
- addListener: vi.fn(),
- removeListener: vi.fn(),
- dispatchEvent: vi.fn(),
- });
+ // The stylesheet decides reduced motion (its transform transition
+ // collapses under the preference); the gesture hook no longer pins an
+ // inline `none` for it, so this models a rendered `transition: none`
+ // directly, as a mid-drag reconcile writes.
+ const nativeGetComputedStyle = window.getComputedStyle;
+ const spy = vi
+ .spyOn(window, 'getComputedStyle')
+ .mockImplementation((element, pseudo) => {
+ const declaration = nativeGetComputedStyle(element, pseudo);
+ if (
+ element instanceof HTMLElement &&
+ element.classList.contains('astryx-bottom-sheet')
+ ) {
+ Object.defineProperty(declaration, 'transition', {
+ value: 'none',
+ configurable: true,
+ });
+ }
+ return declaration;
+ });
const onMotionComplete = vi.fn();
render(
<BottomSheetPanel
@@ -182,6 +192,7 @@ describe('BottomSheetPanel', () => {
);
expect(onMotionComplete).toHaveBeenCalledWith('entering');
+ spy.mockRestore();
});
it('derives its transition backstop from the rendered timing', () => {
diff --git a/packages/core/src/BottomSheet/BottomSheetPanel.tsx b/packages/core/src/BottomSheet/BottomSheetPanel.tsx
index c77b854739..7af3b3273d 100644
--- a/packages/core/src/BottomSheet/BottomSheetPanel.tsx
+++ b/packages/core/src/BottomSheet/BottomSheetPanel.tsx
@@ -34,7 +34,7 @@ import {
} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {BaseProps} from '../BaseProps';
-import {useDevWarning} from '../hooks';
+import {useDevWarning, useMediaQuery} from '../hooks';
import {useScrollableArea} from '../hooks/useScrollableArea';
import {
borderVars,
@@ -118,6 +118,17 @@ function snapPointsKeyFor(
return key;
}
+/**
+ * The queries `design:reduced-motion` names: reduced motion with a coarse
+ * primary pointer cross-fades (DR2); reduced motion otherwise changes at once
+ * (DR3). The cross-fade's ceiling is the record's 200 ms.
+ */
+const REDUCED_MOTION_COARSE =
+ '@media (prefers-reduced-motion: reduce) and (pointer: coarse)';
+export const REDUCED_MOTION_COARSE_QUERY =
+ '(prefers-reduced-motion: reduce) and (pointer: coarse)';
+const CROSS_FADE_MS = 200;
+
const styles = stylex.create({
sheet: {
pointerEvents: 'auto',
@@ -154,18 +165,34 @@ const styles = stylex.create({
overflow: 'hidden',
paddingBlockEnd: `calc(env(safe-area-inset-bottom, 0px) + ${OVERSCROLL_PADDING}px)`,
marginBlockEnd: `${-OVERSCROLL_PADDING}px`,
+ // Under reduced motion no transform runs (design:reduced-motion DR1). On
+ // a coarse primary pointer the entrance is an opacity-only cross-fade of
+ // at most 200 ms (DR2): the sheet appears at its resting place and fades
+ // in; a fine pointer gets the change at once (DR3), the 0.01s collapse.
transform: {
default: 'translateY(0)',
- '@starting-style': 'translateY(100%)',
+ '@starting-style': {
+ default: 'translateY(100%)',
+ '@media (prefers-reduced-motion: reduce)': 'translateY(0)',
+ },
+ },
+ opacity: {
+ default: 1,
+ '@starting-style': {
+ default: 1,
+ [REDUCED_MOTION_COARSE]: 0,
+ },
},
- opacity: 1,
transitionProperty: 'transform, opacity',
- transitionDuration: durationVars['--duration-medium'],
+ transitionDuration: {
+ default: durationVars['--duration-medium'],
+ '@media (prefers-reduced-motion: reduce)': {
+ default: '0.01s',
+ '@media (pointer: coarse)': `0.01s, ${CROSS_FADE_MS}ms`,
+ },
+ },
transitionTimingFunction: easeVars['--ease-standard'],
willChange: 'transform, opacity',
- '@media (prefers-reduced-motion: reduce)': {
- transitionDuration: '0.01s',
- },
},
/**
* The exit is its own motion, not the entrance played backwards.
@@ -186,9 +213,29 @@ const styles = stylex.create({
* scales the motion scale down (neutral's medium is 300ms against 410ms).
*/
sheetClosing: {
- transform: 'translateY(100%)',
+ // Under reduced motion the exit does not travel (DR1); on a coarse
+ // pointer it fades out where it is (DR2), at once on a fine one (DR3).
+ transform: {
+ default: 'translateY(100%)',
+ '@media (prefers-reduced-motion: reduce)': 'translateY(0)',
+ },
+ opacity: {
+ default: null,
+ [REDUCED_MOTION_COARSE]: 0,
+ },
transitionTimingFunction: 'cubic-bezier(0.3, 0, 0.6, 0.6)',
},
+ /**
+ * An exit that cross-fades on a pointer the media query does not cover: a
+ * touch swipe dismissal under reduced motion fades out in place on every
+ * pointer (design:reduced-motion DR2, the touch drag's release). The same
+ * opacity and ceiling the coarse-pointer rule uses.
+ */
+ sheetClosingCrossFade: {
+ transform: 'translateY(0)',
+ opacity: 0,
+ transitionDuration: `0.01s, ${CROSS_FADE_MS}ms`,
+ },
sheetFading: {
opacity: 0,
},
@@ -299,6 +346,13 @@ interface BottomSheetPanelProps extends BaseProps<HTMLDivElement> {
/** Ref forwarded to the visual sheet panel. */
ref?: React.Ref<HTMLDivElement>;
state: BottomSheetPanelState;
+ /**
+ * The host's controlled open state — false as soon as the host has taken
+ * a close, true while it is open or has refused one — distinct from
+ * `state`, which stays `open` until the close settles. Decides whether a
+ * swipe release's dismissal was honored (the reduced-motion cross-fade).
+ */
+ isOpenRequested?: boolean;
height: BottomSheetHeight | number | string;
/** Existing host name, reused for the keyboard scrolling group. */
label: string;
@@ -445,6 +499,7 @@ function parseTransitionTime(value: string): number | null {
export function BottomSheetPanel({
ref,
state,
+ isOpenRequested,
height,
label,
children,
@@ -492,7 +547,12 @@ export function BottomSheetPanel({
const isInactive = isRetained || state.kind === 'exiting';
const isClosing = state.kind === 'exiting';
const isFading = isRetained && state.motion === 'fading';
- const alignmentOffset = isRetained ? state.alignmentOffset : 0;
+ // Under reduced motion a retained sheet does not align down to a shorter
+ // entering sheet: that is travel (design:reduced-motion DR1). It fades where
+ // it is.
+ const isReducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)');
+ const alignmentOffset =
+ isRetained && !isReducedMotion ? state.alignmentOffset : 0;
// Everything derived from the snap points keys off their identity, not the
// array's: the resolver's identity is the hook's signal that the stops
@@ -534,6 +594,7 @@ export function BottomSheetPanel({
settledOffset,
isDragging,
isTraveling,
+ isDismissedByTouchDrag,
sheetHeight,
scrollPreservationInset,
settlingLayoutOffset,
@@ -541,6 +602,7 @@ export function BottomSheetPanel({
completeScrollAreaSettle,
} = useSheetGestures({
isOpen: isInteractive,
+ isOpenRequested: isOpenRequested ?? isInteractive,
canDismiss: isSwipeDismissAllowed,
offscreenBlockEndInset: OVERSCROLL_PADDING,
onDismiss,
@@ -595,6 +657,13 @@ export function BottomSheetPanel({
useImperativeHandle(ref, () => elementRef.current as HTMLDivElement, []);
const motion = motionForState(state);
+ // design:reduced-motion DR2: the cross-fade applies on a coarse pointer, and
+ // to a transition the release of a touch drag started — a finger's swipe
+ // dismissal fades out in place on every pointer. A mouse or pen drag is not
+ // a touch drag; DR3 covers it and the rest.
+ const isCoarseCrossFade = useMediaQuery(REDUCED_MOTION_COARSE_QUERY);
+ const isCrossFade =
+ isCoarseCrossFade || (isReducedMotion && isDismissedByTouchDrag);
useLayoutEffect(() => {
if (motion == null) {
return;
@@ -605,9 +674,16 @@ export function BottomSheetPanel({
pendingMotionCompleteRef.current = motion;
return;
}
+ // What ends a motion: the fade is opacity; the entrance, alignment and
+ // exit are transforms — except that under the reduced-motion cross-fade
+ // (DR2) an exit fades out where it is and its dialog may close only once
+ // the fade has ended, so it waits on opacity. The entrance keeps waiting
+ // on its (instant) transform, so the retained sheet's fade starts at once
+ // and the two fades cross; the alignment is instant.
+ const crossFadeMotion = isCrossFade && motion === 'exiting';
return waitForTransition(
elementRef.current,
- motion === 'fading' ? 'opacity' : 'transform',
+ motion === 'fading' || crossFadeMotion ? 'opacity' : 'transform',
() => {
if (startedMotionRef.current === motion) {
onMotionCompleteRef.current?.(motion);
@@ -616,7 +692,7 @@ export function BottomSheetPanel({
}
},
);
- }, [motion]);
+ }, [motion, isCrossFade]);
// The snap is transform-only; the layout height reconciles when it lands.
// waitForTransition — the same helper the motion states use — resolves that
// even when no `transitionend` is coming: inline or computed
@@ -744,6 +820,7 @@ export function BottomSheetPanel({
overlayPaddingReset.reset,
height === 'hug' ? styles.hugHeight : styles.budget,
isClosing && styles.sheetClosing,
+ isClosing && isCrossFade && styles.sheetClosingCrossFade,
isFading && styles.sheetFading,
isInactive && styles.sheetInactive,
xstyle,
diff --git a/packages/core/src/BottomSheet/BottomSheetReplace.test.tsx b/packages/core/src/BottomSheet/BottomSheetReplace.test.tsx
new file mode 100644
index 0000000000..28967e0403
--- /dev/null
+++ b/packages/core/src/BottomSheet/BottomSheetReplace.test.tsx
@@ -0,0 +1,1526 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file BottomSheetReplace.test.tsx
+ * @input Uses vitest, @testing-library/react, BottomSheet, BottomSheetSwitcher
+ * and the private bottom-sheet stack registry
+ * @output Tests for the replace handoff between standalone sheets: when a
+ * close and an open in one update are a replace and when they are not, the
+ * retained sheet's motion (covered, aligning, fading), one steady scrim,
+ * inertness and dismissal order, focus and the inherited opener, rapid
+ * reversal and dismissal during a handoff, non-modal sheets, and that
+ * switcher flows and lone sheets are untouched
+ * @position Core testing; validates the replace path of bottomSheetStack.ts
+ * and BottomSheet.tsx
+ *
+ * SYNC: When bottomSheetStack.ts or BottomSheet.tsx change the replace
+ * handoff, update these tests to match.
+ */
+
+import {act, fireEvent, render, screen} from '@testing-library/react';
+import {useEffect, useRef, useState} from 'react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {BottomSheet} from './BottomSheet';
+import {REDUCED_MOTION_COARSE_QUERY} from './BottomSheetPanel';
+import {BottomSheetSwitcher} from './BottomSheetSwitcher';
+import {
+ getBottomSheetStackForTests,
+ resetBottomSheetStackForTests,
+} from './bottomSheetStack';
+import {__resetInteractionModalityForTest} from '../utils/interactionModality';
+
+let nativeLog: {
+ call: 'showModal' | 'show' | 'close' | 'showPopover' | 'hidePopover';
+ dialog: HTMLElement;
+}[] = [];
+
+beforeEach(() => {
+ nativeLog = [];
+ resetBottomSheetStackForTests();
+ __resetInteractionModalityForTest();
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ nativeLog.push({call: 'showModal', dialog: this});
+ this.setAttribute('open', '');
+ });
+ HTMLDialogElement.prototype.show = vi.fn(function (this: HTMLDialogElement) {
+ nativeLog.push({call: 'show', dialog: this});
+ this.setAttribute('open', '');
+ });
+ // A non-modal sheet is a manual popover; jsdom's stand-ins keep the same
+ // `open` marker the dialog paths use (the Drawer tests do the same).
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ nativeLog.push({call: 'showPopover', dialog: this});
+ this.setAttribute('open', '');
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ nativeLog.push({call: 'hidePopover', dialog: this});
+ this.removeAttribute('open');
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ nativeLog.push({call: 'close', dialog: this});
+ this.removeAttribute('open');
+ });
+ if (!Element.prototype.setPointerCapture) {
+ Element.prototype.setPointerCapture = vi.fn();
+ Element.prototype.releasePointerCapture = vi.fn();
+ }
+ window.scrollTo = vi.fn();
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn().mockReturnValue({
+ matches: false,
+ media: '',
+ onchange: null,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ }),
+ );
+ vi.stubGlobal(
+ 'requestAnimationFrame',
+ vi.fn((callback: FrameRequestCallback) => {
+ callback(0);
+ return 1;
+ }),
+ );
+ vi.stubGlobal('cancelAnimationFrame', vi.fn());
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function getDialog(label: string): HTMLDialogElement {
+ const dialog = document.querySelector<HTMLDialogElement>(
+ `dialog[aria-label="${label}"]`,
+ );
+ if (dialog == null) {
+ throw new Error(`dialog "${label}" not found`);
+ }
+ return dialog;
+}
+
+function getPanel(dialog: HTMLElement): HTMLElement {
+ const panel = Array.from(
+ dialog.querySelectorAll<HTMLElement>('.astryx-bottom-sheet'),
+ ).find(candidate => candidate.closest('dialog') === dialog);
+ if (panel == null) {
+ throw new Error('sheet panel not found');
+ }
+ return panel;
+}
+
+function scrim(dialog: HTMLElement): string {
+ return dialog.style.getPropertyValue('--_sheet-scrim-opacity');
+}
+
+function calls(): string[] {
+ return nativeLog.map(
+ entry => `${entry.call}:${entry.dialog.getAttribute('aria-label') ?? '?'}`,
+ );
+}
+
+function openDialogs(): string[] {
+ return Array.from(document.querySelectorAll('dialog[open]')).map(
+ dialog => dialog.getAttribute('aria-label') ?? '?',
+ );
+}
+
+/** `label:state` for every registered sheet, bottom to top. */
+function summary(): string[] {
+ return getBottomSheetStackForTests().map(({element, isOpen, view}) => {
+ const label = element?.getAttribute('aria-label') ?? '?';
+ const state = isOpen
+ ? view.isReplacing
+ ? 'replacing'
+ : view.isTop
+ ? 'top'
+ : 'covered'
+ : view.replacedMotion != null
+ ? `replaced-${view.replacedMotion}`
+ : 'exiting';
+ return `${label}:${state}:${view.depth}`;
+ });
+}
+
+function endMotion(dialog: HTMLElement, propertyName: 'transform' | 'opacity') {
+ fireEvent.transitionEnd(getPanel(dialog), {propertyName});
+}
+
+function pressEscape(): void {
+ document.dispatchEvent(
+ new KeyboardEvent('keydown', {
+ key: 'Escape',
+ bubbles: true,
+ cancelable: true,
+ }),
+ );
+}
+
+/** Give an element a fixed box, the way the browser would lay it out. */
+function layout(element: HTMLElement, top: number, height: number) {
+ element.getBoundingClientRect = () => new DOMRect(0, top, 390, height);
+}
+
+type Step = 'one' | 'two' | 'three' | null;
+
+/**
+ * A three-step flow of standalone sheets: one state value names the open
+ * step, so moving on closes one sheet and opens the next in one update.
+ */
+function Flow({
+ hasScrim = true,
+ initialStep = null,
+ withBystander = false,
+ reversed = false,
+ twoHasAutofocusField = false,
+}: {
+ hasScrim?: boolean;
+ initialStep?: Step;
+ withBystander?: boolean;
+ /** Write the steps in reverse order in the tree (three, two, one). */
+ reversed?: boolean;
+ /** Step two carries a `data-autofocus` field. */
+ twoHasAutofocusField?: boolean;
+}) {
+ const [step, setStep] = useState<Step>(initialStep);
+ const [isBystanderOpen, setIsBystanderOpen] = useState(false);
+ const stepProps = (own: Step) => ({
+ isOpen: step === own,
+ onOpenChange: (isOpen: boolean) => {
+ if (!isOpen) {
+ setStep(current => (current === own ? null : current));
+ }
+ },
+ hasScrim,
+ });
+ const steps = [
+ <BottomSheet key="one" {...stepProps('one')} label="One">
+ <button type="button" onClick={() => setStep('two')}>
+ Continue to two
+ </button>
+ <button type="button" onClick={() => setIsBystanderOpen(true)}>
+ Open bystander
+ </button>
+ </BottomSheet>,
+ <BottomSheet key="two" {...stepProps('two')} label="Two">
+ {twoHasAutofocusField ? <input aria-label="Name" data-autofocus /> : null}
+ <button type="button" onClick={() => setStep('one')}>
+ Back to one
+ </button>
+ <button type="button" onClick={() => setStep('three')}>
+ Continue to three
+ </button>
+ <button type="button" onClick={() => setStep(null)}>
+ Finish
+ </button>
+ </BottomSheet>,
+ <BottomSheet key="three" {...stepProps('three')} label="Three">
+ <button type="button" onClick={() => setStep('two')}>
+ Back to two
+ </button>
+ </BottomSheet>,
+ ];
+ return (
+ <>
+ <button type="button" onClick={() => setStep('one')}>
+ Open flow
+ </button>
+ {withBystander ? (
+ <BottomSheet
+ isOpen={isBystanderOpen}
+ onOpenChange={setIsBystanderOpen}
+ label="Bystander">
+ bystander
+ </BottomSheet>
+ ) : null}
+ {reversed ? [...steps].reverse() : steps}
+ </>
+ );
+}
+
+/**
+ * A real tap: the press that a browser delivers before the click, and that
+ * the registry reads to know where the person acted from. A non-modal sheet
+ * never takes focus, so `activeElement` says nothing there; the press does.
+ */
+function tap(element: HTMLElement) {
+ fireEvent.pointerDown(element, {pointerId: 1, button: 0, isPrimary: true});
+ fireEvent.click(element);
+}
+
+function openFlow() {
+ const opener = screen.getByRole('button', {name: 'Open flow'});
+ opener.focus();
+ fireEvent.click(opener);
+ return opener;
+}
+
+// ---------------------------------------------------------------------------
+// R1: what is, and is not, a replace
+// ---------------------------------------------------------------------------
+
+describe('BottomSheet replace: recognising a replace', () => {
+ it('a top sheet closing while another opens in the same update is replaced', () => {
+ render(<Flow />);
+ openFlow();
+ expect(summary()).toEqual(['One:top:0']);
+ fireEvent.click(screen.getByRole('button', {name: 'Continue to two'}));
+ expect(summary()).toEqual(['One:replaced-covered:0', 'Two:replacing:0']);
+ expect(openDialogs()).toEqual(['One', 'Two']);
+ expect(getDialog('One')).toHaveAttribute('data-sheet-stack', 'replaced');
+ expect(getDialog('Two')).toHaveAttribute('data-sheet-stack', 'top');
+ expect(calls()).toEqual(['showModal:One', 'showModal:Two']);
+ });
+
+ it('a sheet opening over an open sheet is a push, not a replace', () => {
+ render(<Flow withBystander />);
+ openFlow();
+ fireEvent.click(screen.getByRole('button', {name: 'Open bystander'}));
+ expect(summary()).toEqual(['One:covered:1', 'Bystander:top:0']);
+ expect(getDialog('One')).toHaveAttribute('data-sheet-stack', 'covered');
+ });
+
+ it('a sheet closing on its own is a pop, not a replace', () => {
+ render(<Flow initialStep="two" />);
+ fireEvent.click(screen.getByRole('button', {name: 'Finish'}));
+ expect(summary()).toEqual(['Two:exiting:0']);
+ expect(getDialog('Two')).not.toHaveAttribute('data-sheet-stack');
+ });
+
+ it('a close and an open in different updates are a pop and a push', () => {
+ render(<Flow initialStep="two" />);
+ fireEvent.click(screen.getByRole('button', {name: 'Finish'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Open flow'}));
+ expect(summary()).toEqual(['Two:exiting:1', 'One:top:0']);
+ });
+
+ it('a covered sheet closing while a sheet opens is not a replace', () => {
+ // Bystander is open over step one; one update closes the covered step
+ // one (not the top) and opens step two: two pushes over the bystander
+ // and one slides out beneath it.
+ function Harness() {
+ const [isOneOpen, setIsOneOpen] = useState(true);
+ const [isBystanderOpen, setIsBystanderOpen] = useState(false);
+ const [isTwoOpen, setIsTwoOpen] = useState(false);
+ return (
+ <>
+ <button
+ type="button"
+ onClick={() => {
+ setIsOneOpen(false);
+ setIsTwoOpen(true);
+ }}>
+ Swap beneath
+ </button>
+ <BottomSheet
+ isOpen={isOneOpen}
+ onOpenChange={setIsOneOpen}
+ label="One">
+ <button type="button" onClick={() => setIsBystanderOpen(true)}>
+ Open bystander
+ </button>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={isBystanderOpen}
+ onOpenChange={setIsBystanderOpen}
+ label="Bystander">
+ x
+ </BottomSheet>
+ <BottomSheet
+ isOpen={isTwoOpen}
+ onOpenChange={setIsTwoOpen}
+ label="Two">
+ x
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<Harness />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open bystander'}));
+ expect(summary()).toEqual(['One:covered:1', 'Bystander:top:0']);
+ fireEvent.click(screen.getByRole('button', {name: 'Swap beneath'}));
+ expect(summary()).toEqual([
+ 'One:exiting:2',
+ 'Bystander:covered:1',
+ 'Two:top:0',
+ ]);
+ });
+
+ it('a switcher flow closing while a standalone sheet opens is never paired', () => {
+ function Harness() {
+ const [active, setActive] = useState<string | null>('step');
+ const [isSheetOpen, setIsSheetOpen] = useState(false);
+ return (
+ <>
+ <button
+ type="button"
+ onClick={() => {
+ setActive(null);
+ setIsSheetOpen(true);
+ }}>
+ Leave flow for sheet
+ </button>
+ <BottomSheetSwitcher
+ activeSheet={active}
+ onActiveSheetChange={setActive}
+ aria-label="Flow">
+ <BottomSheet sheetId="step" label="Step">
+ x
+ </BottomSheet>
+ </BottomSheetSwitcher>
+ <BottomSheet
+ isOpen={isSheetOpen}
+ onOpenChange={setIsSheetOpen}
+ label="Sheet">
+ x
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<Harness />);
+ fireEvent.click(screen.getByRole('button', {name: 'Leave flow for sheet'}));
+ expect(summary()).toEqual(['Flow:exiting:1', 'Sheet:top:0']);
+ });
+
+ it('a sheet on its own carries no replace state', () => {
+ render(<Flow />);
+ openFlow();
+ const [one] = getBottomSheetStackForTests();
+ expect(one.view).toMatchObject({
+ replacedMotion: null,
+ alignmentOffset: 0,
+ isReplacing: false,
+ isStacked: false,
+ });
+ expect(getDialog('One')).not.toHaveAttribute('data-sheet-stack');
+ expect(calls()).toEqual(['showModal:One']);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// R2: the handoff
+// ---------------------------------------------------------------------------
+
+describe('BottomSheet replace: the handoff', () => {
+ it('keeps the replaced sheet in place, inert and hidden, while the new sheet enters', () => {
+ render(<Flow />);
+ openFlow();
+ fireEvent.click(screen.getByRole('button', {name: 'Continue to two'}));
+ const one = getDialog('One');
+ const two = getDialog('Two');
+ expect(one.open).toBe(true);
+ expect(one).toHaveAttribute('inert');
+ expect(one).toHaveAttribute('aria-hidden', 'true');
+ expect(one).not.toHaveAttribute('aria-modal');
+ expect(two).toHaveAttribute('aria-modal', 'true');
+ expect(two).not.toHaveAttribute('inert');
+ // Not receded: a replaced sheet is at the new sheet's level, not under it.
+ expect(one).not.toHaveAttribute('data-sheet-stack-depth');
+ // The retained panel stays put (no exit transform) and takes no pointer.
+ expect(getPanel(one).style.transform).toBe('');
+ expect(getComputedStyle(getPanel(one)).pointerEvents).toBe('none');
+ });
+
+ it('fades the replaced sheet only after the entering motion completes, then closes its dialog', () => {
+ render(<Flow />);
+ openFlow();
+ fireEvent.click(screen.getByRole('button', {name: 'Continue to two'}));
+ const one = getDialog('One');
+ const two = getDialog('Two');
+ expect(summary()).toEqual(['One:replaced-covered:0', 'Two:replacing:0']);
+ endMotion(two, 'transform');
+ expect(summary()).toEqual(['One:replaced-fading:0', 'Two:replacing:0']);
+ expect(one.open).toBe(true);
+ endMotion(one, 'opacity');
+ expect(summary()).toEqual(['Two:top:0']);
+ expect(openDialogs()).toEqual(['Two']);
+ expect(calls()).toEqual(['showModal:One', 'showModal:Two', 'close:One']);
+ expect(two).not.toHaveAttribute('data-sheet-stack');
+ });
+
+ it('moves a taller replaced sheet down to the entering sheet, concurrently, and fades after both finish', () => {
+ render(<Flow />);
+ openFlow();
+ const one = getDialog('One');
+ const two = getDialog('Two');
+ // Step one is 400px tall; step two will rest 160px lower. The panels are
+ // mounted already, so lay them out before the switch: the alignment is
+ // measured when the entering motion starts.
+ layout(getPanel(one), 444, 400);
+ layout(getPanel(two).parentElement as HTMLElement, 604, 240);
+ fireEvent.click(screen.getByRole('button', {name: 'Continue to two'}));
+ expect(summary()).toEqual(['One:replaced-aligning:0', 'Two:replacing:0']);
+ expect(getPanel(one).style.transform).toBe('translateY(160px)');
+ // Entering finished first: wait for the alignment.
+ endMotion(two, 'transform');
+ expect(summary()).toEqual(['One:replaced-aligning:0', 'Two:replacing:0']);
+ endMotion(one, 'transform');
+ expect(summary()).toEqual(['One:replaced-fading:0', 'Two:replacing:0']);
+ endMotion(one, 'opacity');
+ expect(summary()).toEqual(['Two:top:0']);
+ });
+
+ it('waits for the entering motion when the alignment finishes first', () => {
+ render(<Flow />);
+ openFlow();
+ const one = getDialog('One');
+ const two = getDialog('Two');
+ layout(getPanel(one), 444, 400);
+ layout(getPanel(two).parentElement as HTMLElement, 604, 240);
+ fireEvent.click(screen.getByRole('button', {name: 'Continue to two'}));
+ endMotion(one, 'transform');
+ expect(summary()).toEqual(['One:replaced-aligning:0', 'Two:replacing:0']);
+ endMotion(two, 'transform');
+ expect(summary()).toEqual(['One:replaced-fading:0', 'Two:replacing:0']);
+ });
+
+ it('leaves a shorter replaced sheet where it is', () => {
+ render(<Flow />);
+ openFlow();
+ const one = getDialog('One');
+ const two = getDialog('Two');
+ layout(getPanel(one), 604, 240);
+ layout(getPanel(two).parentElement as HTMLElement, 444, 400);
+ fireEvent.click(screen.getByRole('button', {name: 'Continue to two'}));
+ expect(summary()).toEqual(['One:replaced-covered:0', 'Two:replacing:0']);
+ expect(getPanel(one).style.transform).toBe('');
+ });
+
+ it('keeps the scrim on the replaced sheet and hands it to the new sheet with no fade', () => {
+ render(<Flow />);
+ openFlow();
+ fireEvent.click(screen.getByRole('button', {name: 'Continue to two'}));
+ const one = getDialog('One');
+ const two = getDialog('Two');
+ expect(scrim(one)).toBe('1');
+ expect(scrim(two)).toBe('0');
+ // The flip to 1 lands with the transition pinned to 0s (rAF is
+ // synchronous here, so the pin is lifted again by the time we look).
+ const pins: string[] = [];
+ const setProperty = CSSStyleDeclaration.prototype.setProperty;
+ CSSStyleDeclaration.prototype.setProperty = function (name, value) {
+ if (
+ this === two.style &&
+ name === '--_sheet-scrim-opacity' &&
+ value === '1'
+ ) {
+ pins.push(this.getPropertyValue('--_sheet-scrim-duration'));
+ }
+ return setProperty.call(this, name, value);
+ };
+ endMotion(two, 'transform');
+ endMotion(one, 'opacity');
+ CSSStyleDeclaration.prototype.setProperty = setProperty;
+ expect(scrim(two)).toBe('1');
+ expect(pins[0]).toBe('0s');
+ expect(two.style.getPropertyValue('--_sheet-scrim-duration')).toBe('');
+ expect(one.open).toBe(false);
+ });
+
+ it('runs the replace one level up a stack and leaves the sheet beneath covered', () => {
+ function Harness() {
+ const [isBaseOpen, setIsBaseOpen] = useState(true);
+ const [step, setStep] = useState<'a' | 'b' | null>('a');
+ return (
+ <>
+ <BottomSheet
+ isOpen={isBaseOpen}
+ onOpenChange={setIsBaseOpen}
+ label="Base">
+ x
+ </BottomSheet>
+ <BottomSheet
+ isOpen={step === 'a'}
+ onOpenChange={o => !o && setStep(null)}
+ label="A">
+ <button type="button" onClick={() => setStep('b')}>
+ Next
+ </button>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={step === 'b'}
+ onOpenChange={o => !o && setStep(null)}
+ label="B">
+ x
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<Harness />);
+ expect(summary()).toEqual(['Base:covered:1', 'A:top:0']);
+ fireEvent.click(screen.getByRole('button', {name: 'Next'}));
+ expect(summary()).toEqual([
+ 'Base:covered:1',
+ 'A:replaced-covered:0',
+ 'B:replacing:0',
+ ]);
+ expect(scrim(getDialog('Base'))).toBe('1');
+ expect(scrim(getDialog('A'))).toBe('0');
+ expect(scrim(getDialog('B'))).toBe('0');
+ endMotion(getDialog('B'), 'transform');
+ endMotion(getDialog('A'), 'opacity');
+ expect(summary()).toEqual(['Base:covered:1', 'B:top:0']);
+ expect(scrim(getDialog('Base'))).toBe('1');
+ expect(scrim(getDialog('B'))).toBe('0');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// R3: focus, dismissal, and interruptions
+// ---------------------------------------------------------------------------
+
+describe('BottomSheet replace: focus and dismissal', () => {
+ it('moves focus into the entering sheet and keeps it there when the replaced dialog closes', () => {
+ render(<Flow />);
+ openFlow();
+ const one = getDialog('One');
+ const two = getDialog('Two');
+ const next = screen.getByRole('button', {name: 'Continue to two'});
+ next.focus();
+ fireEvent.click(next);
+ expect(document.activeElement).toBe(getPanel(two));
+ endMotion(two, 'transform');
+ endMotion(one, 'opacity');
+ expect(document.activeElement).toBe(getPanel(two));
+ });
+
+ it.each([
+ ['modal', true],
+ ['non-modal', false],
+ ] as const)(
+ 'a %s step entering by a replace focuses its data-autofocus field, even though the native focusing steps already put focus on its panel',
+ (_name, hasScrim) => {
+ // What a browser does: showModal() (or the panel focus of a non-modal
+ // host) moves focus to the entering panel before the registry places
+ // it. The stubs here reproduce that instead of leaving focus on the
+ // pressed button, so the placement has to run after the native steps
+ // and must not stop at "focus is already inside".
+ const focusPanelOnShow = function (this: HTMLElement) {
+ this.setAttribute('open', '');
+ this.querySelector<HTMLElement>('.astryx-bottom-sheet')?.focus();
+ };
+ HTMLDialogElement.prototype.showModal = vi.fn(focusPanelOnShow);
+ HTMLElement.prototype.showPopover = vi.fn(focusPanelOnShow);
+ render(<Flow hasScrim={hasScrim} twoHasAutofocusField />);
+ openFlow();
+ const two = getDialog('Two');
+ const next = screen.getByRole('button', {name: 'Continue to two'});
+ next.focus();
+ fireEvent.click(next);
+ const field = screen.getByRole('textbox', {name: 'Name'});
+ expect(two.contains(field)).toBe(true);
+ expect(document.activeElement).toBe(field);
+ endMotion(two, 'transform');
+ endMotion(getDialog('One'), 'opacity');
+ expect(document.activeElement).toBe(field);
+ },
+ );
+
+ it('a step entering by a replace without a data-autofocus field keeps the focus the native steps put on its panel', () => {
+ HTMLDialogElement.prototype.showModal = vi.fn(function (this: HTMLElement) {
+ this.setAttribute('open', '');
+ this.querySelector<HTMLElement>('.astryx-bottom-sheet')?.focus();
+ });
+ render(<Flow />);
+ openFlow();
+ const two = getDialog('Two');
+ const next = screen.getByRole('button', {name: 'Continue to two'});
+ next.focus();
+ fireEvent.click(next);
+ expect(document.activeElement).toBe(getPanel(two));
+ });
+
+ it('returns focus to the element that opened the flow when the replacing sheet closes it', () => {
+ render(<Flow />);
+ const opener = openFlow();
+ const next = screen.getByRole('button', {name: 'Continue to two'});
+ next.focus();
+ fireEvent.click(next);
+ const one = getDialog('One');
+ const two = getDialog('Two');
+ endMotion(two, 'transform');
+ endMotion(one, 'opacity');
+ fireEvent.click(screen.getByRole('button', {name: 'Finish'}));
+ endMotion(two, 'transform');
+ expect(openDialogs()).toEqual([]);
+ expect(document.activeElement).toBe(opener);
+ });
+
+ it('routes Escape to the replacing sheet, not the replaced one, during the handoff', () => {
+ render(<Flow />);
+ openFlow();
+ fireEvent.click(screen.getByRole('button', {name: 'Continue to two'}));
+ act(() => {
+ pressEscape();
+ });
+ // Two closed the flow; one was dropped at once; both leave.
+ expect(summary()).toEqual(['Two:exiting:0']);
+ expect(getDialog('One').open).toBe(false);
+ expect(getDialog('Two').open).toBe(true);
+ });
+
+ it('routes Escape to the sheet that came back, during a reversal', () => {
+ render(<Flow initialStep="two" />);
+ fireEvent.click(screen.getByRole('button', {name: 'Back to one'}));
+ expect(summary()).toEqual(['Two:replaced-covered:0', 'One:replacing:0']);
+ act(() => {
+ pressEscape();
+ });
+ expect(summary()).toEqual(['One:exiting:0']);
+ });
+
+ it('drops the replaced sheet at once when the replacing sheet is dismissed mid-handoff', () => {
+ render(<Flow />);
+ openFlow();
+ fireEvent.click(screen.getByRole('button', {name: 'Continue to two'}));
+ const one = getDialog('One');
+ const two = getDialog('Two');
+ fireEvent.click(screen.getByRole('button', {name: 'Finish'}));
+ expect(one.open).toBe(false);
+ expect(two.open).toBe(true);
+ expect(scrim(two)).toBe('0');
+ endMotion(two, 'transform');
+ expect(openDialogs()).toEqual([]);
+ });
+
+ it('a reversal mid-handoff replaces the replacing sheet with the one coming back, on top', () => {
+ render(<Flow />);
+ openFlow();
+ fireEvent.click(screen.getByRole('button', {name: 'Continue to two'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Back to one'}));
+ // One was already in place: its entrance completes at once and two
+ // fades straight away, as a switcher step coming back does.
+ expect(summary()).toEqual(['Two:replaced-fading:0', 'One:replacing:0']);
+ const one = getDialog('One');
+ const two = getDialog('Two');
+ expect(one.open).toBe(true);
+ expect(two.open).toBe(true);
+ // Only one is re-shown, above two; two keeps its place, its backdrop
+ // (the scrim stays with the retained sheet) and its motion in flight.
+ expect(calls()).toEqual([
+ 'showModal:One',
+ 'showModal:Two',
+ 'close:One',
+ 'showModal:One',
+ ]);
+ expect(scrim(two)).toBe('1');
+ expect(scrim(one)).toBe('0');
+ expect(getPanel(one).style.transform).toBe('');
+ expect(document.activeElement).toBe(getPanel(one));
+ endMotion(two, 'opacity');
+ expect(summary()).toEqual(['One:top:0']);
+ expect(scrim(one)).toBe('1');
+ });
+
+ describe.each([
+ {order: 'flow order', reversed: false},
+ {order: 'reverse order', reversed: true},
+ ])('reversals with the steps written in $order', ({reversed}) => {
+ it('Back during a Continue handoff: the returning step takes over at once and the entering step fades', () => {
+ render(<Flow reversed={reversed} />);
+ openFlow();
+ fireEvent.click(screen.getByRole('button', {name: 'Continue to two'}));
+ expect(summary()).toEqual(['One:replaced-covered:0', 'Two:replacing:0']);
+ fireEvent.click(screen.getByRole('button', {name: 'Back to one'}));
+ // One was in place: the fade starts in this very update.
+ expect(summary()).toEqual(['Two:replaced-fading:0', 'One:replacing:0']);
+ expect(getDialog('One').open).toBe(true);
+ expect(getDialog('Two').open).toBe(true);
+ endMotion(getDialog('Two'), 'opacity');
+ expect(summary()).toEqual(['One:top:0']);
+ expect(openDialogs()).toEqual(['One']);
+ });
+
+ it('Continue during a Back handoff: the returning step takes over at once and the entering step fades', () => {
+ render(<Flow reversed={reversed} initialStep="two" />);
+ fireEvent.click(screen.getByRole('button', {name: 'Back to one'}));
+ expect(summary()).toEqual(['Two:replaced-covered:0', 'One:replacing:0']);
+ fireEvent.click(screen.getByRole('button', {name: 'Continue to two'}));
+ // Two was in place: it is not dropped by One's close, it comes back
+ // and One fades in this very update.
+ expect(summary()).toEqual(['One:replaced-fading:0', 'Two:replacing:0']);
+ expect(getDialog('One').open).toBe(true);
+ expect(getDialog('Two').open).toBe(true);
+ expect(document.activeElement).toBe(getPanel(getDialog('Two')));
+ endMotion(getDialog('One'), 'opacity');
+ expect(summary()).toEqual(['Two:top:0']);
+ expect(openDialogs()).toEqual(['Two']);
+ });
+
+ it('a double reversal lands on the step last chosen, with one retained sheet fading', () => {
+ render(<Flow reversed={reversed} />);
+ openFlow();
+ fireEvent.click(screen.getByRole('button', {name: 'Continue to two'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Back to one'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Continue to two'}));
+ expect(summary()).toEqual(['One:replaced-fading:0', 'Two:replacing:0']);
+ endMotion(getDialog('One'), 'opacity');
+ expect(summary()).toEqual(['Two:top:0']);
+ });
+ });
+
+ it('after a reversal, closing the flow still returns focus to the flow’s opener', () => {
+ render(<Flow />);
+ const opener = openFlow();
+ tap(screen.getByRole('button', {name: 'Continue to two'}));
+ tap(screen.getByRole('button', {name: 'Back to one'}));
+ endMotion(getDialog('Two'), 'opacity');
+ expect(summary()).toEqual(['One:top:0']);
+ act(() => {
+ fireEvent.keyDown(getDialog('One'), {key: 'Escape'});
+ });
+ endMotion(getDialog('One'), 'transform');
+ expect(openDialogs()).toEqual([]);
+ expect(document.activeElement).toBe(opener);
+ });
+
+ it('a third step mid-handoff drops the first step at once', () => {
+ render(<Flow />);
+ openFlow();
+ fireEvent.click(screen.getByRole('button', {name: 'Continue to two'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Continue to three'}));
+ expect(getDialog('One').open).toBe(false);
+ expect(summary()).toEqual(['Two:replaced-covered:0', 'Three:replacing:0']);
+ });
+
+ it('a purpose on the replacing sheet governs dismissal', () => {
+ function Harness() {
+ const [step, setStep] = useState<'a' | 'b' | null>('a');
+ return (
+ <>
+ <BottomSheet
+ isOpen={step === 'a'}
+ onOpenChange={o => !o && setStep(null)}
+ label="A">
+ <button type="button" onClick={() => setStep('b')}>
+ Next
+ </button>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={step === 'b'}
+ onOpenChange={o => !o && setStep(null)}
+ purpose="required"
+ label="B">
+ x
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<Harness />);
+ fireEvent.click(screen.getByRole('button', {name: 'Next'}));
+ act(() => {
+ pressEscape();
+ });
+ expect(summary()).toEqual(['A:replaced-covered:0', 'B:replacing:0']);
+ expect(getDialog('B')).toHaveAttribute('role', 'alertdialog');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// R4: the boundary — who acted, from where
+// ---------------------------------------------------------------------------
+
+/** A step flow whose step change comes from code, after a delay. */
+function Timed() {
+ const [step, setStep] = useState<Step>('one');
+ return (
+ <>
+ <BottomSheet
+ isOpen={step === 'one'}
+ onOpenChange={open => !open && setStep(null)}
+ label="One">
+ <button
+ type="button"
+ onClick={() => {
+ setTimeout(() => setStep('two'), 500);
+ }}>
+ Save and continue
+ </button>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={step === 'two'}
+ onOpenChange={open => !open && setStep(null)}
+ label="Two">
+ two
+ </BottomSheet>
+ </>
+ );
+}
+
+/**
+ * A flow whose middle step is an interstitial advanced by code: Submit in
+ * Form opens Processing by press; Processing moves on to Done 300 ms later
+ * on its own, well inside the press's freshness window.
+ */
+function Interstitial({onDone}: {onDone?: () => void}) {
+ const [step, setStep] = useState<'form' | 'processing' | 'done' | null>(null);
+ return (
+ <>
+ <button type="button" onClick={() => setStep('form')}>
+ Open form
+ </button>
+ <BottomSheet
+ isOpen={step === 'form'}
+ onOpenChange={open => !open && setStep(null)}
+ label="Form">
+ <button type="button" onClick={() => setStep('processing')}>
+ Submit
+ </button>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={step === 'processing'}
+ onOpenChange={open => !open && setStep(null)}
+ label="Processing">
+ <Advance onElapsed={() => setStep('done')} />
+ </BottomSheet>
+ <BottomSheet
+ isOpen={step === 'done'}
+ onOpenChange={open => !open && setStep(null)}
+ label="Done">
+ <button
+ type="button"
+ onClick={() => {
+ setStep(null);
+ onDone?.();
+ }}>
+ Close
+ </button>
+ </BottomSheet>
+ </>
+ );
+}
+
+function Advance({onElapsed}: {onElapsed: () => void}) {
+ const onElapsedRef = useRef(onElapsed);
+ onElapsedRef.current = onElapsed;
+ useEffect(() => {
+ const id = setTimeout(() => onElapsedRef.current(), 300);
+ return () => clearTimeout(id);
+ }, []);
+ return <span>Processing…</span>;
+}
+
+/**
+ * `matchMedia` answering true for exactly the queries given; the rest of the
+ * stub shape matches the file-level one.
+ */
+function stubMedia(matching: ReadonlyArray<string>): void {
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn((query: string) => ({
+ matches: matching.includes(query),
+ media: query,
+ onchange: null,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ })),
+ );
+}
+
+describe('BottomSheet replace: reduced motion (design:reduced-motion)', () => {
+ // The CSS itself (no transform travel, an opacity-only cross-fade of at
+ // most 200 ms on a coarse pointer, an immediate change on a fine one) is
+ // real-browser evidence; here is what ends each motion in each class.
+ it('coarse pointer (DR2): an exit ends on its opacity fade, not a transform, and a handoff still closes the retained step after its fade', () => {
+ stubMedia([REDUCED_MOTION_COARSE_QUERY]);
+ render(<Flow />);
+ openFlow();
+ const one = getDialog('One');
+ fireEvent.click(screen.getByRole('button', {name: 'Continue to two'}));
+ const two = getDialog('Two');
+ expect(summary()).toEqual(['One:replaced-covered:0', 'Two:replacing:0']);
+ // The entering transform is instant; the retained step then fades.
+ endMotion(two, 'transform');
+ expect(one).toHaveAttribute('open');
+ endMotion(one, 'opacity');
+ expect(one).not.toHaveAttribute('open');
+ expect(summary()).toEqual(['Two:top:0']);
+ // A lone exit fades out where it is: a transform end does not close it.
+ fireEvent.click(screen.getByRole('button', {name: 'Finish'}));
+ endMotion(two, 'transform');
+ expect(two).toHaveAttribute('open');
+ endMotion(two, 'opacity');
+ expect(two).not.toHaveAttribute('open');
+ expect(openDialogs()).toEqual([]);
+ });
+
+ it('fine pointer (DR3): an exit ends on its (collapsed) transform, as without the preference', () => {
+ stubMedia(['(prefers-reduced-motion: reduce)']);
+ render(<Flow />);
+ openFlow();
+ const one = getDialog('One');
+ fireEvent.click(screen.getByRole('button', {name: 'Continue to two'}));
+ const two = getDialog('Two');
+ endMotion(two, 'transform');
+ endMotion(one, 'opacity');
+ expect(summary()).toEqual(['Two:top:0']);
+ fireEvent.click(screen.getByRole('button', {name: 'Finish'}));
+ endMotion(two, 'transform');
+ expect(two).not.toHaveAttribute('open');
+ expect(openDialogs()).toEqual([]);
+ });
+});
+
+describe('BottomSheet replace: a press is spent by the replace it made', () => {
+ it('a step advanced by code shortly after a Submit press replaces the interstitial, and the final close returns to the opener', () => {
+ vi.useFakeTimers();
+ try {
+ render(<Interstitial />);
+ const opener = screen.getByRole('button', {name: 'Open form'});
+ opener.focus();
+ fireEvent.click(opener);
+ const submit = screen.getByRole('button', {name: 'Submit'});
+ submit.focus();
+ fireEvent.click(submit);
+ // Submit's press made Form → Processing a replace…
+ expect(summary()).toEqual([
+ 'Form:replaced-covered:0',
+ 'Processing:replacing:0',
+ ]);
+ endMotion(getDialog('Processing'), 'transform');
+ endMotion(getDialog('Form'), 'opacity');
+ // …and is consumed by it: 300 ms later, still inside the press window,
+ // the code-driven advance is judged by focus, which is in Processing.
+ act(() => {
+ vi.advanceTimersByTime(300);
+ });
+ expect(summary()).toEqual([
+ 'Processing:replaced-covered:0',
+ 'Done:replacing:0',
+ ]);
+ endMotion(getDialog('Done'), 'transform');
+ endMotion(getDialog('Processing'), 'opacity');
+ fireEvent.click(screen.getByRole('button', {name: 'Close'}));
+ endMotion(getDialog('Done'), 'transform');
+ expect(openDialogs()).toEqual([]);
+ expect(opener).toHaveFocus();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
+describe('BottomSheet replace: unrelated owners', () => {
+ /**
+ * Two owners that know nothing of each other, in one tree: X owns sheet A
+ * and its opener, Y owns sheet B and its opener. A page control closes A
+ * and opens B in one update.
+ */
+ function TwoOwners() {
+ const [isAOpen, setIsAOpen] = useState(false);
+ const [isBOpen, setIsBOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsAOpen(true)}>
+ Open A
+ </button>
+ <button type="button" onClick={() => setIsBOpen(true)}>
+ Open B
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ setIsAOpen(false);
+ setIsBOpen(true);
+ }}>
+ Swap from page
+ </button>
+ <BottomSheet isOpen={isAOpen} onOpenChange={setIsAOpen} label="A">
+ <button
+ type="button"
+ onClick={() => {
+ setIsAOpen(false);
+ setIsBOpen(true);
+ }}>
+ Swap from A
+ </button>
+ </BottomSheet>
+ <BottomSheet isOpen={isBOpen} onOpenChange={setIsBOpen} label="B">
+ <button type="button" onClick={() => setIsBOpen(false)}>
+ Close B
+ </button>
+ </BottomSheet>
+ </>
+ );
+ }
+
+ it('a close and an open driven from a control outside the closing sheet are a pop and a push, each with its own opener', () => {
+ render(<TwoOwners />);
+ const openA = screen.getByRole('button', {name: 'Open A'});
+ openA.focus();
+ fireEvent.click(openA);
+ const swap = screen.getByRole('button', {name: 'Swap from page'});
+ swap.focus();
+ fireEvent.click(swap);
+ // Not a replace: A slides out beneath B, B is a fresh push.
+ expect(summary()).toEqual(['A:exiting:1', 'B:top:0']);
+ expect(getDialog('A')).toHaveAttribute('data-sheet-stack', 'exiting');
+ expect(getDialog('A')).not.toHaveAttribute('data-sheet-stack', 'replaced');
+ endMotion(getDialog('A'), 'transform');
+ expect(summary()).toEqual(['B:top:0']);
+ // B's opener is its own (the control that opened it), not A's.
+ fireEvent.click(screen.getByRole('button', {name: 'Close B'}));
+ endMotion(getDialog('B'), 'transform');
+ expect(swap).toHaveFocus();
+ expect(openA).not.toHaveFocus();
+ });
+
+ it('the same close and open driven from inside the closing sheet are a replace', () => {
+ render(<TwoOwners />);
+ const openA = screen.getByRole('button', {name: 'Open A'});
+ openA.focus();
+ fireEvent.click(openA);
+ // Focus is in A (its panel took it on open).
+ fireEvent.click(screen.getByRole('button', {name: 'Swap from A'}));
+ expect(summary()).toEqual(['A:replaced-covered:0', 'B:replacing:0']);
+ endMotion(getDialog('B'), 'transform');
+ endMotion(getDialog('A'), 'opacity');
+ fireEvent.click(screen.getByRole('button', {name: 'Close B'}));
+ endMotion(getDialog('B'), 'transform');
+ // The flow began at A's opener, so that is where it returns.
+ expect(openA).toHaveFocus();
+ });
+
+ it('reads the press, not focus: a tap inside the closing sheet replaces even when nothing in it is focused', () => {
+ render(<TwoOwners />);
+ const openA = screen.getByRole('button', {name: 'Open A'});
+ openA.focus();
+ fireEvent.click(openA);
+ // Focus leaves the sheet (a browser that does not focus clicked buttons,
+ // or the person tabbed out); the tap still comes from inside A.
+ document.body.focus();
+ tap(screen.getByRole('button', {name: 'Swap from A'}));
+ expect(summary()).toEqual(['A:replaced-covered:0', 'B:replacing:0']);
+ });
+
+ it('reads the press, not focus: a tap outside the closing sheet is not a replace even with focus still inside it', () => {
+ render(<TwoOwners />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open A'}));
+ expect(document.activeElement).toBe(getPanel(getDialog('A')));
+ // Focus is in A's panel (it took it on open); the press is on the page.
+ tap(screen.getByRole('button', {name: 'Swap from page'}));
+ expect(summary()).toEqual(['A:exiting:1', 'B:top:0']);
+ });
+
+ it('a step flow whose steps are wrapped in their own components still replaces', () => {
+ function Step({
+ name,
+ step,
+ setStep,
+ next,
+ }: {
+ name: Step;
+ step: Step;
+ setStep: (step: Step) => void;
+ next: Step;
+ }) {
+ return (
+ <div>
+ <BottomSheet
+ isOpen={step === name}
+ onOpenChange={open => !open && setStep(null)}
+ label={String(name)}>
+ <button type="button" onClick={() => setStep(next)}>
+ Go to {next}
+ </button>
+ </BottomSheet>
+ </div>
+ );
+ }
+ function Wizard() {
+ const [step, setStep] = useState<Step>(null);
+ return (
+ <>
+ <button type="button" onClick={() => setStep('one')}>
+ Start
+ </button>
+ <Step name="one" step={step} setStep={setStep} next="two" />
+ <Step name="two" step={step} setStep={setStep} next="three" />
+ <Step name="three" step={step} setStep={setStep} next={null} />
+ </>
+ );
+ }
+ render(<Wizard />);
+ const start = screen.getByRole('button', {name: 'Start'});
+ start.focus();
+ fireEvent.click(start);
+ fireEvent.click(screen.getByRole('button', {name: 'Go to two'}));
+ expect(summary()).toEqual(['one:replaced-covered:0', 'two:replacing:0']);
+ endMotion(getDialog('two'), 'transform');
+ endMotion(getDialog('one'), 'opacity');
+ fireEvent.click(screen.getByRole('button', {name: 'Go to three'}));
+ expect(summary()).toEqual(['two:replaced-covered:0', 'three:replacing:0']);
+ endMotion(getDialog('three'), 'transform');
+ endMotion(getDialog('two'), 'opacity');
+ fireEvent.click(screen.getByRole('button', {name: 'Go to'}));
+ endMotion(getDialog('three'), 'transform');
+ expect(openDialogs()).toEqual([]);
+ expect(start).toHaveFocus();
+ });
+
+ it('a step change made by code while focus is in the step is a replace (focus cannot be anywhere else under a modal sheet)', () => {
+ vi.useFakeTimers();
+ try {
+ render(<Timed />);
+ fireEvent.click(screen.getByRole('button', {name: 'Save and continue'}));
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ expect(summary()).toEqual(['One:replaced-covered:0', 'Two:replacing:0']);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('a press only counts while fresh: an old key press elsewhere does not veto a later replace', () => {
+ vi.useFakeTimers();
+ try {
+ render(<Timed />);
+ // A key pressed on the page a while ago (its target is outside the
+ // sheet); then the sheet's own control, by code, moves the flow on.
+ fireEvent.keyDown(document.body, {key: 'Shift'});
+ act(() => {
+ vi.advanceTimersByTime(1500);
+ });
+ fireEvent.click(screen.getByRole('button', {name: 'Save and continue'}));
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ expect(summary()).toEqual(['One:replaced-covered:0', 'Two:replacing:0']);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
+// ---------------------------------------------------------------------------
+// R5: non-modal sheets take no part
+// ---------------------------------------------------------------------------
+
+describe('BottomSheet replace: several sheets changing in one update', () => {
+ // A open; B opened from A; a control in B closes A and B and opens C in one
+ // handler. Two closes and one open is not a replace, whichever order the
+ // sheets are written in — the pairing is decided by the commit's final
+ // tally, not by which flips the registry heard first.
+ function ThreeSheets({order}: {order: 'ABC' | 'CBA'}) {
+ const [isAOpen, setIsAOpen] = useState(false);
+ const [isBOpen, setIsBOpen] = useState(false);
+ const [isCOpen, setIsCOpen] = useState(false);
+ const a = (
+ <BottomSheet key="A" isOpen={isAOpen} onOpenChange={setIsAOpen} label="A">
+ <button type="button" onClick={() => setIsBOpen(true)}>
+ Open B
+ </button>
+ </BottomSheet>
+ );
+ const b = (
+ <BottomSheet key="B" isOpen={isBOpen} onOpenChange={setIsBOpen} label="B">
+ <button
+ type="button"
+ onClick={() => {
+ setIsAOpen(false);
+ setIsBOpen(false);
+ setIsCOpen(true);
+ }}>
+ Finish to C
+ </button>
+ </BottomSheet>
+ );
+ const c = (
+ <BottomSheet key="C" isOpen={isCOpen} onOpenChange={setIsCOpen} label="C">
+ <button type="button" onClick={() => setIsCOpen(false)}>
+ Close C
+ </button>
+ </BottomSheet>
+ );
+ return (
+ <>
+ <button type="button" onClick={() => setIsAOpen(true)}>
+ Open A
+ </button>
+ {order === 'ABC' ? [a, b, c] : [c, b, a]}
+ </>
+ );
+ }
+
+ for (const order of ['ABC', 'CBA'] as const) {
+ it(`two closes and one open from inside the top sheet are a pop, a pop and a push, written ${order}`, () => {
+ render(<ThreeSheets order={order} />);
+ const openA = screen.getByRole('button', {name: 'Open A'});
+ openA.focus();
+ fireEvent.click(openA);
+ fireEvent.click(screen.getByRole('button', {name: 'Open B'}));
+ expect(summary()).toEqual(['A:covered:1', 'B:top:0']);
+ fireEvent.click(screen.getByRole('button', {name: 'Finish to C'}));
+ // Neither A nor B is replaced; C is a fresh push above the two exits.
+ expect(getDialog('A')).toHaveAttribute('data-sheet-stack', 'exiting');
+ expect(getDialog('B')).toHaveAttribute('data-sheet-stack', 'exiting');
+ expect(getDialog('C')).toHaveAttribute('data-sheet-stack', 'top');
+ expect(getDialog('A')).not.toHaveAttribute(
+ 'data-sheet-stack',
+ 'replaced',
+ );
+ expect(getDialog('B')).not.toHaveAttribute(
+ 'data-sheet-stack',
+ 'replaced',
+ );
+ endMotion(getDialog('B'), 'transform');
+ endMotion(getDialog('A'), 'transform');
+ expect(summary()).toEqual(['C:top:0']);
+ // C's opener is its own (the control in B that opened it is gone with
+ // B), so closing C does not land on A's opener as a replace would.
+ fireEvent.click(screen.getByRole('button', {name: 'Close C'}));
+ endMotion(getDialog('C'), 'transform');
+ expect(openA).not.toHaveFocus();
+ });
+ }
+
+ it('a pair made early in a commit is undone by a third flip in the same commit', () => {
+ // Same scenario, driven so the registry hears B's close and C's open
+ // before A's close: the pair is made and then undone before paint.
+ render(<ThreeSheets order="CBA" />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open A'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Open B'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Finish to C'}));
+ expect(getDialog('B')).not.toHaveAttribute('data-sheet-stack', 'replaced');
+ expect(getDialog('C')).not.toHaveAttribute('data-sheet-stack', 'replacing');
+ const state = getBottomSheetStackForTests();
+ expect(state.filter(entry => entry.view.isReplacing)).toHaveLength(0);
+ expect(
+ state.filter(entry => entry.view.replacedMotion != null),
+ ).toHaveLength(0);
+ });
+});
+
+describe('BottomSheet replace: non-modal sheets', () => {
+ it('non-modal sheets are manual popovers that replace each other without stacking', () => {
+ render(<Flow hasScrim={false} />);
+ openFlow();
+ expect(calls()).toEqual(['showPopover:One']);
+ expect(getDialog('One')).toHaveAttribute('popover', 'manual');
+ // Not a stack level: no modal group entry, no stack attributes, no scrim.
+ expect(getBottomSheetStackForTests()).toEqual([]);
+ expect(getDialog('One')).not.toHaveAttribute('data-sheet-stack');
+ expect(scrim(getDialog('One'))).toBe('');
+ tap(screen.getByRole('button', {name: 'Continue to two'}));
+ // The same handoff as a modal replace, on the non-modal group.
+ expect(
+ getBottomSheetStackForTests(document, false).map(({element, view}) =>
+ [
+ element?.getAttribute('aria-label'),
+ view.replacedMotion ?? (view.isReplacing ? 'replacing' : 'idle'),
+ ].join(':'),
+ ),
+ ).toEqual(['One:covered', 'Two:replacing']);
+ expect(calls()).toEqual(['showPopover:One', 'showPopover:Two']);
+ const one = getDialog('One');
+ const two = getDialog('Two');
+ expect(one).toHaveAttribute('inert');
+ expect(one).toHaveAttribute('aria-hidden', 'true');
+ expect(two).not.toHaveAttribute('aria-modal');
+ expect(getPanel(one).className).not.toContain('sheetClosing');
+ // No stack attributes and no z-index band on either dialog.
+ expect(one).not.toHaveAttribute('data-sheet-stack');
+ expect(two).not.toHaveAttribute('data-sheet-stack');
+ endMotion(two, 'transform');
+ endMotion(one, 'opacity');
+ expect(openDialogs()).toEqual(['Two']);
+ expect(calls()).toEqual([
+ 'showPopover:One',
+ 'showPopover:Two',
+ 'hidePopover:One',
+ ]);
+ // The page stayed interactive: no scroll lock, no focus steal.
+ expect(document.body.style.position).not.toBe('fixed');
+ });
+
+ it('a non-modal reversal re-shows the returning sheet above the other', () => {
+ render(<Flow hasScrim={false} initialStep="two" />);
+ tap(screen.getByRole('button', {name: 'Back to one'}));
+ tap(screen.getByRole('button', {name: 'Continue to two'}));
+ expect(
+ getBottomSheetStackForTests(document, false).map(({element, view}) =>
+ [
+ element?.getAttribute('aria-label'),
+ view.replacedMotion ?? (view.isReplacing ? 'replacing' : 'idle'),
+ ].join(':'),
+ ),
+ ).toEqual(['One:fading', 'Two:replacing']);
+ expect(calls().slice(-2)).toEqual(['hidePopover:Two', 'showPopover:Two']);
+ });
+
+ it('a non-modal flow returns focus to its opener when its last step closes', () => {
+ render(<Flow hasScrim={false} />);
+ const opener = openFlow();
+ const next = screen.getByRole('button', {name: 'Continue to two'});
+ next.focus();
+ tap(next);
+ const one = getDialog('One');
+ const two = getDialog('Two');
+ endMotion(two, 'transform');
+ endMotion(one, 'opacity');
+ const finish = screen.getByRole('button', {name: 'Finish'});
+ finish.focus();
+ fireEvent.click(finish);
+ endMotion(two, 'transform');
+ expect(openDialogs()).toEqual([]);
+ expect(document.activeElement).toBe(opener);
+ });
+
+ describe('with a showPopover() that does not move focus (Safari)', () => {
+ let showPopover: typeof HTMLElement.prototype.showPopover;
+ beforeEach(() => {
+ showPopover = HTMLElement.prototype.showPopover;
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ nativeLog.push({call: 'showPopover', dialog: this});
+ this.setAttribute('open', '');
+ });
+ });
+ afterEach(() => {
+ HTMLElement.prototype.showPopover = showPopover;
+ });
+
+ it('a non-modal replace moves focus into the entering step and the final close returns it to the opener', () => {
+ render(<Flow hasScrim={false} />);
+ const opener = openFlow();
+ // A lone non-modal sheet takes no focus on open.
+ expect(document.activeElement).toBe(opener);
+ const next = screen.getByRole('button', {name: 'Continue to two'});
+ next.focus();
+ tap(next);
+ const one = getDialog('One');
+ const two = getDialog('Two');
+ // The person was in step one; the entering step takes focus even
+ // though the browser moved nothing.
+ expect(document.activeElement).toBe(getPanel(two));
+ endMotion(two, 'transform');
+ endMotion(one, 'opacity');
+ expect(document.activeElement).toBe(getPanel(two));
+ const finish = screen.getByRole('button', {name: 'Finish'});
+ finish.focus();
+ fireEvent.click(finish);
+ endMotion(two, 'transform');
+ expect(openDialogs()).toEqual([]);
+ expect(document.activeElement).toBe(opener);
+ });
+
+ it('a non-modal reversal moves focus into the returning step', () => {
+ render(<Flow hasScrim={false} initialStep="two" />);
+ const back = screen.getByRole('button', {name: 'Back to one'});
+ back.focus();
+ tap(back);
+ expect(document.activeElement).toBe(getPanel(getDialog('One')));
+ const forward = screen.getByRole('button', {name: 'Continue to two'});
+ forward.focus();
+ tap(forward);
+ expect(document.activeElement).toBe(getPanel(getDialog('Two')));
+ });
+
+ it('two non-modal owners swapped from a page control keep focus on the page (not a replace)', () => {
+ function TwoNonModalOwners() {
+ const [isAOpen, setIsAOpen] = useState(true);
+ const [isBOpen, setIsBOpen] = useState(false);
+ return (
+ <>
+ <button
+ type="button"
+ onClick={() => {
+ setIsAOpen(false);
+ setIsBOpen(true);
+ }}>
+ Swap from page
+ </button>
+ <BottomSheet
+ isOpen={isAOpen}
+ onOpenChange={setIsAOpen}
+ hasScrim={false}
+ label="A">
+ a
+ </BottomSheet>
+ <BottomSheet
+ isOpen={isBOpen}
+ onOpenChange={setIsBOpen}
+ hasScrim={false}
+ label="B">
+ b
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<TwoNonModalOwners />);
+ const swap = screen.getByRole('button', {name: 'Swap from page'});
+ swap.focus();
+ tap(swap);
+ // Pop and push, not a replace: B is a lone non-modal sheet opening and
+ // takes no focus; the person stays on the page control.
+ expect(
+ getBottomSheetStackForTests(document, false).some(
+ ({view}) => view.isReplacing || view.replacedMotion != null,
+ ),
+ ).toBe(false);
+ expect(document.activeElement).toBe(swap);
+ });
+ });
+
+ it('a non-modal sheet never pairs with a modal one', () => {
+ function Harness() {
+ const [step, setStep] = useState<'a' | 'b'>('a');
+ return (
+ <>
+ <BottomSheet
+ isOpen={step === 'a'}
+ onOpenChange={() => {}}
+ hasScrim={false}
+ label="A">
+ <button type="button" onClick={() => setStep('b')}>
+ Next
+ </button>
+ </BottomSheet>
+ <BottomSheet isOpen={step === 'b'} onOpenChange={() => {}} label="B">
+ x
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<Harness />);
+ tap(screen.getByRole('button', {name: 'Next'}));
+ expect(summary()).toEqual(['B:top:0']);
+ expect(getDialog('A')).not.toHaveAttribute('data-sheet-stack');
+ expect(getPanel(getDialog('A')).className).toContain('sheetClosing');
+ expect(calls()).toEqual(['showPopover:A', 'showModal:B']);
+ });
+
+ it('falls back to show() and still replaces below the Popover API support floor', () => {
+ const showPopover = HTMLElement.prototype.showPopover;
+ const hidePopover = HTMLElement.prototype.hidePopover;
+ // @ts-expect-error -- emulate a browser without the Popover API
+ delete HTMLElement.prototype.showPopover;
+ // @ts-expect-error -- emulate a browser without the Popover API
+ delete HTMLElement.prototype.hidePopover;
+ try {
+ render(<Flow hasScrim={false} />);
+ openFlow();
+ tap(screen.getByRole('button', {name: 'Continue to two'}));
+ expect(calls()).toEqual(['show:One', 'show:Two']);
+ endMotion(getDialog('Two'), 'transform');
+ endMotion(getDialog('One'), 'opacity');
+ expect(calls()).toEqual(['show:One', 'show:Two', 'close:One']);
+ expect(openDialogs()).toEqual(['Two']);
+ } finally {
+ HTMLElement.prototype.showPopover = showPopover;
+ HTMLElement.prototype.hidePopover = hidePopover;
+ }
+ });
+});
diff --git a/packages/core/src/BottomSheet/BottomSheetStacking.announce.test.tsx b/packages/core/src/BottomSheet/BottomSheetStacking.announce.test.tsx
new file mode 100644
index 0000000000..2d9914c4f1
--- /dev/null
+++ b/packages/core/src/BottomSheet/BottomSheetStacking.announce.test.tsx
@@ -0,0 +1,246 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file BottomSheetStacking.announce.test.tsx
+ * @input BottomSheet, useAnnounce
+ * @output Tests of useAnnounce's modal route (spec:AST-086 FR14) under the
+ * sheet stack (component:BottomSheet FR5–FR12): a message from the top
+ * sheet lands in the top sheet's regions; a message from a covered sheet
+ * — inert and aria-hidden, so not exposed — is delivered beyond it, to the
+ * exposed top sheet, never lost; a same-update replace hands a message
+ * from the leaving sheet to the entering one; a covered sheet that still
+ * contains the top sheet (exposed, but not on top) keeps its words for
+ * when it is on top again, as FR14 rules for a covered modal.
+ * @position Test for BottomSheet; sits beside BottomSheetStacking.test.tsx
+ */
+
+import {act, fireEvent, render, screen} from '@testing-library/react';
+import React, {useState} from 'react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {__resetLiveRegionsForTest, useAnnounce} from '../hooks/useAnnounce';
+import {BottomSheet} from './BottomSheet';
+import {resetBottomSheetStackForTests} from './bottomSheetStack';
+
+function Owner({message, label}: {message: string; label: string}) {
+ const announce = useAnnounce();
+ return (
+ <button type="button" onClick={() => announce(message)}>
+ {label}
+ </button>
+ );
+}
+
+function stubDialogs() {
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ this.dataset.modal = 'true';
+ });
+ HTMLDialogElement.prototype.show = vi.fn(function (this: HTMLDialogElement) {
+ this.setAttribute('open', '');
+ delete this.dataset.modal;
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ this.removeAttribute('open');
+ delete this.dataset.modal;
+ this.dispatchEvent(new Event('close'));
+ });
+ const matches = Element.prototype.matches;
+ vi.spyOn(Element.prototype, 'matches').mockImplementation(function (
+ this: Element,
+ selector: string,
+ ) {
+ return selector === ':modal'
+ ? this instanceof HTMLDialogElement &&
+ this.open &&
+ this.dataset.modal === 'true'
+ : matches.call(this, selector);
+ });
+}
+
+async function nextFrame() {
+ await act(
+ async () =>
+ new Promise<void>(resolve => requestAnimationFrame(() => resolve())),
+ );
+}
+
+const shared = (politeness = 'polite') =>
+ document.querySelector(`[data-astryx-live-region="${politeness}"]`);
+const regionIn = (dialog: Element, politeness = 'polite') =>
+ dialog.querySelector(
+ `:scope > [data-astryx-modal-live-region="${politeness}"]`,
+ );
+const dialog = (label: string) =>
+ document.querySelector<HTMLDialogElement>(`dialog[aria-label="${label}"]`)!;
+
+/** Finishes a sheet's exit the way the panel's motion end would. */
+function finishExit(element: HTMLDialogElement) {
+ act(() => {
+ element
+ .querySelector('[data-bottom-sheet-panel]')
+ ?.dispatchEvent(new Event('transitionend', {bubbles: true}));
+ if (element.open) {
+ element.close();
+ }
+ });
+}
+
+beforeEach(() => {
+ __resetLiveRegionsForTest();
+ resetBottomSheetStackForTests();
+ stubDialogs();
+});
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+/** Two sibling sheets, A beneath B, each with an announcing control. */
+function Siblings({initialB = false}: {initialB?: boolean}) {
+ const [isAOpen, setIsAOpen] = useState(true);
+ const [isBOpen, setIsBOpen] = useState(initialB);
+ return (
+ <>
+ <BottomSheet isOpen={isAOpen} onOpenChange={setIsAOpen} label="A">
+ <Owner message="From A" label="Say A" />
+ <button type="button" onClick={() => setIsBOpen(true)}>
+ Open B
+ </button>
+ </BottomSheet>
+ <BottomSheet isOpen={isBOpen} onOpenChange={setIsBOpen} label="B">
+ <Owner message="From B" label="Say B" />
+ <button type="button" onClick={() => setIsBOpen(false)}>
+ Close B
+ </button>
+ </BottomSheet>
+ </>
+ );
+}
+
+describe('useAnnounce under the sheet stack (FR14 × component:BottomSheet FR5–FR12)', () => {
+ it('a message from the top sheet of a stack lands in the top sheet, not in the covered one or the page', async () => {
+ render(<Siblings />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open B'}));
+ await nextFrame();
+ expect(dialog('A')).toHaveAttribute('inert');
+ expect(dialog('B')).not.toHaveAttribute('inert');
+ fireEvent.click(screen.getByRole('button', {name: 'Say B'}));
+ await nextFrame();
+ expect(regionIn(dialog('B'))).toHaveTextContent('From B');
+ expect(regionIn(dialog('A'))?.textContent ?? '').toBe('');
+ expect(shared()?.textContent ?? '').toBe('');
+ });
+
+ it('a message from a covered sheet (inert, aria-hidden: not exposed) is not lost — it is delivered beyond the covered sheet, to the exposed top sheet', async () => {
+ render(<Siblings />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open B'}));
+ await nextFrame();
+ expect(dialog('A')).toHaveAttribute('aria-hidden', 'true');
+ // The covered sheet's control is aria-hidden; a timer or a resolved
+ // request inside it would announce the same way, so reach it by element.
+ fireEvent.click(screen.getByText('Say A'));
+ await nextFrame();
+ expect(regionIn(dialog('B'))).toHaveTextContent('From A');
+ expect(regionIn(dialog('A'))?.textContent ?? '').toBe('');
+ expect(shared()?.textContent ?? '').toBe('');
+ });
+
+ it('once the top sheet closes and the covered sheet is exposed again, its messages land in it again', async () => {
+ render(<Siblings />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open B'}));
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Close B'}));
+ finishExit(dialog('B'));
+ await nextFrame();
+ expect(dialog('A')).not.toHaveAttribute('inert');
+ fireEvent.click(screen.getByRole('button', {name: 'Say A'}));
+ await nextFrame();
+ expect(regionIn(dialog('A'))).toHaveTextContent('From A');
+ expect(shared()?.textContent ?? '').toBe('');
+ });
+
+ it('a same-update replace: words announced from the leaving sheet by the handler that switches sheets are handed to the entering sheet — not left in the leaving sheet, not lost to the page', async () => {
+ function Next({onNext}: {onNext: () => void}) {
+ const announce = useAnnounce();
+ return (
+ <button
+ type="button"
+ onClick={() => {
+ announce('Moved on');
+ onNext();
+ }}>
+ Next
+ </button>
+ );
+ }
+ function Flow() {
+ const [step, setStep] = useState<'one' | 'two'>('one');
+ return (
+ <>
+ <BottomSheet
+ isOpen={step === 'one'}
+ onOpenChange={() => {}}
+ label="One">
+ <Next onNext={() => setStep('two')} />
+ </BottomSheet>
+ <BottomSheet
+ isOpen={step === 'two'}
+ onOpenChange={() => {}}
+ label="Two">
+ <Owner message="From Two" label="Say Two" />
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<Flow />);
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Next'}));
+ // The leaving sheet is presented, inert and aria-hidden through its
+ // fade (the replace handoff); the entering one is the exposed modal.
+ expect(dialog('One')).toHaveAttribute('inert');
+ expect(dialog('Two')).not.toHaveAttribute('inert');
+ await nextFrame();
+ await nextFrame();
+ // The words were written into One while it was exposed; One stopped
+ // being exposed in the same update, so its provider handed them to the
+ // channel exposed then: the entering sheet.
+ expect(regionIn(dialog('One'))?.textContent ?? '').toBe('');
+ expect(regionIn(dialog('Two'))).toHaveTextContent('Moved on');
+ expect(shared()?.textContent ?? '').toBe('');
+ finishExit(dialog('One'));
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Say Two'}));
+ await nextFrame();
+ expect(regionIn(dialog('Two'))).toHaveTextContent('From Two');
+ });
+
+ it('a covered sheet that contains the top sheet (exposed, but not on top) has its words cleared, as FR14 rules for a covered modal, and the top sheet hears its own', async () => {
+ function Nested() {
+ const [isBOpen, setIsBOpen] = useState(false);
+ return (
+ <BottomSheet isOpen onOpenChange={() => {}} label="A">
+ <Owner message="From A" label="Say A" />
+ <button type="button" onClick={() => setIsBOpen(true)}>
+ Open B
+ </button>
+ <BottomSheet isOpen={isBOpen} onOpenChange={setIsBOpen} label="B">
+ <Owner message="From B" label="Say B" />
+ </BottomSheet>
+ </BottomSheet>
+ );
+ }
+ render(<Nested />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open B'}));
+ await nextFrame();
+ // A contains B's dialog, so the stack leaves A to the browser's modal
+ // blocking rather than marking it inert.
+ expect(dialog('A')).not.toHaveAttribute('inert');
+ fireEvent.click(screen.getByRole('button', {name: 'Say A'}));
+ await nextFrame();
+ expect(regionIn(dialog('A'))?.textContent ?? '').toBe('');
+ fireEvent.click(screen.getByRole('button', {name: 'Say B'}));
+ await nextFrame();
+ expect(regionIn(dialog('B'))).toHaveTextContent('From B');
+ });
+});
diff --git a/packages/core/src/BottomSheet/BottomSheetStacking.test.tsx b/packages/core/src/BottomSheet/BottomSheetStacking.test.tsx
new file mode 100644
index 0000000000..1b006efd13
--- /dev/null
+++ b/packages/core/src/BottomSheet/BottomSheetStacking.test.tsx
@@ -0,0 +1,3184 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file BottomSheetStacking.test.tsx
+ * @input Uses vitest, @testing-library/react, react-dom/server, BottomSheet,
+ * BottomSheetSwitcher, Dialog, and the private bottom-sheet stack registry
+ * @output Tests for stacked bottom sheets, one group per requirement: no new
+ * API, open order, same-commit opens, covered sheets, dismissal, one scrim,
+ * closing a covered sheet, focus, the native top layer, concurrent React,
+ * non-modal sheets, and unchanged standalone behaviour
+ * @position Core testing; validates bottomSheetStack.ts and the stacking
+ * behaviour of BottomSheet.tsx and BottomSheetSwitcher.tsx
+ *
+ * SYNC: When bottomSheetStack.ts, BottomSheet.tsx or BottomSheetSwitcher.tsx
+ * change their stacking behaviour, update these tests to match.
+ */
+
+import {act, fireEvent, render, screen} from '@testing-library/react';
+import {
+ Activity,
+ StrictMode,
+ Suspense,
+ startTransition,
+ useState,
+ type ReactNode,
+} from 'react';
+import {createPortal, flushSync} from 'react-dom';
+import {createRoot, hydrateRoot} from 'react-dom/client';
+import {renderToString} from 'react-dom/server';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {Dialog} from '../Dialog';
+import {Popover} from '../Popover';
+import {subscribeModalOutlets} from '../Layer/modalOutlet';
+import * as BottomSheetModule from './index';
+import {BottomSheet} from './BottomSheet';
+import {BottomSheetSwitcher} from './BottomSheetSwitcher';
+import {
+ BOTTOM_SHEET_STACK_STATE_FOR_TESTS,
+ getBottomSheetStackForTests,
+ registerBottomSheet,
+ resetBottomSheetStackForTests,
+} from './bottomSheetStack';
+import {__resetInteractionModalityForTest} from '../utils/interactionModality';
+
+/**
+ * Every native showModal/show/close, in order, with the dialog. The label is
+ * read when a test asks, because a switcher labels its dialog from state its
+ * items register in the same commit that shows it.
+ */
+let nativeLog: {
+ call: 'showModal' | 'show' | 'close' | 'showPopover' | 'hidePopover';
+ dialog: HTMLElement;
+}[] = [];
+
+beforeEach(() => {
+ nativeLog = [];
+ resetBottomSheetStackForTests();
+ __resetInteractionModalityForTest();
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ nativeLog.push({call: 'showModal', dialog: this});
+ this.setAttribute('open', '');
+ });
+ HTMLDialogElement.prototype.show = vi.fn(function (this: HTMLDialogElement) {
+ nativeLog.push({call: 'show', dialog: this});
+ this.setAttribute('open', '');
+ });
+ // A non-modal sheet is a manual popover; jsdom's stand-ins keep the same
+ // `open` marker the dialog paths use (the Drawer tests do the same).
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ nativeLog.push({call: 'showPopover', dialog: this});
+ this.setAttribute('open', '');
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ nativeLog.push({call: 'hidePopover', dialog: this});
+ this.removeAttribute('open');
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ nativeLog.push({call: 'close', dialog: this});
+ this.removeAttribute('open');
+ });
+ if (!Element.prototype.setPointerCapture) {
+ Element.prototype.setPointerCapture = vi.fn();
+ Element.prototype.releasePointerCapture = vi.fn();
+ }
+ window.scrollTo = vi.fn();
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn().mockReturnValue({
+ matches: false,
+ media: '',
+ onchange: null,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ }),
+ );
+ vi.stubGlobal(
+ 'requestAnimationFrame',
+ vi.fn((callback: FrameRequestCallback) => {
+ callback(0);
+ return 1;
+ }),
+ );
+ vi.stubGlobal('cancelAnimationFrame', vi.fn());
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function getDialog(
+ label: string,
+ root: ParentNode = document,
+): HTMLDialogElement {
+ const dialog = root.querySelector<HTMLDialogElement>(
+ `dialog[aria-label="${label}"]`,
+ );
+ if (dialog == null) {
+ throw new Error(`dialog "${label}" not found`);
+ }
+ return dialog;
+}
+
+function getPanel(dialog: HTMLElement): HTMLElement {
+ const panels = Array.from(
+ dialog.querySelectorAll<HTMLElement>('.astryx-bottom-sheet'),
+ ).filter(panel => panel.closest('dialog') === dialog);
+ const panel =
+ panels.find(candidate => !candidate.parentElement?.hidden) ?? panels[0];
+ if (panel == null) {
+ throw new Error('sheet panel not found');
+ }
+ return panel;
+}
+
+function getPositioner(dialog: HTMLElement): HTMLElement {
+ const positioner = getPanel(dialog).parentElement;
+ if (positioner == null) {
+ throw new Error('positioner not found');
+ }
+ return positioner;
+}
+
+function getHandle(dialog: HTMLElement): HTMLElement {
+ const handle = getPanel(dialog).querySelector<HTMLElement>(
+ '[aria-hidden="true"]',
+ );
+ if (handle == null) {
+ throw new Error('grab handle not found');
+ }
+ return handle;
+}
+
+function scrim(dialog: HTMLElement): string {
+ return dialog.style.getPropertyValue('--_sheet-scrim-opacity');
+}
+
+/** The inline pin on the scrim transition: `0s` for the frame it changes hands. */
+function scrimDuration(dialog: HTMLElement): string {
+ return dialog.style.getPropertyValue('--_sheet-scrim-duration');
+}
+
+/**
+ * Record every scrim-opacity write with the transition pin in force at that
+ * moment. rAF is synchronous in these tests, so the pin is gone by the time
+ * an assertion reads the style; the spy sees it as the browser would.
+ */
+function recordScrimWrites(): {
+ writes: {opacity: string; pin: string}[];
+ restore: () => void;
+} {
+ const writes: {opacity: string; pin: string}[] = [];
+ const setProperty = CSSStyleDeclaration.prototype.setProperty;
+ CSSStyleDeclaration.prototype.setProperty = function (
+ this: CSSStyleDeclaration,
+ name: string,
+ value: string | null,
+ priority?: string,
+ ) {
+ if (name === '--_sheet-scrim-opacity') {
+ writes.push({
+ opacity: String(value),
+ pin: this.getPropertyValue('--_sheet-scrim-duration'),
+ });
+ }
+ return setProperty.call(this, name, value, priority);
+ };
+ return {
+ writes,
+ restore: () => {
+ CSSStyleDeclaration.prototype.setProperty = setProperty;
+ },
+ };
+}
+
+/** `label:state:depth` for every presented modal sheet, bottom to top. */
+function stackSummary(): string[] {
+ return getBottomSheetStackForTests().map(({element, isOpen, view}) => {
+ const label = element?.getAttribute('aria-label') ?? '?';
+ const state = !isOpen ? 'exiting' : view.isTop ? 'top' : 'covered';
+ return `${label}:${state}:${view.depth}`;
+ });
+}
+
+/** The final native top-layer order: the last showModal of each open dialog. */
+function topLayerOrder(): string[] {
+ const order: HTMLElement[] = [];
+ for (const entry of nativeLog) {
+ const index = order.indexOf(entry.dialog);
+ if (index !== -1) {
+ order.splice(index, 1);
+ }
+ if (entry.call === 'showModal') {
+ order.push(entry.dialog);
+ }
+ }
+ return order.map(dialog => dialog.getAttribute('aria-label') ?? '?');
+}
+
+function openDialogs(): string[] {
+ return Array.from(document.querySelectorAll('dialog[open]')).map(
+ dialog => dialog.getAttribute('aria-label') ?? '?',
+ );
+}
+
+// The sheet keeps its dialog open through the exit animation; jsdom never
+// runs it, so end it the way the panel's transition would.
+function finishExit(dialog: HTMLElement) {
+ for (const panel of Array.from(
+ dialog.querySelectorAll<HTMLElement>('.astryx-bottom-sheet'),
+ )) {
+ if (panel.closest('dialog') === dialog) {
+ fireEvent.transitionEnd(panel, {propertyName: 'transform'});
+ }
+ }
+}
+
+/**
+ * Complete a switcher handoff: the entering step's panel finishes its
+ * transform, the retained step fades, and its dialog closes.
+ */
+function finishHandoff(entering: HTMLElement, retained: HTMLElement) {
+ for (const panel of Array.from(
+ entering.querySelectorAll<HTMLElement>('.astryx-bottom-sheet'),
+ )) {
+ if (panel.closest('dialog') === entering) {
+ fireEvent.transitionEnd(panel, {propertyName: 'transform'});
+ }
+ }
+ for (const panel of Array.from(
+ retained.querySelectorAll<HTMLElement>('.astryx-bottom-sheet'),
+ )) {
+ if (panel.closest('dialog') === retained) {
+ fireEvent.transitionEnd(panel, {propertyName: 'opacity'});
+ }
+ }
+}
+
+function pressEscape(): KeyboardEvent {
+ const event = new KeyboardEvent('keydown', {
+ key: 'Escape',
+ bubbles: true,
+ cancelable: true,
+ });
+ document.dispatchEvent(event);
+ return event;
+}
+
+function fireCancel(dialog: Element): Event {
+ const event = new Event('cancel', {bubbles: false, cancelable: true});
+ dialog.dispatchEvent(event);
+ return event;
+}
+
+// Drive a pointer drag on a grab handle. jsdom PointerEvents don't carry
+// clientY, so dispatch plain events with the coords the handlers read.
+function drag(handle: HTMLElement, points: {y: number}[]) {
+ const [down, ...rest] = points;
+ fireEvent.pointerDown(handle, {
+ pointerId: 1,
+ clientY: down.y,
+ button: 0,
+ isPrimary: true,
+ });
+ for (const point of rest) {
+ fireEvent.pointerMove(handle, {pointerId: 1, clientY: point.y});
+ }
+ const last = points[points.length - 1];
+ fireEvent.pointerUp(handle, {pointerId: 1, clientY: last.y});
+}
+
+function classes(element: Element): string {
+ return element.className;
+}
+
+/**
+ * Two sibling sheets, each with its own state, plus an opener for each. The
+ * default writes A before B; `reversed` writes B before A so an open of A
+ * then B is an open out of tree order.
+ */
+function Siblings({
+ reversed = false,
+ purposeB,
+ initialA = false,
+ initialB = false,
+}: {
+ reversed?: boolean;
+ purposeB?: 'info' | 'form' | 'required';
+ initialA?: boolean;
+ initialB?: boolean;
+}) {
+ const [isAOpen, setIsAOpen] = useState(initialA);
+ const [isBOpen, setIsBOpen] = useState(initialB);
+ const a = (
+ <BottomSheet key="A" isOpen={isAOpen} onOpenChange={setIsAOpen} label="A">
+ <button type="button" onClick={() => setIsBOpen(true)}>
+ Open B
+ </button>
+ <input aria-label="A field" defaultValue="" />
+ </BottomSheet>
+ );
+ const b = (
+ <BottomSheet
+ key="B"
+ isOpen={isBOpen}
+ onOpenChange={setIsBOpen}
+ label="B"
+ purpose={purposeB}>
+ <button type="button" onClick={() => setIsBOpen(false)}>
+ Close B
+ </button>
+ <button type="button" onClick={() => setIsAOpen(false)}>
+ Close A from B
+ </button>
+ <input aria-label="B field" defaultValue="" />
+ </BottomSheet>
+ );
+ return (
+ <>
+ <button type="button" onClick={() => setIsAOpen(true)}>
+ Open A
+ </button>
+ {reversed ? [b, a] : [a, b]}
+ </>
+ );
+}
+
+/** A → B → C, each rendered inside the previous sheet's content. */
+function Nested({
+ initial = false,
+ closeAllFromC = false,
+}: {
+ initial?: boolean;
+ closeAllFromC?: boolean;
+}) {
+ const [isAOpen, setIsAOpen] = useState(initial);
+ const [isBOpen, setIsBOpen] = useState(initial);
+ const [isCOpen, setIsCOpen] = useState(initial);
+ return (
+ <>
+ <button type="button" onClick={() => setIsAOpen(true)}>
+ Open A
+ </button>
+ <button type="button" onClick={() => setIsAOpen(false)}>
+ Close A from page
+ </button>
+ <BottomSheet isOpen={isAOpen} onOpenChange={setIsAOpen} label="A">
+ <button type="button" onClick={() => setIsBOpen(true)}>
+ Open B
+ </button>
+ <BottomSheet isOpen={isBOpen} onOpenChange={setIsBOpen} label="B">
+ <button type="button" onClick={() => setIsCOpen(true)}>
+ Open C
+ </button>
+ <BottomSheet isOpen={isCOpen} onOpenChange={setIsCOpen} label="C">
+ <button
+ type="button"
+ onClick={() => {
+ if (closeAllFromC) {
+ setIsAOpen(false);
+ setIsBOpen(false);
+ }
+ setIsCOpen(false);
+ }}>
+ Close C
+ </button>
+ </BottomSheet>
+ </BottomSheet>
+ </BottomSheet>
+ </>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Requirement 1 — no new public API; a lone sheet is unchanged
+// ---------------------------------------------------------------------------
+
+describe('R1 no new public API', () => {
+ it('exports exactly BottomSheet and BottomSheetSwitcher', () => {
+ expect(Object.keys(BottomSheetModule).sort()).toEqual([
+ 'BottomSheet',
+ 'BottomSheetSwitcher',
+ ]);
+ });
+
+ it('a sheet on its own carries no stack state and behaves as before', () => {
+ const onOpenChange = vi.fn();
+ render(
+ <BottomSheet isOpen onOpenChange={onOpenChange} label="Alone">
+ Content
+ </BottomSheet>,
+ );
+ const dialog = getDialog('Alone');
+ expect(dialog).toHaveAttribute('open');
+ expect(dialog).toHaveAttribute('aria-modal', 'true');
+ expect(dialog).not.toHaveAttribute('inert');
+ expect(dialog).not.toHaveAttribute('data-sheet-stack');
+ expect(dialog).not.toHaveAttribute('data-sheet-stack-depth');
+ expect(scrim(dialog)).toBe('1');
+ expect(getComputedStyle(getPositioner(dialog)).transform).toBe('');
+ expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalledTimes(1);
+ expect(getPanel(dialog)).toHaveFocus();
+
+ act(() => {
+ pressEscape();
+ });
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Requirement 2 — order is open order
+// ---------------------------------------------------------------------------
+
+describe('R2 order is open order', () => {
+ it('a sheet opened over another stacks on top; the covered one recedes', () => {
+ render(<Siblings />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open A'}));
+ expect(stackSummary()).toEqual(['A:top:0']);
+
+ fireEvent.click(screen.getByRole('button', {name: 'Open B'}));
+ expect(stackSummary()).toEqual(['A:covered:1', 'B:top:0']);
+ expect(getDialog('A')).toHaveAttribute('data-sheet-stack', 'covered');
+ expect(getDialog('A')).toHaveAttribute('data-sheet-stack-depth', '1');
+ expect(getDialog('B')).toHaveAttribute('data-sheet-stack', 'top');
+ expect(getDialog('B')).not.toHaveAttribute('data-sheet-stack-depth');
+ expect(topLayerOrder()).toEqual(['A', 'B']);
+ });
+
+ it('a sheet that closes and reopens goes back on top', () => {
+ function Three() {
+ const [open, setOpen] = useState({A: true, B: true, C: true});
+ const toggle = (id: 'A' | 'B' | 'C', value: boolean) =>
+ setOpen(current => ({...current, [id]: value}));
+ return (
+ <>
+ <button type="button" onClick={() => toggle('A', false)}>
+ Close A
+ </button>
+ <button type="button" onClick={() => toggle('A', true)}>
+ Reopen A
+ </button>
+ <BottomSheet
+ isOpen={open.A}
+ onOpenChange={v => toggle('A', v)}
+ label="A">
+ a
+ </BottomSheet>
+ <BottomSheet
+ isOpen={open.B}
+ onOpenChange={v => toggle('B', v)}
+ label="B">
+ b
+ </BottomSheet>
+ <BottomSheet
+ isOpen={open.C}
+ onOpenChange={v => toggle('C', v)}
+ label="C">
+ c
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<Three />);
+ expect(stackSummary()).toEqual(['A:covered:2', 'B:covered:1', 'C:top:0']);
+
+ fireEvent.click(screen.getByRole('button', {name: 'Close A'}));
+ finishExit(getDialog('A'));
+ expect(stackSummary()).toEqual(['B:covered:1', 'C:top:0']);
+
+ fireEvent.click(screen.getByRole('button', {name: 'Reopen A'}));
+ expect(stackSummary()).toEqual(['B:covered:2', 'C:covered:1', 'A:top:0']);
+ expect(topLayerOrder()).toEqual(['B', 'C', 'A']);
+ });
+
+ it('a sheet reopened during its exit returns on top', () => {
+ render(<Siblings initialA initialB />);
+ expect(stackSummary()).toEqual(['A:covered:1', 'B:top:0']);
+ fireEvent.click(screen.getByRole('button', {name: 'Close A from B'}));
+ expect(stackSummary()).toEqual(['A:exiting:1', 'B:top:0']);
+ // Reopen before the exit animation has finished.
+ fireEvent.click(screen.getByRole('button', {name: 'Open A'}));
+ expect(stackSummary()).toEqual(['B:covered:1', 'A:top:0']);
+ expect(topLayerOrder()).toEqual(['B', 'A']);
+ expect(scrim(getDialog('A'))).toBe('0');
+ expect(scrim(getDialog('B'))).toBe('1');
+ });
+
+ it('sheets in separate components stack the same way', () => {
+ function Owner({label, children}: {label: string; children?: ReactNode}) {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsOpen(true)}>
+ Open {label}
+ </button>
+ <BottomSheet isOpen={isOpen} onOpenChange={setIsOpen} label={label}>
+ {children}
+ </BottomSheet>
+ </>
+ );
+ }
+ render(
+ <>
+ <Owner label="First" />
+ <Owner label="Second" />
+ </>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Open Second'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Open First'}));
+ expect(stackSummary()).toEqual(['Second:covered:1', 'First:top:0']);
+ });
+
+ it('a sheet inside another sheet’s content stacks above it', () => {
+ render(<Nested />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open A'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Open B'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Open C'}));
+ expect(stackSummary()).toEqual(['A:covered:2', 'B:covered:1', 'C:top:0']);
+ expect(topLayerOrder()).toEqual(['A', 'B', 'C']);
+ });
+
+ it('a whole switcher is one level, and switching its step keeps its place', () => {
+ function App() {
+ const [isAOpen, setIsAOpen] = useState(false);
+ const [step, setStep] = useState<string | null>(null);
+ const [isCOpen, setIsCOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsAOpen(true)}>
+ Open A
+ </button>
+ <button type="button" onClick={() => setStep('one')}>
+ Open switcher
+ </button>
+ <button type="button" onClick={() => setStep('two')}>
+ Step two
+ </button>
+ <button type="button" onClick={() => setIsCOpen(true)}>
+ Open C
+ </button>
+ <BottomSheet isOpen={isAOpen} onOpenChange={setIsAOpen} label="A">
+ a
+ </BottomSheet>
+ <BottomSheetSwitcher activeSheet={step} onActiveSheetChange={setStep}>
+ <BottomSheet sheetId="one" label="One">
+ one
+ </BottomSheet>
+ <BottomSheet sheetId="two" label="Two">
+ two
+ </BottomSheet>
+ </BottomSheetSwitcher>
+ <BottomSheet isOpen={isCOpen} onOpenChange={setIsCOpen} label="C">
+ c
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open A'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Open switcher'}));
+ expect(stackSummary()).toEqual(['A:covered:1', 'One:top:0']);
+ expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalledTimes(2);
+
+ fireEvent.click(screen.getByRole('button', {name: 'Step two'}));
+ // Each step owns its dialog: the entering step's is presented above the
+ // retained one, and the flow's level is now that dialog; its place in
+ // the stack is unchanged.
+ expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalledTimes(3);
+ expect(stackSummary()).toEqual(['A:covered:1', 'Two:top:0']);
+ finishHandoff(getDialog('Two'), getDialog('One'));
+ expect(stackSummary()).toEqual(['A:covered:1', 'Two:top:0']);
+ expect(getDialog('One')).not.toHaveAttribute('open');
+
+ fireEvent.click(screen.getByRole('button', {name: 'Open C'}));
+ expect(stackSummary()).toEqual(['A:covered:2', 'Two:covered:1', 'C:top:0']);
+ const switcherDialog = getDialog('Two');
+ expect(switcherDialog).toHaveAttribute('data-sheet-stack', 'covered');
+ expect(switcherDialog).toHaveAttribute('data-sheet-stack-depth', '1');
+ expect(switcherDialog).toHaveAttribute('inert');
+ expect(switcherDialog).toHaveAttribute('aria-hidden', 'true');
+ // The step's positioner recedes with the switcher.
+ for (const positioner of Array.from(
+ switcherDialog.querySelectorAll<HTMLElement>('.astryx-bottom-sheet'),
+ ).map(panel => panel.parentElement!)) {
+ expect(getComputedStyle(positioner).transform).toContain('scale(.96)');
+ }
+ // One scrim: A, the bottom sheet, owns it; the step and C are clear.
+ expect(scrim(getDialog('A'))).toBe('1');
+ expect(scrim(switcherDialog)).toBe('0');
+ expect(scrim(getDialog('C'))).toBe('0');
+ });
+
+ it('a sheet over a switcher flow keeps the field being typed in when the flow changes step from code (the re-show lands on it, no panel focus)', () => {
+ function App() {
+ const [step, setStep] = useState<string | null>('one');
+ const [isCOpen, setIsCOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setStep('two')}>
+ Step two
+ </button>
+ <button type="button" onClick={() => setIsCOpen(true)}>
+ Open C
+ </button>
+ <BottomSheetSwitcher activeSheet={step} onActiveSheetChange={setStep}>
+ <BottomSheet sheetId="one" label="One">
+ one
+ </BottomSheet>
+ <BottomSheet sheetId="two" label="Two">
+ two
+ </BottomSheet>
+ </BottomSheetSwitcher>
+ <BottomSheet isOpen={isCOpen} onOpenChange={setIsCOpen} label="C">
+ <label>
+ Note <input aria-label="Note" />
+ </label>
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open C'}));
+ expect(stackSummary()).toEqual(['One:covered:1', 'C:top:0']);
+ const note = screen.getByRole('textbox', {name: 'Note'});
+ note.focus();
+ fireEvent.change(note, {target: {value: 'hel'}});
+ expect(note).toHaveFocus();
+ const focusEvents: string[] = [];
+ note.addEventListener('blur', () => focusEvents.push('blur'));
+ note.addEventListener('focus', () => focusEvents.push('focus'));
+ const showsBefore = vi.mocked(HTMLDialogElement.prototype.showModal).mock
+ .calls.length;
+
+ // The flow beneath changes step from code: its level is a new dialog, so
+ // C is closed and shown again to stay on top.
+ fireEvent.click(screen.getByRole('button', {name: 'Step two'}));
+ const cShows = vi
+ .mocked(HTMLDialogElement.prototype.showModal)
+ .mock.contexts.slice(showsBefore)
+ .filter(dialog => dialog === getDialog('C')).length;
+ expect(cShows).toBe(1);
+ expect(stackSummary()).toEqual(['Two:covered:1', 'C:top:0']);
+ // Focus is still in the field; the next keystrokes land there, and the
+ // delegate attribute the re-show used is gone again.
+ expect(note).toHaveFocus();
+ expect(note).not.toHaveAttribute('autofocus');
+ expect((note as HTMLInputElement).value).toBe('hel');
+ // At most one blur and one focus reached the field (the top layer is
+ // append-only: a re-show closes the dialog first); never a focus on the
+ // panel in between.
+ expect(focusEvents.filter(e => e === 'blur').length).toBeLessThanOrEqual(1);
+ expect(focusEvents.filter(e => e === 'focus').length).toBeLessThanOrEqual(
+ 1,
+ );
+ expect(
+ getDialog('C').querySelector('.astryx-bottom-sheet'),
+ ).not.toHaveFocus();
+ });
+
+ it('a Popover presented as a BottomSheet, opened from a sheet, is one level of the stack: it covers the sheet, Escape reaches only it, and focus returns into the sheet', async () => {
+ function App() {
+ const [isAOpen, setIsAOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsAOpen(true)}>
+ Open A
+ </button>
+ <BottomSheet isOpen={isAOpen} onOpenChange={setIsAOpen} label="A">
+ <Popover
+ label="Filters"
+ presentation="bottom-sheet"
+ content={<button type="button">Apply</button>}>
+ <button type="button">Filter</button>
+ </Popover>
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open A'}));
+ const filter = screen.getByRole('button', {name: 'Filter'});
+ filter.focus();
+ await act(async () => {
+ fireEvent.click(filter);
+ // The sheet presentation loads on demand.
+ await Promise.resolve();
+ });
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 0));
+ });
+ expect(stackSummary()).toEqual(['A:covered:1', 'Filters:top:0']);
+ // A contains the Popover's dialog, so it is left to the browser's modal
+ // blocking rather than marked inert (inert on it would reach the top
+ // sheet too); it recedes and loses its scrim like any covered sheet.
+ expect(getDialog('A')).toHaveAttribute('data-sheet-stack', 'covered');
+ expect(getDialog('A')).not.toHaveAttribute('inert');
+ expect(getDialog('Filters')).not.toHaveAttribute('inert');
+ expect(getDialog('Filters')).toHaveAttribute('aria-modal', 'true');
+ // Escape reaches only the top sheet (the Popover's): A stays open.
+ fireEvent.keyDown(getDialog('Filters'), {key: 'Escape'});
+ finishExit(getDialog('Filters'));
+ expect(stackSummary()).toEqual(['A:top:0']);
+ expect(getDialog('A')).not.toHaveAttribute('data-sheet-stack');
+ // Focus returns into A, to the control that opened the Popover.
+ expect(filter).toHaveFocus();
+ });
+
+ it('a standalone sheet inside a switcher step stacks above the switcher', () => {
+ function App() {
+ const [isNestedOpen, setIsNestedOpen] = useState(false);
+ return (
+ <BottomSheetSwitcher
+ activeSheet="details"
+ onActiveSheetChange={() => {}}>
+ <BottomSheet sheetId="details" label="Details">
+ <button type="button" onClick={() => setIsNestedOpen(true)}>
+ Open nested
+ </button>
+ <BottomSheet
+ isOpen={isNestedOpen}
+ onOpenChange={setIsNestedOpen}
+ label="Nested">
+ nested
+ </BottomSheet>
+ </BottomSheet>
+ </BottomSheetSwitcher>
+ );
+ }
+ render(<App />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open nested'}));
+ expect(stackSummary()).toEqual(['Details:covered:1', 'Nested:top:0']);
+ expect(topLayerOrder()).toEqual(['Details', 'Nested']);
+ });
+
+ it('opening out of tree order puts the later-opened sheet on top', () => {
+ render(<Siblings reversed />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open A'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Open B'}));
+ // B is written before A in the DOM, but opened after it.
+ const dialogs = Array.from(document.querySelectorAll('dialog')).map(d =>
+ d.getAttribute('aria-label'),
+ );
+ expect(dialogs).toEqual(['B', 'A']);
+ expect(stackSummary()).toEqual(['A:covered:1', 'B:top:0']);
+ expect(topLayerOrder()).toEqual(['A', 'B']);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Requirement 3 — same-update opens break ties by tree order, first frame
+// ---------------------------------------------------------------------------
+
+describe('R3 same-update opens (deep link)', () => {
+ function mountSync(element: ReactNode) {
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ let microtaskRan = false;
+ void Promise.resolve().then(() => {
+ microtaskRan = true;
+ });
+ // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- the test asserts the first synchronous frame
+ flushSync(() => {
+ root.render(element);
+ });
+ return {
+ container,
+ microtaskRan: () => microtaskRan,
+ unmount: () => {
+ act(() => root.unmount());
+ container.remove();
+ },
+ };
+ }
+
+ it('a depth-3 deep link of nested sheets is right in the first painted frame', () => {
+ const mounted = mountSync(<Nested initial />);
+ expect(mounted.microtaskRan()).toBe(false);
+
+ // Effects ran child first (C, B, A), yet the native top layer ends in
+ // tree order and every sheet already carries its stack state.
+ expect(topLayerOrder()).toEqual(['A', 'B', 'C']);
+ expect(stackSummary()).toEqual(['A:covered:2', 'B:covered:1', 'C:top:0']);
+ expect(getDialog('A')).toHaveAttribute('data-sheet-stack', 'covered');
+ expect(getDialog('A')).toHaveAttribute('data-sheet-stack-depth', '2');
+ expect(getDialog('B')).toHaveAttribute('data-sheet-stack-depth', '1');
+ expect(getDialog('C')).toHaveAttribute('data-sheet-stack', 'top');
+ expect(getComputedStyle(getPositioner(getDialog('A'))).transform).toContain(
+ 'scale(.92)',
+ );
+ expect(getComputedStyle(getPositioner(getDialog('B'))).transform).toContain(
+ 'scale(.96)',
+ );
+ expect(getComputedStyle(getPositioner(getDialog('C'))).transform).toBe('');
+ expect(scrim(getDialog('A'))).toBe('1');
+ expect(scrim(getDialog('B'))).toBe('0');
+ expect(scrim(getDialog('C'))).toBe('0');
+ expect(getPanel(getDialog('C'))).toHaveFocus();
+ expect(mounted.microtaskRan()).toBe(false);
+ mounted.unmount();
+ });
+
+ it('siblings opened in one commit stack in document order', () => {
+ const mounted = mountSync(<Siblings reversed initialA initialB />);
+ // B is written first, so with no open order between them B is below A.
+ expect(stackSummary()).toEqual(['B:covered:1', 'A:top:0']);
+ expect(topLayerOrder()).toEqual(['B', 'A']);
+ mounted.unmount();
+ });
+
+ it('several sheets opened in one later update are ordered by tree, and a later open goes above them', () => {
+ function App() {
+ const [all, setAll] = useState(false);
+ const [isDOpen, setIsDOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setAll(true)}>
+ Deep link
+ </button>
+ <button type="button" onClick={() => setIsDOpen(true)}>
+ Open D
+ </button>
+ <BottomSheet isOpen={all} onOpenChange={() => {}} label="A">
+ <BottomSheet isOpen={all} onOpenChange={() => {}} label="B">
+ b
+ </BottomSheet>
+ </BottomSheet>
+ <BottomSheet isOpen={all} onOpenChange={() => {}} label="C">
+ c
+ </BottomSheet>
+ <BottomSheet isOpen={isDOpen} onOpenChange={setIsDOpen} label="D">
+ d
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ fireEvent.click(screen.getByRole('button', {name: 'Deep link'}));
+ expect(stackSummary()).toEqual(['A:covered:2', 'B:covered:1', 'C:top:0']);
+ expect(topLayerOrder()).toEqual(['A', 'B', 'C']);
+ fireEvent.click(screen.getByRole('button', {name: 'Open D'}));
+ expect(stackSummary()).toEqual([
+ 'A:covered:3',
+ 'B:covered:2',
+ 'C:covered:1',
+ 'D:top:0',
+ ]);
+ expect(topLayerOrder()).toEqual(['A', 'B', 'C', 'D']);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Requirement 4 — covered sheets stay mounted, are blocked, and recede
+// ---------------------------------------------------------------------------
+
+describe('R4 covered sheets', () => {
+ it('keeps a covered sheet mounted with its state and marks a sibling-covered one inert', () => {
+ render(<Siblings />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open A'}));
+ fireEvent.change(screen.getByLabelText('A field'), {
+ target: {value: 'kept'},
+ });
+ fireEvent.click(screen.getByRole('button', {name: 'Open B'}));
+
+ const a = getDialog('A');
+ expect(a).toHaveAttribute('open');
+ expect(a).toHaveAttribute('inert');
+ expect(a).toHaveAttribute('aria-hidden', 'true');
+ expect(getDialog('B')).not.toHaveAttribute('inert');
+ expect(screen.getByLabelText('A field')).toHaveValue('kept');
+
+ fireEvent.click(screen.getByRole('button', {name: 'Close B'}));
+ expect(a).not.toHaveAttribute('inert');
+ expect(a).not.toHaveAttribute('aria-hidden');
+ expect(screen.getByLabelText('A field')).toHaveValue('kept');
+ });
+
+ it('leaves a covered sheet that contains the top sheet to the browser’s modal blocking', () => {
+ render(<Nested initial />);
+ // inert on A would reach C, which lives inside A's content.
+ expect(getDialog('A')).not.toHaveAttribute('inert');
+ expect(getDialog('B')).not.toHaveAttribute('inert');
+ expect(getDialog('C')).not.toHaveAttribute('inert');
+ expect(getDialog('A')).toHaveAttribute('data-sheet-stack', 'covered');
+ expect(getDialog('C')).toHaveAttribute('data-sheet-stack', 'top');
+ // The top sheet is the last modal dialog shown, so the browser blocks
+ // everything outside it, A and B included.
+ expect(topLayerOrder().at(-1)).toBe('C');
+ });
+
+ it('recedes by depth: 0.96 / −8px at depth 1, 0.92 / −16px from depth 2 on', () => {
+ function Four() {
+ return (
+ <>
+ <BottomSheet isOpen onOpenChange={() => {}} label="A">
+ a
+ </BottomSheet>
+ <BottomSheet isOpen onOpenChange={() => {}} label="B">
+ b
+ </BottomSheet>
+ <BottomSheet isOpen onOpenChange={() => {}} label="C">
+ c
+ </BottomSheet>
+ <BottomSheet isOpen onOpenChange={() => {}} label="D">
+ d
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<Four />);
+ const transform = (label: string) =>
+ getComputedStyle(getPositioner(getDialog(label))).transform;
+ expect(getDialog('A')).toHaveAttribute('data-sheet-stack-depth', '3');
+ expect(transform('A')).toBe(
+ 'translateY(calc(-2 * var(--spacing-2))) scale(.92)',
+ );
+ expect(transform('B')).toBe(
+ 'translateY(calc(-2 * var(--spacing-2))) scale(.92)',
+ );
+ expect(transform('C')).toBe(
+ 'translateY(calc(-1 * var(--spacing-2))) scale(.96)',
+ );
+ expect(transform('D')).toBe('');
+ expect(
+ getComputedStyle(getPositioner(getDialog('C'))).transformOrigin,
+ ).toBe('50% 0');
+ });
+
+ it('only sheets count: a Dialog over a sheet does not make it recede', () => {
+ function App() {
+ const [isDialogOpen, setIsDialogOpen] = useState(false);
+ return (
+ <BottomSheet isOpen onOpenChange={() => {}} label="Sheet">
+ <button type="button" onClick={() => setIsDialogOpen(true)}>
+ Open dialog
+ </button>
+ <Dialog
+ isOpen={isDialogOpen}
+ onOpenChange={setIsDialogOpen}
+ aria-label="Over">
+ over
+ </Dialog>
+ </BottomSheet>
+ );
+ }
+ render(<App />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open dialog'}));
+ expect(getDialog('Over')).toHaveAttribute('open');
+ expect(stackSummary()).toEqual(['Sheet:top:0']);
+ expect(getDialog('Sheet')).not.toHaveAttribute('data-sheet-stack');
+ expect(getComputedStyle(getPositioner(getDialog('Sheet'))).transform).toBe(
+ '',
+ );
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Requirement 5 — dismissal reaches only the top sheet, via its own callback
+// ---------------------------------------------------------------------------
+
+describe('R5 dismissal', () => {
+ function Pair({purposeB}: {purposeB?: 'info' | 'form' | 'required'}) {
+ return <Siblings initialA initialB purposeB={purposeB} />;
+ }
+
+ it('Escape closes only the top sheet', () => {
+ render(<Pair />);
+ let event!: KeyboardEvent;
+ act(() => {
+ event = pressEscape();
+ });
+ expect(event.defaultPrevented).toBe(true);
+ // The revealed sheet comes forward as the top sheet slides away.
+ expect(stackSummary()).toEqual(['A:top:0', 'B:exiting:0']);
+ expect(getDialog('B')).toHaveAttribute('open');
+ finishExit(getDialog('B'));
+ expect(stackSummary()).toEqual(['A:top:0']);
+ expect(getDialog('A')).toHaveAttribute('open');
+ });
+
+ it('a scrim tap closes only the top sheet', () => {
+ render(<Pair />);
+ fireEvent.click(getDialog('B'));
+ expect(stackSummary()).toEqual(['A:top:0', 'B:exiting:0']);
+ // Only the exiting sheet went; A is still open, and B's own callback was
+ // the one called (A's state is untouched).
+ expect(getDialog('A')).toHaveAttribute('open');
+ });
+
+ it('a swipe closes only the top sheet', () => {
+ render(<Pair />);
+ drag(getHandle(getDialog('B')), [{y: 0}, {y: 40}, {y: 120}]);
+ expect(stackSummary()).toEqual(['A:top:0', 'B:exiting:0']);
+ finishExit(getDialog('B'));
+ expect(stackSummary()).toEqual(['A:top:0']);
+ });
+
+ it('a platform close request pops the top sheet and is declined by a covered one', () => {
+ render(<Pair />);
+ const declined = fireCancel(getDialog('A'));
+ expect(declined.defaultPrevented).toBe(true);
+ expect(stackSummary()).toEqual(['A:covered:1', 'B:top:0']);
+
+ let accepted!: Event;
+ act(() => {
+ accepted = fireCancel(getDialog('B'));
+ });
+ expect(accepted.defaultPrevented).toBe(true);
+ expect(stackSummary()).toEqual(['A:top:0', 'B:exiting:0']);
+ });
+
+ it('Escape and a platform close reach the top sheet, not a covered sheet nested deeper in the tree', () => {
+ // B is rendered in A's content (one tree level deeper); C is written
+ // outside both and opened last, so C is the top sheet. The dismissal
+ // stack ranks tree depth first, so without the sheet stack standing a
+ // covered sheet down it would hand the press to B.
+ function App() {
+ const [isAOpen, setIsAOpen] = useState(true);
+ const [isBOpen, setIsBOpen] = useState(true);
+ const [isCOpen, setIsCOpen] = useState(false);
+ return (
+ <>
+ <BottomSheet isOpen={isAOpen} onOpenChange={setIsAOpen} label="A">
+ <button type="button" onClick={() => setIsCOpen(true)}>
+ Open C from A
+ </button>
+ <BottomSheet isOpen={isBOpen} onOpenChange={setIsBOpen} label="B">
+ <button type="button" onClick={() => setIsCOpen(true)}>
+ Open C from B
+ </button>
+ </BottomSheet>
+ </BottomSheet>
+ <BottomSheet isOpen={isCOpen} onOpenChange={setIsCOpen} label="C">
+ c
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open C from B'}));
+ expect(stackSummary()).toEqual(['A:covered:2', 'B:covered:1', 'C:top:0']);
+ act(() => {
+ pressEscape();
+ });
+ expect(stackSummary()).toEqual(['A:covered:1', 'B:top:0', 'C:exiting:0']);
+ expect(getDialog('B')).toHaveAttribute('open');
+ finishExit(getDialog('C'));
+ // Now B is the top sheet and takes the next press.
+ act(() => {
+ pressEscape();
+ });
+ expect(stackSummary()).toEqual(['A:top:0', 'B:exiting:0']);
+ finishExit(getDialog('B'));
+ // Platform close: the same rule. Reopen C over A.
+ fireEvent.click(screen.getByRole('button', {name: 'Open C from A'}));
+ expect(stackSummary()).toEqual(['A:covered:1', 'C:top:0']);
+ let accepted!: Event;
+ act(() => {
+ accepted = fireCancel(getDialog('C'));
+ });
+ expect(accepted.defaultPrevented).toBe(true);
+ expect(stackSummary()).toEqual(['A:top:0', 'C:exiting:0']);
+ });
+
+ it('honours the top sheet’s purpose: required blocks every path and shields the sheet below', () => {
+ render(<Pair purposeB="required" />);
+ let event!: KeyboardEvent;
+ act(() => {
+ event = pressEscape();
+ });
+ expect(event.defaultPrevented).toBe(true);
+ fireEvent.click(getDialog('B'));
+ drag(getHandle(getDialog('B')), [{y: 0}, {y: 40}, {y: 120}]);
+ fireCancel(getDialog('B'));
+ expect(stackSummary()).toEqual(['A:covered:1', 'B:top:0']);
+ });
+
+ it('honours a form top sheet: Escape closes, scrim and swipe do not', () => {
+ render(<Pair purposeB="form" />);
+ fireEvent.click(getDialog('B'));
+ drag(getHandle(getDialog('B')), [{y: 0}, {y: 40}, {y: 120}]);
+ expect(stackSummary()).toEqual(['A:covered:1', 'B:top:0']);
+ act(() => {
+ pressEscape();
+ });
+ expect(stackSummary()).toEqual(['A:top:0', 'B:exiting:0']);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Requirement 6 — one visible scrim per stack
+// ---------------------------------------------------------------------------
+
+describe('R6 one scrim', () => {
+ it('only the bottom sheet’s backdrop is visible; upper backdrops are transparent', () => {
+ render(<Nested initial />);
+ expect(scrim(getDialog('A'))).toBe('1');
+ expect(scrim(getDialog('B'))).toBe('0');
+ expect(scrim(getDialog('C'))).toBe('0');
+ });
+
+ it('keeps the dim stable through a push and a pop', () => {
+ render(<Siblings initialA />);
+ const a = getDialog('A');
+ expect(scrim(a)).toBe('1');
+ fireEvent.click(screen.getByRole('button', {name: 'Open B'}));
+ expect(scrim(a)).toBe('1');
+ expect(scrim(getDialog('B'))).toBe('0');
+ fireEvent.click(screen.getByRole('button', {name: 'Close B'}));
+ // The popped sheet's backdrop stays transparent through its exit; the
+ // bottom sheet's stays at full strength throughout.
+ expect(scrim(getDialog('B'))).toBe('0');
+ expect(scrim(a)).toBe('1');
+ finishExit(getDialog('B'));
+ expect(scrim(a)).toBe('1');
+ expect(scrimDuration(a)).toBe('');
+ });
+
+ it('hands the scrim over at once when the visible-backdrop sheet closes under others', () => {
+ render(<Siblings initialA initialB />);
+ const a = getDialog('A');
+ const b = getDialog('B');
+ const recorder = recordScrimWrites();
+ fireEvent.click(screen.getByRole('button', {name: 'Close A from B'}));
+ recorder.restore();
+ // The dim is B's from this frame on: B's backdrop appears with no fade
+ // and A's leaves with no fade, both pinned to 0s for the frame, so the
+ // page neither lightens nor darkens between the two. The pin is lifted
+ // again once the frame has painted.
+ expect(scrim(a)).toBe('0');
+ expect(scrim(b)).toBe('1');
+ expect(recorder.writes).toEqual(
+ expect.arrayContaining([
+ {opacity: '0', pin: '0s'},
+ {opacity: '1', pin: '0s'},
+ ]),
+ );
+ expect(scrimDuration(a)).toBe('');
+ expect(scrimDuration(b)).toBe('');
+ expect(getBottomSheetStackForTests()[0].view.isScrimTakenOver).toBe(true);
+ finishExit(a);
+ expect(stackSummary()).toEqual(['B:top:0']);
+ expect(scrim(b)).toBe('1');
+ });
+
+ it('a sheet closing alone fades its scrim out; no pin is applied', () => {
+ render(<Nested initial={false} />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open A'}));
+ const a = getDialog('A');
+ expect(scrim(a)).toBe('1');
+ const recorder = recordScrimWrites();
+ fireEvent.click(screen.getByRole('button', {name: 'Close A from page'}));
+ recorder.restore();
+ expect(scrim(a)).toBe('0');
+ expect(recorder.writes.every(write => write.pin === '')).toBe(true);
+ expect(classes(a)).toContain('scrimClosing');
+ });
+
+ it('a drag on an upper sheet never thins the visible scrim or reveals its own', () => {
+ render(<Siblings initialA initialB />);
+ // Partial drag that settles back: the gesture reports opacity changes.
+ drag(getHandle(getDialog('B')), [{y: 0}, {y: 10}, {y: 0}]);
+ expect(scrim(getDialog('A'))).toBe('1');
+ expect(scrim(getDialog('B'))).toBe('0');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Requirement 7 — closing a covered sheet from code
+// ---------------------------------------------------------------------------
+
+describe('R7 closing a covered sheet', () => {
+ it('takes the sheets rendered in its content with it, leaving their state to their owners', () => {
+ const onBChange = vi.fn();
+ const onCChange = vi.fn();
+ function App() {
+ const [isAOpen, setIsAOpen] = useState(true);
+ const [isBOpen, setIsBOpen] = useState(true);
+ const [isCOpen, setIsCOpen] = useState(true);
+ return (
+ <>
+ <button type="button" onClick={() => setIsAOpen(false)}>
+ Close A
+ </button>
+ <BottomSheet isOpen={isAOpen} onOpenChange={setIsAOpen} label="A">
+ <BottomSheet
+ isOpen={isBOpen}
+ onOpenChange={value => {
+ onBChange(value);
+ setIsBOpen(value);
+ }}
+ label="B">
+ <BottomSheet
+ isOpen={isCOpen}
+ onOpenChange={value => {
+ onCChange(value);
+ setIsCOpen(value);
+ }}
+ label="C">
+ c
+ </BottomSheet>
+ </BottomSheet>
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ expect(stackSummary()).toEqual(['A:covered:2', 'B:covered:1', 'C:top:0']);
+
+ fireEvent.click(screen.getByRole('button', {name: 'Close A'}));
+ // All three leave together. B and C are not asked to change their state:
+ // their `isOpen` stays the consumer's (a Dialog in a closed Dialog works
+ // the same way), and they come back if A reopens while they are open.
+ expect(onBChange).not.toHaveBeenCalled();
+ expect(onCChange).not.toHaveBeenCalled();
+ expect(stackSummary()).toEqual([
+ 'A:exiting:0',
+ 'B:exiting:0',
+ 'C:exiting:0',
+ ]);
+ finishExit(getDialog('C'));
+ finishExit(getDialog('B'));
+ finishExit(getDialog('A'));
+ expect(stackSummary()).toEqual([]);
+ expect(openDialogs()).toEqual([]);
+ });
+
+ it('a nested sheet still open when its host reopens is presented again, on top', () => {
+ function App() {
+ const [isAOpen, setIsAOpen] = useState(true);
+ return (
+ <>
+ <button type="button" onClick={() => setIsAOpen(false)}>
+ Close A
+ </button>
+ <button type="button" onClick={() => setIsAOpen(true)}>
+ Reopen A
+ </button>
+ <BottomSheet isOpen={isAOpen} onOpenChange={setIsAOpen} label="A">
+ <BottomSheet isOpen onOpenChange={() => {}} label="B">
+ b
+ </BottomSheet>
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ expect(stackSummary()).toEqual(['A:covered:1', 'B:top:0']);
+ fireEvent.click(screen.getByRole('button', {name: 'Close A'}));
+ finishExit(getDialog('B'));
+ finishExit(getDialog('A'));
+ expect(openDialogs()).toEqual([]);
+ fireEvent.click(screen.getByRole('button', {name: 'Reopen A'}));
+ expect(stackSummary()).toEqual(['A:covered:1', 'B:top:0']);
+ expect(openDialogs()).toEqual(['A', 'B']);
+ });
+
+ it('a switcher flow in a sheet’s content leaves with the sheet and returns with it; its state is never written', () => {
+ const onActiveSheetChange = vi.fn();
+ function App() {
+ const [isAOpen, setIsAOpen] = useState(true);
+ const [step, setStep] = useState<string | null>('one');
+ return (
+ <>
+ <button type="button" onClick={() => setIsAOpen(false)}>
+ Close A
+ </button>
+ <button type="button" onClick={() => setIsAOpen(true)}>
+ Reopen A
+ </button>
+ <BottomSheet isOpen={isAOpen} onOpenChange={setIsAOpen} label="A">
+ <BottomSheetSwitcher
+ activeSheet={step}
+ onActiveSheetChange={next => {
+ onActiveSheetChange(next);
+ setStep(next);
+ }}>
+ <BottomSheet sheetId="one" label="One">
+ one
+ </BottomSheet>
+ <BottomSheet sheetId="two" label="Two">
+ two
+ </BottomSheet>
+ </BottomSheetSwitcher>
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ expect(stackSummary()).toEqual(['A:covered:1', 'One:top:0']);
+ fireEvent.click(screen.getByRole('button', {name: 'Close A'}));
+ // The flow leaves with its host, through its own exit, without its
+ // state being written.
+ expect(onActiveSheetChange).not.toHaveBeenCalled();
+ expect(stackSummary()).toEqual(['A:exiting:0', 'One:exiting:0']);
+ finishExit(getDialog('One'));
+ finishExit(getDialog('A'));
+ expect(openDialogs()).toEqual([]);
+ expect(onActiveSheetChange).not.toHaveBeenCalled();
+ // The flow's state still names its step, so it comes back with the host.
+ fireEvent.click(screen.getByRole('button', {name: 'Reopen A'}));
+ expect(stackSummary()).toEqual(['A:covered:1', 'One:top:0']);
+ expect(openDialogs()).toEqual(['A', 'One']);
+ });
+
+ it('a sheet in a closed sheet’s content keeps its state and presents when that sheet opens', () => {
+ const onInnerChange = vi.fn();
+ function App() {
+ const [isOuterOpen, setIsOuterOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsOuterOpen(true)}>
+ Open outer
+ </button>
+ <BottomSheet
+ isOpen={isOuterOpen}
+ onOpenChange={setIsOuterOpen}
+ label="Outer">
+ <BottomSheet isOpen onOpenChange={onInnerChange} label="Inner">
+ inner
+ </BottomSheet>
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ expect(openDialogs()).toEqual([]);
+ // The inner sheet is not asked to close: its host has not closed, it
+ // merely has not opened yet.
+ expect(onInnerChange).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', {name: 'Open outer'}));
+ expect(stackSummary()).toEqual(['Outer:covered:1', 'Inner:top:0']);
+ expect(onInnerChange).not.toHaveBeenCalled();
+ });
+
+ it('never writes a nested sheet’s state: no onOpenChange on mount, rerender, StrictMode replay, or host close', () => {
+ const onInnerChange = vi.fn();
+ function App({tick}: {tick: number}) {
+ const [isOuterOpen, setIsOuterOpen] = useState(true);
+ return (
+ <>
+ <button type="button" onClick={() => setIsOuterOpen(false)}>
+ Close outer {tick}
+ </button>
+ <BottomSheet
+ isOpen={isOuterOpen}
+ onOpenChange={setIsOuterOpen}
+ label="Outer">
+ <BottomSheet
+ isOpen
+ onOpenChange={value => {
+ onInnerChange(value);
+ }}
+ label="Inner">
+ inner
+ </BottomSheet>
+ </BottomSheet>
+ </>
+ );
+ }
+ const {rerender} = render(
+ <StrictMode>
+ <App tick={0} />
+ </StrictMode>,
+ );
+ rerender(
+ <StrictMode>
+ <App tick={1} />
+ </StrictMode>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Close outer 1'}));
+ rerender(
+ <StrictMode>
+ <App tick={2} />
+ </StrictMode>,
+ );
+ expect(onInnerChange).not.toHaveBeenCalled();
+ // The inner sheet left with its host all the same.
+ expect(stackSummary()).toEqual(['Outer:exiting:0', 'Inner:exiting:0']);
+ });
+
+ it('leaves sibling sheets above it open: it slides out from beneath them', () => {
+ render(<Siblings initialA initialB />);
+ fireEvent.click(screen.getByRole('button', {name: 'Close A from B'}));
+ expect(stackSummary()).toEqual(['A:exiting:1', 'B:top:0']);
+ expect(getDialog('B')).toHaveAttribute('open');
+ expect(getDialog('B')).not.toHaveAttribute('inert');
+ finishExit(getDialog('A'));
+ expect(stackSummary()).toEqual(['B:top:0']);
+ expect(getDialog('B')).not.toHaveAttribute('data-sheet-stack');
+ expect(openDialogs()).toEqual(['B']);
+ // Nothing is stuck: B still closes normally.
+ fireEvent.click(screen.getByRole('button', {name: 'Close B'}));
+ finishExit(getDialog('B'));
+ expect(openDialogs()).toEqual([]);
+ });
+
+ it('a sheet in a switcher step leaves when the step is left', () => {
+ const onNestedChange = vi.fn();
+ function App() {
+ const [step, setStep] = useState<string | null>('one');
+ const [isNestedOpen, setIsNestedOpen] = useState(true);
+ return (
+ <>
+ <button type="button" onClick={() => setStep('two')}>
+ Step two
+ </button>
+ <BottomSheetSwitcher activeSheet={step} onActiveSheetChange={setStep}>
+ <BottomSheet sheetId="one" label="One">
+ <BottomSheet
+ isOpen={isNestedOpen}
+ onOpenChange={value => {
+ onNestedChange(value);
+ setIsNestedOpen(value);
+ }}
+ label="Nested">
+ nested
+ </BottomSheet>
+ </BottomSheet>
+ <BottomSheet sheetId="two" label="Two">
+ two
+ </BottomSheet>
+ </BottomSheetSwitcher>
+ </>
+ );
+ }
+ render(<App />);
+ expect(stackSummary()).toEqual(['One:covered:1', 'Nested:top:0']);
+ fireEvent.click(screen.getByRole('button', {name: 'Step two'}));
+ // The nested sheet leaves with the step; its state stays its owner's.
+ expect(onNestedChange).not.toHaveBeenCalled();
+ expect(stackSummary()).toEqual(['Two:top:0', 'Nested:exiting:0']);
+ finishExit(getDialog('Nested'));
+ expect(stackSummary()).toEqual(['Two:top:0']);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Requirement 8 — focus
+// ---------------------------------------------------------------------------
+
+describe('R8 focus', () => {
+ it('moves focus into a sheet when it opens, and returns it to the opener in the revealed sheet', () => {
+ render(<Siblings initialA />);
+ const openB = screen.getByRole('button', {name: 'Open B'});
+ openB.focus();
+ fireEvent.click(openB);
+ expect(getPanel(getDialog('B'))).toHaveFocus();
+
+ fireEvent.click(screen.getByRole('button', {name: 'Close B'}));
+ finishExit(getDialog('B'));
+ expect(openB).toHaveFocus();
+ });
+
+ it('focuses the revealed sheet’s panel when the opener is gone', () => {
+ function App() {
+ const [isAOpen, setIsAOpen] = useState(true);
+ const [isBOpen, setIsBOpen] = useState(false);
+ return (
+ <>
+ <BottomSheet isOpen={isAOpen} onOpenChange={setIsAOpen} label="A">
+ {!isBOpen && (
+ <button type="button" onClick={() => setIsBOpen(true)}>
+ Open B
+ </button>
+ )}
+ </BottomSheet>
+ <BottomSheet isOpen={isBOpen} onOpenChange={setIsBOpen} label="B">
+ <button type="button" onClick={() => setIsBOpen(false)}>
+ Close B
+ </button>
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ const openB = screen.getByRole('button', {name: 'Open B'});
+ openB.focus();
+ fireEvent.click(openB);
+ expect(openB).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', {name: 'Close B'}));
+ finishExit(getDialog('B'));
+ expect(getPanel(getDialog('A'))).toHaveFocus();
+ });
+
+ it('a switcher flow closing over a sheet focuses that sheet’s panel when the opener is gone', () => {
+ // The flow leaves the registry in the same commit its dialog closes
+ // (React runs the registration cleanup first), so the close must have
+ // read the sheet beneath before that.
+ function App() {
+ const [isAOpen, setIsAOpen] = useState(true);
+ const [step, setStep] = useState<string | null>(null);
+ return (
+ <>
+ <BottomSheet isOpen={isAOpen} onOpenChange={setIsAOpen} label="A">
+ {step == null && (
+ <button type="button" onClick={() => setStep('one')}>
+ Open flow
+ </button>
+ )}
+ </BottomSheet>
+ <BottomSheetSwitcher activeSheet={step} onActiveSheetChange={setStep}>
+ <BottomSheet sheetId="one" label="One">
+ <button type="button" onClick={() => setStep(null)}>
+ Close flow
+ </button>
+ </BottomSheet>
+ </BottomSheetSwitcher>
+ </>
+ );
+ }
+ render(<App />);
+ const openFlow = screen.getByRole('button', {name: 'Open flow'});
+ openFlow.focus();
+ fireEvent.click(openFlow);
+ expect(openFlow).not.toBeInTheDocument();
+ expect(stackSummary()).toEqual(['A:covered:1', 'One:top:0']);
+ // The flow's dialog is labelled by its active step; keep a handle.
+ const flowDialog = getDialog('One');
+ fireEvent.click(screen.getByRole('button', {name: 'Close flow'}));
+ finishExit(flowDialog);
+ expect(flowDialog).not.toHaveAttribute('open');
+ expect(stackSummary()).toEqual(['A:top:0']);
+ expect(getPanel(getDialog('A'))).toHaveFocus();
+ });
+
+ it('closing a covered sheet from code leaves focus in the top sheet', () => {
+ render(<Siblings initialA />);
+ const openB = screen.getByRole('button', {name: 'Open B'});
+ openB.focus();
+ fireEvent.click(openB);
+ const field = screen.getByLabelText('B field');
+ field.focus();
+ // jsdom's close() does not move focus; the browser's does, back to the
+ // element focused at showModal() (the button in A). Emulate it.
+ const a = getDialog('A');
+ const close = HTMLDialogElement.prototype.close;
+ HTMLDialogElement.prototype.close = function (this: HTMLDialogElement) {
+ close.call(this);
+ if (this === a) {
+ openB.focus();
+ }
+ };
+ fireEvent.click(screen.getByRole('button', {name: 'Close A from B'}));
+ finishExit(getDialog('A'));
+ expect(field).toHaveFocus();
+ expect(openDialogs()).toEqual(['B']);
+ });
+
+ it('a deep link returns focus into the revealed sheet, not to the page', () => {
+ render(<Nested initial />);
+ expect(getPanel(getDialog('C'))).toHaveFocus();
+ fireEvent.click(screen.getByRole('button', {name: 'Close C'}));
+ finishExit(getDialog('C'));
+ expect(getPanel(getDialog('B'))).toHaveFocus();
+ });
+
+ it('a popped sheet’s finalFocusRef outside the revealed sheet yields to that sheet’s panel; inside it, it is focused', () => {
+ const outside = document.createElement('button');
+ document.body.appendChild(outside);
+ const outsideRef = {current: outside as HTMLElement | null};
+ const insideRef = {current: null as HTMLElement | null};
+ function App() {
+ const [isAOpen, setIsAOpen] = useState(true);
+ const [isBOpen, setIsBOpen] = useState(false);
+ const [isCOpen, setIsCOpen] = useState(false);
+ return (
+ <>
+ <BottomSheet isOpen={isAOpen} onOpenChange={setIsAOpen} label="A">
+ <button
+ type="button"
+ ref={node => {
+ insideRef.current = node;
+ }}>
+ Inside A
+ </button>
+ <button type="button" onClick={() => setIsBOpen(true)}>
+ Open B
+ </button>
+ <button type="button" onClick={() => setIsCOpen(true)}>
+ Open C
+ </button>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={isBOpen}
+ onOpenChange={setIsBOpen}
+ finalFocusRef={outsideRef}
+ label="B">
+ <button type="button" onClick={() => setIsBOpen(false)}>
+ Close B
+ </button>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={isCOpen}
+ onOpenChange={setIsCOpen}
+ finalFocusRef={insideRef}
+ label="C">
+ <button type="button" onClick={() => setIsCOpen(false)}>
+ Close C
+ </button>
+ </BottomSheet>
+ </>
+ );
+ }
+ try {
+ render(<App />);
+ // B's target is on the page, which stays inert under A: A's panel.
+ fireEvent.click(screen.getByRole('button', {name: 'Open B'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Close B'}));
+ finishExit(getDialog('B'));
+ expect(getPanel(getDialog('A'))).toHaveFocus();
+ // C's target is inside A: it is focused.
+ fireEvent.click(screen.getByRole('button', {name: 'Open C'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Close C'}));
+ finishExit(getDialog('C'));
+ expect(screen.getByRole('button', {name: 'Inside A'})).toHaveFocus();
+ } finally {
+ outside.remove();
+ }
+ });
+
+ it('applies the standalone rules when the last sheet closes: the opener, or finalFocusRef', () => {
+ function App() {
+ const [isAOpen, setIsAOpen] = useState(false);
+ const [isBOpen, setIsBOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsAOpen(true)}>
+ Open A
+ </button>
+ <BottomSheet isOpen={isAOpen} onOpenChange={setIsAOpen} label="A">
+ <button type="button" onClick={() => setIsBOpen(true)}>
+ Open B
+ </button>
+ </BottomSheet>
+ <BottomSheet isOpen={isBOpen} onOpenChange={setIsBOpen} label="B">
+ <button
+ type="button"
+ onClick={() => {
+ setIsBOpen(false);
+ setIsAOpen(false);
+ }}>
+ Close all
+ </button>
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ const openA = screen.getByRole('button', {name: 'Open A'});
+ openA.focus();
+ fireEvent.click(openA);
+ fireEvent.click(screen.getByRole('button', {name: 'Open B'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Close all'}));
+ finishExit(getDialog('B'));
+ finishExit(getDialog('A'));
+ expect(openA).toHaveFocus();
+ expect(openDialogs()).toEqual([]);
+ });
+
+ /**
+ * A browser refuses to focus an element outside every open modal dialog
+ * (everything else is inert while a modal is shown) and anything inside a
+ * closed dialog (`display: none`). jsdom lets any focus through, which
+ * hides the "Close all" problem: the exits complete bottom first (all the
+ * panels' transitions end in the same frame, in tree order), so each
+ * sheet returns focus at depth 0 — the bottom sheet to a page opener
+ * refused while the dialogs above are still modal, the upper sheets to
+ * openers inside dialogs that are closed. Emulate the browser's rules.
+ */
+ function withModalFocusBlocking(run: () => void) {
+ const focus = HTMLElement.prototype.focus;
+ HTMLElement.prototype.focus = function (
+ this: HTMLElement,
+ options?: FocusOptions,
+ ) {
+ const own = this.closest('dialog');
+ if (own != null && !own.open) {
+ return;
+ }
+ const modal = [...document.querySelectorAll('dialog[open]')].filter(
+ d => d.getAttribute('aria-modal') === 'true',
+ );
+ if (modal.length > 0 && !modal.some(d => d.contains(this))) {
+ return;
+ }
+ focus.call(this, options);
+ };
+ try {
+ run();
+ } finally {
+ HTMLElement.prototype.focus = focus;
+ }
+ }
+
+ describe('closing every sheet in one update ("Close all")', () => {
+ it('returns focus once, to the bottom sheet’s opener, after the last dialog has closed (standalone sheets, depth 3)', () => {
+ function App() {
+ const [isAOpen, setIsAOpen] = useState(false);
+ const [isBOpen, setIsBOpen] = useState(false);
+ const [isCOpen, setIsCOpen] = useState(false);
+ const closeAll = () => {
+ setIsCOpen(false);
+ setIsBOpen(false);
+ setIsAOpen(false);
+ };
+ return (
+ <>
+ <button type="button" onClick={() => setIsAOpen(true)}>
+ Open A
+ </button>
+ <BottomSheet isOpen={isAOpen} onOpenChange={setIsAOpen} label="A">
+ <button type="button" onClick={() => setIsBOpen(true)}>
+ Open B
+ </button>
+ </BottomSheet>
+ <BottomSheet isOpen={isBOpen} onOpenChange={setIsBOpen} label="B">
+ <button type="button" onClick={() => setIsCOpen(true)}>
+ Open C
+ </button>
+ </BottomSheet>
+ <BottomSheet isOpen={isCOpen} onOpenChange={setIsCOpen} label="C">
+ <button type="button" onClick={closeAll}>
+ Close all
+ </button>
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ const openA = screen.getByRole('button', {name: 'Open A'});
+ openA.focus();
+ fireEvent.click(openA);
+ fireEvent.click(screen.getByRole('button', {name: 'Open B'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Open C'}));
+ expect(stackSummary()).toEqual(['A:covered:2', 'B:covered:1', 'C:top:0']);
+ withModalFocusBlocking(() => {
+ fireEvent.click(screen.getByRole('button', {name: 'Close all'}));
+ // The exits complete bottom first (tree order of the transitionend
+ // events, all in one frame), as in Chromium.
+ finishExit(getDialog('A'));
+ expect(openA).not.toHaveFocus();
+ finishExit(getDialog('B'));
+ expect(openA).not.toHaveFocus();
+ finishExit(getDialog('C'));
+ });
+ expect(openDialogs()).toEqual([]);
+ expect(openA).toHaveFocus();
+ });
+
+ it('returns focus when a member of the group unmounts mid-exit instead of reporting its motion (Close all with the upper sheet unmounting)', () => {
+ function App() {
+ const [isAOpen, setIsAOpen] = useState(false);
+ const [isBOpen, setIsBOpen] = useState(false);
+ const [isBMounted, setIsBMounted] = useState(true);
+ const closeAll = () => {
+ setIsBOpen(false);
+ setIsAOpen(false);
+ };
+ return (
+ <>
+ <button type="button" onClick={() => setIsAOpen(true)}>
+ Open A
+ </button>
+ <button type="button" onClick={() => setIsBMounted(false)}>
+ Unmount B
+ </button>
+ <BottomSheet isOpen={isAOpen} onOpenChange={setIsAOpen} label="A">
+ <button type="button" onClick={() => setIsBOpen(true)}>
+ Open B
+ </button>
+ </BottomSheet>
+ {isBMounted && (
+ <BottomSheet isOpen={isBOpen} onOpenChange={setIsBOpen} label="B">
+ <button type="button" onClick={closeAll}>
+ Close all
+ </button>
+ </BottomSheet>
+ )}
+ </>
+ );
+ }
+ render(<App />);
+ const openA = screen.getByRole('button', {name: 'Open A'});
+ openA.focus();
+ fireEvent.click(openA);
+ fireEvent.click(screen.getByRole('button', {name: 'Open B'}));
+ expect(stackSummary()).toEqual(['A:covered:1', 'B:top:0']);
+ withModalFocusBlocking(() => {
+ fireEvent.click(screen.getByRole('button', {name: 'Close all'}));
+ // Both exits are under way (the group is formed) when B's owner stops
+ // rendering it: its dialog was still open, and no exit motion will
+ // ever be reported for it. A's exit is the only one left.
+ expect(getDialog('B')).toHaveAttribute('open');
+ fireEvent.click(screen.getByRole('button', {name: 'Unmount B'}));
+ expect(screen.queryByRole('dialog', {name: 'B'})).toBeNull();
+ finishExit(getDialog('A'));
+ });
+ expect(openDialogs()).toEqual([]);
+ expect(openA).toHaveFocus();
+ });
+
+ it('prefers the bottom sheet’s finalFocusRef', () => {
+ const target = document.createElement('button');
+ document.body.appendChild(target);
+ const finalFocusRef = {current: target as HTMLElement | null};
+ function App() {
+ const [isAOpen, setIsAOpen] = useState(true);
+ const [isBOpen, setIsBOpen] = useState(true);
+ return (
+ <>
+ <BottomSheet
+ isOpen={isAOpen}
+ onOpenChange={setIsAOpen}
+ finalFocusRef={finalFocusRef}
+ label="A">
+ a
+ </BottomSheet>
+ <BottomSheet isOpen={isBOpen} onOpenChange={setIsBOpen} label="B">
+ <button
+ type="button"
+ onClick={() => {
+ setIsBOpen(false);
+ setIsAOpen(false);
+ }}>
+ Close all
+ </button>
+ </BottomSheet>
+ </>
+ );
+ }
+ try {
+ render(<App />);
+ withModalFocusBlocking(() => {
+ fireEvent.click(screen.getByRole('button', {name: 'Close all'}));
+ finishExit(getDialog('A'));
+ finishExit(getDialog('B'));
+ });
+ expect(target).toHaveFocus();
+ } finally {
+ target.remove();
+ }
+ });
+
+ it('a switcher flow on top closes with the sheet beneath it, focus to the bottom sheet’s opener', () => {
+ function App() {
+ const [isAOpen, setIsAOpen] = useState(false);
+ const [step, setStep] = useState<string | null>(null);
+ return (
+ <>
+ <button type="button" onClick={() => setIsAOpen(true)}>
+ Open A
+ </button>
+ <BottomSheet isOpen={isAOpen} onOpenChange={setIsAOpen} label="A">
+ <button type="button" onClick={() => setStep('one')}>
+ Open flow
+ </button>
+ </BottomSheet>
+ <BottomSheetSwitcher
+ activeSheet={step}
+ onActiveSheetChange={setStep}>
+ <BottomSheet sheetId="one" label="One">
+ <button
+ type="button"
+ onClick={() => {
+ setStep(null);
+ setIsAOpen(false);
+ }}>
+ Close all
+ </button>
+ </BottomSheet>
+ </BottomSheetSwitcher>
+ </>
+ );
+ }
+ render(<App />);
+ const openA = screen.getByRole('button', {name: 'Open A'});
+ openA.focus();
+ fireEvent.click(openA);
+ fireEvent.click(screen.getByRole('button', {name: 'Open flow'}));
+ expect(stackSummary()).toEqual(['A:covered:1', 'One:top:0']);
+ const flowDialog = getDialog('One');
+ withModalFocusBlocking(() => {
+ fireEvent.click(screen.getByRole('button', {name: 'Close all'}));
+ finishExit(getDialog('A'));
+ finishExit(flowDialog);
+ });
+ expect(openDialogs()).toEqual([]);
+ expect(openA).toHaveFocus();
+ });
+
+ it('non-modal sheets closing together keep their own rule: the opener only while focus was inside', () => {
+ function App() {
+ const [isAOpen, setIsAOpen] = useState(false);
+ const [isBOpen, setIsBOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsAOpen(true)}>
+ Open A
+ </button>
+ <BottomSheet
+ isOpen={isAOpen}
+ onOpenChange={setIsAOpen}
+ hasScrim={false}
+ label="A">
+ <button type="button" onClick={() => setIsBOpen(true)}>
+ Open B
+ </button>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={isBOpen}
+ onOpenChange={setIsBOpen}
+ hasScrim={false}
+ label="B">
+ <button
+ type="button"
+ onClick={() => {
+ setIsBOpen(false);
+ setIsAOpen(false);
+ }}>
+ Close all
+ </button>
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ const openA = screen.getByRole('button', {name: 'Open A'});
+ openA.focus();
+ fireEvent.click(openA);
+ const openB = screen.getByRole('button', {name: 'Open B'});
+ openB.focus();
+ fireEvent.click(openB);
+ // No modal dialog blocks anything; B's own close ran with focus
+ // inside B, so it returns to B's opener (inside A, which is leaving),
+ // then A's close finds focus no longer inside it and leaves it.
+ // Nothing is grouped.
+ expect(getBottomSheetStackForTests()).toHaveLength(0);
+ const closeAll = screen.getByRole('button', {name: 'Close all'});
+ closeAll.focus();
+ fireEvent.click(closeAll);
+ finishExit(getDialog('B'));
+ finishExit(getDialog('A'));
+ expect(openDialogs()).toEqual([]);
+ expect(document.activeElement).not.toBe(document.body);
+ });
+
+ it('a modal sheet closing with a non-modal one is not a group', () => {
+ function App() {
+ const [isAOpen, setIsAOpen] = useState(false);
+ const [isBOpen, setIsBOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsAOpen(true)}>
+ Open A
+ </button>
+ <BottomSheet isOpen={isAOpen} onOpenChange={setIsAOpen} label="A">
+ <button type="button" onClick={() => setIsBOpen(true)}>
+ Open B
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ setIsBOpen(false);
+ setIsAOpen(false);
+ }}>
+ Close all
+ </button>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={isBOpen}
+ onOpenChange={setIsBOpen}
+ hasScrim={false}
+ label="B">
+ b
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ const openA = screen.getByRole('button', {name: 'Open A'});
+ openA.focus();
+ fireEvent.click(openA);
+ fireEvent.click(screen.getByRole('button', {name: 'Open B'}));
+ withModalFocusBlocking(() => {
+ fireEvent.click(screen.getByRole('button', {name: 'Close all'}));
+ finishExit(getDialog('A'));
+ finishExit(getDialog('B'));
+ });
+ // The one modal sheet returns focus through its own close.
+ expect(openDialogs()).toEqual([]);
+ expect(openA).toHaveFocus();
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Requirement 9 — the native top layer
+// ---------------------------------------------------------------------------
+
+describe('R9 top layer', () => {
+ it('keeps each sheet’s own dialog where it is written; nothing moves', () => {
+ const {container} = render(
+ <div data-testid="where-written">
+ <Siblings initialA initialB />
+ </div>,
+ );
+ const region = container.querySelector('[data-testid="where-written"]')!;
+ expect(getDialog('A').parentElement).toBe(region);
+ expect(getDialog('B').parentElement).toBe(region);
+ expect(getDialog('A')).toHaveAttribute('open');
+ expect(getDialog('B')).toHaveAttribute('open');
+ expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalledTimes(2);
+ });
+
+ it('a Dialog opened from a stacked sheet paints above it, and a sheet opened from that Dialog paints above the Dialog', () => {
+ function App() {
+ const [isDialogOpen, setIsDialogOpen] = useState(false);
+ const [isCOpen, setIsCOpen] = useState(false);
+ return (
+ <>
+ <BottomSheet isOpen onOpenChange={() => {}} label="A">
+ a
+ </BottomSheet>
+ <BottomSheet isOpen onOpenChange={() => {}} label="B">
+ <button type="button" onClick={() => setIsDialogOpen(true)}>
+ Open dialog
+ </button>
+ <Dialog
+ isOpen={isDialogOpen}
+ onOpenChange={setIsDialogOpen}
+ aria-label="Over">
+ <button type="button" onClick={() => setIsCOpen(true)}>
+ Open C
+ </button>
+ <BottomSheet isOpen={isCOpen} onOpenChange={setIsCOpen} label="C">
+ c
+ </BottomSheet>
+ </Dialog>
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open dialog'}));
+ expect(topLayerOrder()).toEqual(['A', 'B', 'Over']);
+ fireEvent.click(screen.getByRole('button', {name: 'Open C'}));
+ expect(topLayerOrder()).toEqual(['A', 'B', 'Over', 'C']);
+ // The Dialog is not a sheet: C is the top sheet over B, and the Dialog
+ // sits between them in the top layer without entering the stack.
+ expect(stackSummary()).toEqual(['A:covered:2', 'B:covered:1', 'C:top:0']);
+ // B contains the Dialog that contains C, so inert on B would reach C.
+ expect(getDialog('B')).not.toHaveAttribute('inert');
+ expect(getDialog('A')).toHaveAttribute('inert');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Requirement 10 — concurrent React
+// ---------------------------------------------------------------------------
+
+describe('R10 concurrent React', () => {
+ it('StrictMode leaves exactly one entry per sheet and every dialog open', () => {
+ render(
+ <StrictMode>
+ <Siblings initialA initialB />
+ </StrictMode>,
+ );
+ expect(stackSummary()).toEqual(['A:covered:1', 'B:top:0']);
+ expect(openDialogs()).toEqual(['A', 'B']);
+ expect(topLayerOrder()).toEqual(['A', 'B']);
+ expect(getPanel(getDialog('B'))).toHaveFocus();
+ });
+
+ it('StrictMode keeps an out-of-tree-order stack in open order', () => {
+ render(
+ <StrictMode>
+ <Siblings reversed />
+ </StrictMode>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Open A'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Open B'}));
+ expect(stackSummary()).toEqual(['A:covered:1', 'B:top:0']);
+ });
+
+ it('a transition that never commits has no effect', () => {
+ const never = new Promise<never>(() => {});
+ function Gate({children}: {children: ReactNode}): ReactNode {
+ if (children != null) {
+ // eslint-disable-next-line @typescript-eslint/only-throw-error -- Suspense protocol: a thrown promise suspends the subtree
+ throw never;
+ }
+ return children;
+ }
+ let setShow!: (value: boolean) => void;
+ function App() {
+ const [show, set] = useState(false);
+ setShow = set;
+ return (
+ <>
+ <BottomSheet isOpen onOpenChange={() => {}} label="A">
+ a
+ </BottomSheet>
+ <Suspense fallback={null}>
+ {show ? (
+ <Gate>
+ <BottomSheet isOpen onOpenChange={() => {}} label="B">
+ b
+ </BottomSheet>
+ </Gate>
+ ) : null}
+ </Suspense>
+ </>
+ );
+ }
+ render(<App />);
+ act(() => {
+ startTransition(() => setShow(true));
+ });
+ expect(stackSummary()).toEqual(['A:top:0']);
+ expect(openDialogs()).toEqual(['A']);
+ expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalledTimes(1);
+ });
+
+ it('Suspense hide takes a sheet out of the stack; reveal re-presents it on top', async () => {
+ let resolveGate!: () => void;
+ const gate = new Promise<void>(resolve => {
+ resolveGate = resolve;
+ });
+ let isSettled = false;
+ void gate.then(() => {
+ isSettled = true;
+ });
+ function MaybeSuspend({suspend}: {suspend: boolean}) {
+ if (suspend && !isSettled) {
+ // eslint-disable-next-line @typescript-eslint/only-throw-error -- Suspense protocol: a thrown promise suspends the subtree
+ throw gate;
+ }
+ return null;
+ }
+ let setSuspend!: (value: boolean) => void;
+ function App() {
+ const [suspend, set] = useState(false);
+ setSuspend = set;
+ return (
+ <>
+ <BottomSheet isOpen onOpenChange={() => {}} label="A">
+ a
+ </BottomSheet>
+ <Suspense fallback={<span data-testid="fallback" />}>
+ <BottomSheet isOpen onOpenChange={() => {}} label="B">
+ <MaybeSuspend suspend={suspend} />
+ </BottomSheet>
+ </Suspense>
+ <BottomSheet isOpen onOpenChange={() => {}} label="C">
+ c
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ expect(stackSummary()).toEqual(['A:covered:2', 'B:covered:1', 'C:top:0']);
+
+ act(() => setSuspend(true));
+ expect(screen.getByTestId('fallback')).toBeInTheDocument();
+ // The hidden sheet left the stack and the top layer: a modal dialog with
+ // no box would otherwise keep blocking the page.
+ expect(stackSummary()).toEqual(['A:covered:1', 'C:top:0']);
+ expect(openDialogs()).toEqual(['A', 'C']);
+
+ await act(async () => {
+ resolveGate();
+ await gate;
+ });
+ // Revealed: presented again, as the most recent open — on top.
+ expect(stackSummary()).toEqual(['A:covered:2', 'C:covered:1', 'B:top:0']);
+ expect(topLayerOrder()).toEqual(['A', 'C', 'B']);
+ });
+
+ it('Activity hidden takes a sheet out; visible re-presents it on top with its state', () => {
+ let setHidden!: (value: boolean) => void;
+ function App() {
+ const [hidden, set] = useState(false);
+ setHidden = set;
+ return (
+ <>
+ <BottomSheet isOpen onOpenChange={() => {}} label="A">
+ a
+ </BottomSheet>
+ <Activity mode={hidden ? 'hidden' : 'visible'}>
+ <BottomSheet isOpen onOpenChange={() => {}} label="B">
+ <input aria-label="bInput" defaultValue="" />
+ </BottomSheet>
+ </Activity>
+ <BottomSheet isOpen onOpenChange={() => {}} label="C">
+ c
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ fireEvent.change(screen.getByLabelText('bInput'), {
+ target: {value: 'kept'},
+ });
+ act(() => setHidden(true));
+ expect(stackSummary()).toEqual(['A:covered:1', 'C:top:0']);
+ expect(openDialogs()).toEqual(['A', 'C']);
+ act(() => setHidden(false));
+ expect(stackSummary()).toEqual(['A:covered:2', 'C:covered:1', 'B:top:0']);
+ expect(screen.getByLabelText('bInput')).toHaveValue('kept');
+ });
+
+ it('SSR and hydration markup match, and the stack forms on the client', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ function App() {
+ return (
+ <BottomSheet isOpen onOpenChange={() => {}} label="A">
+ <BottomSheet isOpen onOpenChange={() => {}} label="B">
+ b
+ </BottomSheet>
+ </BottomSheet>
+ );
+ }
+ const html = renderToString(<App />);
+ expect(html).not.toContain('data-sheet-stack');
+ const container = document.createElement('div');
+ container.innerHTML = html;
+ document.body.appendChild(container);
+ let root!: ReturnType<typeof hydrateRoot>;
+ await act(async () => {
+ root = hydrateRoot(container, <App />);
+ });
+ expect(error).not.toHaveBeenCalled();
+ expect(stackSummary()).toEqual(['A:covered:1', 'B:top:0']);
+ expect(topLayerOrder()).toEqual(['A', 'B']);
+ act(() => root.unmount());
+ container.remove();
+ error.mockRestore();
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Requirement 11 — non-modal sheets stay out of the stack
+// ---------------------------------------------------------------------------
+
+describe('R11 non-modal sheets', () => {
+ it('a hasScrim={false} sheet neither joins the stack nor recedes a modal sheet', () => {
+ function App() {
+ const [isNonModalOpen, setIsNonModalOpen] = useState(false);
+ return (
+ <>
+ <BottomSheet isOpen onOpenChange={() => {}} label="Modal">
+ <button type="button" onClick={() => setIsNonModalOpen(true)}>
+ Open non-modal
+ </button>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={isNonModalOpen}
+ onOpenChange={setIsNonModalOpen}
+ hasScrim={false}
+ label="NonModal">
+ non-modal
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open non-modal'}));
+ expect(getDialog('NonModal')).toHaveAttribute('open');
+ // Not shown modally and not a stack level. Opened while a modal that
+ // does not contain it is open, it is inert under that modal, so it is
+ // not put in the top layer (there it would paint above the modal while
+ // a press on it lands on the modal): it is shown by show(), beneath.
+ expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled();
+ expect(HTMLDialogElement.prototype.show).toHaveBeenCalledTimes(1);
+ expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalledTimes(1);
+ expect(stackSummary()).toEqual(['Modal:top:0']);
+ expect(getDialog('Modal')).not.toHaveAttribute('data-sheet-stack');
+ expect(getDialog('NonModal')).not.toHaveAttribute('data-sheet-stack');
+ expect(getComputedStyle(getPositioner(getDialog('Modal'))).transform).toBe(
+ '',
+ );
+ });
+
+ it('a hasScrim={false} sheet rendered inside an open modal sheet enters the top layer', () => {
+ function App() {
+ const [isNonModalOpen, setIsNonModalOpen] = useState(false);
+ return (
+ <BottomSheet isOpen onOpenChange={() => {}} label="Modal">
+ <button type="button" onClick={() => setIsNonModalOpen(true)}>
+ Open non-modal
+ </button>
+ <BottomSheet
+ isOpen={isNonModalOpen}
+ onOpenChange={setIsNonModalOpen}
+ hasScrim={false}
+ label="NonModal">
+ non-modal
+ </BottomSheet>
+ </BottomSheet>
+ );
+ }
+ render(<App />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open non-modal'}));
+ // Inside the modal's content it is not inert, so the top layer is right.
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1);
+ expect(HTMLDialogElement.prototype.show).not.toHaveBeenCalled();
+ });
+
+ it('a hasScrim={false} sheet opened from a Dialog and rendered outside it stays beneath the Dialog', () => {
+ function App() {
+ const [isNonModalOpen, setIsNonModalOpen] = useState(false);
+ return (
+ <>
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Edit">
+ <button type="button" onClick={() => setIsNonModalOpen(true)}>
+ Open non-modal
+ </button>
+ </Dialog>
+ <BottomSheet
+ isOpen={isNonModalOpen}
+ onOpenChange={setIsNonModalOpen}
+ hasScrim={false}
+ label="NonModal">
+ non-modal
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open non-modal'}));
+ expect(getDialog('NonModal')).toHaveAttribute('open');
+ expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled();
+ expect(HTMLDialogElement.prototype.show).toHaveBeenCalledTimes(1);
+ });
+
+ it('a hasScrim={false} sheet shown beneath a Dialog enters the top layer once the Dialog closes, announcing its entry', () => {
+ function App() {
+ const [isDialogOpen, setIsDialogOpen] = useState(true);
+ const [isNonModalOpen, setIsNonModalOpen] = useState(false);
+ return (
+ <>
+ <Dialog
+ isOpen={isDialogOpen}
+ onOpenChange={setIsDialogOpen}
+ aria-label="Edit">
+ <button type="button" onClick={() => setIsNonModalOpen(true)}>
+ Open non-modal
+ </button>
+ <button type="button" onClick={() => setIsDialogOpen(false)}>
+ Close dialog
+ </button>
+ </Dialog>
+ <BottomSheet
+ isOpen={isNonModalOpen}
+ onOpenChange={setIsNonModalOpen}
+ hasScrim={false}
+ label="NonModal">
+ non-modal
+ </BottomSheet>
+ </>
+ );
+ }
+ const entries: string[] = [];
+ const unsubscribe = subscribeModalOutlets(change => {
+ entries.push(change);
+ });
+ render(<App />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open non-modal'}));
+ expect(HTMLDialogElement.prototype.show).toHaveBeenCalledTimes(1);
+ expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled();
+ expect(entries).not.toContain('entry');
+ // The Dialog closes: its dialog loses `open` and, as in a browser, a
+ // `close` event follows. The waiting sheet leaves show() for the top
+ // layer and announces the entry global hosts re-enter above.
+ fireEvent.click(screen.getByRole('button', {name: 'Close dialog'}));
+ act(() => {
+ getDialog('Edit').dispatchEvent(new Event('close'));
+ });
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1);
+ expect(getDialog('NonModal')).toHaveAttribute('open');
+ expect(entries).toContain('entry');
+ unsubscribe();
+ });
+
+ it('a hasScrim={false} sheet shown beneath a Dialog enters the top layer when that Dialog unmounts while open (no close event fires)', async () => {
+ function App() {
+ const [isEditing, setIsEditing] = useState(true);
+ const [isNonModalOpen, setIsNonModalOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsNonModalOpen(true)}>
+ Open non-modal
+ </button>
+ <button type="button" onClick={() => setIsEditing(false)}>
+ Unmount dialog
+ </button>
+ {isEditing && (
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Edit">
+ editing
+ </Dialog>
+ )}
+ <BottomSheet
+ isOpen={isNonModalOpen}
+ onOpenChange={setIsNonModalOpen}
+ hasScrim={false}
+ label="NonModal">
+ non-modal
+ </BottomSheet>
+ </>
+ );
+ }
+ const entries: string[] = [];
+ const unsubscribe = subscribeModalOutlets(change => {
+ entries.push(change);
+ });
+ render(<App />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open non-modal'}));
+ expect(HTMLDialogElement.prototype.show).toHaveBeenCalledTimes(1);
+ expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled();
+ // The Dialog is removed from the document still open: no `close` event
+ // and no sheet-stack update follow. The removal itself is the signal.
+ fireEvent.click(screen.getByRole('button', {name: 'Unmount dialog'}));
+ expect(screen.queryByRole('dialog', {name: 'Edit'})).toBeNull();
+ // Mutation records are delivered on a microtask.
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1);
+ expect(getDialog('NonModal')).toHaveAttribute('open');
+ expect(entries).toContain('entry');
+ unsubscribe();
+ });
+
+ it('a hasScrim={false} sheet opened in the update that closes a modal sheet enters the top layer at once (the closing modal is gone for this decision)', () => {
+ function App() {
+ const [isModalOpen, setIsModalOpen] = useState(true);
+ const [isNonModalOpen, setIsNonModalOpen] = useState(false);
+ return (
+ <>
+ <BottomSheet
+ isOpen={isModalOpen}
+ onOpenChange={setIsModalOpen}
+ label="Modal">
+ <button
+ type="button"
+ onClick={() => {
+ setIsModalOpen(false);
+ setIsNonModalOpen(true);
+ }}>
+ Swap
+ </button>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={isNonModalOpen}
+ onOpenChange={setIsNonModalOpen}
+ hasScrim={false}
+ label="NonModal">
+ non-modal
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ // A browser keeps answering `:modal` for the closing dialog until its
+ // close(); jsdom answers false to `:modal` for everything, so give this
+ // dialog the browser's answer.
+ const modal = getDialog('Modal');
+ const nativeMatches = modal.matches.bind(modal);
+ vi.spyOn(modal, 'matches').mockImplementation((selectors: string) =>
+ selectors === ':modal'
+ ? modal.hasAttribute('open')
+ : nativeMatches(selectors),
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Swap'}));
+ // The modal sheet is mid-exit: still an open modal dialog, but inert.
+ expect(modal).toHaveAttribute('open');
+ expect(modal).toHaveAttribute('inert');
+ expect(modal.matches(':modal')).toBe(true);
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1);
+ expect(HTMLDialogElement.prototype.show).not.toHaveBeenCalled();
+ });
+
+ it('a hasScrim={false} sheet deferred under a plain showModal() dialog with no aria-modal (a MobileNav or Lightbox host) is promoted when that dialog is removed while open', async () => {
+ // A bare <dialog> presented with showModal(): the browser answers
+ // `:modal` for it and nothing sets aria-modal. jsdom answers false to
+ // `:modal` for everything, so give this dialog the browser's answer —
+ // only while it is in the document and open, as a browser would.
+ const plain = document.createElement('dialog');
+ plain.setAttribute('aria-label', 'Nav');
+ plain.textContent = 'nav';
+ document.body.appendChild(plain);
+ plain.setAttribute('open', '');
+ const nativeMatches = plain.matches.bind(plain);
+ vi.spyOn(plain, 'matches').mockImplementation((selectors: string) =>
+ selectors === ':modal'
+ ? plain.isConnected && plain.hasAttribute('open')
+ : nativeMatches(selectors),
+ );
+ function App() {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsOpen(true)}>
+ Open non-modal
+ </button>
+ <BottomSheet
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ hasScrim={false}
+ label="NonModal">
+ non-modal
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open non-modal'}));
+ expect(HTMLDialogElement.prototype.show).toHaveBeenCalledTimes(1);
+ expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled();
+ // The nav is removed from the document still open: no close event, and
+ // nothing on the removed node says it was modal.
+ plain.remove();
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1);
+ expect(getDialog('NonModal')).toHaveAttribute('open');
+ });
+
+ it('a hasScrim={false} sheet deferred under one Dialog that is replaced by another in a single update is promoted when the second unmounts while open (the re-check records the new blocker)', async () => {
+ function App() {
+ const [editor, setEditor] = useState<'caption' | 'alt' | null>('caption');
+ const [isNonModalOpen, setIsNonModalOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsNonModalOpen(true)}>
+ Open non-modal
+ </button>
+ <button type="button" onClick={() => setEditor('alt')}>
+ Switch editor
+ </button>
+ <button type="button" onClick={() => setEditor(null)}>
+ Unmount editor
+ </button>
+ {editor === 'caption' && (
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Caption">
+ caption
+ </Dialog>
+ )}
+ {editor === 'alt' && (
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Alt text">
+ alt text
+ </Dialog>
+ )}
+ <BottomSheet
+ isOpen={isNonModalOpen}
+ onOpenChange={setIsNonModalOpen}
+ hasScrim={false}
+ label="NonModal">
+ non-modal
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open non-modal'}));
+ expect(HTMLDialogElement.prototype.show).toHaveBeenCalledTimes(1);
+ expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled();
+ // One update: the Caption dialog leaves (still open, no close event) and
+ // the Alt text dialog arrives open. The sheet stays beneath the new one.
+ fireEvent.click(screen.getByRole('button', {name: 'Switch editor'}));
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(screen.queryByRole('dialog', {name: 'Caption'})).toBeNull();
+ expect(getDialog('Alt text')).toHaveAttribute('open');
+ expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled();
+ // The second dialog unmounts while open too.
+ fireEvent.click(screen.getByRole('button', {name: 'Unmount editor'}));
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1);
+ expect(getDialog('NonModal')).toHaveAttribute('open');
+ });
+
+ it('a hasScrim={false} sheet opened with no modal open enters the top layer', () => {
+ function App() {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsOpen(true)}>
+ Open non-modal
+ </button>
+ <BottomSheet
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ hasScrim={false}
+ label="NonModal">
+ non-modal
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open non-modal'}));
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1);
+ expect(HTMLDialogElement.prototype.show).not.toHaveBeenCalled();
+ });
+
+ it('a modal sheet opened over a non-modal sheet does not recede it', () => {
+ function App() {
+ const [isModalOpen, setIsModalOpen] = useState(false);
+ return (
+ <>
+ <BottomSheet
+ isOpen
+ onOpenChange={() => {}}
+ hasScrim={false}
+ label="NonModal">
+ <button type="button" onClick={() => setIsModalOpen(true)}>
+ Open modal
+ </button>
+ </BottomSheet>
+ <BottomSheet
+ isOpen={isModalOpen}
+ onOpenChange={setIsModalOpen}
+ label="Modal">
+ modal
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open modal'}));
+ expect(stackSummary()).toEqual(['Modal:top:0']);
+ expect(getDialog('NonModal')).not.toHaveAttribute('data-sheet-stack');
+ expect(getDialog('NonModal')).not.toHaveAttribute('inert');
+ expect(
+ getComputedStyle(getPositioner(getDialog('NonModal'))).transform,
+ ).toBe('');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Requirement 13 — one registry per realm, per document
+// ---------------------------------------------------------------------------
+
+describe('R13 registry state', () => {
+ it('keeps its state on globalThis under a shared symbol, with its shape', () => {
+ const holder = globalThis as Record<symbol, unknown>;
+ const shared = holder[BOTTOM_SHEET_STACK_STATE_FOR_TESTS.key] as {
+ shape: number;
+ entries: unknown[];
+ };
+ expect(shared.shape).toBe(BOTTOM_SHEET_STACK_STATE_FOR_TESTS.shape);
+ render(<Siblings initialA />);
+ expect(shared.entries).toHaveLength(1);
+ });
+
+ it('everything the stack reads across commits is in the shared state, nothing per copy: the deferred non-modal sheets and the element to keep focused are shared by a second same-protocol copy', async () => {
+ const holder = globalThis as Record<symbol, unknown>;
+ const shared = holder[BOTTOM_SHEET_STACK_STATE_FOR_TESTS.key] as {
+ entries: unknown[];
+ shownOrder: WeakMap<Document, unknown>;
+ listenedDocuments: WeakMap<Document, unknown>;
+ lastPress: WeakMap<Document, unknown>;
+ focusToKeep: WeakMap<Document, unknown>;
+ deferredTopLayer: WeakMap<Document, {deferred: Map<unknown, unknown>}>;
+ };
+ // The shape carries every per-document table the stack keeps.
+ for (const table of [
+ 'shownOrder',
+ 'listenedDocuments',
+ 'lastPress',
+ 'focusToKeep',
+ 'deferredTopLayer',
+ ] as const) {
+ expect(shared[table]).toBeInstanceOf(WeakMap);
+ }
+ // A deferral made by this copy is visible to a fresh same-protocol copy:
+ // a non-modal sheet shown beneath an open Dialog waits in the shared
+ // state, and the copy's own promotion pass finds it and promotes it.
+ function App() {
+ const [isDialogOpen, setIsDialogOpen] = useState(true);
+ const [isNonModalOpen, setIsNonModalOpen] = useState(false);
+ return (
+ <>
+ <Dialog
+ isOpen={isDialogOpen}
+ onOpenChange={setIsDialogOpen}
+ aria-label="Edit">
+ <button type="button" onClick={() => setIsNonModalOpen(true)}>
+ Open non-modal
+ </button>
+ <button type="button" onClick={() => setIsDialogOpen(false)}>
+ Close dialog
+ </button>
+ </Dialog>
+ <BottomSheet
+ isOpen={isNonModalOpen}
+ onOpenChange={setIsNonModalOpen}
+ hasScrim={false}
+ label="NonModal">
+ non-modal
+ </BottomSheet>
+ </>
+ );
+ }
+ render(<App />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open non-modal'}));
+ expect(shared.deferredTopLayer.get(document)?.deferred.size).toBe(1);
+ vi.resetModules();
+ const copy = await import('./bottomSheetStack');
+ // The Dialog closes without the event the listener would need (the stub
+ // close() fires none): the second copy's promotion pass, reading the
+ // shared deferrals, promotes the sheet this copy deferred.
+ fireEvent.click(screen.getByRole('button', {name: 'Close dialog'}));
+ act(() => {
+ copy.promoteDeferredNonModal(document);
+ });
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1);
+ expect(shared.deferredTopLayer.get(document)?.deferred.size).toBe(0);
+ });
+
+ it('a second copy of the module shares the same state', async () => {
+ // Two copies of the package on one page (two bundles, a dev server
+ // serving one file under two URLs) must see one stack.
+ vi.resetModules();
+ const copy = await import('./bottomSheetStack');
+ expect(copy.registerBottomSheet).not.toBe(registerBottomSheet);
+ render(<Siblings initialA />);
+ expect(copy.getBottomSheetStackForTests()).toHaveLength(1);
+ expect(copy.getBottomSheetStackForTests()[0].element).toBe(getDialog('A'));
+ });
+
+ it('the document-global key names the protocol version', () => {
+ const {key, protocolVersion, keyFor} = BOTTOM_SHEET_STACK_STATE_FOR_TESTS;
+ expect(key).toBe(keyFor(protocolVersion));
+ expect(key.description).toBe(`astryx.bottomSheetStack.v${protocolVersion}`);
+ });
+
+ it('two copies on different protocol versions keep two independent stacks: each orders only the sheets its copy renders (PR1)', async () => {
+ // A copy on another protocol version writes its state under its own
+ // key, so neither copy ever reads a state of the wrong shape. Modelled
+ // with this copy's state parked under the previous version's key, the
+ // way an older bundle on the page would have left it.
+ const holder = globalThis as Record<symbol, unknown>;
+ const {key, keyFor, protocolVersion} = BOTTOM_SHEET_STACK_STATE_FOR_TESTS;
+ const olderKey = keyFor(protocolVersion - 1);
+ const thisState = holder[key];
+ holder[olderKey] = {...(thisState as object), shape: protocolVersion - 1};
+ try {
+ render(<Siblings initialA />);
+ expect(getBottomSheetStackForTests()).toHaveLength(1);
+ // A fresh copy of the module speaks this protocol and joins this stack.
+ vi.resetModules();
+ const sameProtocol = await import('./bottomSheetStack');
+ expect(sameProtocol.getBottomSheetStackForTests()).toHaveLength(1);
+ // The older state under the older key saw nothing of it: the two
+ // stacks are independent, and the older copy's would order only what
+ // that copy rendered.
+ const older = holder[olderKey] as {entries: unknown[]; shape: number};
+ expect(older.shape).toBe(protocolVersion - 1);
+ expect(older).not.toBe(holder[key]);
+ } finally {
+ Reflect.deleteProperty(holder, olderKey);
+ }
+ });
+
+ it('a state found under this version key with another shape (a key collision) is not shared', async () => {
+ const holder = globalThis as Record<symbol, unknown>;
+ const shared = holder[BOTTOM_SHEET_STACK_STATE_FOR_TESTS.key] as {
+ shape: number;
+ };
+ const shape = shared.shape;
+ shared.shape = shape + 1000;
+ try {
+ vi.resetModules();
+ const copy = await import('./bottomSheetStack');
+ render(<Siblings initialA />);
+ expect(copy.getBottomSheetStackForTests()).toHaveLength(0);
+ } finally {
+ shared.shape = shape;
+ }
+ });
+
+ it('the press listeners are installed once per document with its first sheet, removed when its last sheet leaves, and installed again by the next (INV5)', () => {
+ const {isListeningForPresses} = BOTTOM_SHEET_STACK_STATE_FOR_TESTS;
+ const add = vi.spyOn(document, 'addEventListener');
+ const remove = vi.spyOn(document, 'removeEventListener');
+ const pressAdds = () =>
+ add.mock.calls.filter(
+ ([type, , options]) =>
+ ['pointerdown', 'click', 'keydown'].includes(type) &&
+ options === true,
+ ).length;
+ const pressRemoves = () =>
+ remove.mock.calls.filter(
+ ([type, , options]) =>
+ ['pointerdown', 'click', 'keydown'].includes(type) &&
+ options === true,
+ ).length;
+ expect(isListeningForPresses(document)).toBe(false);
+ const view = render(<Siblings initialA initialB />);
+ // Two sheets, one set of three listeners.
+ expect(isListeningForPresses(document)).toBe(true);
+ expect(pressAdds()).toBe(3);
+ // The top sheet leaves: the other still reads presses.
+ fireEvent.click(screen.getByRole('button', {name: 'Close B'}));
+ finishExit(getDialog('B'));
+ view.rerender(<Siblings initialA />);
+ expect(isListeningForPresses(document)).toBe(true);
+ expect(pressRemoves()).toBe(0);
+ // The last sheet leaves the registry (unmounted): the listeners go.
+ view.unmount();
+ expect(isListeningForPresses(document)).toBe(false);
+ expect(pressRemoves()).toBe(3);
+ // The next sheet installs them again.
+ render(<Siblings initialA />);
+ expect(isListeningForPresses(document)).toBe(true);
+ expect(pressAdds()).toBe(6);
+ add.mockRestore();
+ remove.mockRestore();
+ });
+
+ it('a recorded press holds its target weakly: a removed, collected target is not an actor', () => {
+ // WeakRef cannot be forced to clear in a test; what can be checked is
+ // that the record is a WeakRef whose deref is read, by swapping in one
+ // that answers undefined and seeing the actor fall back to focus.
+ render(<Siblings initialA />);
+ const holder = globalThis as Record<symbol, unknown>;
+ const shared = holder[BOTTOM_SHEET_STACK_STATE_FOR_TESTS.key] as {
+ lastPress: WeakMap<Document, {target: WeakRef<Element>; at: number}>;
+ };
+ fireEvent.pointerDown(screen.getByRole('button', {name: 'Open B'}));
+ const press = shared.lastPress.get(document);
+ expect(press).toBeDefined();
+ expect(press!.target).toBeInstanceOf(WeakRef);
+ expect(press!.target.deref()).toBe(
+ screen.getByRole('button', {name: 'Open B'}),
+ );
+ });
+
+ it('two copies, one presenting in an iframe document and one in the main document, keep both sheets shown', async () => {
+ // Everything the reconcile reads — the per-document shown order and the
+ // press listener registry — lives in the shared state, so a copy that
+ // first meets a document does not mistake it for another copy's.
+ vi.resetModules();
+ const {BottomSheet: CopyBottomSheet} = await import('./BottomSheet');
+ const copyStack = await import('./bottomSheetStack');
+ expect(copyStack.registerBottomSheet).not.toBe(registerBottomSheet);
+ const frame = document.createElement('iframe');
+ document.body.appendChild(frame);
+ const frameDocument = frame.contentDocument as Document;
+ const FrameDialog = (frame.contentWindow as Window & typeof globalThis)
+ .HTMLDialogElement;
+ FrameDialog.prototype.showModal = HTMLDialogElement.prototype.showModal;
+ FrameDialog.prototype.close = HTMLDialogElement.prototype.close;
+ const mount = frameDocument.createElement('div');
+ frameDocument.body.appendChild(mount);
+ function App() {
+ return (
+ <>
+ {createPortal(
+ <CopyBottomSheet isOpen onOpenChange={() => {}} label="Framed">
+ framed
+ </CopyBottomSheet>,
+ mount,
+ )}
+ <BottomSheet isOpen onOpenChange={() => {}} label="A">
+ a
+ </BottomSheet>
+ </>
+ );
+ }
+ try {
+ render(<App />);
+ expect(
+ nativeLog.map(
+ ({call, dialog}) => `${call}:${dialog.getAttribute('aria-label')}`,
+ ),
+ ).toEqual(['showModal:Framed', 'showModal:A']);
+ expect(stackSummary()).toEqual(['A:top:0']);
+ expect(
+ copyStack
+ .getBottomSheetStackForTests(frameDocument)
+ .map(({element}) => element?.getAttribute('aria-label')),
+ ).toEqual(['Framed']);
+ expect(
+ getBottomSheetStackForTests(frameDocument).map(({element}) =>
+ element?.getAttribute('aria-label'),
+ ),
+ ).toEqual(['Framed']);
+ expect(frameDocument.querySelector('dialog')).toHaveAttribute('open');
+ } finally {
+ frame.remove();
+ }
+ });
+
+ it('sheets in another document form their own stack', () => {
+ const frame = document.createElement('iframe');
+ document.body.appendChild(frame);
+ const frameDocument = frame.contentDocument as Document;
+ // jsdom has no showModal/close in any realm; the frame's realm gets the
+ // same stand-ins as the main one.
+ const FrameDialog = (frame.contentWindow as Window & typeof globalThis)
+ .HTMLDialogElement;
+ FrameDialog.prototype.showModal = HTMLDialogElement.prototype.showModal;
+ FrameDialog.prototype.close = HTMLDialogElement.prototype.close;
+ const mount = frameDocument.createElement('div');
+ frameDocument.body.appendChild(mount);
+ function App() {
+ return (
+ <>
+ <BottomSheet isOpen onOpenChange={() => {}} label="A">
+ a
+ </BottomSheet>
+ {createPortal(
+ <BottomSheet isOpen onOpenChange={() => {}} label="Framed">
+ framed
+ </BottomSheet>,
+ mount,
+ )}
+ </>
+ );
+ }
+ try {
+ render(<App />);
+ expect(stackSummary()).toEqual(['A:top:0']);
+ expect(
+ getBottomSheetStackForTests(frameDocument).map(
+ ({element, view}) =>
+ `${element?.getAttribute('aria-label')}:${view.isTop ? 'top' : 'covered'}`,
+ ),
+ ).toEqual(['Framed:top']);
+ expect(getDialog('A')).not.toHaveAttribute('data-sheet-stack');
+ } finally {
+ frame.remove();
+ }
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Requirement 12 — existing behaviour: the standalone and switcher contracts
+// ---------------------------------------------------------------------------
+
+describe('R14 a switcher flow stacked with standalone sheets', () => {
+ function Mixed() {
+ const [isAOpen, setIsAOpen] = useState(false);
+ const [step, setStep] = useState<string | null>(null);
+ const [isCOpen, setIsCOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsAOpen(true)}>
+ Open A
+ </button>
+ <button type="button" onClick={() => setStep('one')}>
+ Open flow
+ </button>
+ <button type="button" onClick={() => setStep('two')}>
+ Step two
+ </button>
+ <button type="button" onClick={() => setStep(null)}>
+ Close flow
+ </button>
+ <button type="button" onClick={() => setIsCOpen(true)}>
+ Open C
+ </button>
+ <BottomSheet isOpen={isAOpen} onOpenChange={setIsAOpen} label="A">
+ <button type="button" onClick={() => setStep('one')}>
+ Open flow from A
+ </button>
+ </BottomSheet>
+ <BottomSheetSwitcher activeSheet={step} onActiveSheetChange={setStep}>
+ <BottomSheet sheetId="one" label="One">
+ <button type="button" onClick={() => setIsCOpen(true)}>
+ Open C from one
+ </button>
+ </BottomSheet>
+ <BottomSheet sheetId="two" label="Two">
+ two
+ </BottomSheet>
+ </BottomSheetSwitcher>
+ <BottomSheet isOpen={isCOpen} onOpenChange={setIsCOpen} label="C">
+ <button type="button" onClick={() => setIsCOpen(false)}>
+ Close C
+ </button>
+ </BottomSheet>
+ </>
+ );
+ }
+
+ it('a flow over a standalone sheet: one scrim (the sheet’s), the sheet recedes, the flow’s steps stay clear through a handoff', () => {
+ render(<Mixed />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open A'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Open flow from A'}));
+ expect(stackSummary()).toEqual(['A:covered:1', 'One:top:0']);
+ expect(topLayerOrder()).toEqual(['A', 'One']);
+ expect(scrim(getDialog('A'))).toBe('1');
+ expect(scrim(getDialog('One'))).toBe('0');
+ expect(getDialog('A')).toHaveAttribute('data-sheet-stack', 'covered');
+ expect(getDialog('A')).toHaveAttribute('inert');
+ expect(getDialog('One')).toHaveAttribute('data-sheet-stack', 'top');
+ expect(getDialog('One')).not.toHaveAttribute('inert');
+
+ fireEvent.click(screen.getByRole('button', {name: 'Step two'}));
+ // Neither step dims: A still owns the stack's scrim.
+ expect(scrim(getDialog('One'))).toBe('0');
+ expect(scrim(getDialog('Two'))).toBe('0');
+ expect(topLayerOrder()).toEqual(['A', 'One', 'Two']);
+ finishHandoff(getDialog('Two'), getDialog('One'));
+ expect(stackSummary()).toEqual(['A:covered:1', 'Two:top:0']);
+ expect(scrim(getDialog('A'))).toBe('1');
+ expect(scrim(getDialog('Two'))).toBe('0');
+ expect(getDialog('A')).toHaveAttribute('data-sheet-stack', 'covered');
+
+ // Escape reaches the flow, not the covered sheet.
+ act(() => {
+ pressEscape();
+ });
+ expect(stackSummary()).toEqual(['A:top:0', 'Two:exiting:0']);
+ finishExit(getDialog('Two'));
+ expect(stackSummary()).toEqual(['A:top:0']);
+ expect(getDialog('A')).not.toHaveAttribute('data-sheet-stack');
+ expect(getDialog('A')).not.toHaveAttribute('inert');
+ expect(scrim(getDialog('A'))).toBe('1');
+ });
+
+ it('a flow closing over a standalone sheet returns focus into that sheet', () => {
+ render(<Mixed />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open A'}));
+ const opener = screen.getByRole('button', {name: 'Open flow from A'});
+ opener.focus();
+ fireEvent.click(opener);
+ expect(stackSummary()).toEqual(['A:covered:1', 'One:top:0']);
+ fireEvent.click(screen.getByRole('button', {name: 'Close flow'}));
+ finishExit(getDialog('One'));
+ expect(stackSummary()).toEqual(['A:top:0']);
+ // The opener is inside the revealed sheet, so it takes focus back.
+ expect(opener).toHaveFocus();
+ });
+
+ it('a standalone sheet over a flow: the flow owns the one scrim and recedes as a whole; the sheet is clear', () => {
+ render(<Mixed />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open flow'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Open C from one'}));
+ expect(stackSummary()).toEqual(['One:covered:1', 'C:top:0']);
+ expect(topLayerOrder()).toEqual(['One', 'C']);
+ expect(scrim(getDialog('One'))).toBe('1');
+ expect(scrim(getDialog('C'))).toBe('0');
+ const stepDialog = getDialog('One');
+ expect(stepDialog).toHaveAttribute('data-sheet-stack', 'covered');
+ expect(stepDialog).toHaveAttribute('data-sheet-stack-depth', '1');
+ expect(stepDialog).toHaveAttribute('inert');
+ expect(stepDialog).toHaveAttribute('aria-hidden', 'true');
+ expect(
+ getComputedStyle(getPanel(stepDialog).parentElement!).transform,
+ ).toContain('scale(.96)');
+
+ // Escape reaches C, the top sheet; the covered flow stands down.
+ act(() => {
+ pressEscape();
+ });
+ expect(stackSummary()).toEqual(['One:top:0', 'C:exiting:0']);
+ finishExit(getDialog('C'));
+ expect(stackSummary()).toEqual(['One:top:0']);
+ expect(stepDialog).not.toHaveAttribute('data-sheet-stack');
+ expect(stepDialog).not.toHaveAttribute('inert');
+ expect(scrim(stepDialog)).toBe('1');
+ });
+
+ it('a step switch while the flow is covered keeps the covering sheet on top', () => {
+ render(<Mixed />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open flow'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Open C'}));
+ expect(topLayerOrder()).toEqual(['One', 'C']);
+ // Only code can switch a covered flow; the new step's dialog is presented
+ // on top, and the registry puts C back above it in the same commit.
+ fireEvent.click(screen.getByRole('button', {name: 'Step two'}));
+ expect(topLayerOrder()).toEqual(['One', 'Two', 'C']);
+ expect(stackSummary()).toEqual(['Two:covered:1', 'C:top:0']);
+ expect(scrim(getDialog('C'))).toBe('0');
+ finishHandoff(getDialog('Two'), getDialog('One'));
+ expect(topLayerOrder()).toEqual(['Two', 'C']);
+ expect(scrim(getDialog('Two'))).toBe('1');
+ expect(getDialog('Two')).toHaveAttribute('inert');
+ });
+
+ it('a standalone sheet closing over a flow returns focus into the flow’s active step', () => {
+ render(<Mixed />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open flow'}));
+ const opener = screen.getByRole('button', {name: 'Open C from one'});
+ opener.focus();
+ fireEvent.click(opener);
+ fireEvent.click(screen.getByRole('button', {name: 'Close C'}));
+ finishExit(getDialog('C'));
+ expect(stackSummary()).toEqual(['One:top:0']);
+ expect(opener).toHaveFocus();
+ });
+});
+
+describe('R12 existing behaviour', () => {
+ it('a standalone sheet presented alone keeps its full contract after a stack has come and gone', () => {
+ render(<Siblings initialA />);
+ const a = getDialog('A');
+ fireEvent.click(screen.getByRole('button', {name: 'Open B'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Close B'}));
+ finishExit(getDialog('B'));
+ expect(stackSummary()).toEqual(['A:top:0']);
+ expect(a).not.toHaveAttribute('data-sheet-stack');
+ expect(a).not.toHaveAttribute('inert');
+ expect(scrim(a)).toBe('1');
+ expect(getComputedStyle(getPositioner(a)).transform).toBe('');
+ expect(classes(getPositioner(a))).not.toContain('positionerStackMotion');
+ act(() => {
+ pressEscape();
+ });
+ expect(stackSummary()).toEqual(['A:exiting:0']);
+ finishExit(a);
+ expect(openDialogs()).toEqual([]);
+ });
+
+ it('a switcher on its own presents each step in its own dialog, hands its scrim over, and carries no stack state', () => {
+ function Flow() {
+ const [step, setStep] = useState<string | null>('one');
+ return (
+ <BottomSheetSwitcher activeSheet={step} onActiveSheetChange={setStep}>
+ <BottomSheet sheetId="one" label="One">
+ <button type="button" onClick={() => setStep('two')}>
+ Next
+ </button>
+ </BottomSheet>
+ <BottomSheet sheetId="two" label="Two">
+ two
+ </BottomSheet>
+ </BottomSheetSwitcher>
+ );
+ }
+ render(<Flow />);
+ expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalledTimes(1);
+ fireEvent.click(screen.getByRole('button', {name: 'Next'}));
+ expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalledTimes(2);
+ const dialog = getDialog('Two');
+ // The retained step keeps the flow's scrim through the handoff.
+ expect(scrim(getDialog('One'))).toBe('1');
+ expect(scrim(dialog)).toBe('0');
+ finishHandoff(dialog, getDialog('One'));
+ expect(dialog).not.toHaveAttribute('data-sheet-stack');
+ expect(dialog).not.toHaveAttribute('inert');
+ expect(scrim(dialog)).toBe('1');
+ expect(getDialog('One')).not.toHaveAttribute('open');
+ });
+});
diff --git a/packages/core/src/BottomSheet/BottomSheetSwitcher.doc.mjs b/packages/core/src/BottomSheet/BottomSheetSwitcher.doc.mjs
index 100458ea56..6c750b0573 100644
--- a/packages/core/src/BottomSheet/BottomSheetSwitcher.doc.mjs
+++ b/packages/core/src/BottomSheet/BottomSheetSwitcher.doc.mjs
@@ -142,7 +142,7 @@ 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. 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.',
+ 'Deprecated: write each step as its own BottomSheet with isOpen, controlled by one state value that names the open step. Closing the top sheet and opening the next in the same update, from a control inside the open step, runs the same replace handoff (see BottomSheet, Replacing a sheet), with no sheetId and no switcher; a step changed from a control outside the flow (a page control, or code after focus left the step) closes and opens with ordinary push and pop motion. BottomSheetSwitcher keeps working until a future minor release removes it: a flow used on its own behaves as released (with two fixes: a toast raised from a step renders above the flow and can be pressed, and under reduced motion its steps follow the reduced-motion rule), and a flow stacked with other sheets is one level of the stack (it recedes and is blocked when covered, shares the one scrim, and stands down from dismissal while covered). Modal and hasScrim={false} flows migrate the same way. 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>: a modal flow presents each sheet with showModal(), as a standalone modal sheet does, so the browser supplies modality (the page is inert and focus stays in the top-layer dialog, so both hold across a handoff) and the switcher holds the shared body scroll lock once for the whole modal flow. A no-scrim flow presents each sheet with show() inside the isolated flow wrapper of the switcher, which orders the step dialogs with local values; this differs from a standalone hasScrim={false} sheet, which is hosted in the top layer as a manual popover with no page-level z-index, and it is one reason to migrate. 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',
@@ -187,17 +187,17 @@ export const docs = {
usage: {
anatomy,
description:
- "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.",
+ "Deprecated: write each step as its own BottomSheet with isOpen, controlled by one state value that names the open step. Closing the top sheet and opening the next in the same update, from a control inside the open step, runs the same replace handoff (see BottomSheet, Replacing a sheet), with no sheetId and no switcher; a step changed from a control outside the flow (a page control, or code after focus left the step) closes and opens with ordinary push and pop motion. BottomSheetSwitcher keeps working until a future minor release removes it: a flow used on its own behaves as released (with two fixes: a toast raised from a step renders above the flow and can be pressed, and under reduced motion its steps follow the reduced-motion rule), and a flow stacked with other sheets is one level of the stack (it recedes and is blocked when covered, shares the one scrim, and stands down from dismissal while covered). Modal and hasScrim={false} flows migrate the same way. Set activeSheet to a nested BottomSheet's sheetId to open or switch steps, and to null to close.\n\nStacking. A scrim flow is one level in the stack of open sheets (see BottomSheet, Stacking). Open it while a standalone sheet is open and the flow sits on top of that sheet, which recedes and is blocked; open a standalone sheet while the flow is open, from a step's content or from anywhere else, and that sheet sits on top while the whole flow recedes as one. Switching the step in place never changes the flow's position. Escape, the scrim, a swipe, and a platform close request reach only the top level: the flow's onActiveSheetChange(null) when the flow is on top, the standalone sheet's onOpenChange(false) when that sheet is. A standalone sheet rendered inside a step's content is presented only while that step is the active one: it leaves when the flow switches step or closes, its isOpen stays yours, and it is presented again, on top, if the step returns while it is still open. Only the bottom level's backdrop dims the page. A no-scrim flow stays out of the stack.",
bestPractices: [
{
guidance: true,
description:
- 'Use when each step depends on the previous one and only one step needs attention at a time.',
+ 'Prefer one standalone BottomSheet per step with one state value naming the open step; the replace handoff is the same and nothing has to be nested under a switcher.',
},
{
guidance: true,
description:
- 'Give every child a unique sheetId and non-empty label, choose its purpose to match dismissal requirements, and follow the WAI-ARIA Dialog (Modal) pattern for scrim-backed flows: https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/.',
+ 'Migrate an existing flow in place: replace activeSheet / onActiveSheetChange with one step value, give each step isOpen={step === id} and a guarded onOpenChange (clear the step only if it is still the open one) in place of sheetId, remove the wrapper and move its hasScrim onto every step. Map the other switcher props: onCancel becomes a guarded onOpenChange on each step (ignore false while the flow must stay open) — a standalone sheet reports Escape, the platform close, the scrim tap and the swipe all as onOpenChange(false) with no reason, so the guard holds the step against all of them while it applies, and a veto of Escape alone has no equivalent; the only per-path lever is purpose (form keeps Escape and blocks the scrim tap and the swipe; required blocks all three and exposes the step as an alertdialog). A consumer aria-label or aria-labelledby becomes each step label, which names its dialog. ref, id, data-testid, className, style, xstyle and the other dialog props have no dialog-level equivalent: a standalone sheet sends its ref and base props to the panel div and its dialog is implementation, so a test or anchor that needs the dialog queries the panel closest("dialog"), and dialog-level styling is dropped.',
},
{
guidance: false,
@@ -207,35 +207,31 @@ export const docs = {
{
guidance: false,
description:
- "Don't use the switcher when multiple panels must stay interactive or visible together; activeSheet intentionally selects one interactive step.",
+ "Don't use a step flow when multiple panels must stay interactive or visible together; a flow intentionally selects one interactive step.",
},
],
},
examples: [
{
- label: 'Three-step flow',
- code: `const [activeSheet, setActiveSheet] = useState(null);
+ label: 'Replacement: the same three-step flow as standalone sheets',
+ code: `const [step, setStep] = useState(null);
<>
- <Button label="Start" onClick={() => setActiveSheet('details')} />
- <BottomSheetSwitcher
- activeSheet={activeSheet}
- onActiveSheetChange={setActiveSheet}>
- <BottomSheet sheetId="details" label="Details" height="hug">
- <SetupDetails />
- <Button label="Continue" onClick={() => setActiveSheet('preferences')} />
- </BottomSheet>
- <BottomSheet sheetId="preferences" label="Preferences" height="hug">
- <Preferences />
- <Button label="Back" onClick={() => setActiveSheet('details')} />
- <Button label="Continue" onClick={() => setActiveSheet('confirm')} />
- </BottomSheet>
- <BottomSheet sheetId="confirm" label="Confirm" height="hug">
- <Confirmation />
- <Button label="Back" onClick={() => setActiveSheet('preferences')} />
- <Button label="Done" onClick={() => setActiveSheet(null)} />
- </BottomSheet>
- </BottomSheetSwitcher>
+ <Button label="Start" onClick={() => setStep('details')} />
+ <BottomSheet isOpen={step === 'details'} onOpenChange={o => !o && setStep(c => (c === 'details' ? null : c))} label="Details" height="hug">
+ <SetupDetails />
+ <Button label="Continue" onClick={() => setStep('preferences')} />
+ </BottomSheet>
+ <BottomSheet isOpen={step === 'preferences'} onOpenChange={o => !o && setStep(c => (c === 'preferences' ? null : c))} label="Preferences" height="hug">
+ <Preferences />
+ <Button label="Back" onClick={() => setStep('details')} />
+ <Button label="Continue" onClick={() => setStep('confirm')} />
+ </BottomSheet>
+ <BottomSheet isOpen={step === 'confirm'} onOpenChange={o => !o && setStep(c => (c === 'confirm' ? null : c))} label="Confirm" height="hug">
+ <Confirmation />
+ <Button label="Back" onClick={() => setStep('preferences')} />
+ <Button label="Done" onClick={() => setStep(null)} />
+ </BottomSheet>
</>`,
},
],
@@ -244,21 +240,21 @@ export const docs = {
/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */
export const docsDense = {
description:
- 'controller for mutually exclusive multi-step BottomSheets, one native dialog per sheet',
+ 'deprecated: use one standalone BottomSheet per step with one state value naming the open step (same replace handoff when stepped from inside the open step, no sheetId); keeps working until a future minor removes it. controller for mutually exclusive multi-step BottomSheets, one native dialog per sheet; a scrim flow is one level of the bottom-sheet stack (stacks over or under standalone sheets in open order, recedes as a whole, switching steps keeps its place)',
usage: {
anatomy,
description:
- "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.",
+ "Deprecated: write each step as a standalone BottomSheet with isOpen driven by one state value; a same-update close and open from inside the open step is the same replace handoff. Still works: set activeSheet to a nested BottomSheet's sheetId to open or switch steps, and to null to close. A scrim flow stacks with standalone sheets as one level; a standalone sheet inside a step leaves when the step is left and returns with it while still open.",
bestPractices: [
{
guidance: true,
description:
- 'Use when each step depends on the previous one and only one step needs attention at a time.',
+ 'Prefer one standalone BottomSheet per step with one state value naming the open step; the replace handoff is the same and nothing has to be nested under a switcher.',
},
{
guidance: true,
description:
- 'Give every child a unique sheetId and non-empty label, choose its purpose to match dismissal requirements, and follow the WAI-ARIA Dialog (Modal) pattern for scrim-backed flows: https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/.',
+ 'Migrate an existing flow in place: replace activeSheet / onActiveSheetChange with one step value, give each step isOpen={step === id} and a guarded onOpenChange (clear the step only if it is still the open one) in place of sheetId, remove the wrapper and move its hasScrim onto every step. Map the other switcher props: onCancel becomes a guarded onOpenChange on each step (ignore false while the flow must stay open) — a standalone sheet reports Escape, the platform close, the scrim tap and the swipe all as onOpenChange(false) with no reason, so the guard holds the step against all of them while it applies, and a veto of Escape alone has no equivalent; the only per-path lever is purpose (form keeps Escape and blocks the scrim tap and the swipe; required blocks all three and exposes the step as an alertdialog). A consumer aria-label or aria-labelledby becomes each step label, which names its dialog. ref, id, data-testid, className, style, xstyle and the other dialog props have no dialog-level equivalent: a standalone sheet sends its ref and base props to the panel div and its dialog is implementation, so a test or anchor that needs the dialog queries the panel closest("dialog"), and dialog-level styling is dropped.',
},
{
guidance: false,
@@ -268,7 +264,7 @@ export const docsDense = {
{
guidance: false,
description:
- "Don't use the switcher when multiple panels must stay interactive or visible together; activeSheet intentionally selects one interactive step.",
+ "Don't use a step flow when multiple panels must stay interactive or visible together; a flow intentionally selects one interactive step.",
},
],
},
diff --git a/packages/core/src/BottomSheet/BottomSheetSwitcher.spec.md b/packages/core/src/BottomSheet/BottomSheetSwitcher.spec.md
index ea12679596..10bf169f4a 100644
--- a/packages/core/src/BottomSheet/BottomSheetSwitcher.spec.md
+++ b/packages/core/src/BottomSheet/BottomSheetSwitcher.spec.md
@@ -13,6 +13,8 @@ review_triggers: [public-api, behavior, layout, theming, accessibility]
verified_by:
[
packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx,
+ packages/core/src/BottomSheet/BottomSheetStacking.test.tsx,
+ packages/core/src/Toast/ToastViewport.modalHost.test.tsx,
packages/core/src/BottomSheet/__tests__/BottomSheetNativeModal.a11y.browser.spec.ts,
apps/storybook/stories/BottomSheetSwitcher.stories.tsx,
scripts/check-knowledge.mjs,
@@ -50,11 +52,8 @@ requirement in this record stays in force, and the replacement — one standalon
FR10 replaces in place when the step changes from inside the open step — is
what maintained docs, templates, stories, and agent guidance teach. Removal
happens only in a future declared minor through a `[breaking]` change.
-Implementation gap: on current `main` no declaration carries `@deprecated`, the
-switcher's consumer docs and `component:BottomSheet`'s consumer doc recommend
-the switcher for multi-step flows, and the CLI block templates and Lab's
-`MobileTokenizer` use it. Lab's `MobilePowerSearch` uses the switcher
-and is migrated by its own change. Where the shipped
+Implementation gap: Lab's `MobilePowerSearch` uses the switcher and is migrated
+by its own change. Where the shipped
switcher does not yet meet a requirement, the row carries a present-tense
implementation gap note. The modality, identifier, and theming questions below
stay open.
@@ -79,8 +78,6 @@ stay open.
FR29); the `@deprecated` metadata lives on the TypeScript declarations of
`BottomSheetSwitcher`, `BottomSheetSwitcherProps`, and `BottomSheet`'s
`sheetId`, and the consumer docs carry the replacement route (FR29a, FR29b).
- Implementation gap: on current `main` the declarations carry no
- `@deprecated` and the consumer docs carry no replacement route
- Controlled/uncontrolled behavior: `activeSheet` remains fully controlled
- Migration decision: DEC-3; the migration is DEP-0015's
@@ -100,9 +97,9 @@ Consumer migration instructions belong in consumer docs and release notes.
| warning | `@deprecated` on the declarations; consumer docs, templates, stories, and release notes name the replacement. No runtime warning (`spec:AST-017` FR29) |
| migration | Ordered and testable, per flow: (1) replace `activeSheet` / `onActiveSheetChange` with one `step` value; (2) give each step `isOpen={step === 'id'}` and `onOpenChange={isOpen => !isOpen && setStep(current => (current === 'id' ? null : current))}` in place of `sheetId="id"`; (3) remove the wrapper, moving its `hasScrim` onto every step; (4) keep the step controls as they are (`setStep('next')`); (5) a flow stepped by a control outside its sheets (a page control beside a non-modal flow, or code acting while focus is on a page control) gets push and pop motion in place of the handoff — move such a control into the step, or accept the motion; code acting while focus is in the step or on the body keeps the handoff; (6) the switcher's other props: `onCancel` becomes a guarded `onOpenChange` on each step — one that ignores `false` while the flow must stay open — which keeps the step's dialog role; a standalone sheet reports Escape, the platform close, the scrim tap, and the swipe all as `onOpenChange(false)` with no reason, so the guard holds the step open against all of them while it applies, where the switcher's `onCancel` vetoed only the cancel request; a veto of Escape alone has no equivalent, and the only per-path lever is `purpose` (`form` keeps Escape and blocks the scrim tap and the swipe; `required` blocks all three and exposes the step as an `alertdialog`); there is no per-event veto; a consumer `aria-label` / `aria-labelledby` becomes each step's `label`, which names its dialog; `ref`, `id`, `data-testid`, `className`, `style`, `xstyle`, and the other dialog props have no dialog-level equivalent — a standalone sheet's `ref` and base props reach its panel `<div>` and its dialog is implementation — so a test or an anchor that needs the dialog queries the panel's `closest('dialog')`, and dialog-level styling is dropped |
| codemod | None; the rewrite moves state the caller owns and is short enough to read |
-| downstream | The maintained published surfaces migrate in the deprecation patch (`spec:AST-017` FR29c): the CLI block templates and the stories. `@astryxdesign/lab` is marked `private` and is published to npm only under the `@canary` dist-tag, never as a stable `latest` release; `spec:AST-017` calls it "the private canary-only Lab package" (FR27), lists private packages among its non-goals, puts them outside the published compatibility promise (FR2), and says canary-only surfaces carry no stable compatibility promise, which this record reads as FR29c's "maintained Astryx packages" not reaching Lab, so Lab's migration is optional under it: Lab's `MobileTokenizer` migrates with the patch; Lab's `MobilePowerSearch` keeps the switcher until its own change migrates it, and the switcher keeps working for it. Whether `spec:AST-017` is read that way is its owner's to settle. The switcher's own stories remain as its labelled reference. Implementation gap: on current `main` the templates and `MobileTokenizer` use the switcher |
+| downstream | The maintained published surfaces migrate in the deprecation patch (`spec:AST-017` FR29c): the CLI block templates and the stories. `@astryxdesign/lab` is marked `private` and is published to npm only under the `@canary` dist-tag, never as a stable `latest` release; `spec:AST-017` calls it "the private canary-only Lab package" (FR27), lists private packages among its non-goals, puts them outside the published compatibility promise (FR2), and says canary-only surfaces carry no stable compatibility promise, which this record reads as FR29c's "maintained Astryx packages" not reaching Lab, so Lab's migration is optional under it: Lab's `MobileTokenizer` migrates with the patch; Lab's `MobilePowerSearch` keeps the switcher until its own change migrates it, and the switcher keeps working for it. Whether `spec:AST-017` is read that way is its owner's to settle. The switcher's own stories remain as its labelled reference. |
| transition | no prior transition |
-| state | `deprecated`: supported, documented with its replacement, unchanged at runtime — the deprecation patch `spec:AST-017` FR28 requires before a removal, projected through declarations and docs (FR29a, FR29b). Implementation gap: on current `main` the declarations, consumer docs, CLI block templates, and Lab consumers do not yet carry or use the replacement, so the state is not yet realized |
+| state | `deprecated`: supported, documented with its replacement, unchanged at runtime — the deprecation patch `spec:AST-017` FR28 requires before a removal, projected through declarations and docs (FR29a, FR29b). |
| open decision | Which declared minor removes the surface, and whether a renamed compatibility export precedes the removal; either is a `[breaking]` change of a declared minor (`spec:AST-017` FR28, FR31) |
| target plan | Removal in a future declared minor through a `[breaking]` Changeset; no release is named |
@@ -144,18 +141,18 @@ Consumer migration instructions belong in consumer docs and release notes.
## 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. | 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. Under reduced motion the handoff follows `design:reduced-motion`: no transform motion runs, and the sheets cross-fade (DR2) or change at once (DR3) in the same order. Implementation gap: under reduced motion the shipped switcher still runs the entering and alignment transforms, shortened, and does not fade the entering sheet in on a coarse pointer. | Current source and transition tests; `design:reduced-motion` DR2, DR3 |
-| 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 |
-| FR10 | Presented while other modal sheets are open, a modal switcher flow is one level of the `component:BottomSheet` stack: the active step's dialog is the level and keeps the flow's place across the flow's own handoffs; when covered, the flow's dialogs recede and are blocked as covered sheets are, its backdrop is transparent while a lower sheet owns the one scrim, and its dismissal registration stands down; when it closes over a lower sheet, focus returns into that sheet by `component:BottomSheet` FR9. A modal flow's host dialog is a passive global outlet for toasts like a standalone scrim sheet's, following each handoff and ranked among sheets by the stack (`component:BottomSheet` FR13). Under reduced motion a flow's steps move as `component:BottomSheet` FR15 says, the same panel motion as standalone sheets (FR3). A standalone sheet rendered in a step's content stacks above the flow and leaves with the step. A step is never paired in a replace with a standalone sheet. Implementation gap: on current `main` a switcher flow and a standalone sheet open together are unrelated dialogs, each painting its backdrop, and a switcher flow supplies no toast outlet (no step calls into the outlet registry, and `architecture:layer-runtime` lists a scrim switcher among the modals toasts stay behind), so a toast raised from a step lands behind the flow and a press on it hits the step. | `component:BottomSheet` DEC-2, FR12 |
-| 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 |
+| 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. Under reduced motion the handoff follows `design:reduced-motion`: no transform motion runs, and the sheets cross-fade (DR2) or change at once (DR3) in the same order. | Current source and transition tests; `design:reduced-motion` DR2, DR3 |
+| 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 |
+| FR10 | Presented while other modal sheets are open, a modal switcher flow is one level of the `component:BottomSheet` stack: the active step's dialog is the level and keeps the flow's place across the flow's own handoffs; when covered, the flow's dialogs recede and are blocked as covered sheets are, its backdrop is transparent while a lower sheet owns the one scrim, and its dismissal registration stands down; when it closes over a lower sheet, focus returns into that sheet by `component:BottomSheet` FR9. A modal flow's host dialog is a passive global outlet for toasts like a standalone scrim sheet's, following each handoff and ranked among sheets by the stack (`component:BottomSheet` FR13). Under reduced motion a flow's steps move as `component:BottomSheet` FR15 says, the same panel motion as standalone sheets (FR3). A standalone sheet rendered in a step's content stacks above the flow and leaves with the step. A step is never paired in a replace with a standalone sheet. | `component:BottomSheet` DEC-2, FR12 |
+| 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
@@ -260,14 +257,14 @@ Consumer migration instructions belong in consumer docs and release notes.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- |
-| FR1–FR4, FR8 | `BottomSheetSwitcher.test.tsx` | closed, first open, handoffs in either completion order, rapid replacement, unmount, close; a handoff under reduced motion on a coarse and a fine pointer | A child becomes interactive at the wrong time, a retained child disappears early, a second backdrop paints, or a sheet dialog's lifecycle breaks. Under reduced motion, a handoff that moves a sheet, or on a coarse pointer does not cross-fade. | `audit:BottomSheetSwitcher/behavior` |
-| FR5–FR7, AR1–AR3 | `BottomSheetSwitcher.test.tsx`; `BottomSheetNativeModal.a11y.browser.spec.ts` | modal/non-modal, info/form/required, nested layer, IME, focus return, scroll lock in engines, non-modal local ordering | Modality, dismissal order, naming, inertness, scroll lock, or focus behavior diverges, or a sheet dialog takes a page-level z-index. | `audit:BottomSheetSwitcher/accessibility` |
-| FR9 | `BottomSheetSwitcher.test.tsx`; export checks | ref across open/handoff/close/unmount, callback-ref cleanup, `id` once, DOM/ARIA/data/events, class, style, xstyle | A supported input is dropped or duplicated, an object ref is null while a sheet is mounted or skips a cleanup, or an input overrides component-owned semantics accidentally. | `audit:BottomSheetSwitcher/api` |
-| Theming anatomy | `scripts/check-knowledge.mjs`; theming tests | dialog, delegated sheet panel, scrim | A non-painting host gains a target, a delegated panel loses its owner, or the scrim gap disappears without review. | `audit:BottomSheetSwitcher/theming` |
-| FR10 | `component:BottomSheet`'s stacking suite (the switcher-as-a-level cases); real-browser dim and recede sampling of a flow stacked over, and under, a standalone sheet | switcher base covered by a standalone sheet, switcher on top of a standalone sheet, a sheet in a step's content, flow closing over a lower sheet | Two backdrops paint, the covered level does not recede, a covered flow takes Escape, or focus lands on `body` when the flow closes over a sheet. Implementation gap: the suite does not exist on current `main`. | `audit:BottomSheetSwitcher/behavior` |
-| DEP-0015 | Declaration and consumer-doc inspection (the switcher's and `component:BottomSheet`'s consumer doc); `@deprecated` metadata on the three declarations; CLI template and story sources | the switcher's declarations, docs, templates, and stories, and BottomSheet's consumer doc | A declaration lacks `@deprecated`, a maintained template, story or BottomSheet's consumer doc teaches the switcher as the multi-step route, or a production runtime branch, log, or output changes with the deprecation. Implementation gap: on current `main` every declaration lacks `@deprecated`, BottomSheet's consumer doc recommends the switcher for multi-step flows, and the templates teach the switcher. | `audit:BottomSheetSwitcher/api` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- |
+| FR1–FR4, FR8 | `BottomSheetSwitcher.test.tsx` | closed, first open, handoffs in either completion order, rapid replacement, unmount, close; a handoff under reduced motion on a coarse and a fine pointer | A child becomes interactive at the wrong time, a retained child disappears early, a second backdrop paints, or a sheet dialog's lifecycle breaks. Under reduced motion, a handoff that moves a sheet, or on a coarse pointer does not cross-fade. | `audit:BottomSheetSwitcher/behavior` |
+| FR5–FR7, AR1–AR3 | `BottomSheetSwitcher.test.tsx`; `BottomSheetNativeModal.a11y.browser.spec.ts` | modal/non-modal, info/form/required, nested layer, IME, focus return, scroll lock in engines, non-modal local ordering | Modality, dismissal order, naming, inertness, scroll lock, or focus behavior diverges, or a sheet dialog takes a page-level z-index. | `audit:BottomSheetSwitcher/accessibility` |
+| FR9 | `BottomSheetSwitcher.test.tsx`; export checks | ref across open/handoff/close/unmount, callback-ref cleanup, `id` once, DOM/ARIA/data/events, class, style, xstyle | A supported input is dropped or duplicated, an object ref is null while a sheet is mounted or skips a cleanup, or an input overrides component-owned semantics accidentally. | `audit:BottomSheetSwitcher/api` |
+| Theming anatomy | `scripts/check-knowledge.mjs`; theming tests | dialog, delegated sheet panel, scrim | A non-painting host gains a target, a delegated panel loses its owner, or the scrim gap disappears without review. | `audit:BottomSheetSwitcher/theming` |
+| FR10 | `component:BottomSheet`'s stacking suite (the switcher-as-a-level cases); real-browser dim and recede sampling of a flow stacked over, and under, a standalone sheet | switcher base covered by a standalone sheet, switcher on top of a standalone sheet, a sheet in a step's content, flow closing over a lower sheet | Two backdrops paint, the covered level does not recede, a covered flow takes Escape, or focus lands on `body` when the flow closes over a sheet. | `audit:BottomSheetSwitcher/behavior` |
+| DEP-0015 | Declaration and consumer-doc inspection (the switcher's and `component:BottomSheet`'s consumer doc); `@deprecated` metadata on the three declarations; CLI template and story sources | the switcher's declarations, docs, templates, and stories, and BottomSheet's consumer doc | A declaration lacks `@deprecated`, a maintained template, story or BottomSheet's consumer doc teaches the switcher as the multi-step route, or a production runtime branch, log, or output changes with the deprecation. | `audit:BottomSheetSwitcher/api` |
## Decision log
diff --git a/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx b/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx
index d9da5e7ea8..83ae1ff1b2 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, shared layer dismissal, BottomSheetSwitcherContext
+ * @input Uses React context, StyleX, shared layer dismissal, the modal outlet registry, the private bottom-sheet stack, BottomSheetSwitcherContext, BottomSheetHostContext
* @output Exports BottomSheetSwitcher and BottomSheetSwitcherProps
* @position Core switcher for mutually exclusive BottomSheet flows
*
@@ -15,11 +15,13 @@
* down at the same time until their top edges align; otherwise it stays
* stationary. The previous sheet fades only after both motions complete.
*
- * 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
+ * Every child sheet owns a native `<dialog>`: a scrim flow presents each
+ * sheet with showModal(), as a standalone modal sheet does, and a no-scrim
+ * flow with show() inside the flow wrapper (a standalone no-scrim sheet is a
+ * manual popover in the top layer instead; this deprecated path keeps its
+ * released hosting). For a modal flow 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
@@ -43,8 +45,26 @@
* Every other dialog prop and handler, `onCancel` included, applies to every
* sheet dialog; the browser raises `cancel` on the dialog it presents.
*
+ * A scrim flow is one level of the private bottom-sheet stack
+ * (bottomSheetStack.ts) while it is visible: it stacks over, or under, other
+ * modal sheets in open order, recedes as a whole when covered, and switching
+ * its step in place never changes its position. The level is realized by the
+ * active step's dialog; on a handoff the registry is told the dialog changed
+ * so the sheets above the flow stay above its new dialog. A flow stacked
+ * above another sheet keeps every step backdrop clear; a flow beneath owns
+ * the stack's one scrim and hands it between its own steps as it always did.
+ * A switcher step is never paired in a replace: the flow replaces its own
+ * steps. A flow rendered in another sheet's content leaves and returns with
+ * that sheet, like a standalone sheet, without its state being written. A
+ * modal flow's host dialog is a toast outlet like a standalone scrim sheet's
+ * (Layer/modalOutlet.ts), following the handoff. The switcher is deprecated
+ * in favour of standalone step sheets.
+ *
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/BottomSheet/BottomSheet.tsx
+ * - /packages/core/src/BottomSheet/bottomSheetStack.ts
+ * - /packages/core/src/BottomSheet/BottomSheetHostContext.ts
+ * - /packages/core/src/BottomSheet/BottomSheetStacking.test.tsx
* - /packages/core/src/BottomSheet/BottomSheetSwitcherContext.ts
* - /packages/core/src/BottomSheet/BottomSheetSwitcher.doc.mjs
* - /packages/core/src/BottomSheet/BottomSheetSwitcher.spec.md
@@ -55,7 +75,9 @@
*/
import {
+ use,
useCallback,
+ useEffect,
useLayoutEffect,
useMemo,
useRef,
@@ -74,6 +96,26 @@ import {dispatchLayerEscapeKeyDown} from '../Layer/layerStack';
import {useLayerDismissal} from '../Layer/useLayerDismissal';
import {composeEventHandlers} from '../utils';
import {mergeRefs} from '../utils/mergeRefs';
+import {useModalOutlet} from '../Layer/modalOutlet';
+import {BottomSheetHostContext} from './BottomSheetHostContext';
+import {
+ BOTTOM_SHEET_STACK_DEFAULT_VIEW,
+ cancelScrimWrite,
+ closeDialogKeepingFocus,
+ focusSheetPanel,
+ getBottomSheetBeneath,
+ isClosingTogether,
+ notifyBottomSheetHostChanged,
+ presentStepModally,
+ presentWithClearScrim,
+ registerBottomSheet,
+ reportClosedTogether,
+ sealBottomSheetBatch,
+ setBottomSheetOpen,
+ writeScrimOpacity,
+ type BottomSheetScrimWrite,
+ type BottomSheetStackView,
+} from './bottomSheetStack';
import {
BottomSheetSwitcherContext,
type BottomSheetSwitcherContextValue,
@@ -203,6 +245,15 @@ function takeOverScrim(dialog: HTMLDialogElement, opacity: number): void {
dialog.style.removeProperty('--_sheet-scrim-duration');
}
+/**
+ * @deprecated Write each step as its own `BottomSheet` with `isOpen`, driven
+ * by one state value that names the open step; closing the top sheet and
+ * opening the next in the same update, from inside the open step, runs the
+ * same replace handoff (see BottomSheet, "Replacing a sheet"). Keeps working until a future minor
+ * release removes it: on its own as released (plus two fixes: a toast raised
+ * from a step now renders above the flow and can be pressed, and reduced motion
+ * follows design:reduced-motion), as one stack level when stacked.
+ */
export interface BottomSheetSwitcherProps extends BaseProps<HTMLDialogElement> {
/**
* Ref resolved to the native dialog hosting the flow: the active sheet's
@@ -243,18 +294,28 @@ export interface BottomSheetSwitcherProps extends BaseProps<HTMLDialogElement> {
* 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
+ * @deprecated Write each step as its own `BottomSheet` with `isOpen`, driven
+ * by one state value that names the open step:
+ *
* ```
- * <BottomSheetSwitcher
- * activeSheet={activeSheet}
- * onActiveSheetChange={setActiveSheet}>
- * <BottomSheet sheetId="details" label="Details">…</BottomSheet>
- * <BottomSheet sheetId="confirm" label="Confirm">…</BottomSheet>
- * </BottomSheetSwitcher>
+ * const [step, setStep] = useState(null);
+ * const close = own => isOpen => !isOpen && setStep(c => (c === own ? null : c));
+ * <BottomSheet isOpen={step === 'details'} onOpenChange={close('details')} label="Details">…</BottomSheet>
+ * <BottomSheet isOpen={step === 'confirm'} onOpenChange={close('confirm')} label="Confirm">…</BottomSheet>
* ```
+ *
+ * Closing the top sheet and opening the next in the same update, from a
+ * control inside the open step, runs the same replace handoff, with no
+ * `sheetId` and no switcher, for modal and `hasScrim={false}` flows alike; a
+ * step changed from outside the flow's sheets closes and opens with the
+ * sheets' own motion. The switcher keeps working until a future
+ * minor release removes it: on its own as released (plus two fixes: a toast
+ * raised from a step now renders above the flow and can be pressed, and reduced
+ * motion follows design:reduced-motion), and as one level of the stack when
+ * stacked with other sheets.
*/
export function BottomSheetSwitcher({
- activeSheet,
+ activeSheet: activeSheetProp,
onActiveSheetChange,
hasScrim = true,
children,
@@ -267,6 +328,14 @@ export function BottomSheetSwitcher({
xstyle,
...restDialogProps
}: BottomSheetSwitcherProps) {
+ // A flow rendered in another sheet's content is part of that sheet, as a
+ // standalone sheet is: it is presented only while its host is open, leaves
+ // with it, and comes back with it if its own `activeSheet` still names a
+ // step (see BottomSheetHostContext). The consumer's state is never written
+ // for it; with the host closed the flow simply reads as closed.
+ const host = use(BottomSheetHostContext);
+ const isHostOpen = host?.isOpen ?? true;
+ const activeSheet = isHostOpen ? activeSheetProp : null;
// Every sheet host applies the switcher's dialog surface to its own dialog.
const dialogProps = useShallowStable<BottomSheetSwitcherDialogProps>({
...restDialogProps,
@@ -275,6 +344,7 @@ export function BottomSheetSwitcher({
xstyle,
});
const hostDialogRef = useRef<HTMLDialogElement | null>(null);
+ const flowRef = useRef<HTMLDivElement | 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
@@ -293,6 +363,27 @@ export function BottomSheetSwitcher({
const committedActiveSheetRef = useRef(activeSheet);
const scrimOpacityRef = useRef(1);
const scrimOwnerRef = useRef<string | null>(null);
+ // The flow's place in the stack of presented modal sheets; default until
+ // the stack reports, in the commit that presents the flow. The whole flow
+ // is one level, keyed once for its lifetime, so a handoff keeps its rank.
+ const stackKeyRef = useRef<object>({});
+ const [stackView, setStackView] = useState<BottomSheetStackView>(
+ BOTTOM_SHEET_STACK_DEFAULT_VIEW,
+ );
+ const stackViewRef = useRef(stackView);
+ stackViewRef.current = stackView;
+ const scrimWriteRef = useRef<BottomSheetScrimWrite>({frame: null});
+ useEffect(() => () => cancelScrimWrite(scrimWriteRef.current), []);
+ // What the flow's place in the stack was when it left the registry: its
+ // depth and the open sheet beneath it. React runs the registration
+ // effect's cleanup before the focus-return effect below in the same
+ // commit, so by then the registry no longer knows the flow; the cleanup
+ // records what the return needs.
+ const leftStackRef = useRef<{
+ depth: number;
+ revealed: {element: HTMLDialogElement; focus: () => void} | null;
+ closingTogether: boolean;
+ } | null>(null);
const [sheetPurposes, setSheetPurposes] = useState<
ReadonlyMap<string, DialogPurpose>
>(() => new Map());
@@ -344,6 +435,13 @@ export function BottomSheetSwitcher({
// 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;
+ // Whether the flow's one scrim is the stack's visible scrim. A flow stacked
+ // above another sheet keeps every step backdrop clear: the sheet beneath
+ // dims the page, and a second dim would double it.
+ const flowOwnsStackScrim = !stackView.isStacked || stackView.ownsScrim;
+ const isFlowOpen = activeSheet != null;
+ const isFlowOpenRef = useRef(isFlowOpen);
+ isFlowOpenRef.current = isFlowOpen;
const isFlowClosing = isFlowVisible && activeSheet == null;
const activeSheetPurpose =
(activeSheet == null ? null : sheetPurposes.get(activeSheet)) ?? 'info';
@@ -392,7 +490,11 @@ export function BottomSheetSwitcher({
escapeBehavior: allowsEscapeDismiss ? 'close' : 'block',
onDismiss: dismissOnEscape,
getContainer: () => hostDialogRef.current,
- isPresent: () => hostDialogRef.current?.open ?? false,
+ // A covered flow stands down from dismissal while a sheet covers it, so
+ // Escape and the platform close request reach the top sheet; see the
+ // standalone host.
+ isPresent: () =>
+ (hostDialogRef.current?.open ?? false) && !stackViewRef.current.isCovered,
});
// Point the consumer ref and the dismissal registration at the host dialog.
@@ -415,7 +517,13 @@ export function BottomSheetSwitcher({
hostSheet == null
? (sheetDialogsRef.current.values().next().value ?? null)
: (sheetDialogsRef.current.get(hostSheet) ?? null);
+ const previousHost = hostDialogRef.current;
hostDialogRef.current = host;
+ if (host != null && host !== previousHost) {
+ // The level's dialog changed on a handoff; the registry puts the
+ // sheets above the flow back above its new dialog.
+ notifyBottomSheetHostChanged(stackKeyRef.current);
+ }
const attached = attachedRef.current;
if (attached?.host === host && attached.ref === ref) {
return;
@@ -441,6 +549,22 @@ export function BottomSheetSwitcher({
[],
);
+ // The flow's host dialog is an outlet for app-global surfaces (toasts)
+ // while the flow is a modal one, as a standalone scrim sheet's dialog is
+ // (`component:BottomSheet` FR13): every open scrim sheet supplies one, the
+ // latest among sheets follows the stack, and a Dialog supplied later stays
+ // above. The host changes on a handoff, so the supply follows `hostSheet`;
+ // the retained step's dialog, inert and fading, is never the outlet. A
+ // closing flow stops supplying at once, as a closing sheet does. Passive:
+ // it runs after the layout effects that present the step dialogs.
+ useModalOutlet(
+ hostDialogRef,
+ isModal && isFlowOpen,
+ stackView.isTop || !stackView.isStacked,
+ 'bottom-sheet',
+ hostSheet,
+ );
+
// 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
@@ -465,17 +589,139 @@ export function BottomSheetSwitcher({
}
return;
}
+ const left = leftStackRef.current;
+ leftStackRef.current = null;
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});
+ const depth = left?.depth ?? stackViewRef.current.depth;
+ if (depth > 0) {
+ // Closed from code beneath open sheets: focus stays in the sheet on
+ // top; the flow's own close must not pull it back to the opener.
+ } else if (left?.closingTogether) {
+ // Closing together with the other sheets of its stack ("Close all"):
+ // the registry returns focus once, after the last dialog has left.
+ reportClosedTogether(stackKeyRef.current);
+ } else {
+ // With a sheet still open beneath the flow, focus returns into that
+ // sheet: to the opener when it is there, else to the sheet's panel.
+ // Otherwise, 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.
+ const revealed =
+ left?.revealed ?? getBottomSheetBeneath(stackKeyRef.current);
+ const trigger = triggerRef.current;
+ if (
+ revealed != null &&
+ (trigger == null || !revealed.element.contains(trigger))
+ ) {
+ revealed.focus();
+ } else {
+ trigger?.focus({preventScroll: true});
+ }
+ }
}
triggerRef.current = null;
modalFlowRef.current = false;
presentationOrderRef.current.clear();
}, [hasScrim, isFlowVisible]);
+ // A scrim flow is one level of the bottom-sheet stack while it is visible.
+ // The step hosts present their own dialogs; the registry re-presents the
+ // level's dialog only to restore open order, moves focus into the active
+ // panel when the flow lands on top, and reports the flow's view (top,
+ // covered, depth, scrim ownership). Switching the step never
+ // re-registers, so a switch in place keeps the flow's position.
+ useLayoutEffect(() => {
+ if (!isFlowVisible || !hasScrim) {
+ return;
+ }
+ const key = stackKeyRef.current;
+ const unregister = registerBottomSheet(
+ {
+ key,
+ getElement: () => hostDialogRef.current,
+ // The flow wrapper contains every step dialog, so it orders the flow
+ // against sheets opened in the same commit whichever step is active.
+ getTreeAnchor: () => flowRef.current,
+ show: () => {
+ const dialog = hostDialogRef.current;
+ if (dialog == null || dialog.open) {
+ return;
+ }
+ const hostId = [...sheetDialogsRef.current].find(
+ ([, candidate]) => candidate === dialog,
+ )?.[0];
+ if (hostId != null) {
+ onBeforeSheetPresent(hostId);
+ }
+ const ownsFlowScrim =
+ hostId != null && hostId === scrimOwnerRef.current;
+ const view = stackViewRef.current;
+ if (ownsFlowScrim && (!view.isStacked || view.ownsScrim)) {
+ dialog.style.setProperty(
+ '--_sheet-scrim-opacity',
+ String(scrimOpacityRef.current),
+ );
+ presentStepModally(dialog);
+ } else {
+ presentWithClearScrim(dialog);
+ }
+ },
+ hide: () => closeDialogKeepingFocus(hostDialogRef.current),
+ getReturnTarget: () => triggerRef.current,
+ focus: reason => {
+ const active = committedActiveSheetRef.current;
+ const panel =
+ active == null ? undefined : sheetElementsRef.current.get(active);
+ focusSheetPanel(panel ?? null, reason, true);
+ },
+ onView: view => {
+ const previous = stackViewRef.current;
+ stackViewRef.current = view;
+ setStackView(view);
+ // A change of the stack's scrim owner lands with no fade on the
+ // flow's own owner dialog; see writeScrimOpacity.
+ const owner =
+ scrimOwnerRef.current == null
+ ? null
+ : (sheetDialogsRef.current.get(scrimOwnerRef.current) ?? null);
+ if (owner == null) {
+ return;
+ }
+ const ownsNow = !view.isStacked || view.ownsScrim;
+ const ownedBefore = !previous.isStacked || previous.ownsScrim;
+ if (isFlowOpenRef.current && ownsNow !== ownedBefore) {
+ writeScrimOpacity(
+ owner,
+ ownsNow && scrimOpacityRef.current > 0 ? '1' : '0',
+ scrimWriteRef.current,
+ );
+ } else if (!isFlowOpenRef.current && view.isScrimTakenOver) {
+ writeScrimOpacity(owner, '0', scrimWriteRef.current);
+ }
+ },
+ },
+ isFlowOpenRef.current,
+ );
+ return () => {
+ // Read before the entry leaves: the focus-return effect runs after.
+ leftStackRef.current = {
+ depth: stackViewRef.current.depth,
+ revealed: getBottomSheetBeneath(key),
+ closingTogether: isClosingTogether(key),
+ };
+ unregister();
+ };
+ }, [hasScrim, isFlowVisible, onBeforeSheetPresent]);
+ useLayoutEffect(() => {
+ if (isFlowVisible && hasScrim) {
+ setBottomSheetOpen(stackKeyRef.current, isFlowOpen);
+ }
+ }, [hasScrim, isFlowOpen, isFlowVisible]);
+ // Closes a batch of same-commit opens; see sealBottomSheetBatch.
+ useEffect(() => {
+ sealBottomSheetBatch();
+ });
+
const getSheetPhase = useCallback(
(sheetId: string): BottomSheetSwitcherPhase => {
if (sheetId === activeSheet) {
@@ -681,11 +927,14 @@ export function BottomSheetSwitcher({
// 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.
+ // A flow stacked above another sheet keeps every backdrop clear: the
+ // stack's owner beneath dims the page (`flowOwnsStackScrim`).
const applyScrimOpacity = useCallback(() => {
const owner =
scrimOwnerSheet == null
? null
: (sheetDialogsRef.current.get(scrimOwnerSheet) ?? null);
+ const value = flowOwnsStackScrim ? scrimOpacityRef.current : 0;
// A fresh open keeps the backdrop's @starting-style fade; only a hand
// from one presented dialog to another swaps without one.
const ownerChanged =
@@ -695,18 +944,15 @@ export function BottomSheetSwitcher({
for (const [sheetId, dialog] of sheetDialogsRef.current) {
if (dialog === owner) {
if (ownerChanged && dialog.open) {
- takeOverScrim(dialog, scrimOpacityRef.current);
+ takeOverScrim(dialog, value);
} else {
- dialog.style.setProperty(
- '--_sheet-scrim-opacity',
- String(scrimOpacityRef.current),
- );
+ dialog.style.setProperty('--_sheet-scrim-opacity', String(value));
}
} else if (sheetId !== scrimOwnerSheet) {
dialog.style.setProperty('--_sheet-scrim-opacity', '0');
}
}
- }, [scrimOwnerSheet]);
+ }, [flowOwnsStackScrim, scrimOwnerSheet]);
const onSheetScrimOpacityChange = useCallback(
(sheetId: string, opacity: number) => {
// A pointer captured by the outgoing sheet can keep delivering gesture
@@ -802,6 +1048,7 @@ export function BottomSheetSwitcher({
onSheetEnterStart,
onSheetTransitionComplete,
onSheetScrimOpacityChange,
+ stackView,
dialogProps,
onDialogCancel,
onDialogClick,
@@ -828,12 +1075,14 @@ export function BottomSheetSwitcher({
registerSheetDialog,
registerSheetElement,
registerSheetPurpose,
+ stackView,
],
);
return (
<BottomSheetSwitcherContext value={contextValue}>
<div
+ ref={flowRef}
{...stylex.props(
styles.flow,
!hasScrim && isFlowVisible && styles.flowNonModal,
diff --git a/packages/core/src/BottomSheet/BottomSheetSwitcherContext.ts b/packages/core/src/BottomSheet/BottomSheetSwitcherContext.ts
index ae64dedeb0..9d594a74b0 100644
--- a/packages/core/src/BottomSheet/BottomSheetSwitcherContext.ts
+++ b/packages/core/src/BottomSheet/BottomSheetSwitcherContext.ts
@@ -22,6 +22,7 @@ import type {
import {createContext} from 'react';
import type {BaseProps} from '../BaseProps';
import type {DialogPurpose} from '../Dialog';
+import type {BottomSheetStackView} from './bottomSheetStack';
export type BottomSheetSwitcherPhase =
| 'entering'
@@ -93,6 +94,11 @@ export interface BottomSheetSwitcherContextValue {
event: BottomSheetSwitcherTransitionEvent,
) => void;
onSheetScrimOpacityChange: (sheetId: string, opacity: number) => void;
+ /**
+ * The switcher's place in the stack of presented modal sheets. The whole
+ * switcher is one level; each step's positioner recedes by this view.
+ */
+ stackView: BottomSheetStackView;
/** Consumer dialog props the switcher forwards to every sheet dialog. */
dialogProps: BottomSheetSwitcherDialogProps;
onDialogCancel: (event: SyntheticEvent<HTMLDialogElement>) => void;
diff --git a/packages/core/src/BottomSheet/bottomSheetStack.ts b/packages/core/src/BottomSheet/bottomSheetStack.ts
new file mode 100644
index 0000000000..d650619165
--- /dev/null
+++ b/packages/core/src/BottomSheet/bottomSheetStack.ts
@@ -0,0 +1,2031 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file bottomSheetStack.ts
+ * @input Uses the DOM (dialog elements, document order) and focusForLastInput
+ * @output Exports the private bottom-sheet stack registry: registration of
+ * sheet hosts (modal sheets stack; non-modal sheets are a group of their
+ * own, hosted as manual popovers), open-order ranking with tree-order
+ * ties, native top-layer reconciliation, one view per host (top, covered,
+ * recede depth, scrim ownership, blocking), the replace handoff between a
+ * sheet closing and a sheet opening in the same update, and the native
+ * show/hide and focus helpers the hosts share
+ * @position Internal to BottomSheet; consumed by the standalone host in
+ * BottomSheet.tsx and by BottomSheetSwitcher. Not exported from the package
+ * root, and no public API reaches it.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/BottomSheet/BottomSheet.tsx
+ * - /packages/core/src/BottomSheet/BottomSheetSwitcher.tsx
+ * - /packages/core/src/BottomSheet/BottomSheetStacking.test.tsx
+ * - /packages/core/src/BottomSheet/BottomSheetReplace.test.tsx
+ * - /packages/core/src/BottomSheet/BottomSheet.doc.mjs
+ * - /apps/storybook/stories/BottomSheetReplace.stories.tsx
+ *
+ * ## Why a registry and not a component
+ *
+ * Every modal sheet keeps its own native `<dialog>` and its own open state. A
+ * sheet opened while another sheet is open is a stacked sheet: the browser's
+ * top layer already paints the later `showModal()` above the earlier one, and
+ * the later modal dialog already blocks the earlier one. What the browser does
+ * NOT know is that the two dialogs are sheets of one stack, so this registry
+ * supplies the rest: which sheet is on top, how far back each covered sheet
+ * recedes, whose `::backdrop` is the one visible scrim, and when the native
+ * order would come out wrong (several sheets opening in one commit) it puts
+ * the top layer right before the frame paints. Nothing here is a public
+ * surface; the hosts call it from their commit-phase effects only.
+ *
+ * ## Order is open order, ties are tree order
+ *
+ * Each open cycle of a sheet gets a rank: the batch it opened in, then a
+ * running sequence. A batch is one React commit: registrations that arrive
+ * between two seals belong to the same commit, because the hosts seal in
+ * passive effects and React runs every pending passive effect before the next
+ * commit's layout effects (and flushes them synchronously after a sync
+ * commit). Later batch is higher. Within one batch there is no open order, so
+ * document order of the dialog elements decides: a sheet before the sheets
+ * rendered in its content, siblings in the order they are written. That is the
+ * order the first painted frame of a deep link must show, and effect order
+ * (child first) gets it backwards; the rank is read at compare time, after
+ * every registration of the commit has arrived, so it does not.
+ *
+ * ## The top layer is reconciled, not trusted
+ *
+ * The registry remembers the order it called `showModal()` in. After every
+ * change it computes the order the ranks want; where the two diverge it closes
+ * the dialogs from the first divergence up and shows them again in rank order.
+ * That happens inside the commit, before paint, so a deep link whose inner
+ * sheet registered first is repaired without a frame in between. A sheet that
+ * closes and reopens gets a new rank and is re-shown on top the same way;
+ * only the dialogs that have to move up are re-shown, the rest keep their
+ * place, their backdrop and any motion in flight.
+ *
+ * ## A replace is a move the person makes from one sheet to the next
+ *
+ * One sheet closing and another opening in the same commit, where the closing
+ * sheet was the top open sheet of its stack (no other open sheet above it,
+ * the opening sheet aside) and the interaction came from inside it (the
+ * control last pressed — or, with no fresh press, the focused element — was
+ * in its dialog), is a replace: the person is moving from one step to the
+ * next, not stacking one on the other. The registry then runs the handoff a BottomSheetSwitcher runs
+ * between its steps, on the two standalone dialogs: the entering sheet rises
+ * above the retained one; a taller retained sheet moves down to meet it; the
+ * retained sheet fades only after both motions complete, then its dialog
+ * closes and the entering sheet takes over the scrim in the same frame. The
+ * retained sheet is inert at once, keeps no place in the dismissal order, and
+ * lends its opener to the sheet replacing it, so closing the flow later
+ * returns focus to where the flow began. A covered sheet closing (not the
+ * top), a sheet closing in a different update from the open, or a close and
+ * an open driven from a control outside the closing sheet (two owners acting
+ * in one update) is never a replace, so a push over a stack and a pop out of
+ * one keep their motion and their own openers. Non-modal sheets
+ * (`hasScrim={false}`) replace each other too: they are hosted as manual
+ * popovers, so the top layer orders them, but they are a group of their own
+ * that never stacks, recedes, or owns a scrim.
+ *
+ * ## One state per page, per document
+ *
+ * The state lives on `globalThis` so that two copies of this module on one
+ * page that speak the same stack protocol version share one stack (see
+ * StackState); everything the stack reads and writes across commits — the
+ * entries, each document's shown order, which documents have the press
+ * listeners, the deferred non-modal sheets and their watchers, the element to
+ * keep focused across a re-show — is in that shared state and none of it is
+ * per copy. The one module-level value is the engine probe's answer, a fact
+ * about the browser that every copy measures alike. A copy on another
+ * protocol version keeps a stack of its own. Within a state, each document is
+ * its own stack: a sheet portaled into another document has that document's
+ * top layer, focus and order.
+ */
+
+import {notifyTopLayerEntry} from '../Layer/modalOutlet';
+import {focusForLastInput} from '../utils/focusReturn';
+
+export interface BottomSheetStackView {
+ /** Another modal sheet is presented alongside this one. */
+ readonly isStacked: boolean;
+ /** This sheet is the open sheet that is on top. */
+ readonly isTop: boolean;
+ /** This sheet is open with at least one open sheet above it. */
+ readonly isCovered: boolean;
+ /** Open sheets above this one; drives how far the sheet recedes. */
+ readonly depth: number;
+ /** This sheet's `::backdrop` is the one visible scrim of the stack. */
+ readonly ownsScrim: boolean;
+ /**
+ * This sheet took the scrim over from a sheet below it that is still
+ * sliding out, so its backdrop must appear at once rather than fade in.
+ */
+ readonly isScrimHandoff: boolean;
+ /**
+ * This sheet is covered and contains no presented sheet, so its whole
+ * dialog can be marked inert and hidden from assistive technology.
+ */
+ readonly isBlocked: boolean;
+ /**
+ * This sheet is closing and an open sheet above it owns the scrim now, so
+ * its own backdrop must leave at once rather than fade: the dim is the
+ * other sheet's from this frame on, and two backdrops would double it.
+ */
+ readonly isScrimTakenOver: boolean;
+ /**
+ * This closed sheet is being replaced by the sheet opened in the same
+ * update: it stays in place (`covered`), moves down to the entering sheet's
+ * top edge (`aligning`), or fades (`fading`), instead of sliding out.
+ */
+ readonly replacedMotion: BottomSheetReplacedMotion | null;
+ /** How far down a replaced sheet moves to meet the entering sheet, in px. */
+ readonly alignmentOffset: number;
+ /** This open sheet is replacing the sheet that closed in the same update. */
+ readonly isReplacing: boolean;
+}
+
+export type BottomSheetReplacedMotion = 'covered' | 'aligning' | 'fading';
+
+/** The motions a host's panel reports to the registry during a replace. */
+export type BottomSheetReplaceMotion =
+ 'entering' | 'aligning' | 'fading' | 'exiting';
+
+export const BOTTOM_SHEET_STACK_DEFAULT_VIEW: BottomSheetStackView = {
+ isStacked: false,
+ isTop: false,
+ isCovered: false,
+ depth: 0,
+ ownsScrim: false,
+ isScrimHandoff: false,
+ isBlocked: false,
+ isScrimTakenOver: false,
+ replacedMotion: null,
+ alignmentOffset: 0,
+ isReplacing: false,
+};
+
+/**
+ * Why the registry moves focus into a sheet: it was shown on top (`open`), a
+ * close above it revealed it (`reveal`), or it is replacing the sheet the
+ * person was in (`replace`: focus follows the person from one step to the
+ * next, whatever the native host did with it).
+ */
+export type BottomSheetFocusReason = 'open' | 'reveal' | 'replace';
+
+/** The sheets of one document's modal stack that close in the same update. */
+interface ClosingGroup {
+ /** Bottom to top. */
+ members: Entry[];
+ /** Members whose dialogs have not left the top layer yet. */
+ pending: Set<Entry>;
+ /** The bottom-most member's return target, read when the group is sealed. */
+ returnTarget: HTMLElement | null;
+ /** Focus has been returned for this group. */
+ reported?: boolean;
+}
+
+export interface BottomSheetStackRegistration {
+ /** Stable identity of the host component instance. */
+ key: object;
+ /** The host's native dialog. */
+ getElement: () => HTMLDialogElement | null;
+ /**
+ * The element whose place in the tree orders this level against the other
+ * sheets of its commit, when it is not the dialog itself: a switcher flow
+ * is realized by whichever step dialog is active, so its flow wrapper — the
+ * one element that contains every step — stands for it, and a handoff
+ * cannot reorder the flow against a sheet opened in the same commit.
+ */
+ getTreeAnchor?: () => Element | null;
+ /** Present the dialog modally (`showModal()`), capturing the opener first. */
+ show: () => void;
+ /** Take the dialog out of the top layer (`close()`) for a re-show. */
+ hide: () => void;
+ /** Move focus into the sheet: shown on top, or revealed by a close above. */
+ focus: (reason: BottomSheetFocusReason) => void;
+ /**
+ * Where focus returns when this sheet closes the stack: its explicit
+ * final-focus target, else the element that opened it. Read by the
+ * registry when several sheets close in one update.
+ */
+ getReturnTarget?: () => HTMLElement | null;
+ /** Receive this host's view whenever it changes. */
+ onView: (view: BottomSheetStackView) => void;
+ /**
+ * What a host must supply to take part in a replace. A host without it (a
+ * switcher flow, which replaces its own steps) is never paired.
+ */
+ replaceable?: BottomSheetReplaceable;
+}
+
+export interface BottomSheetReplaceable {
+ /** The host's visual panel, measured for the replace alignment. */
+ getPanel: () => HTMLElement | null;
+ /** The element focus returns to when the sheet closes the flow. */
+ getOpener: () => HTMLElement | null;
+ /** Adopt the replaced sheet's opener, so the flow closes back to it. */
+ setOpener: (opener: HTMLElement | null) => void;
+ /** The replace is over: this replaced sheet is hidden and its dialog closed. */
+ finish: () => void;
+}
+
+interface Rank {
+ batch: number;
+ seq: number;
+}
+
+interface ReplaceState {
+ /** The sheet that opened in the same update and now stands in for this one. */
+ replacer: Entry;
+ motion: BottomSheetReplacedMotion;
+ alignmentOffset: number;
+ isAlignmentComplete: boolean;
+ isEnteringComplete: boolean;
+}
+
+interface Entry extends BottomSheetStackRegistration {
+ rank: Rank;
+ isOpen: boolean;
+ /** The document whose top layer this sheet's dialog is in. */
+ doc: Document;
+ /**
+ * Modal sheets stack with each other; non-modal sheets (`hasScrim={false}`)
+ * form their own group per document: they never stack, recede or own a
+ * scrim, but they replace each other and keep their top-layer order.
+ */
+ isModal: boolean;
+ view: BottomSheetStackView;
+ /** Set on a closed sheet while another sheet replaces it. */
+ replace: ReplaceState | null;
+ /** Set on an open sheet while it replaces the sheet that closed with it. */
+ replacing: Entry | null;
+ /**
+ * Reopened while it was being replaced: its panel is already in place, so
+ * when it replaces in turn its entrance is complete the moment it starts.
+ */
+ isEnteringInPlace: boolean;
+}
+
+const ALIGNMENT_THRESHOLD_PX = 1;
+
+/**
+ * The registry's state. One per JavaScript realm, shared by every copy of this
+ * module in it that speaks the same stack protocol version: two copies of
+ * the package on one page (two bundles, a dev server serving the same file
+ * under two URLs, a micro-frontend) must see one stack, or each would show
+ * its own sheets over the other's with two scrims and no order. The state
+ * lives on `globalThis` under a symbol that names the protocol version
+ * (STACK_PROTOCOL_VERSION), so a copy on another version finds no state of
+ * its own and keeps a stack of its own; the shape it carries is the guard
+ * against a key collision.
+ */
+interface StackState {
+ shape: number;
+ entries: Entry[];
+ // The order the presented entries were shown in, per group (one document's
+ // modal sheets, one document's non-modal sheets): each document has its
+ // own top layer, and the two groups never reorder each other.
+ shownOrder: WeakMap<Document, {modal: Entry[]; nonModal: Entry[]}>;
+ // Documents that have the press listeners, each with the function that
+ // removes them: one set per document, installed with the document's first
+ // registered sheet and removed when its last one leaves (the listeners
+ // feed this shared state, so a second copy must not add another set).
+ listenedDocuments: WeakMap<Document, () => void>;
+ // The open/close flips of the current batch (one commit); a replace pairs
+ // one of each. Cleared with the seal.
+ batchOpened: Entry[];
+ batchClosed: Entry[];
+ // The control the person acted from, for the batch's first flip: the
+ // target of the last pointer or key press in the document (recorded in the
+ // capture phase, so it is known whether or not the press moved focus — a
+ // non-modal sheet takes no focus, and some browsers do not focus a clicked
+ // button), else where focus was, read before any dialog of this commit is
+ // shown. A replace is recognised by it.
+ batchActor: Element | null;
+ // The target is held weakly: a press on an element that has since been
+ // removed and dropped must not keep it alive until the next press.
+ lastPress: WeakMap<Document, {target: WeakRef<Element>; at: number}>;
+ // Retained sheets whose replacer closed in this batch; dropped once the
+ // batch's pairing is known, unless the batch reopened them.
+ pendingDrops: Entry[];
+ // A replacer that still owes the move of focus into itself (done once its
+ // dialog is shown).
+ pendingReplaceFocus: Entry | null;
+ // The pair this batch made, and the opener the replacer had before it
+ // adopted the replaced sheet's: a later flip of the same commit (a third
+ // sheet closing or opening) makes the tally no longer one close and one
+ // open, and the pair is undone — the commit is then several sheets
+ // changing, which keep their own push and pop motion.
+ batchPair: {
+ replaced: Entry;
+ replacer: Entry;
+ replacerOpener: HTMLElement | null;
+ } | null;
+ // Modal sheets closing together in one update ("Close all"): focus returns
+ // once, from the bottom-most of them, after the last of them has left the
+ // top layer. Sealed from `batchClosed` when the batch ends.
+ closingTogether: Map<Entry, ClosingGroup>;
+ // Rank persists across a StrictMode replay (unregister and register in one
+ // synchronous pass) so the replay cannot promote a sheet. A rank marked
+ // closed is spent: the next open takes a new one.
+ rankByKey: WeakMap<
+ object,
+ Rank & {isClosed: boolean; detachedBatch: number | null}
+ >;
+ currentBatch: number;
+ nextSeq: number;
+ isBatchDirty: boolean;
+ isSealScheduled: boolean;
+ // The element a step present blurred while the person was in a sheet above
+ // the flow; the next top-layer reconcile lands focus on it again. Per
+ // document, within one commit.
+ focusToKeep: WeakMap<Document, HTMLElement>;
+ // Non-modal sheets presented by `show()` because a modal outside them was
+ // open, waiting to enter the top layer, with the watchers that look again
+ // (see deferTopLayerEntry).
+ deferredTopLayer: WeakMap<Document, DeferredTopLayer>;
+}
+
+interface DeferredTopLayer {
+ deferred: Map<HTMLDialogElement, HTMLElement | null>;
+ blockers: WeakSet<HTMLDialogElement>;
+ removals: MutationObserver | null;
+ /** Removes the document `close` listener; set while anything waits. */
+ stopListeningForClose: (() => void) | null;
+}
+
+/**
+ * The stack protocol version: the shape and meaning of Entry, the
+ * registration, the batch/seal protocol and the shared listeners. Copies of
+ * the package on one page share one stack per document when they speak the
+ * same protocol (`component:BottomSheet` PR1); the version is part of the
+ * document-global key, so a copy on another protocol finds no state of its
+ * own version and keeps a stack of its own — two independent stacks, each
+ * ordering only the sheets its copy renders, never a shared state read with
+ * the wrong shape. Bump it whenever any of those change.
+ */
+const STACK_PROTOCOL_VERSION = 8;
+const STACK_STATE_KEY = Symbol.for(
+ `astryx.bottomSheetStack.v${STACK_PROTOCOL_VERSION}`,
+);
+const STACK_STATE_SHAPE = STACK_PROTOCOL_VERSION;
+
+function createStackState(): StackState {
+ return {
+ shape: STACK_STATE_SHAPE,
+ entries: [],
+ shownOrder: new WeakMap(),
+ listenedDocuments: new WeakMap(),
+ batchOpened: [],
+ batchClosed: [],
+ batchActor: null,
+ batchPair: null,
+ lastPress: new WeakMap(),
+ pendingDrops: [],
+ pendingReplaceFocus: null,
+ closingTogether: new Map(),
+ rankByKey: new WeakMap(),
+ currentBatch: 0,
+ nextSeq: 0,
+ isBatchDirty: false,
+ isSealScheduled: false,
+ focusToKeep: new WeakMap(),
+ deferredTopLayer: new WeakMap(),
+ };
+}
+
+function acquireStackState(): StackState {
+ const holder = globalThis as {[STACK_STATE_KEY]?: StackState};
+ const shared = holder[STACK_STATE_KEY];
+ if (shared != null) {
+ // The key names the version, so a state found under it is this
+ // protocol's; the shape check is the guard against a key collision.
+ return shared.shape === STACK_STATE_SHAPE ? shared : createStackState();
+ }
+ const created = createStackState();
+ holder[STACK_STATE_KEY] = created;
+ return created;
+}
+
+const state = acquireStackState();
+
+function takeRank(): Rank {
+ state.isBatchDirty = true;
+ scheduleSeal();
+ return {batch: state.currentBatch, seq: state.nextSeq++};
+}
+
+function scheduleSeal(): void {
+ // Backstop for a commit whose hosts run no passive effect afterwards (a
+ // subtree React just hid). A later task is always a later batch.
+ if (state.isSealScheduled || typeof queueMicrotask !== 'function') {
+ return;
+ }
+ state.isSealScheduled = true;
+ queueMicrotask(() => {
+ state.isSealScheduled = false;
+ sealBottomSheetBatch();
+ });
+}
+
+/**
+ * End the current batch. Hosts call it from a passive effect, which React runs
+ * after every layout effect of the same commit and before the next commit;
+ * registrations on either side of it are therefore different open orders.
+ */
+export function sealBottomSheetBatch(): void {
+ flushPendingDrops();
+ sealClosingGroups();
+ if (state.isBatchDirty) {
+ state.currentBatch += 1;
+ state.isBatchDirty = false;
+ }
+ state.batchOpened = [];
+ state.batchClosed = [];
+ state.batchActor = null;
+ state.batchPair = null;
+}
+
+/**
+ * Two or more modal sheets of one stack closing in the same update with no
+ * sheet of that stack left open and nothing opening: "Close all". Each one
+ * would return focus on its own, at depth 0, to an opener that is either
+ * inside a dialog that is closing with it or on a page that is still inert
+ * behind the other modals — so none of them can. The group returns focus
+ * once instead, from its bottom-most sheet, after the last of its dialogs
+ * has left the top layer. A single sheet closing, a non-modal sheet, and a
+ * batch that also opens a sheet are not groups: their own close handles
+ * focus (the replace and the pop have their own rules).
+ */
+function sealClosingGroups(): void {
+ if (state.batchOpened.length > 0) {
+ return;
+ }
+ const closingModal = state.batchClosed.filter(
+ entry => entry.isModal && entry.replace == null && entry.replacing == null,
+ );
+ if (closingModal.length < 2) {
+ return;
+ }
+ const byDoc = new Map<Document, Entry[]>();
+ for (const entry of closingModal) {
+ const list = byDoc.get(entry.doc) ?? [];
+ list.push(entry);
+ byDoc.set(entry.doc, list);
+ }
+ for (const [doc, closing] of byDoc) {
+ if (closing.length < 2) {
+ continue;
+ }
+ const stack = sortedEntries(doc, true);
+ if (stack.some(entry => entry.isOpen)) {
+ // Sheets remain open beneath: the pops return into the revealed sheet
+ // through the ordinary close path.
+ continue;
+ }
+ const members = stack.filter(entry => closing.includes(entry));
+ const bottom = members[0];
+ const group: ClosingGroup = {
+ members,
+ pending: new Set(members),
+ returnTarget: bottom.getReturnTarget?.() ?? null,
+ };
+ for (const entry of members) {
+ state.closingTogether.set(entry, group);
+ }
+ }
+}
+
+/**
+ * Whether `key` closes as part of a "Close all" group. Its host then leaves
+ * the top layer without returning focus itself; the registry returns it
+ * once the whole group has left.
+ */
+export function isClosingTogether(key: object): boolean {
+ const entry = state.entries.find(candidate => candidate.key === key);
+ return entry != null && state.closingTogether.has(entry);
+}
+
+function completeClosingGroup(group: ClosingGroup): void {
+ if (group.pending.size > 0 || group.reported) {
+ return;
+ }
+ group.reported = true;
+ const target = group.returnTarget;
+ if (target != null && target.isConnected) {
+ focusForLastInput(target);
+ }
+}
+
+/**
+ * A member of a "Close all" group has left the top layer. When it is the
+ * last one, focus returns to the group's target: the bottom-most sheet's
+ * final-focus target or opener, now that no modal dialog stands in the way.
+ */
+export function reportClosedTogether(key: object): void {
+ const entry = state.entries.find(candidate => candidate.key === key);
+ const group = entry == null ? undefined : state.closingTogether.get(entry);
+ if (entry == null || group == null) {
+ return;
+ }
+ leaveClosingGroup(entry, group);
+}
+
+function leaveClosingGroup(entry: Entry, group: ClosingGroup): void {
+ state.closingTogether.delete(entry);
+ group.pending.delete(entry);
+ completeClosingGroup(group);
+}
+
+/**
+ * Remember the last press in a document: a pointer down, a click (pointer,
+ * touch, keyboard activation or code: it is what runs the handler that flips
+ * the sheets) or a key down. One capture-phase listener per event per
+ * document, installed with the first sheet registered in it; the target is
+ * kept weakly.
+ */
+function listenForPresses(doc: Document): void {
+ if (state.listenedDocuments.has(doc)) {
+ return;
+ }
+ const record = (event: Event) => {
+ if (event.target instanceof Element) {
+ state.lastPress.set(doc, {
+ target: new WeakRef(event.target),
+ at: Date.now(),
+ });
+ }
+ };
+ doc.addEventListener('pointerdown', record, true);
+ doc.addEventListener('click', record, true);
+ doc.addEventListener('keydown', record, true);
+ state.listenedDocuments.set(doc, () => {
+ doc.removeEventListener('pointerdown', record, true);
+ doc.removeEventListener('click', record, true);
+ doc.removeEventListener('keydown', record, true);
+ state.lastPress.delete(doc);
+ });
+}
+
+/**
+ * The document's last registered sheet left: nothing feeds the press record
+ * any more, so the listeners go (`architecture:react-component-runtime`
+ * INV5: a subscription lives as long as what reads it). The next sheet to
+ * register in the document installs them again.
+ */
+function stopListeningForPresses(doc: Document): void {
+ if (state.entries.some(entry => entry.doc === doc)) {
+ return;
+ }
+ const remove = state.listenedDocuments.get(doc);
+ if (remove != null) {
+ state.listenedDocuments.delete(doc);
+ remove();
+ }
+}
+
+/**
+ * A press is the actor of a flip only while it is fresh: the handler a press
+ * runs flips the sheets within the same task, milliseconds later. A flip
+ * that arrives later (a step change after a save resolves) is not that
+ * press's doing, and reads focus instead. A press is also spent once the
+ * sheet it landed in has been replaced or has closed — its target sits in
+ * an inert or no longer presented dialog — or once a replace has consumed
+ * it: a step advanced by code shortly after a Submit press (a "Processing"
+ * interstitial) is then judged by where focus is, inside the step, and
+ * hands off as DEP-0015 promises.
+ */
+const PRESS_ACTOR_WINDOW_MS = 1000;
+
+function actorFor(doc: Document, flipping: Entry): Element | null {
+ const press = state.lastPress.get(doc);
+ const target = press?.target.deref();
+ if (
+ press != null &&
+ target != null &&
+ target.isConnected &&
+ Date.now() - press.at <= PRESS_ACTOR_WINDOW_MS &&
+ !isPressSpent(target, flipping)
+ ) {
+ return target;
+ }
+ return doc.activeElement;
+}
+
+/**
+ * A press is spent when the sheet it landed in was already closed or
+ * replaced before this flip — not the sheet this very flip is closing, which
+ * is the ordinary replace made from inside it.
+ */
+function isPressSpent(target: Element, flipping: Entry): boolean {
+ const owning = state.entries.find(entry => {
+ const element = entry.getElement();
+ return (
+ entry.doc === flipping.doc && element != null && element.contains(target)
+ );
+ });
+ if (owning == null || owning === flipping) {
+ return false;
+ }
+ return !owning.isOpen || owning.replace != null;
+}
+
+/** Record a flip of the current batch, and who acted if it is the first. */
+function recordFlip(entry: Entry, flip: 'opened' | 'closed'): void {
+ if (state.batchOpened.length === 0 && state.batchClosed.length === 0) {
+ state.batchActor = actorFor(entry.doc, entry);
+ }
+ (flip === 'opened' ? state.batchOpened : state.batchClosed).push(entry);
+}
+
+function compareRank(a: Entry, b: Entry): number {
+ if (a.rank.batch !== b.rank.batch) {
+ return a.rank.batch - b.rank.batch;
+ }
+ // One commit: tree order. A dialog that precedes another in document order
+ // (including one that contains the other) is below it.
+ const aEl = a.getTreeAnchor?.() ?? a.getElement();
+ const bEl = b.getTreeAnchor?.() ?? b.getElement();
+ if (aEl != null && bEl != null && aEl !== bEl) {
+ const position = aEl.compareDocumentPosition(bEl);
+ if (position & Node.DOCUMENT_POSITION_FOLLOWING) {
+ return -1;
+ }
+ if (position & Node.DOCUMENT_POSITION_PRECEDING) {
+ return 1;
+ }
+ }
+ return a.rank.seq - b.rank.seq;
+}
+
+/** The sheets of one group (document + modality), bottom to top. */
+function sortedEntries(doc: Document, isModal: boolean): Entry[] {
+ return state.entries
+ .filter(entry => entry.doc === doc && entry.isModal === isModal)
+ .sort(compareRank);
+}
+
+/** The sheets `entry` shares a group with, bottom to top. */
+function groupOf(entry: Entry): Entry[] {
+ return sortedEntries(entry.doc, entry.isModal);
+}
+
+/** The shown order of one group, read from or written to the shared state. */
+function getShownOrder(doc: Document, isModal: boolean): Entry[] {
+ const orders = state.shownOrder.get(doc);
+ if (orders == null) {
+ return [];
+ }
+ return isModal ? orders.modal : orders.nonModal;
+}
+function setShownOrder(doc: Document, isModal: boolean, order: Entry[]): void {
+ const orders = state.shownOrder.get(doc) ?? {modal: [], nonModal: []};
+ if (isModal) {
+ orders.modal = order;
+ } else {
+ orders.nonModal = order;
+ }
+ state.shownOrder.set(doc, orders);
+}
+
+function isSameView(a: BottomSheetStackView, b: BottomSheetStackView): boolean {
+ return (
+ a.isStacked === b.isStacked &&
+ a.isTop === b.isTop &&
+ a.isCovered === b.isCovered &&
+ a.depth === b.depth &&
+ a.ownsScrim === b.ownsScrim &&
+ a.isScrimHandoff === b.isScrimHandoff &&
+ a.isBlocked === b.isBlocked &&
+ a.isScrimTakenOver === b.isScrimTakenOver &&
+ a.replacedMotion === b.replacedMotion &&
+ a.alignmentOffset === b.alignmentOffset &&
+ a.isReplacing === b.isReplacing
+ );
+}
+
+function computeViews(order: Entry[], isModal: boolean): void {
+ const changed: Entry[] = [];
+ if (!isModal) {
+ // Non-modal sheets never stack: no recede, no scrim, no top-layer order
+ // against modal sheets. Their view carries only the replace a pair of
+ // them may be running.
+ for (const entry of order) {
+ const view: BottomSheetStackView = {
+ ...BOTTOM_SHEET_STACK_DEFAULT_VIEW,
+ replacedMotion: entry.replace?.motion ?? null,
+ alignmentOffset: entry.replace?.alignmentOffset ?? 0,
+ isReplacing: entry.replacing != null,
+ };
+ if (!isSameView(entry.view, view)) {
+ entry.view = view;
+ changed.push(entry);
+ }
+ }
+ for (const entry of changed) {
+ entry.onView(entry.view);
+ }
+ return;
+ }
+ const openEntries = order.filter(entry => entry.isOpen);
+ const top = openEntries[openEntries.length - 1] ?? null;
+ // A replaced sheet keeps the scrim while it is retained; the sheet replacing
+ // it takes the scrim over, instantly, when the replaced sheet leaves.
+ const owner =
+ order.find(entry => entry.isOpen || entry.replace != null) ?? null;
+ order.forEach((entry, index) => {
+ let depth = 0;
+ for (let above = index + 1; above < order.length; above += 1) {
+ // The sheet replacing this one stands in its place, not above it.
+ if (order[above].isOpen && order[above] !== entry.replace?.replacer) {
+ depth += 1;
+ }
+ }
+ const isCovered = entry.isOpen && depth > 0;
+ const element = entry.getElement();
+ const containsPresented =
+ element != null &&
+ order.some(other => {
+ const otherElement = other.getElement();
+ return (
+ other !== entry &&
+ otherElement != null &&
+ element.contains(otherElement)
+ );
+ });
+ const ownsScrim = entry === owner;
+ const isScrimHandoff =
+ ownsScrim &&
+ entry.isOpen &&
+ order.slice(0, index).some(below => !below.isOpen);
+ const view: BottomSheetStackView = {
+ isStacked: order.length > 1,
+ isTop: entry === top,
+ isCovered,
+ depth,
+ ownsScrim,
+ isScrimHandoff,
+ isBlocked: isCovered && !containsPresented,
+ isScrimTakenOver: !entry.isOpen && owner != null && owner !== entry,
+ replacedMotion: entry.replace?.motion ?? null,
+ alignmentOffset: entry.replace?.alignmentOffset ?? 0,
+ isReplacing: entry.replacing != null,
+ };
+ if (!isSameView(entry.view, view)) {
+ entry.view = view;
+ changed.push(entry);
+ }
+ });
+ for (const entry of changed) {
+ entry.onView(entry.view);
+ }
+}
+
+/**
+ * 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.
+ */
+export function presentStepModally(dialog: HTMLDialogElement): void {
+ const doc = dialog.ownerDocument;
+ const focused = doc.activeElement;
+ if (focused instanceof HTMLElement && focused !== doc.body) {
+ // Focus in another open dialog that does not contain this step — a sheet
+ // stacked over the flow, with the person typing in it while code moves
+ // the flow on — is theirs to keep: the registry puts that sheet back on
+ // top right after this and lands focus on this element again.
+ const focusedDialog = focused.closest('dialog');
+ if (
+ focusedDialog != null &&
+ focusedDialog !== dialog &&
+ !focusedDialog.contains(dialog) &&
+ !dialog.contains(focusedDialog) &&
+ isSheetHostPresented(focusedDialog)
+ ) {
+ state.focusToKeep.set(doc, focused);
+ }
+ 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.
+ */
+export 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');
+}
+
+/** The pending restore of a dialog's scrim transition; one per host. */
+export interface BottomSheetScrimWrite {
+ frame: number | null;
+}
+
+/**
+ * Write a dialog's scrim opacity. A change while the dialog is up is a change
+ * of scrim owner, and lands with no transition at all: a `0.01s` duration
+ * still paints one frame at the old value, which reads as a dip or, with the
+ * old owner's backdrop still fading, as a doubled dim. The pin
+ * (`--_sheet-scrim-duration: 0s`, inline) stays for two animation frames
+ * (two nested `requestAnimationFrame`s: the first frame paints the new value,
+ * the second confirms it is on screen before the stylesheet's duration
+ * returns). Hosts cancel the pending restore with `cancelScrimWrite` when
+ * they unmount.
+ */
+export function writeScrimOpacity(
+ dialog: HTMLDialogElement | null,
+ opacity: '0' | '1',
+ pending: BottomSheetScrimWrite,
+): void {
+ if (dialog == null) {
+ return;
+ }
+ if (
+ !dialog.open ||
+ dialog.style.getPropertyValue('--_sheet-scrim-opacity') === opacity
+ ) {
+ dialog.style.setProperty('--_sheet-scrim-opacity', opacity);
+ return;
+ }
+ dialog.style.setProperty('--_sheet-scrim-duration', '0s');
+ dialog.style.setProperty('--_sheet-scrim-opacity', opacity);
+ cancelScrimWrite(pending);
+ pending.frame = requestAnimationFrame(() => {
+ pending.frame = requestAnimationFrame(() => {
+ pending.frame = null;
+ dialog.style.removeProperty('--_sheet-scrim-duration');
+ });
+ });
+}
+
+export function cancelScrimWrite(pending: BottomSheetScrimWrite): void {
+ if (pending.frame != null) {
+ cancelAnimationFrame(pending.frame);
+ pending.frame = null;
+ }
+}
+
+/**
+ * Whether a sheet's dialog is presented by the browser: as a modal dialog
+ * (`open`), as a manual popover (a non-modal sheet in the top layer), or by
+ * `show()` (a non-modal sheet below the Popover API support floor).
+ */
+export function isSheetHostPresented(
+ dialog: HTMLDialogElement | null,
+): boolean {
+ if (dialog == null) {
+ return false;
+ }
+ if (dialog.open) {
+ return true;
+ }
+ try {
+ return dialog.matches(':popover-open');
+ } catch {
+ // jsdom and pre-Popover browsers do not recognise :popover-open.
+ return false;
+ }
+}
+
+/**
+ * Whether a modal dialog that does not contain `element` is open in its
+ * document. Such a modal makes everything outside it inert, so a non-modal
+ * sheet outside it must not paint above it.
+ */
+export function hasOpenModalOutside(element: Element): boolean {
+ return openModalsOutside(element).length > 0;
+}
+
+/** The open modal dialogs that do not contain `element`; see above. */
+function openModalsOutside(element: Element): HTMLDialogElement[] {
+ const blockers: HTMLDialogElement[] = [];
+ for (const dialog of Array.from(
+ element.ownerDocument.querySelectorAll<HTMLDialogElement>('dialog[open]'),
+ )) {
+ if (dialog === element || dialog.contains(element)) {
+ continue;
+ }
+ // A modal on its way out (a closing sheet keeps its dialog modal through
+ // the exit animation, inert and hidden) blocks nothing any more: it is
+ // gone for this decision.
+ if (
+ dialog.hasAttribute('inert') ||
+ dialog.getAttribute('aria-hidden') === 'true'
+ ) {
+ continue;
+ }
+ if (isModalDialog(dialog)) {
+ blockers.push(dialog);
+ }
+ }
+ return blockers;
+}
+
+/**
+ * Non-modal sheets presented by `show()` because a modal outside them was
+ * open, waiting to enter the top layer once it has gone. Per document, with
+ * one `close` listener per document: any dialog closing is a reason to look
+ * again, and so is every sheet-stack update (a closing modal sheet turns
+ * inert before its dialog closes). An open modal removed from the document
+ * fires no `close` — a `{isEditing && <Dialog isOpen>}` that unmounts while
+ * open — so while anything waits, a mutation observer watches removals too
+ * and looks again when a removed subtree held one of the dialogs that caused
+ * a deferral. Those blockers are recorded at defer time: `:modal` is the
+ * mark that matters, and it leaves with the dialog's top-layer membership,
+ * so it cannot be read off a removed node (nor can `aria-modal`, which a
+ * `showModal()` host such as MobileNav or Lightbox does not set).
+ */
+
+function deferTopLayerEntry(
+ dialog: HTMLDialogElement,
+ panel: HTMLElement | null,
+ blockers: ReadonlyArray<HTMLDialogElement>,
+): void {
+ const doc = dialog.ownerDocument;
+ let entry = state.deferredTopLayer.get(doc);
+ if (entry == null) {
+ entry = {
+ deferred: new Map(),
+ blockers: new WeakSet(),
+ removals: null,
+ stopListeningForClose: null,
+ };
+ state.deferredTopLayer.set(doc, entry);
+ }
+ if (entry.stopListeningForClose == null) {
+ // Installed with the first deferral and removed with the last promotion
+ // (`architecture:react-component-runtime` INV5), like the observer below.
+ const onClose = () => {
+ promoteDeferredNonModal(doc);
+ };
+ doc.addEventListener('close', onClose, true);
+ entry.stopListeningForClose = () => {
+ doc.removeEventListener('close', onClose, true);
+ };
+ }
+ entry.deferred.set(dialog, panel);
+ for (const blocker of blockers) {
+ entry.blockers.add(blocker);
+ }
+ if (entry.removals == null && typeof MutationObserver === 'function') {
+ const {blockers: known} = entry;
+ const observer = new MutationObserver(records => {
+ if (records.some(record => removedABlocker(record, known))) {
+ promoteDeferredNonModal(doc);
+ }
+ });
+ observer.observe(doc, {childList: true, subtree: true});
+ entry.removals = observer;
+ }
+}
+
+function removedABlocker(
+ record: MutationRecord,
+ blockers: WeakSet<HTMLDialogElement>,
+): boolean {
+ for (const node of Array.from(record.removedNodes)) {
+ if (!(node instanceof Element)) {
+ continue;
+ }
+ const dialogs =
+ node instanceof HTMLDialogElement
+ ? [node]
+ : Array.from(node.querySelectorAll<HTMLDialogElement>('dialog'));
+ if (dialogs.some(dialog => blockers.has(dialog))) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * Move every waiting non-modal sheet whose outside modals have all gone into
+ * the top layer: it leaves `show()` and is presented again as a manual
+ * popover, announcing its entry so global hosts re-enter above it. Focus
+ * stays where it was.
+ */
+export function promoteDeferredNonModal(doc: Document): void {
+ const entry = state.deferredTopLayer.get(doc);
+ if (entry == null || entry.deferred.size === 0) {
+ return;
+ }
+ const {deferred} = entry;
+ for (const [dialog, panel] of Array.from(deferred)) {
+ if (!dialog.isConnected || !dialog.open) {
+ deferred.delete(dialog);
+ continue;
+ }
+ const blockers = openModalsOutside(dialog);
+ if (blockers.length > 0) {
+ // Still waiting, maybe on a modal that was not there at defer time (one
+ // Dialog replaced by another in a single update): it is a blocker now,
+ // and its removal must be a reason to look again too.
+ for (const blocker of blockers) {
+ entry.blockers.add(blocker);
+ }
+ continue;
+ }
+ deferred.delete(dialog);
+ const activeElement = doc.activeElement;
+ dialog.close();
+ showSheetHostNonModal(dialog, panel);
+ if (
+ doc.activeElement !== activeElement &&
+ activeElement instanceof HTMLElement &&
+ activeElement.isConnected
+ ) {
+ activeElement.focus({preventScroll: true});
+ }
+ }
+ if (deferred.size === 0) {
+ releaseDeferralWatchers(entry);
+ }
+}
+
+function releaseDeferralWatchers(entry: DeferredTopLayer): void {
+ entry.removals?.disconnect();
+ entry.removals = null;
+ entry.stopListeningForClose?.();
+ entry.stopListeningForClose = null;
+}
+
+function isModalDialog(dialog: HTMLDialogElement): boolean {
+ // `:modal` is the browser's own answer (every browser with the Popover
+ // API has it). jsdom answers false to it for every dialog, so the modal
+ // hosts' own `aria-modal="true"` (Dialog, a scrim BottomSheet) decides
+ // there.
+ try {
+ if (dialog.matches(':modal')) {
+ return true;
+ }
+ } catch {
+ // An engine without :modal; fall through to the attribute.
+ }
+ return dialog.getAttribute('aria-modal') === 'true';
+}
+
+/**
+ * Present a non-modal sheet: in the top layer as a manual popover where the
+ * Popover API exists (Tier 2 and up), so later sheets order above earlier
+ * ones and no page-level z-index is needed; by `show()` below that floor.
+ * A manual popover has no light dismiss, no backdrop and no focus or scroll
+ * side effects, so the non-modal contract is otherwise unchanged.
+ *
+ * A non-modal sheet shown while a modal dialog that does not contain it is
+ * open (a modal sheet, a Dialog) is inert under that modal, so it is not put
+ * in the top layer — there it would paint above the modal while a press on
+ * it lands on the modal beneath — and is presented by `show()` instead, in
+ * page stacking order beneath the modal, with no page-level z-index; once
+ * the last such modal has gone it is presented again in the top layer
+ * (`promoteDeferredNonModal`). A non-modal sheet rendered inside the modal's
+ * content is not inert and enters the top layer at once.
+ */
+export function showSheetHostNonModal(
+ dialog: HTMLDialogElement,
+ panel: HTMLElement | null,
+): void {
+ if (typeof dialog.showPopover !== 'function') {
+ dialog.show();
+ return;
+ }
+ const blockers = openModalsOutside(dialog);
+ if (blockers.length > 0) {
+ dialog.show();
+ deferTopLayerEntry(dialog, panel, blockers);
+ return;
+ }
+ // Both native paths run the engine's focusing steps, and engines differ.
+ // Chromium's `show()` lands on the first focusable area in tree order,
+ // the panel (`tabindex="-1"`, no focus ring), while its `showPopover()`
+ // skips such containers and lands on the first control; Firefox lands on
+ // the first control on both paths. The sheet must focus as it did with
+ // `show()` in the engine at hand, and no control may be focused and
+ // blurred on the way (a field validating on blur would show its error on
+ // open). So the popover's focusing steps are pointed at the panel first:
+ // `autofocus` on the panel for the duration of `showPopover()` makes it
+ // the steps' autofocus delegate in every engine, and the panel is where a
+ // container-focusing engine's `show()` lands. Where the engine's `show()`
+ // skips the container and lands on the first control, focus moves from
+ // the panel to that control once — a focus on the control, no blur.
+ const doc = dialog.ownerDocument;
+ const hadAutofocus = panel?.hasAttribute('autofocus') ?? false;
+ if (panel != null && !hadAutofocus) {
+ panel.setAttribute('autofocus', '');
+ }
+ try {
+ dialog.showPopover();
+ } finally {
+ if (panel != null && !hadAutofocus) {
+ panel.removeAttribute('autofocus');
+ }
+ }
+ // The sheet is now the newest top-layer entry: global hosts shown before
+ // it (the toast viewport) re-enter above it, as they do above a modal.
+ notifyTopLayerEntry();
+ if (
+ panel != null &&
+ doc.activeElement === panel &&
+ !nativeShowFocusesContainer(dialog)
+ ) {
+ firstSequentiallyFocusable(panel)?.focus({preventScroll: true});
+ }
+}
+
+/**
+ * The first element inside `root`, in tree order, that sequential focus
+ * navigation reaches: focusable, with a tab index of zero or more, not
+ * disabled, not inert, and rendered. This is where an engine whose
+ * `show()` skips programmatically focusable containers lands.
+ */
+function firstSequentiallyFocusable(root: HTMLElement): HTMLElement | null {
+ const candidates = root.querySelectorAll<HTMLElement>(
+ 'a[href], area[href], button, input, select, textarea, iframe, summary, [contenteditable]:not([contenteditable="false"]), [tabindex]',
+ );
+ for (const candidate of Array.from(candidates)) {
+ if (candidate === root || candidate.tabIndex < 0) {
+ continue;
+ }
+ if (
+ (candidate as HTMLButtonElement).disabled === true ||
+ candidate.closest('[inert]') != null ||
+ candidate.getAttribute('type') === 'hidden' ||
+ candidate.hidden ||
+ (typeof candidate.checkVisibility === 'function' &&
+ !candidate.checkVisibility())
+ ) {
+ continue;
+ }
+ return candidate;
+ }
+ return null;
+}
+
+let showFocusesContainer: boolean | null = null;
+
+/**
+ * Whether this engine's `dialog.show()` focusing steps land on a
+ * programmatically focusable container (`tabindex="-1"`) that comes before
+ * the first control — Chromium does, Firefox skips it. Measured once, on a
+ * throwaway non-modal dialog that is shown, read and removed inside one
+ * task (no paint); focus is put back where it was. The probe lives inside
+ * `host`, the sheet's own dialog, which is in the top layer and interactive
+ * at this point (a lone sheet, or one inside the open modal's content): a
+ * probe appended to the body could sit under an open modal's inertness,
+ * where `show()` moves no focus, and cache the wrong answer for the page.
+ */
+function nativeShowFocusesContainer(host: HTMLDialogElement): boolean {
+ if (showFocusesContainer != null) {
+ return showFocusesContainer;
+ }
+ const doc = host.ownerDocument;
+ const activeBefore = doc.activeElement;
+ const probe = doc.createElement('dialog');
+ probe.setAttribute('aria-hidden', 'true');
+ probe.style.cssText =
+ 'position:fixed;inset:auto;opacity:0;pointer-events:none';
+ const container = doc.createElement('div');
+ container.tabIndex = -1;
+ const control = doc.createElement('button');
+ control.type = 'button';
+ container.appendChild(control);
+ probe.appendChild(container);
+ host.appendChild(probe);
+ try {
+ probe.show();
+ showFocusesContainer = doc.activeElement === container;
+ probe.close();
+ } catch {
+ showFocusesContainer = true;
+ } finally {
+ probe.remove();
+ if (
+ doc.activeElement !== activeBefore &&
+ activeBefore instanceof HTMLElement &&
+ activeBefore.isConnected
+ ) {
+ activeBefore.focus({preventScroll: true});
+ }
+ }
+ return showFocusesContainer;
+}
+
+/** Leave the native host, whichever one presents the sheet. */
+export function hideSheetHost(dialog: HTMLDialogElement): void {
+ const entry = state.deferredTopLayer.get(dialog.ownerDocument);
+ if (entry != null && entry.deferred.delete(dialog)) {
+ if (entry.deferred.size === 0) {
+ releaseDeferralWatchers(entry);
+ }
+ }
+ if (
+ dialog.hasAttribute('popover') &&
+ typeof dialog.hidePopover === 'function'
+ ) {
+ try {
+ dialog.hidePopover();
+ } catch {
+ // Not showing as a popover (the show() fallback); nothing to hide here.
+ }
+ }
+ if (dialog.open) {
+ dialog.close();
+ }
+}
+
+/**
+ * Close a dialog without letting the browser move focus. `close()` returns
+ * focus to the element that was focused when `showModal()` ran; with another
+ * sheet still open on top, that would pull focus out of the sheet the person
+ * is using (a re-show that repairs the top-layer order, a covered sheet
+ * closing from code, a replaced sheet leaving). Focus stays where it is; the
+ * caller decides where it goes next, if anywhere.
+ */
+export function closeDialogKeepingFocus(
+ dialog: HTMLDialogElement | null,
+): void {
+ if (dialog == null || !isSheetHostPresented(dialog)) {
+ return;
+ }
+ const doc = dialog.ownerDocument;
+ const activeElement = doc.activeElement;
+ hideSheetHost(dialog);
+ if (
+ doc.activeElement !== activeElement &&
+ activeElement instanceof HTMLElement &&
+ activeElement.isConnected
+ ) {
+ activeElement.focus({preventScroll: true});
+ }
+}
+
+/**
+ * Pair the one close and the one open of this batch as a replace. A replace
+ * is a move the person makes from one sheet to the next, and that is what
+ * the conditions check:
+ *
+ * - exactly one sheet closed and exactly one opened in this update;
+ * - both are standalone sheets of one group — one document, both modal or
+ * both non-modal (a switcher flow replaces its own steps and is never
+ * paired);
+ * - the closing sheet was the top sheet of its stack once the opening sheet
+ * is set aside — a covered sheet closing while a sheet opens is a pop
+ * beneath a push;
+ * - neither dialog contains the other — a sheet in another's content closes
+ * with it, it does not replace it;
+ * - the interaction came from inside the closing sheet: the control the
+ * person last pressed (or, with no recent press, the element focused when
+ * this update's first flip arrived, before any dialog of the update was
+ * shown) is in its dialog, or nowhere (a control that left with the step).
+ * A close and an open driven from a control outside the closing sheet are
+ * two unrelated owners acting in one update, so the sheets keep their own
+ * openers and their own push and pop motion.
+ *
+ * The opening sheet then adopts the closing sheet's opener: its own opener
+ * is inside the sheet that is leaving, and the flow began where the closing
+ * sheet's did.
+ */
+function detectReplace(): void {
+ if (state.batchOpened.length !== 1 || state.batchClosed.length !== 1) {
+ // A pair made earlier in this commit, before a third flip arrived, is
+ // undone: the commit's final tally decides, and several sheets changing
+ // in one update keep their own push and pop motion.
+ undoBatchPair();
+ return;
+ }
+ const [replacer] = state.batchOpened;
+ const [replaced] = state.batchClosed;
+ if (state.batchPair != null && state.batchPair.replaced === replaced) {
+ return;
+ }
+ if (
+ replaced === replacer ||
+ replaced.replaceable == null ||
+ replacer.replaceable == null ||
+ replaced.doc !== replacer.doc ||
+ replaced.isModal !== replacer.isModal ||
+ replaced.replace?.replacer === replacer ||
+ !replacer.isOpen ||
+ replaced.isOpen
+ ) {
+ return;
+ }
+ const replacedElement = replaced.getElement();
+ const replacerElement = replacer.getElement();
+ if (
+ replacedElement == null ||
+ replacerElement == null ||
+ replacedElement.contains(replacerElement) ||
+ replacerElement.contains(replacedElement)
+ ) {
+ return;
+ }
+ const wasTop = !groupOf(replaced).some(
+ other =>
+ other !== replacer &&
+ other !== replaced &&
+ other.isOpen &&
+ compareRank(other, replaced) > 0,
+ );
+ if (!wasTop) {
+ return;
+ }
+ const actor = state.batchActor;
+ const actedFromReplaced =
+ actor == null ||
+ actor === replaced.doc.body ||
+ replacedElement.contains(actor);
+ if (!actedFromReplaced) {
+ return;
+ }
+ // A third sheet the closing sheet was itself replacing is dropped at once,
+ // the way a switcher drops a step that is left mid-handoff. The sheet it
+ // was replacing may instead be the one coming back now (a reversal): then
+ // the roles swap and nothing is dropped.
+ if (replaced.replacing != null && replaced.replacing !== replacer) {
+ finishReplace(replaced.replacing);
+ }
+ if (replaced.replace != null) {
+ replaced.replace.replacer.replacing = null;
+ }
+ if (replacer.replace != null) {
+ replacer.replace = null;
+ }
+ replaced.replace = {
+ replacer,
+ motion: 'covered',
+ alignmentOffset: 0,
+ isAlignmentComplete: false,
+ isEnteringComplete: false,
+ };
+ replacer.replacing = replaced;
+ state.batchPair = {
+ replaced,
+ replacer,
+ replacerOpener: replacer.replaceable.getOpener(),
+ };
+ // The press that made this replace is consumed by it.
+ state.lastPress.delete(replacer.doc);
+ replacer.replaceable.setOpener(replaced.replaceable.getOpener());
+ state.pendingReplaceFocus = replacer;
+}
+
+/**
+ * Undo the pair this batch made: the replaced sheet is an ordinary closing
+ * sheet again, the replacer an ordinary opening one with its own opener, and
+ * no focus is owed. Called when a later flip of the same commit changes the
+ * tally, before the commit paints.
+ */
+function undoBatchPair(): void {
+ const pair = state.batchPair;
+ if (pair == null) {
+ return;
+ }
+ state.batchPair = null;
+ const {replaced, replacer, replacerOpener} = pair;
+ if (replaced.replace?.replacer === replacer) {
+ replaced.replace = null;
+ }
+ if (replacer.replacing === replaced) {
+ replacer.replacing = null;
+ }
+ replacer.replaceable?.setOpener(replacerOpener);
+ if (state.pendingReplaceFocus === replacer) {
+ state.pendingReplaceFocus = null;
+ }
+}
+
+/**
+ * The person moves from the replaced step to the entering one, so focus
+ * does too, and it lands on the step's `data-autofocus` descendant when it
+ * has one. The dialog is shown by now, so the native focusing steps have
+ * run: a modal replacer's `showModal()` put focus on the entering panel, a
+ * non-modal replacer's `showPopover()` may have left it where it was (Safari;
+ * the replaced step is inert from this frame). Either way the placement runs
+ * after them — focus sitting on the panel, or anywhere that is not the
+ * `data-autofocus` descendant, is the native steps' doing, not the
+ * person's, so it does not count as placed. Only focus the person already
+ * moved to a control inside the entering step is left alone.
+ */
+function focusPendingReplacer(): void {
+ const replacer = state.pendingReplaceFocus;
+ if (replacer == null) {
+ return;
+ }
+ const element = replacer.getElement();
+ if (element == null || !isSheetHostPresented(element)) {
+ return;
+ }
+ state.pendingReplaceFocus = null;
+ replacer.focus('replace');
+}
+
+/**
+ * End a replace: the replaced sheet is hidden and its dialog closed; the
+ * views computed next hand the scrim to the sheet that replaced it, which
+ * takes it in the same frame. Focus stays where it is.
+ */
+function finishReplace(replaced: Entry): void {
+ const replace = replaced.replace;
+ if (replace == null) {
+ return;
+ }
+ const {replacer} = replace;
+ replaced.replace = null;
+ if (replacer.replacing === replaced) {
+ replacer.replacing = null;
+ }
+ replaced.hide();
+ replaced.replaceable?.finish();
+}
+
+function alignmentOffsetForPanels(
+ enteringPanel: HTMLElement | null,
+ retainedPanel: HTMLElement | null,
+): number {
+ if (enteringPanel == null || retainedPanel == null) {
+ return 0;
+ }
+ // The positioner is where the entering sheet will rest; the panel itself
+ // is still rising from below the viewport.
+ const enteringTop =
+ enteringPanel.parentElement?.getBoundingClientRect().top ??
+ enteringPanel.getBoundingClientRect().top;
+ return Math.max(0, enteringTop - retainedPanel.getBoundingClientRect().top);
+}
+
+/**
+ * A host's panel reports the start and end of its motions here. During a
+ * replace they drive the handoff: when the entering sheet starts to rise, a
+ * taller retained sheet starts moving down to its top edge; the retained
+ * sheet fades once both have finished; when the fade ends the replace is over.
+ */
+export function reportBottomSheetMotion(
+ key: object,
+ event: 'start' | 'complete',
+ motion: BottomSheetReplaceMotion,
+): void {
+ const entry = state.entries.find(candidate => candidate.key === key);
+ if (entry == null) {
+ return;
+ }
+ if (motion === 'entering') {
+ const replaced = entry.replacing;
+ const replace = replaced?.replace ?? null;
+ if (replaced == null || replace == null || replace.replacer !== entry) {
+ return;
+ }
+ if (event === 'start') {
+ if (replace.motion !== 'covered') {
+ return;
+ }
+ const alignmentOffset = alignmentOffsetForPanels(
+ entry.replaceable?.getPanel() ?? null,
+ replaced.replaceable?.getPanel() ?? null,
+ );
+ if (alignmentOffset > ALIGNMENT_THRESHOLD_PX) {
+ replace.motion = 'aligning';
+ replace.alignmentOffset = alignmentOffset;
+ replace.isAlignmentComplete = false;
+ }
+ // A sheet that came back while fading is already where it belongs:
+ // its entrance is over as soon as it starts, like a switcher step's.
+ if (entry.isEnteringInPlace) {
+ entry.isEnteringInPlace = false;
+ replace.isEnteringComplete = true;
+ if (replace.motion !== 'aligning') {
+ replace.motion = 'fading';
+ }
+ } else if (replace.motion === 'covered') {
+ return;
+ }
+ } else {
+ replace.isEnteringComplete = true;
+ if (replace.motion === 'aligning' && !replace.isAlignmentComplete) {
+ return;
+ }
+ replace.motion = 'fading';
+ }
+ update(entry.doc, entry.isModal);
+ return;
+ }
+ const replace = entry.replace;
+ if (replace == null || event !== 'complete') {
+ return;
+ }
+ if (motion === 'aligning' && replace.motion === 'aligning') {
+ if (replace.isEnteringComplete) {
+ replace.motion = 'fading';
+ } else {
+ replace.isAlignmentComplete = true;
+ }
+ update(entry.doc, entry.isModal);
+ } else if (motion === 'fading' && replace.motion === 'fading') {
+ finishReplace(entry);
+ update(entry.doc, entry.isModal);
+ }
+}
+
+/**
+ * Make a document's top layer match the ranked order. The top layer is
+ * append-only, so a dialog can only move up, by closing and showing it again:
+ * the longest prefix of the wanted order that the shown order already
+ * contains, in order, is kept, and every dialog after it is re-shown in
+ * order (closing them from the top first). A deep link whose inner sheet
+ * registered first therefore re-shows inner and outer; a sheet that must
+ * rise above the sheets shown after it re-shows only itself, so a retained
+ * sheet beneath it keeps its backdrop and any motion in flight. Runs inside
+ * the commit, so a wrong intermediate order never paints. Focus moves into
+ * the top open sheet when anything was shown — unless the person was already
+ * in a sheet that is only re-shown to keep its place (a switcher flow it
+ * covers changed step from code, say): the element they were in, a field
+ * being typed in, is the dialog's focus delegate for that `showModal()` and
+ * is focused again right after it, so the keystrokes that follow still land
+ * there. The top layer is append-only, so the re-show has to close the dialog
+ * first and the field sees one blur and one focus; nothing shorter exists.
+ */
+function reconcileTopLayer(
+ doc: Document,
+ isModal: boolean,
+ order: Entry[],
+): void {
+ const shownOrder = getShownOrder(doc, isModal);
+ const presentable = order.filter(entry => {
+ const element = entry.getElement();
+ return element != null && element.isConnected;
+ });
+ let kept = 0;
+ let cursor = 0;
+ while (kept < presentable.length) {
+ const next = shownOrder.indexOf(presentable[kept], cursor);
+ if (next === -1) {
+ break;
+ }
+ cursor = next + 1;
+ kept += 1;
+ }
+ const keptEntries = new Set(presentable.slice(0, kept));
+ const reshown = presentable.slice(kept);
+ const keptActive = activeElementToKeep(doc, reshown);
+ let didShow = false;
+ for (let index = shownOrder.length - 1; index >= 0; index -= 1) {
+ if (!keptEntries.has(shownOrder[index])) {
+ shownOrder[index].hide();
+ }
+ }
+ for (const entry of reshown) {
+ const delegate =
+ keptActive != null && entry.getElement()?.contains(keptActive)
+ ? keptActive
+ : null;
+ // The native focusing steps follow an `autofocus` delegate, so the
+ // re-shown dialog lands on the element the person was in instead of its
+ // first focusable area; the attribute is the dialog's for this call only.
+ const hadAutofocus = delegate?.hasAttribute('autofocus') ?? false;
+ if (delegate != null && !hadAutofocus) {
+ delegate.setAttribute('autofocus', '');
+ }
+ entry.show();
+ if (delegate != null && !hadAutofocus) {
+ delegate.removeAttribute('autofocus');
+ }
+ didShow = true;
+ }
+ setShownOrder(doc, isModal, presentable);
+ if (!didShow) {
+ return;
+ }
+ // A dialog shown again (closed and re-shown to keep its place) went back
+ // into the top layer above everything shown before, a global host's
+ // popover hosted inside it included: that popover still reads as showing
+ // but paints beneath the dialog now. Hosts re-enter the top layer in
+ // place, as they do above a non-modal surface that just entered, so toasts
+ // raised in the re-shown sheet still paint above it. A first show needs
+ // none of this: the outlet it supplies moves the hosts.
+ if (reshown.some(entry => shownOrder.includes(entry))) {
+ notifyTopLayerEntry();
+ }
+ if (keptActive != null && keptActive.isConnected) {
+ if (doc.activeElement !== keptActive) {
+ keptActive.focus({preventScroll: true});
+ }
+ return;
+ }
+ const openEntries = presentable.filter(entry => entry.isOpen);
+ openEntries[openEntries.length - 1]?.focus('open');
+}
+
+/**
+ * The element to keep focused across a re-show: the document's active
+ * element when it is inside an open sheet that is about to be re-shown.
+ */
+function activeElementToKeep(
+ doc: Document,
+ reshown: ReadonlyArray<Entry>,
+): HTMLElement | null {
+ const remembered = state.focusToKeep.get(doc);
+ state.focusToKeep.delete(doc);
+ const current = doc.activeElement;
+ const active =
+ remembered != null && remembered.isConnected
+ ? remembered
+ : current instanceof HTMLElement && current !== doc.body
+ ? current
+ : null;
+ if (active == null) {
+ return null;
+ }
+ for (const entry of reshown) {
+ const element = entry.getElement();
+ if (entry.isOpen && element != null && element.contains(active)) {
+ return active;
+ }
+ }
+ return null;
+}
+
+function update(doc: Document, isModal: boolean): void {
+ detectReplace();
+ // A drop can land as soon as the batch has both of its flips: the pairing
+ // is decided then, and anything left `replace`d is a retained sheet whose
+ // replacer left the flow.
+ if (state.batchOpened.length > 0 && state.batchClosed.length > 0) {
+ flushPendingDrops();
+ }
+ const order = sortedEntries(doc, isModal);
+ computeViews(order, isModal);
+ reconcileTopLayer(doc, isModal, order);
+ state.focusToKeep.delete(doc);
+ focusPendingReplacer();
+ promoteDeferredNonModal(doc);
+}
+
+/**
+ * Join the stack for as long as the sheet is presented. Call from a layout
+ * effect; the returned function leaves the stack (also from its cleanup).
+ * `isOpen` is the controlled open state; a presented sheet whose `isOpen` is
+ * false is sliding out and keeps its place without counting as a layer.
+ */
+export function registerBottomSheet(
+ registration: BottomSheetStackRegistration,
+ isOpen: boolean,
+ isModal: boolean = true,
+): () => void {
+ const {key} = registration;
+ const remembered = state.rankByKey.get(key);
+ let rank: Rank;
+ if (
+ remembered != null &&
+ !remembered.isClosed &&
+ // A StrictMode replay unregisters and registers again in one synchronous
+ // pass, before any seal; the rank is kept so the replay cannot reorder.
+ // A sheet React hid (Suspense, Activity) and later revealed comes back in
+ // a later batch and re-presents on top, like a fresh open.
+ (remembered.detachedBatch == null ||
+ remembered.detachedBatch === state.currentBatch)
+ ) {
+ rank = {batch: remembered.batch, seq: remembered.seq};
+ remembered.detachedBatch = null;
+ } else {
+ rank = takeRank();
+ state.rankByKey.set(key, {
+ ...rank,
+ isClosed: !isOpen,
+ detachedBatch: null,
+ });
+ }
+ const doc = registration.getElement()?.ownerDocument ?? document;
+ listenForPresses(doc);
+ const entry: Entry = {
+ ...registration,
+ rank,
+ isOpen,
+ doc,
+ isModal,
+ view: BOTTOM_SHEET_STACK_DEFAULT_VIEW,
+ replace: null,
+ replacing: null,
+ isEnteringInPlace: false,
+ };
+ state.entries.push(entry);
+ if (isOpen && rank.batch === state.currentBatch && state.isBatchDirty) {
+ recordFlip(entry, 'opened');
+ }
+ update(entry.doc, entry.isModal);
+
+ return () => {
+ const index = state.entries.indexOf(entry);
+ if (index === -1) {
+ return;
+ }
+ state.entries.splice(index, 1);
+ stopListeningForPresses(entry.doc);
+ setShownOrder(
+ entry.doc,
+ entry.isModal,
+ getShownOrder(entry.doc, entry.isModal).filter(shown => shown !== entry),
+ );
+ state.batchOpened = state.batchOpened.filter(other => other !== entry);
+ state.batchClosed = state.batchClosed.filter(other => other !== entry);
+ state.pendingDrops = state.pendingDrops.filter(other => other !== entry);
+ if (state.pendingReplaceFocus === entry) {
+ state.pendingReplaceFocus = null;
+ }
+ if (
+ state.batchPair?.replaced === entry ||
+ state.batchPair?.replacer === entry
+ ) {
+ state.batchPair = null;
+ }
+ // A member of a "Close all" group leaving the registry has left for
+ // good: a host that unmounts mid-exit never sends its motion report, so
+ // leaving is its completion. Reported after `hide()` below, once its
+ // dialog is out of the top layer, so the return focus has nothing modal
+ // in its way; a host that still reports afterwards finds nothing to do.
+ const closingGroup = state.closingTogether.get(entry);
+ if (entry.replace != null) {
+ entry.replace.replacer.replacing = null;
+ entry.replace = null;
+ }
+ if (entry.replacing != null) {
+ // The sheet it was replacing is left as an ordinary closing sheet.
+ entry.replacing.replace = null;
+ entry.replacing = null;
+ }
+ // A sheet that leaves while its dialog is still open was hidden by React
+ // (Suspense, Activity) or is unmounting: a modal dialog with no box would
+ // keep blocking the page, so it leaves the top layer here.
+ entry.hide();
+ if (closingGroup != null) {
+ leaveClosingGroup(entry, closingGroup);
+ }
+ const current = state.rankByKey.get(key);
+ if (current != null) {
+ current.detachedBatch = state.currentBatch;
+ state.isBatchDirty = true;
+ scheduleSeal();
+ }
+ entry.view = BOTTOM_SHEET_STACK_DEFAULT_VIEW;
+ entry.onView(entry.view);
+ update(entry.doc, entry.isModal);
+ };
+}
+
+/**
+ * The dialog that realizes a level changed: a switcher flow handed off to a
+ * step with its own dialog, which its host presented on top of the top layer
+ * in this same commit. The level keeps its rank; the registry records the new
+ * dialog as the most recently shown and puts the sheets that belong above it
+ * back on top before paint. A level on its own, or already on top, is left
+ * alone.
+ */
+export function notifyBottomSheetHostChanged(key: object): void {
+ const entry = state.entries.find(candidate => candidate.key === key);
+ if (entry == null || !entry.isModal) {
+ return;
+ }
+ const element = entry.getElement();
+ if (element == null || !isSheetHostPresented(element)) {
+ return;
+ }
+ const shown = getShownOrder(entry.doc, true).filter(
+ shownEntry => shownEntry !== entry,
+ );
+ shown.push(entry);
+ setShownOrder(entry.doc, true, shown);
+ update(entry.doc, true);
+}
+
+/**
+ * Report the controlled open state of a registered sheet. Closing keeps the
+ * sheet's place while it slides out; reopening takes a new rank, so the sheet
+ * returns on top.
+ */
+export function setBottomSheetOpen(key: object, isOpen: boolean): void {
+ const entry = state.entries.find(candidate => candidate.key === key);
+ if (entry == null || entry.isOpen === isOpen) {
+ return;
+ }
+ entry.isOpen = isOpen;
+ const remembered = state.rankByKey.get(key);
+ if (isOpen) {
+ if (state.closingTogether.has(entry)) {
+ const group = state.closingTogether.get(entry);
+ state.closingTogether.delete(entry);
+ group?.pending.delete(entry);
+ }
+ entry.rank = takeRank();
+ state.rankByKey.set(key, {
+ ...entry.rank,
+ isClosed: false,
+ detachedBatch: null,
+ });
+ recordFlip(entry, 'opened');
+ // Reopened while being replaced: it is a sheet again, not a fading one.
+ if (entry.replace != null) {
+ entry.replace.replacer.replacing = null;
+ entry.replace = null;
+ entry.isEnteringInPlace = true;
+ }
+ } else {
+ if (remembered != null) {
+ remembered.isClosed = true;
+ }
+ state.isBatchDirty = true;
+ scheduleSeal();
+ recordFlip(entry, 'closed');
+ entry.isEnteringInPlace = false;
+ // A replacing sheet that closes drops the sheet it was replacing, the way
+ // a switcher hides a retained step when the flow is left — unless that
+ // sheet is the one coming back in this same update (Continue pressed
+ // during a Back handoff), which `detectReplace` pairs as the reverse
+ // replace. The other flips of this commit may not have arrived yet, so
+ // the drop waits for the seal; a paired sheet is no longer `replace`d by
+ // then and is left alone.
+ if (entry.replacing != null) {
+ state.pendingDrops.push(entry.replacing);
+ }
+ }
+ update(entry.doc, entry.isModal);
+}
+
+/**
+ * Drop the retained sheets whose replacer closed in this batch and that no
+ * replace of this batch took back. Runs when the batch is sealed and, before
+ * that, whenever a pairing has been decided, so the drop lands in the same
+ * commit as the close that caused it.
+ */
+function flushPendingDrops(): void {
+ if (state.pendingDrops.length === 0) {
+ return;
+ }
+ const drops = state.pendingDrops;
+ state.pendingDrops = [];
+ for (const replaced of drops) {
+ const replacer = replaced.replace?.replacer;
+ if (replacer != null && !replacer.isOpen) {
+ finishReplace(replaced);
+ }
+ }
+}
+
+/**
+ * The open sheet directly beneath `key`: its dialog, and a way to move focus
+ * into it. Null when nothing open is beneath. A closing top sheet asks this
+ * to return focus into the sheet it reveals.
+ */
+export function getBottomSheetBeneath(
+ key: object,
+): {element: HTMLDialogElement; focus: () => void} | null {
+ const own = state.entries.find(entry => entry.key === key);
+ if (own == null) {
+ return null;
+ }
+ const order = groupOf(own);
+ for (let below = order.indexOf(own) - 1; below >= 0; below -= 1) {
+ const entry = order[below];
+ const element = entry.getElement();
+ if (entry.isOpen && element != null) {
+ return {element, focus: () => entry.focus('reveal')};
+ }
+ }
+ return null;
+}
+
+// preventScroll on both: presenting a sheet must not scroll the page to reveal
+// what it just focused. For an autofocused field that reveal is the mobile
+// keyboard's, and it moves the document under a fixed sheet; useMobileKeyboard
+// brings the field into view within the sheet instead.
+/**
+ * Move focus into a sheet panel. Focus already inside the sheet stays put:
+ * on `open` the native host has normally run its own focusing steps, which
+ * land on the panel (`tabindex="-1"`), so a `data-autofocus` descendant is
+ * reached only where the host moved nothing (a stubbed host, or a browser
+ * whose focusing steps skipped the sheet) — the released behavior. On
+ * `replace` the entering step takes focus whatever its modality and whatever
+ * the host did, a `data-autofocus` descendant first; on `reveal` the panel
+ * itself takes focus, with a ring only after keyboard input.
+ */
+export function focusSheetPanel(
+ panel: HTMLElement | null,
+ reason: BottomSheetFocusReason,
+ isModal: boolean,
+): void {
+ if (panel == null) {
+ return;
+ }
+ // A covered sheet takes no focus: its dialog is inert (the stack marks it
+ // so, and a modal above it blocks it in the browser anyway), so a step that
+ // enters beneath a sheet on top — a covered switcher flow changing step from
+ // code — leaves the person where they are, in the sheet on top.
+ const host = panel.closest('dialog');
+ if (
+ host != null &&
+ (host.hasAttribute('inert') || host.getAttribute('aria-hidden') === 'true')
+ ) {
+ return;
+ }
+ // Focus already inside this sheet's own content stays put. Focus inside a
+ // sheet rendered within this content (a closing nested sheet) does not
+ // count: that sheet's dialog is leaving, and this one is being revealed.
+ // On a replace entry the native focusing steps have just run and may have
+ // put focus on the panel itself; that is not a placement, so only focus on
+ // a control inside the panel (the person's, or the field this placement
+ // chose) stays put.
+ const activeElement = panel.ownerDocument.activeElement;
+ const isInsidePanel =
+ activeElement != null &&
+ panel.contains(activeElement) &&
+ activeElement.closest('dialog') === panel.closest('dialog');
+ if (isInsidePanel && (reason !== 'replace' || activeElement !== panel)) {
+ return;
+ }
+ if (reason === 'reveal') {
+ focusForLastInput(panel);
+ return;
+ }
+ const autofocus = panel.querySelector<HTMLElement>('[data-autofocus]');
+ if (autofocus != null) {
+ autofocus.focus({preventScroll: true});
+ } else if (!isInsidePanel && (isModal || reason === 'replace')) {
+ // A lone non-modal sheet takes no focus on open; the step replacing the
+ // one the person was in does, so the keyboard stays in the flow. Focus
+ // the native steps already put on the panel needs no second focus().
+ panel.focus({preventScroll: true});
+ }
+}
+
+/** Test-only: the presented sheets' dialogs, bottom to top, with their views. */
+export function getBottomSheetStackForTests(
+ doc: Document = document,
+ isModal: boolean = true,
+): ReadonlyArray<{
+ element: HTMLDialogElement | null;
+ isOpen: boolean;
+ view: BottomSheetStackView;
+}> {
+ return sortedEntries(doc, isModal).map(entry => ({
+ element: entry.getElement(),
+ isOpen: entry.isOpen,
+ view: entry.view,
+ }));
+}
+
+/** Test-only: forget every sheet and start the batch counter over. */
+export function resetBottomSheetStackForTests(): void {
+ showFocusesContainer = null;
+ // The press listeners go with the entries they served.
+ for (const entry of state.entries) {
+ const remove = state.listenedDocuments.get(entry.doc);
+ if (remove != null) {
+ state.listenedDocuments.delete(entry.doc);
+ remove();
+ }
+ }
+ state.entries.length = 0;
+ state.shownOrder = new WeakMap();
+ state.batchOpened = [];
+ state.batchClosed = [];
+ state.batchActor = null;
+ state.pendingDrops = [];
+ state.pendingReplaceFocus = null;
+ state.closingTogether = new Map();
+ state.currentBatch = 0;
+ state.nextSeq = 0;
+ state.isBatchDirty = false;
+ state.isSealScheduled = false;
+ state.focusToKeep = new WeakMap();
+ // Deferral watchers on the test document go with the deferrals they
+ // served (a WeakMap cannot be walked; the test document is the one place
+ // a test can have deferred into).
+ const deferral = state.deferredTopLayer.get(document);
+ if (deferral != null) {
+ releaseDeferralWatchers(deferral);
+ }
+ state.deferredTopLayer = new WeakMap();
+}
+
+/** Test-only: the shared state's key, shape and protocol version, for the two-copies tests. */
+export const BOTTOM_SHEET_STACK_STATE_FOR_TESTS = {
+ key: STACK_STATE_KEY,
+ shape: STACK_STATE_SHAPE,
+ protocolVersion: STACK_PROTOCOL_VERSION,
+ keyFor: (version: number) =>
+ Symbol.for(`astryx.bottomSheetStack.v${version}`),
+ /** Whether the document has the press listeners installed. */
+ isListeningForPresses: (doc: Document) => state.listenedDocuments.has(doc),
+};
diff --git a/packages/core/src/BottomSheet/useSheetGestures.ts b/packages/core/src/BottomSheet/useSheetGestures.ts
index 57ad69c869..b012cf9e84 100644
--- a/packages/core/src/BottomSheet/useSheetGestures.ts
+++ b/packages/core/src/BottomSheet/useSheetGestures.ts
@@ -4,8 +4,7 @@
/**
* @file useSheetGestures.ts
- * @input Uses React (useCallback, useEffect, useMemo, useRef, useState) and
- * the core useMediaQuery hook
+ * @input Uses React (useCallback, useEffect, useMemo, useRef, useState)
* @output Exports useSheetGestures hook and its option/result types
* @position Internal to BottomSheet; not exported from the core entry point
*
@@ -85,7 +84,7 @@ import {
type TouchEvent as ReactTouchEvent,
type UIEvent as ReactUIEvent,
} from 'react';
-import {useMediaQuery} from '../hooks';
+
import {
computeDetentOffsets,
peekOffsetFor,
@@ -299,6 +298,13 @@ function visibleHeightForOffset(
export interface UseSheetGesturesOptions {
/** Whether the owning sheet is open. Drag state resets when it closes. */
isOpen: boolean;
+ /**
+ * The host's controlled answer to the last close request: false once the
+ * host has taken a dismissal (its own state says closed, even while the
+ * sheet still animates out), true while it is open or has refused one.
+ * Settles whether a release's dismissal was honored. Defaults to `isOpen`.
+ */
+ isOpenRequested?: boolean;
/**
* Whether a downward swipe may dismiss the sheet. When false, a gesture
* past the dismiss threshold settles at the shortest detent instead.
@@ -401,6 +407,16 @@ export interface UseSheetGesturesResult {
isDragging: boolean;
/** Whether the drag in progress has moved the sheet off its base detent. */
isTraveling: boolean;
+ /**
+ * Whether the sheet's current dismissal was started by the release of a
+ * touch drag (a finger's swipe or fling past the dismiss line). True from
+ * the release until the sheet is open again; false for a dismissal from a
+ * control, Escape, the scrim or code, and for a mouse or pen drag. Under
+ * reduced motion a transition a touch drag's release starts cross-fades on
+ * every pointer (`design:reduced-motion` DR2), so the exit's motion needs
+ * to know.
+ */
+ isDismissedByTouchDrag: boolean;
/**
* The sheet's offset right now, in px: the settled detent at rest, the live
* position during a drag. Written per input sample without a render; read
@@ -458,6 +474,7 @@ function prefersReducedMotion(): boolean {
*/
export function useSheetGestures({
isOpen,
+ isOpenRequested = isOpen,
canDismiss = true,
offscreenBlockEndInset = 0,
onDismiss,
@@ -468,6 +485,35 @@ export function useSheetGestures({
const [dragOffset, setDragOffset] = useState(0);
const [settledOffset, setSettledOffset] = useState(0);
const [isDragging, setIsDragging] = useState(false);
+ // Scoped to the one close the release requested. The release calls
+ // onDismiss() and sets `pending`; the host answers in the same update, so
+ // the first render afterwards says whether it took the close (its
+ // controlled state now says closed: the exit under way is the drag's) or
+ // refused it (a guarded onOpenChange left it open: the sheet snaps back and
+ // the request is spent). Either way the flag is settled during render, the
+ // prev-prop pattern, and derived back to false once the sheet is open
+ // again — so a later close from a control, Escape or code is never
+ // mistaken for a drag.
+ const [touchDragDismissal, setTouchDragDismissal] = useState<{
+ isTouch: boolean;
+ pending: boolean;
+ } | null>(null);
+ if (touchDragDismissal != null) {
+ if (touchDragDismissal.pending) {
+ setTouchDragDismissal(
+ isOpenRequested
+ ? null
+ : {isTouch: touchDragDismissal.isTouch, pending: false},
+ );
+ } else if (isOpenRequested) {
+ setTouchDragDismissal(null);
+ }
+ }
+ const isDismissedByTouchDrag =
+ touchDragDismissal != null &&
+ !touchDragDismissal.pending &&
+ touchDragDismissal.isTouch &&
+ !isOpenRequested;
// Whether the drag in flight has moved the sheet off its base detent. One
// state change per drag, for hosts that react to travel beginning.
const [isTraveling, setIsTraveling] = useState(false);
@@ -597,6 +643,8 @@ export function useSheetGestures({
// capture and takes its events from `touchmove`, so every real-pointer
// handler has to leave it alone.
syntheticTouch: boolean;
+ /** The pointer's kind: a finger, a pen, or a mouse. */
+ pointerType: string;
pointerId: number;
startCoord: number;
lastCoord: number;
@@ -960,6 +1008,7 @@ export function useSheetGestures({
renderedOffset: number,
layoutOffset: number,
naturalEndGap: number,
+ isTouch: boolean,
) => {
const {offsets, peekOffset} = resolveDetents(height);
const maxOffset = offsets[offsets.length - 1];
@@ -1018,6 +1067,7 @@ export function useSheetGestures({
naturalEndGap,
false,
);
+ setTouchDragDismissal({isTouch, pending: true});
onDismissRef.current();
} else {
settleAt(maxOffset);
@@ -1060,6 +1110,7 @@ export function useSheetGestures({
const baseLayoutOffset = settledLayoutOffsetRef.current;
dragStateRef.current = {
syntheticTouch,
+ pointerType: syntheticTouch ? 'touch' : event.pointerType,
pointerId: event.pointerId,
startCoord: start,
lastCoord: event.clientY,
@@ -1258,6 +1309,7 @@ export function useSheetGestures({
state.renderedOffset,
state.layoutOffset,
state.naturalEndGap,
+ state.pointerType === 'touch',
);
},
[settleFromDrag],
@@ -1582,11 +1634,6 @@ export function useSheetGestures({
}
}, []);
- // Subscribed, not memoized: the preference can change while a sheet is open,
- // and this branch decides whether the settle runs as a transition at all.
- // The imperative gesture paths read prefersReducedMotion() directly.
- const reducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)');
-
const reconcileScrollPreservationInset = useCallback(
(body: HTMLElement) => {
if (scrollPreservationInsetRef.current <= 0) {
@@ -1678,9 +1725,13 @@ export function useSheetGestures({
// Gated on the sheet being up: suppression must not outlive the sheet
// it was suppressing for. The host swaps the panel to its closing
// state in whatever frame the dismissal lands, and a stale `none`
- // would apply to that transform too, cutting the exit.
+ // would apply to that transform too, cutting the exit. Reduced motion
+ // is the panel's own stylesheet's to honor (its transform transition
+ // collapses under the preference), not an inline `none` here: the
+ // shorthand would also silence the panel's opacity transition, the
+ // cross-fade `design:reduced-motion` DR2 asks for on a coarse pointer.
transition:
- isOpen && (isDragging || isScrollAreaReconciling || reducedMotion)
+ isOpen && (isDragging || isScrollAreaReconciling)
? 'none'
: undefined,
// One-finger drags are the sheet's; a pinch stays the browser's.
@@ -1688,7 +1739,7 @@ export function useSheetGestures({
overscrollBehavior: 'contain',
},
}),
- [activeOffset, isDragging, isOpen, isScrollAreaReconciling, reducedMotion],
+ [activeOffset, isDragging, isOpen, isScrollAreaReconciling],
);
const handleProps = useMemo<SheetHandleProps>(
@@ -1746,6 +1797,7 @@ export function useSheetGestures({
settledOffset,
isDragging,
isTraveling,
+ isDismissedByTouchDrag,
activeOffsetRef,
sheetHeight,
scrollPreservationInset,
diff --git a/packages/core/src/Layer/layerDismissalInvariants.test.tsx b/packages/core/src/Layer/layerDismissalInvariants.test.tsx
index 2f2d1d4461..f41385ca96 100644
--- a/packages/core/src/Layer/layerDismissalInvariants.test.tsx
+++ b/packages/core/src/Layer/layerDismissalInvariants.test.tsx
@@ -440,11 +440,20 @@ describe('a standalone BottomSheet is one more layer', () => {
}
beforeEach(() => {
+ // A non-modal sheet is a manual popover in the top layer (show() below
+ // the Popover API floor); jsdom's stand-ins keep the `open` marker the
+ // census reads.
HTMLDialogElement.prototype.show = vi.fn(function (
this: HTMLDialogElement,
) {
this.setAttribute('open', '');
});
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ this.setAttribute('open', '');
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ this.removeAttribute('open');
+ });
});
it('peels a Dialog opened inside the sheet before the sheet', () => {
diff --git a/packages/core/src/Layer/modalOutlet.ts b/packages/core/src/Layer/modalOutlet.ts
index 41e46ebe74..dee9fd3090 100644
--- a/packages/core/src/Layer/modalOutlet.ts
+++ b/packages/core/src/Layer/modalOutlet.ts
@@ -6,8 +6,9 @@
* @file modalOutlet.ts
* @input The open Dialog and scrim BottomSheet `<dialog>` elements
* @output Exports useModalOutlet (a modal supplies its outlet),
- * getActiveModalOutlet, and subscribeModalOutlets (a global host follows
- * the latest one)
+ * getActiveModalOutlet, subscribeModalOutlets (a global host follows the
+ * latest one), and notifyTopLayerEntry (a non-modal surface entered the
+ * top layer above the hosts)
* @position Private layer infrastructure; spec:AST-003 FR18
*
* A native modal makes everything outside it inert and paints over every
@@ -18,29 +19,66 @@
* fallback) must see modals rendered by the app. Listeners run synchronously,
* so a host can leave a modal before React removes it from the document.
*
+ * A non-modal top-layer surface (a `popover="manual"` host shown by
+ * `showPopover()`, such as a `hasScrim={false}` BottomSheet) blocks nothing,
+ * so it is not an outlet, but it still enters the top layer above the hosts
+ * shown before it. It announces the entry here, and a host re-enters the top
+ * layer in place so it paints above the surface again.
+ *
* SYNC: When modified, update:
* - /packages/core/src/Toast/ToastViewport.modalHost.test.tsx
* - /docs/architecture/layer-runtime.md
*/
-import {useEffect, useLayoutEffect, type RefObject} from 'react';
+import {useEffect, useLayoutEffect, useRef, type RefObject} from 'react';
const outlets: HTMLDialogElement[] = [];
-const listeners = new Set<() => void>();
+// Outlets whose order among themselves is decided by their caller (a stack of
+// bottom sheets), keyed by that caller's group. Reordering stays inside the
+// group: such an outlet never moves above an outlet of another group supplied
+// later (a Dialog opened from a sheet).
+const outletGroups = new WeakMap<HTMLDialogElement, string>();
+
+/**
+ * Why a host is told to place itself: `outlet` when the latest open modal
+ * may have changed (the host moves into it or back out), `entry` when a
+ * non-modal surface entered the top layer above the host (the host stays
+ * where it is and re-enters the top layer).
+ */
+export type ModalOutletChange = 'outlet' | 'entry';
+
+const listeners = new Set<(change: ModalOutletChange) => void>();
-function notify(): void {
+function notify(change: ModalOutletChange): void {
for (const listener of listeners) {
- listener();
+ listener(change);
}
}
-function addOutlet(element: HTMLDialogElement): void {
+/**
+ * Supply an outlet. The latest goes on top. One re-supplied beneath its
+ * group's top — a covered switcher flow whose level became a new dialog on a
+ * step change made from code, while a sheet stays on top of it — goes
+ * directly beneath that top, so the sheet on top stays the latest outlet and
+ * a toast raised from it still lands there, not in the covered, inert step.
+ */
+function addOutlet(element: HTMLDialogElement, beneathGroupTop: boolean): void {
const index = outlets.indexOf(element);
if (index !== -1) {
outlets.splice(index, 1);
}
+ const group = outletGroups.get(element);
+ if (beneathGroupTop && group != null) {
+ for (let other = outlets.length - 1; other >= 0; other -= 1) {
+ if (outletGroups.get(outlets[other]) === group) {
+ outlets.splice(other, 0, element);
+ notify('outlet');
+ return;
+ }
+ }
+ }
outlets.push(element);
- notify();
+ notify('outlet');
}
function removeOutlet(element: HTMLDialogElement): void {
@@ -49,7 +87,39 @@ function removeOutlet(element: HTMLDialogElement): void {
return;
}
outlets.splice(index, 1);
- notify();
+ outletGroups.delete(element);
+ notify('outlet');
+}
+
+/**
+ * Move `element` to the top of its own group: directly above the highest
+ * outlet of the same group, and never above an outlet of another group that
+ * was supplied later. A sheet revealed beneath an open Dialog stays beneath
+ * the Dialog; a sheet re-shown by its stack stays beneath everything that is
+ * not a sheet.
+ */
+function raiseWithinGroup(element: HTMLDialogElement): void {
+ const group = outletGroups.get(element);
+ const index = outlets.indexOf(element);
+ if (group == null || index === -1) {
+ return;
+ }
+ let target = outlets.length;
+ for (let other = outlets.length - 1; other > index; other -= 1) {
+ if (outletGroups.get(outlets[other]) !== group) {
+ target = other;
+ } else {
+ break;
+ }
+ }
+ // Nothing of another group sits above the group's top: go to the end.
+ // Otherwise land just beneath the lowest foreign outlet above us.
+ if (target - 1 === index) {
+ return;
+ }
+ outlets.splice(index, 1);
+ outlets.splice(target - 1, 0, element);
+ notify('outlet');
}
/** The latest open native modal, or null when none is open. */
@@ -57,40 +127,111 @@ export function getActiveModalOutlet(): HTMLDialogElement | null {
return outlets[outlets.length - 1] ?? null;
}
-/** Call `listener` whenever the latest open native modal may have changed. */
-export function subscribeModalOutlets(listener: () => void): () => void {
+/**
+ * Call `listener` whenever the latest open native modal may have changed
+ * (`'outlet'`), or a non-modal surface entered the top layer (`'entry'`).
+ */
+export function subscribeModalOutlets(
+ listener: (change: ModalOutletChange) => void,
+): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
+/**
+ * A surface was just shown into the top layer above the global hosts: a
+ * non-modal surface shown (`showPopover()` on a `popover="manual"` host), or
+ * a modal dialog closed and shown again by a stack keeping its order, which
+ * carries the host inside it back above the host's own popover. Global hosts
+ * re-enter the top layer so they paint above it, as they do above a modal
+ * that just opened.
+ */
+export function notifyTopLayerEntry(): void {
+ notify('entry');
+}
+
/**
* Supply `ref`'s `<dialog>` as the passive global outlet while it is an open
* modal. Call it after the effect that runs `showModal()`, so the modal is
* already in the top layer when global hosts move into it.
+ *
+ * `isLatest`, `group`, and `hostKey` are for a caller whose modals are ordered among
+ * themselves by something other than the order they were supplied in (a
+ * stack of bottom sheets that is re-shown to keep open order, or reveals a
+ * sheet by closing the one above it). By default the most recently supplied
+ * outlet is the latest, which is the native top layer's order for modals
+ * opened one after another. Such a caller names its `group` and passes the
+ * ordering's own answer as `isLatest`: when it turns true the outlet is
+ * raised to the top of its group — above the group's other outlets, never
+ * above an outlet of another group supplied later, such as a Dialog opened
+ * from the sheet — and when it turns false the outlet stays supplied (every
+ * open modal supplies one) but is no longer the group's latest.
*/
export function useModalOutlet(
ref: RefObject<HTMLDialogElement | null>,
isActive: boolean,
+ isLatest: boolean = true,
+ group?: string,
+ hostKey?: string | null,
): void {
+ // `hostKey` names which element `ref` currently resolves to, for a caller
+ // whose ref moves between dialogs while it stays active (a switcher flow
+ // whose host dialog changes on a handoff): a change re-supplies the outlet
+ // from the new element and withdraws the old one. A re-supply made while
+ // the caller is not its group's latest (read through a ref, so a flip of
+ // `isLatest` alone never re-supplies) goes beneath the group's top: the
+ // sheet covering the flow keeps the outlet. A first supply always goes on
+ // top; the stack's answer arrives a render later and the raise below
+ // settles it.
+ const isLatestRef = useRef(isLatest);
+ isLatestRef.current = isLatest;
+ const suppliedRef = useRef<HTMLDialogElement | null>(null);
useEffect(() => {
const element = ref.current;
if (!isActive || element == null) {
+ suppliedRef.current = null;
return;
}
+ const isResupply = suppliedRef.current != null;
+ suppliedRef.current = element;
+ if (group != null) {
+ outletGroups.set(element, group);
+ }
// A native close (a `method="dialog"` form) ends the modal without a
- // render.
+ // render. A `close` that arrives while the dialog is open again is stale:
+ // the dialog was closed and re-shown in one task (a stack putting its
+ // dialogs back in order, a sheet reopened during its exit), and the
+ // event queued by that close must not take the outlet away from a modal
+ // that is open.
const handleClose = () => {
+ if (element.open) {
+ return;
+ }
removeOutlet(element);
};
element.addEventListener('close', handleClose);
- addOutlet(element);
+ addOutlet(element, isResupply && !isLatestRef.current);
return () => {
element.removeEventListener('close', handleClose);
removeOutlet(element);
};
- }, [ref, isActive]);
+ }, [ref, isActive, group, hostKey]);
+
+ // Becoming the latest of its group again (a sheet revealed by the close of
+ // the one above it, or put back on top by its stack) raises the outlet
+ // within that group only: an outlet of another group supplied later (a
+ // Dialog opened from the sheet) stays above it, so a toast raised from
+ // that Dialog keeps landing in the Dialog. The first supply above already
+ // placed the outlet at the end.
+ useEffect(() => {
+ const element = ref.current;
+ if (!isActive || !isLatest || element == null) {
+ return;
+ }
+ raiseWithinGroup(element);
+ }, [ref, isActive, isLatest, hostKey]);
// Unmounting removes the dialog without a close event, and a passive
// cleanup runs after React has detached it. A layout cleanup runs before,
diff --git a/packages/core/src/Toast/ToastViewport.modalHost.test.tsx b/packages/core/src/Toast/ToastViewport.modalHost.test.tsx
index e4588c541d..6dd193b4c7 100644
--- a/packages/core/src/Toast/ToastViewport.modalHost.test.tsx
+++ b/packages/core/src/Toast/ToastViewport.modalHost.test.tsx
@@ -5,8 +5,9 @@
* @input Uses vitest, @testing-library/react, ToastViewport, useToast, Dialog,
* BottomSheet
* @output Tests that a top-layer ToastViewport moves into the latest open
- * native modal (a Dialog or a scrim BottomSheet) and back without remounting
- * its toasts
+ * native modal (a Dialog or a scrim BottomSheet, the top sheet of a stack)
+ * and back without remounting its toasts, and re-enters the top layer above
+ * a non-modal sheet shown after it
* @position Testing; validates ToastViewport.tsx with Layer/modalOutlet.ts
*
* SYNC: When ToastViewport hosting or Layer/modalOutlet.ts changes, update
@@ -20,8 +21,9 @@ import {describe, it, expect, vi, afterEach, beforeEach} from 'vitest';
import {act, fireEvent, render, screen} from '@testing-library/react';
import {ToastViewport} from './ToastViewport';
import {useToast} from './useToast';
-import {BottomSheet} from '../BottomSheet';
+import {BottomSheet, BottomSheetSwitcher} from '../BottomSheet';
import {Dialog} from '../Dialog';
+import {getActiveModalOutlet} from '../Layer/modalOutlet';
import type {ToastDismissReason} from './types';
// jsdom does not implement the native dialog methods.
@@ -75,6 +77,24 @@ function DialogFixture({
);
}
+function NonModalSheetFixture({label}: {label: string}) {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsOpen(open => !open)}>
+ {`Toggle ${label}`}
+ </button>
+ <BottomSheet
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ hasScrim={false}
+ label={label}>
+ <ToastButton label={`Show toast in ${label}`} />
+ </BottomSheet>
+ </>
+ );
+}
+
function getDialog(label: string): HTMLDialogElement {
return document.querySelector<HTMLDialogElement>(
`dialog[aria-label="${label}"]`,
@@ -82,7 +102,9 @@ function getDialog(label: string): HTMLDialogElement {
}
function getViewport(): HTMLElement {
- return document.querySelector<HTMLElement>('[popover="manual"]')!;
+ // A non-modal BottomSheet is a manual popover too; the viewport is the one
+ // that is not a dialog.
+ return document.querySelector<HTMLElement>('[popover="manual"]:not(dialog)')!;
}
/** Call order of `fn`'s latest call on `context`, or -1 if it has none. */
@@ -149,6 +171,35 @@ function SheetFixture({label, hasScrim}: {label: string; hasScrim?: boolean}) {
);
}
+/**
+ * jsdom's popover stand-ins are stateless: track which elements are shown so
+ * `:popover-open` answers as a browser would.
+ */
+function trackPopoverState() {
+ const showing = new WeakSet<Element>();
+ const showPopover = vi
+ .spyOn(HTMLElement.prototype, 'showPopover')
+ .mockImplementation(function (this: HTMLElement) {
+ showing.add(this);
+ });
+ const hidePopover = vi
+ .spyOn(HTMLElement.prototype, 'hidePopover')
+ .mockImplementation(function (this: HTMLElement) {
+ showing.delete(this);
+ });
+ const matches = Element.prototype.matches;
+ vi.spyOn(Element.prototype, 'matches').mockImplementation(function (
+ this: Element,
+ selector: string,
+ ) {
+ if (selector === ':popover-open') {
+ return showing.has(this);
+ }
+ return matches.call(this, selector);
+ });
+ return {showPopover, hidePopover};
+}
+
describe('ToastViewport modal hosting', () => {
it('moves into an open Dialog and back when it closes, keeping the toast', () => {
const {container} = render(
@@ -193,6 +244,71 @@ describe('ToastViewport modal hosting', () => {
expect(showsOnViewport()).toBe(3);
});
+ /**
+ * jsdom's Popover stand-ins keep no state and `:popover-open` never
+ * matches; these keep a showing set so the viewport can tell it is already
+ * in the top layer, as a browser does.
+ */
+ it('re-enters the top layer in place when a non-modal sheet is shown after it', () => {
+ // A `hasScrim={false}` sheet is a manual popover: it enters the top
+ // layer above the viewport and blocks nothing, so the viewport stays
+ // where it is and leaves and re-enters to paint above the sheet again.
+ const {showPopover, hidePopover} = trackPopoverState();
+ render(
+ <ToastViewport>
+ <ToastButton />
+ <NonModalSheetFixture label="Filters" />
+ </ToastViewport>,
+ );
+ const viewport = getViewport();
+ const onViewport = (spy: typeof showPopover) =>
+ spy.mock.contexts.filter(context => context === viewport).length;
+ fireEvent.click(screen.getByRole('button', {name: 'Show toast'}));
+ expect(onViewport(showPopover)).toBe(1);
+ const root = viewport.parentNode;
+
+ fireEvent.click(screen.getByRole('button', {name: 'Toggle Filters'}));
+ expect(getDialog('Filters')).toHaveAttribute('popover', 'manual');
+ // Re-entered (hide, then show) after the sheet's own showPopover, and
+ // not moved: the sheet is not an outlet.
+ expect(onViewport(hidePopover)).toBe(1);
+ expect(onViewport(showPopover)).toBe(2);
+ const sheetShow = showPopover.mock.contexts.indexOf(getDialog('Filters'));
+ const viewportReshow = showPopover.mock.contexts.lastIndexOf(viewport);
+ expect(sheetShow).toBeGreaterThan(-1);
+ expect(viewportReshow).toBeGreaterThan(sheetShow);
+ expect(viewport.parentNode).toBe(root);
+ expect(screen.getByText('Saved')).toBeInTheDocument();
+
+ // A toast raised while the sheet is open lands in the same viewport.
+ fireEvent.click(
+ screen.getByRole('button', {name: 'Show toast in Filters'}),
+ );
+ expect(screen.getAllByText('Saved')).toHaveLength(2);
+
+ // Closing the sheet moves nothing and re-enters nothing.
+ fireEvent.click(screen.getByRole('button', {name: 'Toggle Filters'}));
+ expect(onViewport(hidePopover)).toBe(1);
+ expect(onViewport(showPopover)).toBe(2);
+ });
+
+ it('keeps focus inside the viewport across a re-entry', () => {
+ trackPopoverState();
+ render(
+ <ToastViewport>
+ <ToastButton />
+ <NonModalSheetFixture label="Filters" />
+ </ToastViewport>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Show toast'}));
+ const viewport = getViewport();
+ const dismiss = viewport.querySelector('button');
+ expect(dismiss).not.toBeNull();
+ dismiss!.focus();
+ fireEvent.click(screen.getByRole('button', {name: 'Toggle Filters'}));
+ expect(document.activeElement).toBe(dismiss);
+ });
+
it("keeps each toast's auto-hide timer running across a move", () => {
vi.useFakeTimers();
try {
@@ -387,14 +503,388 @@ describe('ToastViewport above a BottomSheet', () => {
});
it('stays in place when a sheet without a scrim opens', () => {
+ trackPopoverState();
const {container} = render(
<ToastViewport>
<SheetFixture label="Filters" hasScrim={false} />
</ToastViewport>,
);
fireEvent.click(screen.getByRole('button', {name: 'Open Filters'}));
- // A non-modal sheet leaves the page operable, so the viewport stays put.
- expect(getDialog('Filters')).toHaveAttribute('open');
+ // A non-modal sheet (a manual popover) leaves the page operable, so the
+ // viewport stays put; it only re-enters the top layer in place.
+ expect(getDialog('Filters').matches(':popover-open')).toBe(true);
+ expect(getViewport().closest('dialog')).toBeNull();
+ expect(container.contains(getViewport())).toBe(true);
+ });
+
+ it('is hosted by the top sheet of a stack, and by the sheet beneath once that one closes', () => {
+ function Stack() {
+ const [isAOpen, setIsAOpen] = useState(false);
+ const [isBOpen, setIsBOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsAOpen(true)}>
+ Open A
+ </button>
+ <BottomSheet isOpen={isAOpen} onOpenChange={setIsAOpen} label="A">
+ <button type="button" onClick={() => setIsBOpen(true)}>
+ Open B
+ </button>
+ </BottomSheet>
+ <BottomSheet isOpen={isBOpen} onOpenChange={setIsBOpen} label="B">
+ <button type="button" onClick={() => setIsBOpen(false)}>
+ Close B
+ </button>
+ </BottomSheet>
+ </>
+ );
+ }
+ render(
+ <ToastViewport>
+ <Stack />
+ </ToastViewport>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Open A'}));
+ expect(getViewport().closest('dialog')).toBe(getDialog('A'));
+ expect(getActiveModalOutlet()).toBe(getDialog('A'));
+ fireEvent.click(screen.getByRole('button', {name: 'Open B'}));
+ // A is covered (inert) but still an active native modal, so it still
+ // supplies an outlet; the latest outlet follows the stack, so the
+ // viewport moves into B, the top sheet.
+ expect(getDialog('A')).toHaveAttribute('inert');
+ expect(getActiveModalOutlet()).toBe(getDialog('B'));
+ expect(getViewport().closest('dialog')).toBe(getDialog('B'));
+ expect(getViewport().closest('[inert]')).toBeNull();
+ fireEvent.click(screen.getByRole('button', {name: 'Close B'}));
+ // B starts closing and stops supplying; A, revealed, is the latest
+ // outlet again and takes the viewport back at once.
+ expect(getActiveModalOutlet()).toBe(getDialog('A'));
+ expect(getViewport().closest('dialog')).toBe(getDialog('A'));
+ expect(getViewport().closest('[inert]')).toBeNull();
+ });
+
+ it('a sheet revealed beneath an open Dialog does not take the outlet from the Dialog', () => {
+ // Sheet A → Dialog from A → sheet B from the Dialog → close B. A is
+ // revealed as the top sheet, but the Dialog above it is still open and
+ // was supplied later: it keeps the outlet, so a toast raised from the
+ // Dialog stays in the Dialog and pressable.
+ function Nested() {
+ const [isAOpen, setIsAOpen] = useState(false);
+ const [isBOpen, setIsBOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsAOpen(true)}>
+ Open A
+ </button>
+ <BottomSheet isOpen={isAOpen} onOpenChange={setIsAOpen} label="A">
+ <DialogFixture label="Edit">
+ <button type="button" onClick={() => setIsBOpen(true)}>
+ Open B
+ </button>
+ <ToastButton label="Toast from Edit" />
+ </DialogFixture>
+ </BottomSheet>
+ <BottomSheet isOpen={isBOpen} onOpenChange={setIsBOpen} label="B">
+ <button type="button" onClick={() => setIsBOpen(false)}>
+ Close B
+ </button>
+ </BottomSheet>
+ </>
+ );
+ }
+ render(
+ <ToastViewport>
+ <Nested />
+ </ToastViewport>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Open A'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Toggle Edit'}));
+ expect(getActiveModalOutlet()).toBe(getDialog('Edit'));
+ fireEvent.click(screen.getByRole('button', {name: 'Open B'}));
+ expect(getActiveModalOutlet()).toBe(getDialog('B'));
+ fireEvent.click(screen.getByRole('button', {name: 'Close B'}));
+ // A is the top sheet again, but the Dialog was supplied after A and is
+ // still open: it is the latest outlet, not A.
+ expect(getActiveModalOutlet()).toBe(getDialog('Edit'));
+ fireEvent.click(screen.getByRole('button', {name: 'Toast from Edit'}));
+ const toast = screen.getByText('Saved');
+ expect(toast.closest('dialog')).toBe(getDialog('Edit'));
+ expect(toast.closest('[inert]')).toBeNull();
+ // Closing the Dialog hands the outlet back to A.
+ fireEvent.click(screen.getByRole('button', {name: 'Close Edit'}));
+ expect(getActiveModalOutlet()).toBe(getDialog('A'));
+ });
+
+ it('keeps a reopened sheet as the outlet when the stale native close event of its re-show arrives', () => {
+ // A stack re-shows a dialog (close(), then showModal()) to keep open
+ // order; a sheet reopened during its exit is re-shown too. The native
+ // `close` event that close() queued fires while the dialog is open again
+ // and must not take the outlet away.
+ function Pair() {
+ const [isAOpen, setIsAOpen] = useState(false);
+ const [isBOpen, setIsBOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsAOpen(true)}>
+ Open A
+ </button>
+ <BottomSheet isOpen={isAOpen} onOpenChange={setIsAOpen} label="A">
+ <button type="button" onClick={() => setIsBOpen(true)}>
+ Open B
+ </button>
+ </BottomSheet>
+ <BottomSheet isOpen={isBOpen} onOpenChange={setIsBOpen} label="B">
+ <button type="button" onClick={() => setIsBOpen(false)}>
+ Close B
+ </button>
+ <ToastButton label="Toast from B" />
+ </BottomSheet>
+ </>
+ );
+ }
+ render(
+ <ToastViewport>
+ <Pair />
+ </ToastViewport>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Open A'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Open B'}));
+ // Close B and reopen it during its exit: the registry re-shows B's
+ // dialog, and the close() of that re-show queues a `close` event.
+ fireEvent.click(screen.getByRole('button', {name: 'Close B'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Open B'}));
+ expect(getDialog('B')).toHaveAttribute('open');
+ expect(getActiveModalOutlet()).toBe(getDialog('B'));
+ act(() => {
+ getDialog('B').dispatchEvent(new Event('close'));
+ });
+ // The stale close changes nothing: B is open and still the latest outlet.
+ expect(getActiveModalOutlet()).toBe(getDialog('B'));
+ fireEvent.click(screen.getByRole('button', {name: 'Toast from B'}));
+ const toast = screen.getByText('Saved');
+ expect(toast.closest('dialog')).toBe(getDialog('B'));
+ expect(toast.closest('[inert]')).toBeNull();
+ });
+});
+
+describe('ToastViewport above a BottomSheetSwitcher flow', () => {
+ function finishHandoff(entering: HTMLElement, retained: HTMLElement) {
+ for (const panel of Array.from(
+ entering.querySelectorAll<HTMLElement>('.astryx-bottom-sheet'),
+ )) {
+ fireEvent.transitionEnd(panel, {propertyName: 'transform'});
+ }
+ for (const panel of Array.from(
+ retained.querySelectorAll<HTMLElement>('.astryx-bottom-sheet'),
+ )) {
+ fireEvent.transitionEnd(panel, {propertyName: 'opacity'});
+ }
+ }
+
+ function Flow({hasScrim = true}: {hasScrim?: boolean}) {
+ const [step, setStep] = useState<string | null>(null);
+ return (
+ <>
+ <button type="button" onClick={() => setStep('one')}>
+ Open flow
+ </button>
+ <BottomSheetSwitcher
+ activeSheet={step}
+ onActiveSheetChange={setStep}
+ hasScrim={hasScrim}>
+ <BottomSheet sheetId="one" label="One">
+ <button type="button" onClick={() => setStep('two')}>
+ Next
+ </button>
+ <ToastButton label="Toast from one" />
+ </BottomSheet>
+ <BottomSheet sheetId="two" label="Two">
+ <button type="button" onClick={() => setStep(null)}>
+ Done
+ </button>
+ <ToastButton label="Toast from two" />
+ </BottomSheet>
+ </BottomSheetSwitcher>
+ </>
+ );
+ }
+
+ it('is hosted by the active step of a modal flow, follows a handoff, and returns when the flow closes', () => {
+ const {container} = render(
+ <ToastViewport>
+ <Flow />
+ </ToastViewport>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Open flow'}));
+ expect(getActiveModalOutlet()).toBe(getDialog('One'));
+ expect(getViewport().closest('dialog')).toBe(getDialog('One'));
+ fireEvent.click(screen.getByRole('button', {name: 'Toast from one'}));
+ const toast = screen.getByText('Saved');
+ expect(toast.closest('dialog')).toBe(getDialog('One'));
+ // The handoff moves the host to the entering step; the retained step,
+ // inert and fading, never hosts.
+ fireEvent.click(screen.getByRole('button', {name: 'Next'}));
+ expect(getActiveModalOutlet()).toBe(getDialog('Two'));
+ expect(getViewport().closest('dialog')).toBe(getDialog('Two'));
+ expect(getViewport().closest('[inert]')).toBeNull();
+ expect(screen.getByText('Saved')).toBe(toast);
+ finishHandoff(getDialog('Two'), getDialog('One'));
+ expect(getActiveModalOutlet()).toBe(getDialog('Two'));
+ fireEvent.click(screen.getByRole('button', {name: 'Done'}));
+ // A closing flow stops supplying at once.
+ expect(getActiveModalOutlet()).toBeNull();
+ expect(getViewport().closest('dialog')).toBeNull();
+ expect(container.contains(getViewport())).toBe(true);
+ });
+
+ it('a modal flow stacked over a standalone sheet is the latest outlet; the sheet takes it back when the flow closes', () => {
+ function Mixed() {
+ const [isAOpen, setIsAOpen] = useState(false);
+ const [step, setStep] = useState<string | null>(null);
+ return (
+ <>
+ <button type="button" onClick={() => setIsAOpen(true)}>
+ Open A
+ </button>
+ <BottomSheet isOpen={isAOpen} onOpenChange={setIsAOpen} label="A">
+ <button type="button" onClick={() => setStep('one')}>
+ Open flow
+ </button>
+ </BottomSheet>
+ <BottomSheetSwitcher activeSheet={step} onActiveSheetChange={setStep}>
+ <BottomSheet sheetId="one" label="One">
+ <button type="button" onClick={() => setStep(null)}>
+ Done
+ </button>
+ </BottomSheet>
+ </BottomSheetSwitcher>
+ </>
+ );
+ }
+ render(
+ <ToastViewport>
+ <Mixed />
+ </ToastViewport>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Open A'}));
+ expect(getActiveModalOutlet()).toBe(getDialog('A'));
+ fireEvent.click(screen.getByRole('button', {name: 'Open flow'}));
+ expect(getActiveModalOutlet()).toBe(getDialog('One'));
+ expect(getViewport().closest('[inert]')).toBeNull();
+ fireEvent.click(screen.getByRole('button', {name: 'Done'}));
+ expect(getActiveModalOutlet()).toBe(getDialog('A'));
+ });
+
+ it('a standalone sheet opened from a step is the latest outlet while the covered flow keeps supplying', () => {
+ function Mixed() {
+ const [step, setStep] = useState<string | null>(null);
+ const [isCOpen, setIsCOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setStep('one')}>
+ Open flow
+ </button>
+ <BottomSheetSwitcher activeSheet={step} onActiveSheetChange={setStep}>
+ <BottomSheet sheetId="one" label="One">
+ <button type="button" onClick={() => setIsCOpen(true)}>
+ Open C
+ </button>
+ </BottomSheet>
+ </BottomSheetSwitcher>
+ <BottomSheet isOpen={isCOpen} onOpenChange={setIsCOpen} label="C">
+ <button type="button" onClick={() => setIsCOpen(false)}>
+ Close C
+ </button>
+ </BottomSheet>
+ </>
+ );
+ }
+ render(
+ <ToastViewport>
+ <Mixed />
+ </ToastViewport>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Open flow'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Open C'}));
+ expect(getActiveModalOutlet()).toBe(getDialog('C'));
+ expect(getDialog('One')).toHaveAttribute('inert');
+ fireEvent.click(screen.getByRole('button', {name: 'Close C'}));
+ expect(getActiveModalOutlet()).toBe(getDialog('One'));
+ });
+
+ it('the top sheet stays the latest outlet when the covered flow beneath it changes step from code: a toast raised from the sheet lands in it, not in the inert step', () => {
+ function Mixed() {
+ const [step, setStep] = useState<string | null>(null);
+ const [isCOpen, setIsCOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setStep('one')}>
+ Open flow
+ </button>
+ <button type="button" onClick={() => setStep('two')}>
+ Step two
+ </button>
+ <BottomSheetSwitcher activeSheet={step} onActiveSheetChange={setStep}>
+ <BottomSheet sheetId="one" label="One">
+ <button type="button" onClick={() => setIsCOpen(true)}>
+ Open C
+ </button>
+ </BottomSheet>
+ <BottomSheet sheetId="two" label="Two">
+ two
+ </BottomSheet>
+ </BottomSheetSwitcher>
+ <BottomSheet isOpen={isCOpen} onOpenChange={setIsCOpen} label="C">
+ <ToastButton label="Toast from C" />
+ <button type="button" onClick={() => setIsCOpen(false)}>
+ Close C
+ </button>
+ </BottomSheet>
+ </>
+ );
+ }
+ render(
+ <ToastViewport>
+ <Mixed />
+ </ToastViewport>,
+ );
+ const {showPopover, hidePopover} = trackPopoverState();
+ fireEvent.click(screen.getByRole('button', {name: 'Open flow'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Open C'}));
+ expect(getActiveModalOutlet()).toBe(getDialog('C'));
+ const viewport = getViewport();
+ const onViewport = (spy: typeof showPopover) =>
+ spy.mock.contexts.filter(context => context === viewport).length;
+ const hidesBefore = onViewport(hidePopover);
+ const showsBefore = onViewport(showPopover);
+ // The flow's level becomes step two's dialog, re-supplied while C stays
+ // on top: the re-supply goes beneath C, which keeps the outlet.
+ fireEvent.click(screen.getByRole('button', {name: 'Step two'}));
+ expect(getDialog('Two')).toHaveAttribute('inert');
+ expect(getDialog('C')).not.toHaveAttribute('inert');
+ expect(getActiveModalOutlet()).toBe(getDialog('C'));
+ // C was closed and shown again to stay on top, carrying the viewport's
+ // popover back beneath it in the top layer: the viewport re-entered
+ // (hide, then show) so toasts paint above the re-shown C.
+ expect(onViewport(hidePopover)).toBe(hidesBefore + 1);
+ expect(onViewport(showPopover)).toBe(showsBefore + 1);
+ fireEvent.click(screen.getByRole('button', {name: 'Toast from C'}));
+ const toast = screen.getByText('Saved');
+ expect(toast.closest('dialog')).toBe(getDialog('C'));
+ // Closing C hands the outlet to the flow's current step.
+ fireEvent.click(screen.getByRole('button', {name: 'Close C'}));
+ expect(getActiveModalOutlet()).toBe(getDialog('Two'));
+ });
+
+ it('a non-modal flow supplies no outlet', () => {
+ trackPopoverState();
+ const {container} = render(
+ <ToastViewport>
+ <Flow hasScrim={false} />
+ </ToastViewport>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Open flow'}));
+ expect(getActiveModalOutlet()).toBeNull();
expect(getViewport().closest('dialog')).toBeNull();
expect(container.contains(getViewport())).toBe(true);
});
diff --git a/packages/core/src/Toast/ToastViewport.tsx b/packages/core/src/Toast/ToastViewport.tsx
index 7202d40827..777b9fc24f 100644
--- a/packages/core/src/Toast/ToastViewport.tsx
+++ b/packages/core/src/Toast/ToastViewport.tsx
@@ -36,6 +36,7 @@ import {LayerContentBoundary} from '../Layer/layerScopedContext';
import {
getActiveModalOutlet,
subscribeModalOutlets,
+ type ModalOutletChange,
} from '../Layer/modalOutlet';
import {ToastSurface} from './Toast';
import {ToastContext, type ToastContextValue} from './ToastContext';
@@ -583,7 +584,7 @@ export function ToastViewport({
if (!isTopLayer || host == null) {
return;
}
- const place = () => {
+ const place = (change: ModalOutletChange = 'outlet') => {
const parent = getActiveModalOutlet() ?? rootOutletRef.current;
if (parent == null) {
return;
@@ -599,7 +600,9 @@ export function ToastViewport({
}
// Leaving the document hid the popover. Showing it again puts it above
// the modal that just opened, or above everything once the last modal
- // closed.
+ // closed. A non-modal surface that entered the top layer (`entry`)
+ // moved nothing, so the viewport leaves and re-enters in place to get
+ // above it; focus inside it is kept across the re-entry.
const el = viewportRef.current;
if (el == null || typeof el.showPopover !== 'function') {
return;
@@ -610,6 +613,28 @@ export function ToastViewport({
} catch {
/* :popover-open unsupported */
}
+ if (isShowing && change === 'entry') {
+ const active = document.activeElement;
+ const hadFocus = active instanceof HTMLElement && el.contains(active);
+ try {
+ el.hidePopover();
+ isShowing = false;
+ } catch {
+ /* not a showing popover */
+ }
+ if (isShowing) {
+ return;
+ }
+ try {
+ el.showPopover();
+ } catch {
+ /* already showing */
+ }
+ if (hadFocus) {
+ active.focus({preventScroll: true});
+ }
+ return;
+ }
if (!isShowing) {
try {
el.showPopover();
diff --git a/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx b/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx
index 5b530352fe..ae1ad01fb4 100644
--- a/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx
+++ b/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx
@@ -5,7 +5,7 @@
/**
* @file MobileTokenizer.tsx
* @input Uses public @astryxdesign/core components only (AlertDialog,
- * BottomSheet, BottomSheetSwitcher, Button, CheckboxIndicator, EmptyState,
+ * BottomSheet, Button, CheckboxIndicator, EmptyState,
* Field, Icon, Text, TextInput, Token)
* @output Exports MobileTokenizer — Lab prototype of the touch Tokenizer
* flow with a single searchable sheet, stable in-session checkbox ordering,
@@ -33,7 +33,6 @@ import * as stylex from '@stylexjs/stylex';
import type {BaseProps} from '@astryxdesign/core';
import {AlertDialog} from '@astryxdesign/core/AlertDialog';
import {BottomSheet} from '@astryxdesign/core/BottomSheet';
-import {BottomSheetSwitcher} from '@astryxdesign/core/BottomSheet';
import {Button} from '@astryxdesign/core/Button';
import {EmptyState} from '@astryxdesign/core/EmptyState';
import {Field} from '@astryxdesign/core/Field';
@@ -87,7 +86,6 @@ export interface MobileTokenizerProps<T extends SearchableItem> extends Omit<
onChangeQuery?: (query: string) => void;
}
-type SheetId = 'manage';
const CREATABLE_ID_PREFIX = '__xds_create__';
const LIST_RENDER_BATCH_SIZE = 50;
const LIST_LOAD_MORE_THRESHOLD_PX = 200;
@@ -280,7 +278,7 @@ export function MobileTokenizer<T extends SearchableItem>({
xstyle,
}: MobileTokenizerProps<T>) {
const triggerId = useId();
- const [activeSheet, setActiveSheet] = useState<SheetId | null>(null);
+ const [isSheetOpen, setIsSheetOpen] = useState(false);
const [isClearConfirmationOpen, setIsClearConfirmationOpen] = useState(false);
const selectedIds = useMemo(() => new Set(value.map(v => v.id)), [value]);
const isAtMax = maxEntries != null && value.length >= maxEntries;
@@ -326,7 +324,6 @@ export function MobileTokenizer<T extends SearchableItem>({
const seqRef = useRef(0);
const lastLoadScrollHeightRef = useRef<number | null>(null);
const [selectedItemsAtOpen, setSelectedItemsAtOpen] = useState<T[]>(value);
- const isSheetOpen = activeSheet === 'manage';
useEffect(() => {
if (!isSheetOpen) {
return;
@@ -430,7 +427,7 @@ export function MobileTokenizer<T extends SearchableItem>({
type="button"
id={triggerId}
aria-haspopup="dialog"
- aria-expanded={activeSheet != null}
+ aria-expanded={isSheetOpen}
aria-label={label}
aria-disabled={isDisabled || undefined}
onClick={() => {
@@ -440,7 +437,7 @@ export function MobileTokenizer<T extends SearchableItem>({
setSelectedItemsAtOpen(value);
lastLoadScrollHeightRef.current = null;
setRenderedItemCount(LIST_RENDER_BATCH_SIZE);
- setActiveSheet('manage');
+ setIsSheetOpen(true);
}}
{...stylex.props(styles.trigger, isDisabled && styles.triggerDisabled)}>
{value.length > 0 ? (
@@ -464,185 +461,186 @@ export function MobileTokenizer<T extends SearchableItem>({
</button>
{!isDisabled && (
- <BottomSheetSwitcher
- activeSheet={activeSheet}
- onActiveSheetChange={id => setActiveSheet(id as SheetId | null)}>
- <BottomSheet sheetId="manage" label={label} height="tall" padding={0}>
- <div {...stylex.props(styles.sheetBody)}>
- <div {...stylex.props(styles.filterRow)}>
- <TextInput
- label={`Search ${label}`}
- isLabelHidden
- placeholder="Search..."
- startIcon="search"
- value={query}
- size="lg"
- width="100%"
- hasClear
- onChange={next => {
- lastLoadScrollHeightRef.current = null;
- setRenderedItemCount(LIST_RENDER_BATCH_SIZE);
- setQuery(next);
- onChangeQuery?.(next);
- }}
- controlXstyle={styles.filterInput}
- />
- </div>
- <div
- {...stylex.props(styles.list)}
- role="group"
- aria-label={label}
- data-testid="mobile-tokenizer-list"
- data-rendered-count={renderedItems.length}
- data-total-count={visibleItems.length}
- onScroll={event => {
- const list = event.currentTarget;
- const distanceFromBottom =
- list.scrollHeight - list.scrollTop - list.clientHeight;
- if (
- distanceFromBottom <= LIST_LOAD_MORE_THRESHOLD_PX &&
- lastLoadScrollHeightRef.current !== list.scrollHeight
- ) {
- lastLoadScrollHeightRef.current = list.scrollHeight;
- setRenderedItemCount(current =>
- Math.min(
- current + LIST_RENDER_BATCH_SIZE,
- visibleItems.length,
- ),
- );
- }
- }}>
- {createItem != null && (
- <div
- data-testid="mobile-tokenizer-create-row"
- {...stylex.props(styles.createRow)}>
- <span {...stylex.props(styles.createLabel)}>
- <Text type="body">{createItem.label}</Text>
- </span>
- <Button
- label="Add"
- aria-label={`Add ${query.trim()}`}
- variant="secondary"
- size="lg"
- onClick={() => {
- handleAdd(createItem);
- lastLoadScrollHeightRef.current = null;
- setRenderedItemCount(LIST_RENDER_BATCH_SIZE);
- setQuery('');
- }}
- />
- </div>
- )}
- {!isSearching &&
- visibleItems.length === 0 &&
- createItem == null ? (
- <EmptyState
- icon={
- <Icon
- icon={query.trim() === '' ? ListBulletIcon : 'search'}
- size="lg"
- color="secondary"
- />
- }
- title={
- query.trim() === ''
- ? 'No items available'
- : emptySearchResultsText
- }
- description={
- query.trim() === ''
- ? 'There are no items to choose from.'
- : 'Try a different search.'
- }
- isCompact
- xstyle={styles.empty}
- />
- ) : (
- renderedItems.map(item => {
- const isSelected = selectedIds.has(item.id);
- const rowDisabled = !isSelected && isAtMax;
- return (
- <button
- key={item.id}
- type="button"
- role="checkbox"
- aria-checked={isSelected}
- aria-label={item.label}
- aria-disabled={rowDisabled || undefined}
- onClick={() => {
- if (rowDisabled) {
- return;
- }
- if (isSelected) {
- handleRemove(item);
- } else {
- handleAdd(item);
- }
- }}
- {...stylex.props(
- styles.row,
- rowDisabled && styles.rowDisabled,
- )}>
- <span {...stylex.props(styles.rowLabel)}>
- {renderItem ? (
- renderItem(item)
- ) : (
- <Text
- type="body"
- color={rowDisabled ? 'inherit' : undefined}>
- {item.label}
- </Text>
- )}
- </span>
- <CheckboxIndicator
- state={isSelected ? 'checked' : 'unchecked'}
- size="md"
- isDisabled={rowDisabled}
- xstyle={
- rowDisabled ? styles.indicatorDisabled : undefined
- }
- />
- </button>
- );
- })
- )}
- </div>
- {query.trim() === '' && (
- <div {...stylex.props(styles.footer)}>
+ <BottomSheet
+ isOpen={isSheetOpen}
+ onOpenChange={setIsSheetOpen}
+ label={label}
+ height="tall"
+ padding={0}>
+ <div {...stylex.props(styles.sheetBody)}>
+ <div {...stylex.props(styles.filterRow)}>
+ <TextInput
+ label={`Search ${label}`}
+ isLabelHidden
+ placeholder="Search..."
+ startIcon="search"
+ value={query}
+ size="lg"
+ width="100%"
+ hasClear
+ onChange={next => {
+ lastLoadScrollHeightRef.current = null;
+ setRenderedItemCount(LIST_RENDER_BATCH_SIZE);
+ setQuery(next);
+ onChangeQuery?.(next);
+ }}
+ controlXstyle={styles.filterInput}
+ />
+ </div>
+ <div
+ {...stylex.props(styles.list)}
+ role="group"
+ aria-label={label}
+ data-testid="mobile-tokenizer-list"
+ data-rendered-count={renderedItems.length}
+ data-total-count={visibleItems.length}
+ onScroll={event => {
+ const list = event.currentTarget;
+ const distanceFromBottom =
+ list.scrollHeight - list.scrollTop - list.clientHeight;
+ if (
+ distanceFromBottom <= LIST_LOAD_MORE_THRESHOLD_PX &&
+ lastLoadScrollHeightRef.current !== list.scrollHeight
+ ) {
+ lastLoadScrollHeightRef.current = list.scrollHeight;
+ setRenderedItemCount(current =>
+ Math.min(
+ current + LIST_RENDER_BATCH_SIZE,
+ visibleItems.length,
+ ),
+ );
+ }
+ }}>
+ {createItem != null && (
+ <div
+ data-testid="mobile-tokenizer-create-row"
+ {...stylex.props(styles.createRow)}>
+ <span {...stylex.props(styles.createLabel)}>
+ <Text type="body">{createItem.label}</Text>
+ </span>
<Button
- label="Clear all"
+ label="Add"
+ aria-label={`Add ${query.trim()}`}
variant="secondary"
size="lg"
- isDisabled={value.length === 0}
- onClick={() => setIsClearConfirmationOpen(true)}
- xstyle={styles.footerAction}
- />
- <Button
- label="Done"
- variant="primary"
- size="lg"
onClick={() => {
+ handleAdd(createItem);
+ lastLoadScrollHeightRef.current = null;
+ setRenderedItemCount(LIST_RENDER_BATCH_SIZE);
setQuery('');
- setActiveSheet(null);
}}
- xstyle={styles.footerAction}
/>
</div>
)}
- <AlertDialog
- isOpen={isClearConfirmationOpen}
- onOpenChange={setIsClearConfirmationOpen}
- title="Clear all selected items?"
- description={`This removes all selected items from ${label}.`}
- actionLabel="Clear selection"
- onAction={() => {
- handleClearAll();
- setIsClearConfirmationOpen(false);
- }}
- />
+ {!isSearching &&
+ visibleItems.length === 0 &&
+ createItem == null ? (
+ <EmptyState
+ icon={
+ <Icon
+ icon={query.trim() === '' ? ListBulletIcon : 'search'}
+ size="lg"
+ color="secondary"
+ />
+ }
+ title={
+ query.trim() === ''
+ ? 'No items available'
+ : emptySearchResultsText
+ }
+ description={
+ query.trim() === ''
+ ? 'There are no items to choose from.'
+ : 'Try a different search.'
+ }
+ isCompact
+ xstyle={styles.empty}
+ />
+ ) : (
+ renderedItems.map(item => {
+ const isSelected = selectedIds.has(item.id);
+ const rowDisabled = !isSelected && isAtMax;
+ return (
+ <button
+ key={item.id}
+ type="button"
+ role="checkbox"
+ aria-checked={isSelected}
+ aria-label={item.label}
+ aria-disabled={rowDisabled || undefined}
+ onClick={() => {
+ if (rowDisabled) {
+ return;
+ }
+ if (isSelected) {
+ handleRemove(item);
+ } else {
+ handleAdd(item);
+ }
+ }}
+ {...stylex.props(
+ styles.row,
+ rowDisabled && styles.rowDisabled,
+ )}>
+ <span {...stylex.props(styles.rowLabel)}>
+ {renderItem ? (
+ renderItem(item)
+ ) : (
+ <Text
+ type="body"
+ color={rowDisabled ? 'inherit' : undefined}>
+ {item.label}
+ </Text>
+ )}
+ </span>
+ <CheckboxIndicator
+ state={isSelected ? 'checked' : 'unchecked'}
+ size="md"
+ isDisabled={rowDisabled}
+ xstyle={
+ rowDisabled ? styles.indicatorDisabled : undefined
+ }
+ />
+ </button>
+ );
+ })
+ )}
</div>
- </BottomSheet>
- </BottomSheetSwitcher>
+ {query.trim() === '' && (
+ <div {...stylex.props(styles.footer)}>
+ <Button
+ label="Clear all"
+ variant="secondary"
+ size="lg"
+ isDisabled={value.length === 0}
+ onClick={() => setIsClearConfirmationOpen(true)}
+ xstyle={styles.footerAction}
+ />
+ <Button
+ label="Done"
+ variant="primary"
+ size="lg"
+ onClick={() => {
+ setQuery('');
+ setIsSheetOpen(false);
+ }}
+ xstyle={styles.footerAction}
+ />
+ </div>
+ )}
+ <AlertDialog
+ isOpen={isClearConfirmationOpen}
+ onOpenChange={setIsClearConfirmationOpen}
+ title="Clear all selected items?"
+ description={`This removes all selected items from ${label}.`}
+ actionLabel="Clear selection"
+ onAction={() => {
+ handleClearAll();
+ setIsClearConfirmationOpen(false);
+ }}
+ />
+ </div>
+ </BottomSheet>
)}
</Field>
);