An open source design system that's fully customizable and agent ready
TypeScript
feat(Popover): presentation — a BottomSheet on a phone when asked, as iOS presents a popover (#8229)
Christopher Chedeau2af4d305a620
diff --git a/.changeset/bottom-sheet-fewer-elements.md b/.changeset/bottom-sheet-fewer-elements.mdnew file mode 100644index 0000000000..7c2ec8f309--- /dev/null+++ b/.changeset/bottom-sheet-fewer-elements.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] BottomSheet renders fewer elements, with no visual change: an open sheet's dialog positions the panel itself, the grab bar draws its pill, and a closed sheet renders no edge tint. A switcher's sheets keep their positioner.++@vjeuxdiff --git a/.changeset/popover-presentation.md b/.changeset/popover-presentation.mdnew file mode 100644index 0000000000..196ebd9268--- /dev/null+++ b/.changeset/popover-presentation.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feature] Popover takes `presentation`, with the values DropdownMenu and Selector use: `'popover'` (the default, unchanged) anchors it to its trigger, `'bottom-sheet'` presents its content in a modal BottomSheet labeled by `label`, and `'adaptive'` uses the BottomSheet on a compact touch screen (a phone) and the anchored popover elsewhere, the way iOS presents a popover on an iPhone. Compact is the theme's compact definition: narrower than its `md` width point or shorter than 500 px. In a sheet, `placement`, `alignment`, `width`, `role`, `isModal` and `hasAutoFocus` do not apply, and `xstyle`, `className` and `style` style the sheet's panel. The sheet loads only when a popover can present one.++@vjeuxdiff --git a/apps/storybook/stories/Popover.stories.tsx b/apps/storybook/stories/Popover.stories.tsxindex b445b53133..b0f91b7575 100644--- a/apps/storybook/stories/Popover.stories.tsx+++ b/apps/storybook/stories/Popover.stories.tsx@@ -863,6 +863,31 @@ export const BottomSheetPresentationOption: Story = {},};+export const AdaptivePresentation: Story = {+ name: 'Adaptive Presentation',+ parameters: {+ layout: 'fullscreen',+ docs: {+ story: {inline: false, height: '844px'},+ description: {+ story:+ 'presentation="adaptive": on a compact touch screen (a phone) the content is presented in a BottomSheet, the way iOS presents a popover on an iPhone; with a mouse or on a larger screen it stays anchored to its trigger.',+ },+ },+ },+ render: () => (+ <div style={{padding: 16}}>+ <Popover+ label="Filter by status"+ presentation="adaptive"+ width={280}+ content={<FilterContent />}>+ <Button label="Filter">Filter</Button>+ </Popover>+ </div>+ ),+};+export const AdaptivePopoverRecipe: PresentationRecipeStory = {name: 'Adaptive Popover Recipe',args: {diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.mdindex 8e10b28403..26c0b8c82d 100644--- a/docs/architecture/layer-runtime.md+++ b/docs/architecture/layer-runtime.md@@ -506,7 +506,8 @@ be updated only as that work ships.INV14 and INV15 are not met yet, and `spec:AST-003` does not cover them: noshared presentation hold, exit copy, runtime backdrop tint, or lift moduleexists, and Dialog, Drawer, BottomSheet, Lightbox, MobileNav, ToastViewport,-and Selector each build their own top-layer mounting, exit, or backdrop.+and Selector each build their own top-layer mounting, exit, or backdrop, and+Popover builds its own presentation hold for its sheet presentation.## Change couplingdiff --git a/packages/core/src/BottomSheet/BottomSheet.spec.md b/packages/core/src/BottomSheet/BottomSheet.spec.mdindex 28bfd7ec63..be949fa553 100644--- a/packages/core/src/BottomSheet/BottomSheet.spec.md+++ b/packages/core/src/BottomSheet/BottomSheet.spec.md@@ -212,17 +212,23 @@ remain documented in `BottomSheet.doc.mjs`.- Element jobs (`architecture:component-style-authoring` INV7; theopen-layer allowance of `spec:AST-017` FR60, DEC-29). An open sheet's framehas these elements, each with one job:- - the dialog carries the sheet's dialog role, and modality and the top- layer when the sheet is modal;- - the positioner holds the panel at the block end;+ - 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;- the panel paints the `bottom-sheet` target;- - the grabber bar is the drag handle, and its pill draws the handle;+ - the grabber bar is the drag handle, and its `::before` draws the handle;- the body is the scroll area;- the content box carries the padding and is the observed content box (FR3);- - the edge tint gives iOS Safari's toolbar the sheet's color.-- Fewer is preferred: the pill and the edge tint are decoration that should- move to pseudo-elements, and the positioner should merge into the panel;- each is an open gap.+ - the edge tint gives iOS Safari's toolbar the sheet's color: its own+ element outside the panel's transform, so it stays flush with the+ viewport's bottom edge at every detent, rendered only while the sheet is+ presented;+ - in a BottomSheetSwitcher, each sheet's positioner holds its panel at the+ block end and hides a sheet that is not presented, so one dialog can+ switch between sheets.+- The handle's pill is a pseudo-element and a standalone sheet's dialog holds+ the panel in place, so a standalone sheet's frame has no positioner or pill+ element of its own.- Elements a presenting component adds beyond this frame are its own tojustify.- **PR1 — One stack per document.** Sheets rendered by every copy of thediff --git a/packages/core/src/BottomSheet/BottomSheet.test.tsx b/packages/core/src/BottomSheet/BottomSheet.test.tsxindex 6652d30386..32b8dc8dad 100644--- a/packages/core/src/BottomSheet/BottomSheet.test.tsx+++ b/packages/core/src/BottomSheet/BottomSheet.test.tsx@@ -13,6 +13,7 @@ import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';import {act, render, screen, fireEvent} from '@testing-library/react';import {createRef, useState} from 'react';import {BottomSheet} from './BottomSheet';+import {BottomSheetEscapeContext} from './bottomSheetEscape';import {BottomSheetSwitcher} from './BottomSheetSwitcher';import {__resetInteractionModalityForTest} from '../utils/interactionModality';@@ -498,6 +499,28 @@ describe('BottomSheet', () => {expect(dialog).toHaveStyle({'--_sheet-scrim-opacity': '1'});});+ it("the internal Escape gate (Popover's sheet) blocks Escape and the close request, not the scrim or swipe", () => {+ const onOpenChange = vi.fn();+ render(+ <BottomSheetEscapeContext value={false}>+ <BottomSheet isOpen onOpenChange={onOpenChange} label="Filters">+ Content+ </BottomSheet>+ </BottomSheetEscapeContext>,+ );+ const dialog = screen.getByRole('dialog');++ fireEvent.keyDown(dialog, {key: 'Escape'});+ fireEvent(dialog, new Event('cancel', {cancelable: true}));+ expect(onOpenChange).not.toHaveBeenCalled();++ fireEvent.click(dialog);+ expect(onOpenChange).toHaveBeenCalledTimes(1);+ drag(getHandle(), [{y: 0}, {y: 40}, {y: 120}]);+ expect(onOpenChange).toHaveBeenCalledTimes(2);+ expect(onOpenChange).toHaveBeenNthCalledWith(2, false);+ });+it('stays open when a file picker inside it is dismissed, and still closes on its own close request', () => {// A file input fires a bubbling `cancel` at itself when its picker is// dismissed. It reaches the <dialog> like a close request but is not one.diff --git a/packages/core/src/BottomSheet/BottomSheet.tsx b/packages/core/src/BottomSheet/BottomSheet.tsxindex 12e49da63c..29cfb4256a 100644--- a/packages/core/src/BottomSheet/BottomSheet.tsx+++ b/packages/core/src/BottomSheet/BottomSheet.tsx@@ -80,6 +80,7 @@ import {export type {BottomSheetHeight, BottomSheetSnapPoint} from './BottomSheetPanel';import type {BottomSheetHeight, BottomSheetSnapPoint} from './BottomSheetPanel';+import {BottomSheetEscapeContext} from './bottomSheetEscape';const styles = stylex.create({dialog: {@@ -101,6 +102,15 @@ const styles = stylex.create({dialogOpen: {display: 'block',},+ // 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.+ dialogPanelHost: {+ display: 'grid',+ alignContent: 'end',+ justifyItems: 'center',+ },dialogNonModal: {pointerEvents: 'none',zIndex: 1000,@@ -332,11 +342,13 @@ function StandaloneBottomSheet({? {kind: 'exiting'}: {kind: 'hidden'};+ // Popover's sheet may turn Escape off on its own (bottomSheetEscape.ts).+ const isEscapeAllowed = use(BottomSheetEscapeContext);const dismissOnEscape = useCallback(() => {- if (isOpen && purpose !== 'required') {+ if (isOpen && purpose !== 'required' && isEscapeAllowed) {onOpenChange(false);}- }, [isOpen, onOpenChange, purpose]);+ }, [isEscapeAllowed, isOpen, onOpenChange, purpose]);const dismissOnLightInteraction = useCallback(() => {if (purpose === 'info') {onOpenChange(false);@@ -432,7 +444,8 @@ function StandaloneBottomSheet({// rather than letting it close a layer behind it. `required` blocks too.const {shouldDismissOnCloseRequest} = useLayerDismissal({isActive: shouldPresent,- escapeBehavior: isOpen && purpose !== 'required' ? 'close' : 'block',+ escapeBehavior:+ isOpen && purpose !== 'required' && isEscapeAllowed ? 'close' : 'block',onDismiss: dismissOnEscape,getContainer: () => dialogRef.current,isPresent: () => dialogRef.current?.open ?? false,@@ -470,6 +483,7 @@ function StandaloneBottomSheet({{...stylex.props(styles.dialog,shouldPresent && styles.dialogOpen,+ shouldPresent && styles.dialogPanelHost,hasScrim && styles.scrim,hasScrim && !isOpen && isPresented && styles.scrimClosing,!hasScrim && styles.dialogNonModal,@@ -482,25 +496,29 @@ function StandaloneBottomSheet({inert={!isOpen && isPresented ? true : undefined}onCancel={handleCancel}onClick={handleClick}>- <div {...stylex.props(styles.positioner)}>- <BottomSheetPanel- {...props}- ref={ref}- state={panelState}- height={height}- label={label}- snapPoints={snapPoints}- isSwipeDismissAllowed={purpose === 'info'}- isPageScrollLocked={shouldPresent && hasScrim}- xstyle={xstyle}- onDismiss={dismissOnLightInteraction}- onScrimOpacity={handleScrimOpacity}- onElementChange={handlePanelElementChange}- onMotionComplete={handleMotionComplete}>- <LayerDepthProvider>{children}</LayerDepthProvider>- </BottomSheetPanel>- </div>- <BottomSheetEdgeTint />+ <BottomSheetPanel+ {...props}+ ref={ref}+ state={panelState}+ height={height}+ label={label}+ snapPoints={snapPoints}+ isSwipeDismissAllowed={purpose === 'info'}+ isPageScrollLocked={shouldPresent && hasScrim}+ xstyle={xstyle}+ onDismiss={dismissOnLightInteraction}+ onScrimOpacity={handleScrimOpacity}+ onElementChange={handlePanelElementChange}+ onMotionComplete={handleMotionComplete}>+ <LayerDepthProvider>+ {/* A sheet opened inside this one starts from Escape on. */}+ <BottomSheetEscapeContext value>{children}</BottomSheetEscapeContext>+ </LayerDepthProvider>+ </BottomSheetPanel>+ {/* Its own element, outside the panel's transform, so it stays flush+ with the viewport's bottom edge at every detent; only while the+ sheet is presented, so a closed sheet renders no extra element. */}+ {shouldPresent && <BottomSheetEdgeTint />}</dialog>);}@@ -805,7 +823,12 @@ function SwitcherBottomSheetItem({fresh ownership scope so a nested BottomSheet is standalone unlessit establishes a nested BottomSheetSwitcher of its own. */}<BottomSheetSwitcherContext value={null}>- <LayerDepthProvider>{children}</LayerDepthProvider>+ <LayerDepthProvider>+ {/* A sheet opened inside this one starts from Escape on. */}+ <BottomSheetEscapeContext value>+ {children}+ </BottomSheetEscapeContext>+ </LayerDepthProvider></BottomSheetSwitcherContext></BottomSheetPanel></div>diff --git a/packages/core/src/BottomSheet/BottomSheetPanel.tsx b/packages/core/src/BottomSheet/BottomSheetPanel.tsxindex fd08cb5bc7..c77b854739 100644--- a/packages/core/src/BottomSheet/BottomSheetPanel.tsx+++ b/packages/core/src/BottomSheet/BottomSheetPanel.tsx@@ -219,12 +219,15 @@ const styles = stylex.create({default: 'grab',':is(:disabled,[aria-disabled="true"])': 'default',},- },- handlePill: {- width: sizeVars['--size-element-lg'],- height: spacingVars['--spacing-1'],- borderRadius: radiusVars['--radius-full'],- backgroundColor: colorVars['--color-border'],+ // The pill, drawn on the grab bar itself: decoration with no role of its+ // own (architecture:component-style-authoring INV7).+ '::before': {+ content: '""',+ width: sizeVars['--size-element-lg'],+ height: spacingVars['--spacing-1'],+ borderRadius: radiusVars['--radius-full'],+ backgroundColor: colorVars['--color-border'],+ },},body: {flexGrow: 1,@@ -316,6 +319,19 @@ interface BottomSheetPanelProps extends BaseProps<HTMLDivElement> {onMotionComplete?: (motion: BottomSheetPanelMotion) => void;}+/**+ * A hidden sheet observes nothing (component:Popover PR1, FR5): the scroll+ * area's measuring ref attaches as the sheet presents and detaches once it is+ * hidden again, so a closed sheet that stays mounted holds no resize,+ * mutation or viewport observers.+ */+function whilePresented<P extends {ref?: unknown}>(+ isPresented: boolean,+ props: P,+): P {+ return isPresented ? props : {...props, ref: undefined};+}+function motionForState(state: BottomSheetPanelState,): BottomSheetPanelMotion | null {@@ -543,14 +559,24 @@ export function BottomSheetPanel({stickyContainment: 'always',});+ // The sheet measures its own height only while it is presented; a hidden+ // sheet that stays mounted observes nothing.+ const isPresentedRef = useRef(isPresented);const setElement = useCallback((element: HTMLDivElement | null) => {- sheetRef(element);+ sheetRef(isPresentedRef.current ? element : null);elementRef.current = element;onElementChange?.(element);},[onElementChange, sheetRef],);+ useLayoutEffect(() => {+ if (isPresentedRef.current === isPresented) {+ return;+ }+ isPresentedRef.current = isPresented;+ sheetRef(isPresented ? elementRef.current : null);+ }, [isPresented, sheetRef]);useMobileKeyboard({bodyRef: bodyElementRef,bottomClearance: MOBILE_KEYBOARD_BOTTOM_CLEARANCE,@@ -736,49 +762,54 @@ export function BottomSheetPanel({<div{...stylex.props(styles.handleBar)}{...handleProps}- aria-hidden="true">- <div {...stylex.props(styles.handlePill)} />- </div>+ aria-hidden="true"+ /><div- {...getViewportProps<HTMLDivElement>({- ...bodyProps,- ...mergeProps(- stylex.props(- focusOutlineStyles.focusVisible,- styles.body,- height === 'tall' && styles.tallKeyboardBody,+ {...whilePresented(+ isPresented,+ getViewportProps<HTMLDivElement>({+ ...bodyProps,+ ...mergeProps(+ stylex.props(+ focusOutlineStyles.focusVisible,+ styles.body,+ height === 'tall' && styles.tallKeyboardBody,+ ),+ scrollPreservationInset > 0+ ? {style: {paddingBlockEnd: `${scrollPreservationInset}px`}}+ : {},),- scrollPreservationInset > 0- ? {style: {paddingBlockEnd: `${scrollPreservationInset}px`}}- : {},- ),- })}>+ }),+ )}><div- {...getContentProps<HTMLDivElement>(- stylex.props(- styles.content,- ...container(- usesThemePadding- ? {useThemeDefault: 'bottom-sheet'}- : {- paddingInnerX: paddingToken,- paddingInnerY: paddingToken,- paddingOuterX: paddingToken,- paddingOuterY: paddingToken,- },+ {...whilePresented(+ isPresented,+ getContentProps<HTMLDivElement>(+ stylex.props(+ styles.content,+ ...container(+ usesThemePadding+ ? {useThemeDefault: 'bottom-sheet'}+ : {+ paddingInnerX: paddingToken,+ paddingInnerY: paddingToken,+ paddingOuterX: paddingToken,+ paddingOuterY: paddingToken,+ },+ ),+ !usesThemePadding &&+ effectivePadding !== 4 &&+ paddingStyles[effectivePadding],+ !usesThemePadding &&+ effectivePadding !== 4 &&+ containerPaddingInlineVarStyles[effectivePadding],+ !usesThemePadding &&+ effectivePadding !== 4 &&+ containerPaddingBlockStartVarStyles[effectivePadding],+ !usesThemePadding &&+ effectivePadding !== 4 &&+ containerPaddingBlockEndVarStyles[effectivePadding],),- !usesThemePadding &&- effectivePadding !== 4 &&- paddingStyles[effectivePadding],- !usesThemePadding &&- effectivePadding !== 4 &&- containerPaddingInlineVarStyles[effectivePadding],- !usesThemePadding &&- effectivePadding !== 4 &&- containerPaddingBlockStartVarStyles[effectivePadding],- !usesThemePadding &&- effectivePadding !== 4 &&- containerPaddingBlockEndVarStyles[effectivePadding],),)}><LayerContentBoundary>{children}</LayerContentBoundary>diff --git a/packages/core/src/BottomSheet/bottomSheetEscape.ts b/packages/core/src/BottomSheet/bottomSheetEscape.tsnew file mode 100644index 0000000000..61edf358f5--- /dev/null+++ b/packages/core/src/BottomSheet/bottomSheetEscape.ts@@ -0,0 +1,21 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file bottomSheetEscape.ts+ * @input React context+ * @output BottomSheetEscapeContext: whether Escape (and the platform's close+ * request) may dismiss the standalone sheet below it+ * @position Internal to Core, not exported from the package: Popover's sheet+ * presentation passes `hasEscapeDismiss` through it, so its sheet can+ * light-dismiss (scrim tap, swipe down) while Escape stays off+ * (component:Popover DEC-8). A standalone BottomSheet reads the default+ * (true), so its `purpose` rule is unchanged.+ */++import {createContext} from 'react';++/** Whether Escape may dismiss the sheet; `purpose="required"` still blocks it. */+export const BottomSheetEscapeContext = createContext(true);+BottomSheetEscapeContext.displayName = 'BottomSheetEscapeContext';diff --git a/packages/core/src/BottomSheet/useSheetGestures.ts b/packages/core/src/BottomSheet/useSheetGestures.tsindex 46ba8fb7e1..57ad69c869 100644--- a/packages/core/src/BottomSheet/useSheetGestures.ts+++ b/packages/core/src/BottomSheet/useSheetGestures.ts@@ -930,6 +930,10 @@ export function useSheetGestures({);useEffect(() => {+ // Only an open sheet can be dragged; a closed one listens to nothing.+ if (!isOpen) {+ return;+ }const handleWindowBlur = () => cancelDrag();const handleVisibilityChange = () => {if (document.visibilityState === 'hidden') {@@ -942,7 +946,7 @@ export function useSheetGestures({window.removeEventListener('blur', handleWindowBlur);document.removeEventListener('visibilitychange', handleVisibilityChange);};- }, [cancelDrag]);+ }, [cancelDrag, isOpen]);const settleFromDrag = useCallback((diff --git a/packages/core/src/Popover/Popover.doc.mjs b/packages/core/src/Popover/Popover.doc.mjsindex 408f4e700e..21e5b5b575 100644--- a/packages/core/src/Popover/Popover.doc.mjs+++ b/packages/core/src/Popover/Popover.doc.mjs@@ -99,7 +99,8 @@ export const docs = {{name: 'label',type: 'string',- description: 'Accessible label for the popover dialog.',+ description:+ 'Accessible label for the popover dialog. A sheet without one is named by the trigger\u2019s text.',},{name: 'role',@@ -149,6 +150,13 @@ export const docs = {'Whether pressing Escape dismisses the popover. Only takes full effect together with hasLightDismiss={false}, since native light dismiss also closes on Escape.',default: 'true',},+ {+ name: 'presentation',+ type: "'popover' | 'bottom-sheet' | 'adaptive'",+ description:+ "The surface that holds the content. 'popover' anchors it to the trigger, 'bottom-sheet' presents it in a modal BottomSheet labeled by label, and 'adaptive' uses the BottomSheet on a compact touch screen (a coarse pointer on a screen the theme counts as compact: narrower than its md width point or shorter than 500 px, so a phone in either orientation) and the anchored popover elsewhere. In a sheet, placement, alignment, width, role, isModal and hasAutoFocus do not apply, and xstyle, className and style style the sheet's panel; the sheet always light-dismisses (a tap outside it or a swipe down closes it, whatever hasLightDismiss says), Escape follows hasEscapeDismiss, and the fallback close stays hidden. The surface is chosen as it opens and kept until it closes.",+ default: "'popover'",+ },{name: 'xstyle',type: 'StyleXStyles',@@ -259,6 +267,12 @@ export const docs = {description:'Painted surface owned and themed by Popover through the canonical popover target.',},+ {+ name: 'Touch sheet',+ required: false,+ description:+ 'BottomSheet surface that holds the same content in place of the popover surface for presentation="bottom-sheet", or "adaptive" on a compact touch screen; themed through the bottom-sheet target.',+ },{name: 'Popover content',required: true,@@ -348,7 +362,8 @@ export const docsZh = {{name: 'label',type: 'string',- description: '弹出框对话框的无障碍标签。',+ description:+ '弹出框对话框的无障碍标签。没有标签的底部面板以触发器的文本命名。',},{name: 'role',@@ -397,6 +412,13 @@ export const docsZh = {'按 Escape 是否关闭弹出框。仅在 hasLightDismiss={false} 时生效,因为原生 light dismiss 行为同样响应 Escape。',default: 'true',},+ {+ name: 'presentation',+ type: "'popover' | 'bottom-sheet' | 'adaptive'",+ description:+ "承载内容的界面。'popover' 锚定在触发器上,'bottom-sheet' 以模态 BottomSheet 呈现(由 label 命名),'adaptive' 在紧凑触屏(粗指针,且屏幕按主题定义为紧凑:宽度小于其 md 断点或高度小于 500 px,即任意方向的手机)上使用 BottomSheet,在其他设备上使用锚定的弹出框。在底部面板中,placement、alignment、width、role、isModal 和 hasAutoFocus 不生效,xstyle、className 和 style 作用于面板;底部面板始终支持轻触关闭(点按面板外部或向下轻扫即可关闭,不受 hasLightDismiss 影响),Escape 遵循 hasEscapeDismiss,后备关闭按钮保持隐藏。界面在打开时选定,并保持到关闭。",+ default: "'popover'",+ },],},],@@ -463,6 +485,12 @@ export const docsZh = {description:'Painted surface owned and themed by Popover through the canonical popover target.',},+ {+ name: 'Touch sheet',+ required: false,+ description:+ 'BottomSheet surface that holds the same content in place of the popover surface for presentation="bottom-sheet", or "adaptive" on a compact touch screen; themed through the bottom-sheet target.',+ },{name: 'Popover content',required: true,@@ -530,6 +558,12 @@ export const docsDense = {description:'Painted surface owned and themed by Popover through the canonical popover target.',},+ {+ name: 'Touch sheet',+ required: false,+ description:+ 'BottomSheet surface that holds the same content in place of the popover surface for presentation="bottom-sheet", or "adaptive" on a compact touch screen; themed through the bottom-sheet target.',+ },{name: 'Popover content',required: true,@@ -573,6 +607,8 @@ export const docsDense = {'Outside click dismisses; false for explicit-dismiss surfaces (coachmarks).',hasEscapeDismiss:'Escape dismisses; full effect only with hasLightDismiss=false.',+ presentation:+ "Surface: 'popover' (anchored), 'bottom-sheet' (modal BottomSheet), or 'adaptive' (BottomSheet on a coarse pointer on a compact screen, popover elsewhere); chosen on open, kept until close.",},},],diff --git a/packages/core/src/Popover/Popover.spec.md b/packages/core/src/Popover/Popover.spec.mdindex deb00e40a9..234ec026bc 100644--- a/packages/core/src/Popover/Popover.spec.md+++ b/packages/core/src/Popover/Popover.spec.md@@ -16,6 +16,7 @@ verified_by:packages/core/src/Popover/Popover.doc.mjs,packages/core/src/Popover/usePopover.doc.mjs,packages/core/src/hooks/useFocusTrap.test.tsx,+ packages/core/src/Popover/PopoverPresentation.test.tsx,packages/cli/foundation/discovery/theming-targets.mjs,packages/cli/foundation/discovery/theming-targets.test.mjs,scripts/check-knowledge.mjs,@@ -61,7 +62,7 @@ rung, so a caller whose content owns its own edges can ask for a flush surface.- `presentation` (DEC-6) defaults to `popover`, the released anchored surface;`presentation="popover"` is also the value that keeps it wherever a touchdefault would otherwise apply (`architecture:public-component-api` INV16,- `spec:AST-017` FR3, DEC-23). Popover does not implement `presentation` yet.+ `spec:AST-017` FR3, DEC-23).- Canonical target: `popover` owns the broad painted-surface contract for`<Popover>` and public `usePopover` compositions- Removed alias: 0.7.0 removes `popover-surface`; themes and CSS selectors migrate@@ -271,12 +272,13 @@ table owns their semantic effect.## Design relationships-| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |-| ---------------------- | ------------------------------------------------------------------------------------------------------------------ | ------------------------------ | -------------- | --------------------- |-| Trigger element | Supplies or references the control and anchor without becoming Popover-owned presentation. | Caller content | Supporting | FR6, AR1 |-| Popover surface | Paints the component surface, owns the canonical `popover` target, and carries scroll, focus, and dialog behavior. | Current source and owner DEC-2 | Prominent | FR2, FR4–FR7, AR2–AR4 |-| Popover content | Renders caller-supplied interaction or information inside the surface. | Caller content | Prominent | FR2, FR6 |-| Fallback close control | Provides an end-of-trap close affordance without becoming the initial focus destination. | `component:Button` | Supporting | FR2, AR3 |+| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |+| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------ | -------------- | --------------------- |+| Trigger element | Supplies or references the control and anchor without becoming Popover-owned presentation. | Caller content | Supporting | FR6, AR1 |+| Popover surface | Paints the component surface, owns the canonical `popover` target, and carries scroll, focus, and dialog behavior. | Current source and owner DEC-2 | Prominent | FR2, FR4–FR7, AR2–AR4 |+| Touch sheet | Holds the same content in place of the surface when `presentation` resolves to `bottom-sheet`; paints BottomSheet's `bottom-sheet` target. | `component:BottomSheet` | Prominent | DEC-6, AR1, AR4 |+| Popover content | Renders caller-supplied interaction or information inside the surface. | Caller content | Prominent | FR2, FR6 |+| Fallback close control | Provides an end-of-trap close affordance without becoming the initial focus destination. | `component:Button` | Supporting | FR2, AR3 |### Theming anatomy@@ -290,6 +292,9 @@ table owns their semantic effect.}},"Popover surface": {"target": "popover"},+ "Touch sheet": {+ "delegatesTo": {"owner": "component:BottomSheet", "target": "bottom-sheet"}+ },"Popover content": {"none": {"reason": "intentional: Caller-supplied content is caller-owned; normal CSS may inherit from the surface, but Popover provides no content target."@@ -301,6 +306,15 @@ table owns their semantic effect.}```+`Popover surface` and `Touch sheet` are alternative presentations of the same+content, not simultaneous anatomy.++Any element the open touch sheet renders beyond the anchored popover under a+fine pointer is part of BottomSheet's frame, with its job in+`component:BottomSheet`'s element jobs, within the open-layer allowance of+`spec:AST-017` FR60 (DEC-29). Popover adds only its fallback close control to+the sheet, as the Button itself.+Every public `usePopover` painted surface belongs to the broad `popover` target.A composed component may add its own authoritative refinement target, such as`selector-popup` or `multi-selector-popup`, on that same element. New direct hook@@ -338,6 +352,7 @@ consumers that need distinct theme reachability provide and document an owned| FR5 | `Popover.test.tsx` scheduling and observer-lifecycle suites | Closed, opened, repeated signals, cleanup | Constructing observers while closed or measuring more than once per pending frame fails lifecycle assertions. | `audit:Popover/resources` || FR6, FR7 and theming anatomy | `Popover.test.tsx`, `Popover.doc.mjs`, `usePopover.doc.mjs`, `astryx theme targets Popover --json`, and `scripts/check-knowledge.mjs` | One real surface with canonical `popover` plus composed-component refinements | A fake anatomy part, missing canonical output, or an active target without a real owner fails review or validation. | `audit:Popover/theming` || AR5 | `Popover.stories.tsx` manual-AT fixture and PR #5373 test record | Read-only dialog manual-AT fixture; no recorded NVDA/VoiceOver announcement result | A fixture without recorded AT/browser observations cannot be cited as announcement proof. | `audit:Popover/at-evidence` |+| Presentation (DEC-6, DEC-8) | `PopoverPresentation.test.tsx` | Default on a phone, adaptive on a phone and a desktop, forced sheet, close, controlled, dismissal mapping | A sheet on a default phone popover, an anchored popover where the sheet is asked for, or a trigger state that ignores the sheet fails. | `audit:Popover/api` |## Decision log@@ -401,6 +416,7 @@ placement and bypasses the shared focus-indication owner.### DEC-6 — Presentation: the anchored popover, a sheet, or adaptive**Reference:** `component:Popover/DEC-6`+**Decider:** `cixzhang`, `2026-10-25`Popover takes `presentation` with the vocabulary the menus already use:@@ -410,6 +426,25 @@ BottomSheet. `adaptive` chooses exactly as the menus do: the sheet under`spec:AST-094` FR13's touch rule, with compact governed by `spec:AST-012` FR9,and the anchored popover elsewhere.+### DEC-8 — The sheet Popover presents: label, size, dismissal and loading++**Reference:** `component:Popover/DEC-8`++**Decider:** `cixzhang`, `2026-10-25`++In a sheet, Popover's content is labeled by its `label`, or by the trigger's+text when it has none, so the dialog always has a name. The sheet always+light-dismisses: a tap outside it or a swipe down closes it, whatever+`hasLightDismiss` says, so a finger always has a way out. Its fallback close+stays hidden, as in an anchored popover. Everything else follows Popover's+existing props. The sheet of DEC-6 is a modal BottomSheet at the sheet's tall+height and inset by Popover's `padding`; `xstyle`, `className` and `style`+style its panel, and `placement`, `alignment` and `width` do not apply. The+surface is chosen when the popover opens and stays until it closes, and the+trigger's expanded state and controlled element follow whichever surface is+open. The sheet loads on demand, so pages whose popovers stay anchored do not+load it.+## Verification gapsThese implementation and evidence items remain required follow-up, but they dodiff --git a/packages/core/src/Popover/Popover.tsx b/packages/core/src/Popover/Popover.tsxindex 66d77713de..8788ac2f63 100644--- a/packages/core/src/Popover/Popover.tsx+++ b/packages/core/src/Popover/Popover.tsx@@ -10,25 +10,47 @@** For hover-triggered overlays, use HoverCard instead.*+ * `presentation` chooses the surface, with the vocabulary DropdownMenu and+ * Selector use: the anchored popover (the default), a BottomSheet, or+ * `adaptive` — a BottomSheet on a compact touch screen and the popover+ * elsewhere (the shared adaptive presentation policy), which is what iOS does+ * with a popover unless the app keeps it. The surface is chosen when the+ * popover opens; whichever is open stays until it closes. The BottomSheet+ * loads on demand (lazyPopoverBottomSheet.ts).+ ** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/Popover/Popover.test.tsx* - /packages/core/src/Popover/index.ts+ * - /packages/core/src/Popover/PopoverPresentation.test.tsx* - /apps/storybook/stories/Popover.stories.tsx* - /packages/cli/assets/templates/blocks/components/Popover/ (showcase blocks)*/import React, {useCallback,+ useEffect,+ useMemo,useRef,useState,+ useSyncExternalStore,type ReactElement,type ReactNode,} from 'react';import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';+import type {+ AdaptivePresentation,+ ResolvedAdaptivePresentation,+} from '../hooks/useAdaptivePresentation';+import {+ compactDefinition,+ DEFAULT_COMPACT_DEFINITION,+} from '../theme/themeAdaptations';+import {useThemeDefinition} from '../theme/useTheme';import * as stylex from '@stylexjs/stylex';import {devWarn} from '../utils/devWarning';import type {BaseProps} from '../BaseProps';import {usePopover} from './usePopover';+import {FOCUSABLE_SELECTOR} from '../hooks/focusableSelector';import type {LayerAlignment, LayerPlacement} from '../Layer/useLayer';import {layerAnimations} from '../Layer/layerAnimations.stylex';import {layerViewportInset} from '../Layer/layerViewportInset.stylex';@@ -36,12 +58,66 @@ import {clampInlineSize, isIntrinsicInlineSize} from '../Layer/clampInlineSize';import {spacingVars} from '../theme/tokens.stylex';import {InteractiveRoleContext} from '../InteractiveRoleContext/InteractiveRoleContext';import type {SpacingStep} from '../utils/types';+import {BottomSheetEscapeContext} from '../BottomSheet/bottomSheetEscape';+import {+ PopoverBottomSheet,+ preloadPopoverBottomSheet,+} from './lazyPopoverBottomSheet';+import {Button} from '../Button';+import {useTranslator} from '../i18n';// =============================================================================// Helpers// =============================================================================const BUTTON_SELECTOR = 'button, [role="button"]';++const subscribeToNothing = () => () => {};+const notCompactTouch = () => false;++/**+ * The surface `presentation` resolves to now. `adaptive` takes the sheet on a+ * compact screen with a coarse pointer, compact as the active theme defines+ * it (spec:AST-012 FR9: narrower than its `md` point or shorter than 500).+ * Only an adaptive popover reads the theme and subscribes to that query, so a+ * default popover holds no viewport or document listener. The theme is the+ * nearest Theme provider's; without one, the registered root theme's, as+ * AppShell reads it (architecture:theme-application).+ */+function usePresentationSurface(+ presentation: AdaptivePresentation,+): ResolvedAdaptivePresentation {+ const isAdaptive = presentation === 'adaptive';+ const points =+ useThemeDefinition(isAdaptive)?.__adaptations?.widthBreakpoints;+ const query = useMemo(+ () =>+ (points == null ? DEFAULT_COMPACT_DEFINITION : compactDefinition(points))+ .coarsePointerQuery,+ [points],+ );+ const subscribe = useCallback(+ (onStoreChange: () => void) => {+ const mql = window.matchMedia(query);+ mql.addEventListener('change', onStoreChange);+ return () => mql.removeEventListener('change', onStoreChange);+ },+ [query],+ );+ const getSnapshot = useCallback(+ () => window.matchMedia(query).matches,+ [query],+ );+ const isCompactTouch = useSyncExternalStore(+ isAdaptive ? subscribe : subscribeToNothing,+ isAdaptive ? getSnapshot : notCompactTouch,+ notCompactTouch,+ );+ if (!isAdaptive) {+ return presentation;+ }+ return isCompactTouch ? 'bottom-sheet' : 'popover';+}/*** Find the trigger button inside a container element.* Looks for `<button>` or `[role="button"]` — either the element itself@@ -54,10 +130,26 @@ function findTriggerButton(el: HTMLElement): HTMLElement | null {return el.querySelector<HTMLElement>(BUTTON_SELECTOR);}+/** The trigger's own name: its `aria-label`, else its text. */+function readTriggerText(trigger: HTMLElement): string {+ return (+ trigger.getAttribute('aria-label')?.trim() ||+ trigger.textContent?.trim() ||+ ''+ );+}+// =============================================================================// Types// =============================================================================+/**+ * The surface a Popover presents its content on: anchored to the trigger, in+ * a BottomSheet, or adaptive (a BottomSheet on a compact touch screen, the+ * popover elsewhere).+ */+export type PopoverPresentation = AdaptivePresentation;+/*** Props passed to render-prop children for explicit trigger wiring.*/@@ -181,7 +273,9 @@ export interface PopoverProps extends Pick</*** Accessible label for the popover dialog.- * Recommended for accessibility when `role` is `'dialog'`.+ * Recommended for accessibility when `role` is `'dialog'`. A sheet+ * (`presentation`) without one is named by the trigger's text, so it is+ * never an unnamed dialog.*/label?: string;@@ -246,6 +340,28 @@ export interface PopoverProps extends Pick<*/hasEscapeDismiss?: boolean;+ /**+ * The surface that holds the content. `'popover'` anchors it to the+ * trigger. `'bottom-sheet'` presents it in a modal BottomSheet, labeled+ * by `label`. `'adaptive'` presents the BottomSheet on a compact touch+ * screen (a coarse pointer on a screen the theme counts as compact:+ * narrower than its `md` width point or shorter than 500px, so a phone in+ * either orientation) and the anchored popover elsewhere, which is what iOS+ * does with a popover by default.+ *+ * In a sheet, `placement`, `alignment`, `width`, `role`, `isModal` and+ * `hasAutoFocus` do not apply (the sheet is a modal dialog with its own+ * focus handling); `xstyle`, `className` and `style` style the sheet's+ * panel, as they style the anchored surface; `padding` insets the+ * sheet's content. The sheet always light-dismisses (a tap outside it or a+ * swipe down closes it, whatever `hasLightDismiss` says), Escape follows+ * `hasEscapeDismiss`, and the fallback close stays hidden as on the+ * anchored surface. The surface is+ * chosen when the popover opens and kept until it closes.+ * @default 'popover'+ */+ presentation?: PopoverPresentation;+/*** Test ID for the popover container.*/@@ -265,6 +381,35 @@ const styles = stylex.create({anchorWrapper: {display: 'inline-flex',},+ // The sheet's fallback close control: hidden until it is reached, as the+ // anchored surface's is, on the Button itself rather than a wrapper+ // (architecture:component-style-authoring INV7). Taken out of flow and+ // clipped at rest, it rejoins the flow when focused, set below the content+ // with room for its focus ring.+ sheetFallbackClose: {+ position: {+ default: 'absolute',+ ':focus': 'relative',+ },+ clipPath: {+ default: 'inset(50%)',+ ':focus': 'none',+ },+ marginBlockStart: {+ default: 0,+ ':focus': spacingVars['--spacing-3'],+ },+ // Block-level when revealed, so it starts its own line below inline+ // content rather than sitting on its last line.+ display: {+ default: null,+ ':focus': 'flex',+ },+ width: {+ default: null,+ ':focus': 'fit-content',+ },+ },// The painted surface is capped to the viewport with the layer runtime's// one definition (spec:AST-059 FR2, FR3): the layer box above it caps the// block axis itself and leaves the inline axis to the surface, so a flip is@@ -359,15 +504,21 @@ export function Popover({hasAutoFocus,hasLightDismiss = true,hasEscapeDismiss = true,+ presentation = 'popover',xstyle,className,style,'data-testid': testId,}: PopoverProps): ReactElement {+ const t = useTranslator();const wrapperRef = useRef<HTMLDivElement>(null);const measurementFrameRef = useRef<number | null>(null);const [hasOverflow, setHasOverflow] = useState(false);const isControlled = isOpen !== undefined;+ // The bottom-sheet presentation: the surface it resolves to now, and+ // whether the sheet is the surface that is open.+ const resolvedPresentation = usePresentationSurface(presentation);+ const [isSheetOpenState, setIsSheetOpenState] = useState(false);const handlePopoverShow = useCallback(() => {onOpenChange?.(true);@@ -404,6 +555,144 @@ export function Popover({onHide: handlePopoverHide,});+ // A controlled popover opens on the surface its presentation resolves to+ // as it opens, and keeps that surface until it closes: a phone rotated past+ // the compact width while the sheet is open keeps its sheet.+ const [controlledSurface, setControlledSurface] = useState<+ 'popover' | 'bottom-sheet' | null+ >(null);+ // The latch is set during render, as the controlled `isOpen` turns on or+ // off, so the open surface is known in the same render that opens it.+ if (isControlled) {+ if (isOpen !== true && controlledSurface != null) {+ setControlledSurface(null);+ } else if (isOpen === true && controlledSurface == null) {+ setControlledSurface(popover.isOpen ? 'popover' : resolvedPresentation);+ }+ }+ const isSheetOpen = isControlled+ ? isOpen === true && controlledSurface === 'bottom-sheet'+ : isSheetOpenState;+ // One presentation at a time (architecture:component-style-authoring+ // INV7): the sheet is mounted, in place of the anchored layer, while it is+ // the surface an opening would choose (a compact touch screen, or+ // `'bottom-sheet'`) and the anchored popover is not the open one, while it+ // is open, and through its exit after it was. Closed, it holds the content+ // as the anchored layer does, so state kept in the content (a ticked box,+ // typed text) survives a reopen. After a sheet closes on a screen that has+ // stopped being compact, it stays through its exit, so the exit plays out+ // and its dialog hands focus back to the trigger (component:Popover AR4),+ // and gives way to the anchored layer once its dialog has closed.+ const [hasSheetBeenOpen, setHasSheetBeenOpen] = useState(false);+ // The trigger's text, which names a sheet that has no `label` (DEC-8).+ const [triggerText, setTriggerText] = useState('');+ if (isSheetOpen && !hasSheetBeenOpen) {+ setHasSheetBeenOpen(true);+ }+ const isSheetMounted =+ isSheetOpen ||+ hasSheetBeenOpen ||+ (resolvedPresentation === 'bottom-sheet' && !popover.isOpen);+ const sheetPanelRef = useRef<HTMLDivElement | null>(null);+ const [isSheetPanelAttached, setSheetPanelAttached] = useState(false);+ const attachSheetPanel = useCallback((panel: HTMLDivElement | null) => {+ sheetPanelRef.current = panel;+ setSheetPanelAttached(panel != null);+ }, []);+ // Focus enters the sheet at each opening as it enters the anchored popover+ // (FR2): a caller's `[data-autofocus]`, else the first genuine content+ // control (never the injected fallback close, never BottomSheet's own+ // scroll area), else that scroll area: the sheet's labelled surface, which+ // paints the shared focus ring under the keyboard. It runs a frame after+ // BottomSheet presents the dialog; BottomSheet is unchanged.+ useEffect(() => {+ if (!isSheetOpen || !isSheetPanelAttached) {+ return;+ }+ const frame = requestAnimationFrame(() => {+ const sheetPanel = sheetPanelRef.current;+ if (sheetPanel == null) {+ return;+ }+ const dialog = sheetPanel.closest('dialog');+ if (dialog == null || !dialog.open) {+ return;+ }+ const active = sheetPanel.ownerDocument.activeElement;+ if (+ active != null &&+ active !== sheetPanel &&+ active !== dialog &&+ sheetPanel.contains(active)+ ) {+ return;+ }+ const target =+ sheetPanel.querySelector<HTMLElement>('[data-autofocus]') ??+ Array.from(+ sheetPanel.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),+ ).find(+ element =>+ // BottomSheet's scroll area is the panel's own child; content+ // sits inside it.+ element.parentElement !== sheetPanel &&+ element.closest('[data-astryx-popover-fallback-close]') == null,+ );+ if (target != null) {+ target.focus({preventScroll: true});+ return;+ }+ // The scroll area is a tab stop only while its content overflows; it is+ // focusable from script either way.+ const surface = Array.from(sheetPanel.children).find(+ (child): child is HTMLElement =>+ child instanceof HTMLElement &&+ child.getAttribute('role') === 'group',+ );+ if (surface == null) {+ return;+ }+ if (!surface.hasAttribute('tabindex')) {+ surface.tabIndex = -1;+ }+ surface.focus({preventScroll: true});+ });+ return () => cancelAnimationFrame(frame);+ }, [isSheetOpen, isSheetPanelAttached]);+ useEffect(() => {+ if (isSheetOpen || !hasSheetBeenOpen) {+ return;+ }+ const dialog = sheetPanelRef.current?.closest('dialog');+ if (dialog == null || !dialog.open) {+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- syncs with the sheet's <dialog>: it is already closed, so its close event has fired and its exit is over; unmount it+ setHasSheetBeenOpen(false);+ return;+ }+ const handleClose = () => setHasSheetBeenOpen(false);+ dialog.addEventListener('close', handleClose);+ return () => dialog.removeEventListener('close', handleClose);+ }, [hasSheetBeenOpen, isSheetOpen]);+ // An open on a compact touch screen shows the sheet at once: its module+ // loads as soon as the sheet can be the surface, with nothing rendered.+ useEffect(() => {+ if (resolvedPresentation === 'bottom-sheet') {+ preloadPopoverBottomSheet();+ }+ }, [resolvedPresentation]);+ const isAnySurfaceOpen = popover.isOpen || isSheetOpen;+ const sheetId = `${popover.id}-sheet`;++ const setSheetOpen = useCallback(+ (next: boolean) => {+ if (!isControlled) {+ setIsSheetOpenState(next);+ }+ onOpenChange?.(next);+ },+ [isControlled, onOpenChange],+ );+const measureOverflow = useCallback(() => {const surface = popover.contentRef.current;if (!surface) {@@ -481,6 +770,16 @@ export function Popover({}, [content, popover.isOpen, scheduleOverflowMeasurement]);// Shared handler for click events on the trigger button.+ // A render-prop trigger is the caller's element, reached through the ref+ // the render prop hands it; its text names a sheet that has no `label`.+ const renderTriggerRef = useRef<HTMLElement | null>(null);+ const setRenderTrigger = useCallback(+ (element: HTMLElement | null) => {+ renderTriggerRef.current = element;+ popover.triggerRef(element);+ },+ [popover],+ );const handleTriggerClick = useCallback((event?: {currentTarget: EventTarget | null}) => {// An aria-disabled trigger stays focusable but opens nothing@@ -493,9 +792,22 @@ export function Popover({) {return;}+ // Opening chooses the surface; an open popover closes as a popover.+ if (+ isSheetOpen ||+ (!popover.isOpen && resolvedPresentation === 'bottom-sheet')+ ) {+ const opener =+ trigger instanceof HTMLElement ? trigger : renderTriggerRef.current;+ if (opener != null) {+ setTriggerText(readTriggerText(opener));+ }+ setSheetOpen(!isSheetOpen);+ return;+ }popover.toggle();},- [isEnabled, popover],+ [isEnabled, isSheetOpen, popover, resolvedPresentation, setSheetOpen],);// Shared handler for keydown events on role="button" elements.@@ -518,18 +830,20 @@ export function Popover({const attachTrigger = useCallback((button: HTMLElement) => {// ARIA attributes+ // The sheet's surface is a dialog whatever the popover's role.button.setAttribute('aria-haspopup',- popover.triggerProps['aria-haspopup'],- );- button.setAttribute(- 'aria-expanded',- String(popover.triggerProps['aria-expanded']),+ isSheetMounted ? 'dialog' : popover.triggerProps['aria-haspopup'],);+ button.setAttribute('aria-expanded', String(isAnySurfaceOpen));button.setAttribute('aria-controls',- popover.triggerProps['aria-controls'],+ isSheetMounted ? sheetId : popover.triggerProps['aria-controls'],);+ // The trigger's text is in the DOM the caller rendered, read as the+ // trigger attaches; it names a sheet that has no `label` (DEC-8).+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- reads the caller-rendered trigger's text, which only the DOM holds+ setTriggerText(readTriggerText(button));// Event handlersbutton.addEventListener('click', handleTriggerClick);@@ -551,7 +865,14 @@ export function Popover({}};},- [popover, handleTriggerClick, handleTriggerKeyDown],+ [+ popover,+ isAnySurfaceOpen,+ isSheetMounted,+ sheetId,+ handleTriggerClick,+ handleTriggerKeyDown,+ ],);// Sibling mode: attach to external anchorRef@@ -629,17 +950,23 @@ export function Popover({};}, [anchorRef, popover, attachTrigger]);- // Sync controlled state+ // Sync controlled state: show or hide the anchored popover, the one surface+ // with an imperative API, to follow the latch. The sheet follows the latch+ // in render (`isSheetOpen`).useIsomorphicLayoutEffect(() => {if (!isControlled) {return;}- if (isOpen && !popover.isOpen) {+ if (!isOpen) {+ if (popover.isOpen) {+ popover.hide();+ }+ return;+ }+ if (controlledSurface === 'popover' && !popover.isOpen) {popover.show();- } else if (!isOpen && popover.isOpen) {- popover.hide();}- }, [isOpen, isControlled, popover]);+ }, [isOpen, isControlled, popover, controlledSurface]);// Popover's one sizing fact: an explicit width wins over trigger matching.// Fit against the viewport is the layer runtime's (spec:AST-059).@@ -652,16 +979,63 @@ export function Popover({);const layerXstyle = [popoverSizeXstyle, layerAnimations[placement]];+ // One instance of the content at a time: the sheet holds it while it is+ // mounted, the anchored layer otherwise.+ const isContentInSheet = isSheetMounted;+ const anchoredContent = (+ <div data-testid={isContentInSheet ? undefined : testId}>+ {isContentInSheet ? null : content}+ </div>+ );+ // The sheet renders while it is the open surface and through its exit. It+ // always light-dismisses: a tap outside it or a swipe down closes it,+ // whatever `hasLightDismiss` says, so a finger always has a way out+ // (DEC-8). Escape follows `hasEscapeDismiss`, and the fallback close stays+ // hidden until it is reached, as on the anchored surface.+ const sheet = isSheetMounted ? (+ <BottomSheetEscapeContext value={hasEscapeDismiss}>+ <PopoverBottomSheet+ ref={attachSheetPanel}+ id={sheetId}+ isOpen={isSheetOpen}+ onOpenChange={setSheetOpen}+ label={label ?? triggerText}+ height="tall"+ padding={padding}+ xstyle={xstyle}+ className={className}+ style={style}+ data-testid={isContentInSheet ? testId : undefined}>+ {isContentInSheet ? content : null}+ {isContentInSheet && hasCloseButton !== false ? (+ <Button+ data-astryx-popover-fallback-close=""+ variant="secondary"+ label={closeButtonLabel ?? t('@astryx.popover.close')}+ onClick={() => setSheetOpen(false)}+ xstyle={styles.sheetFallbackClose}+ />+ ) : null}+ </PopoverBottomSheet>+ </BottomSheetEscapeContext>+ ) : null;++ // The anchored layer, unless the sheet is the presentation that is mounted.+ const anchoredLayer = isSheetMounted+ ? null+ : popover.render(anchoredContent, {+ placement,+ alignment,+ offset: spacingVars['--spacing-1'],+ xstyle: layerXstyle,+ });+// Sibling mode: render only the popover (no wrapper needed)if (anchorRef && children == null) {return (<>- {popover.render(<div data-testid={testId}>{content}</div>, {- placement,- alignment,- offset: spacingVars['--spacing-1'],- xstyle: layerXstyle,- })}+ {anchoredLayer}+ {sheet}</>);}@@ -671,23 +1045,19 @@ export function Popover({if (isRenderProp) {const triggerProps: PopoverTriggerRenderProps = {- ref: popover.triggerRef,+ ref: setRenderTrigger,// The caller renders and owns this trigger element.onClick: () => handleTriggerClick(),'aria-haspopup': 'dialog',- 'aria-expanded': popover.isOpen,- 'aria-controls': popover.id,+ 'aria-expanded': isAnySurfaceOpen,+ 'aria-controls': isSheetMounted ? sheetId : popover.id,};return (<>{children(triggerProps)}- {popover.render(<div data-testid={testId}>{content}</div>, {- placement,- alignment,- offset: spacingVars['--spacing-1'],- xstyle: layerXstyle,- })}+ {anchoredLayer}+ {sheet}</>);}@@ -700,12 +1070,8 @@ export function Popover({{children}</div></InteractiveRoleContext>- {popover.render(<div data-testid={testId}>{content}</div>, {- placement,- alignment,- offset: spacingVars['--spacing-1'],- xstyle: layerXstyle,- })}+ {anchoredLayer}+ {sheet}</>);}diff --git a/packages/core/src/Popover/PopoverPresentation.test.tsx b/packages/core/src/Popover/PopoverPresentation.test.tsxnew file mode 100644index 0000000000..fb4881914e--- /dev/null+++ b/packages/core/src/Popover/PopoverPresentation.test.tsx@@ -0,0 +1,952 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file PopoverPresentation.test.tsx+ * @input vitest (jsdom), Testing Library, Popover, a stand-in matchMedia and+ * jsdom stubs for <dialog>+ * @output Checks Popover's `presentation`: the default stays anchored on a+ * phone; `adaptive` presents a BottomSheet on a compact touch screen and the+ * popover elsewhere; `bottom-sheet` always presents the sheet; the trigger's+ * expanded state and controlled element follow the sheet; closing the sheet+ * reports it; controlled visibility drives the sheet; dismissal maps to the+ * sheet's purpose+ * @position Testing for Popover.tsx (presentation)+ */++import {act, fireEvent, render, screen} from '@testing-library/react';+import React, {useState} from 'react';+import {+ afterEach,+ beforeAll,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from 'vitest';+import {Button} from '../Button';+import {defineTheme} from '../theme/defineTheme';+import {+ compactDefinition,+ DEFAULT_COMPACT_DEFINITION,+} from '../theme/themeAdaptations';+import {BottomSheet} from '../BottomSheet';+import {Popover, type PopoverPresentation} from './Popover';++// Compact as spec:AST-012 FR9 defines it, with a coarse pointer.+const COMPACT_TOUCH_QUERY = DEFAULT_COMPACT_DEFINITION.coarsePointerQuery;++let isCompactTouch = false;+// The media query's change listeners, so a test can turn the phone.+const mediaListeners = new Set<() => void>();+function setCompactTouch(next: boolean) {+ isCompactTouch = next;+ act(() => {+ for (const listener of mediaListeners) {+ listener();+ }+ });+}++beforeAll(async () => {+ // The sheet loads on demand; load it once so the first open in a test does+ // not wait on the import.+ await import('../BottomSheet/BottomSheet');+});++beforeEach(() => {+ isCompactTouch = false;+ mediaListeners.clear();+ // jsdom implements no <dialog> open/close or pointer capture.+ HTMLDialogElement.prototype.showModal = vi.fn(function (+ this: HTMLDialogElement,+ ) {+ this.setAttribute('open', '');+ });+ HTMLDialogElement.prototype.show = vi.fn(function (this: HTMLDialogElement) {+ this.setAttribute('open', '');+ });+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {+ this.removeAttribute('open');+ // A closed dialog fires `close`, as the browsers do.+ this.dispatchEvent(new Event('close'));+ });+ if (!Element.prototype.setPointerCapture) {+ Element.prototype.setPointerCapture = vi.fn();+ Element.prototype.releasePointerCapture = vi.fn();+ }+ vi.stubGlobal(+ 'matchMedia',+ vi.fn((query: string) => ({+ matches: query === COMPACT_TOUCH_QUERY ? isCompactTouch : false,+ media: query,+ onchange: null,+ addEventListener: vi.fn((_type: string, listener: () => void) => {+ mediaListeners.add(listener);+ }),+ removeEventListener: vi.fn((_type: string, listener: () => void) => {+ mediaListeners.delete(listener);+ }),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),+ );+ window.scrollTo = vi.fn();+});++afterEach(() => {+ vi.unstubAllGlobals();+});++function Filters({+ presentation,+ onOpenChange,+ hasLightDismiss,+ hasEscapeDismiss,+ hasCloseButton,+}: {+ presentation?: PopoverPresentation;+ onOpenChange?: (isOpen: boolean) => void;+ hasLightDismiss?: boolean;+ hasEscapeDismiss?: boolean;+ hasCloseButton?: boolean;+}) {+ return (+ <Popover+ label="Filters"+ presentation={presentation}+ onOpenChange={onOpenChange}+ hasLightDismiss={hasLightDismiss}+ hasEscapeDismiss={hasEscapeDismiss}+ hasCloseButton={hasCloseButton}+ content={<button type="button">Apply</button>}>+ <Button label="Filter">Filter</Button>+ </Popover>+ );+}++const trigger = () => screen.getByRole('button', {name: 'Filter'});+const compactQueryReads = () =>+ vi+ .mocked(window.matchMedia)+ .mock.calls.filter(([query]) => query === COMPACT_TOUCH_QUERY).length;+const sheetDialog = () =>+ document.querySelector<HTMLDialogElement>('dialog[aria-label="Filters"]');+const openLayer = () =>+ document.querySelector(+ '[popover]:has([role="dialog"][aria-label="Filters"])',+ );++async function tapTrigger() {+ await act(async () => {+ fireEvent.click(trigger());+ await Promise.resolve();+ });+}++describe('Popover presentation', () => {+ it('a closed sheet holds no observers or viewport listeners until it opens', async () => {+ isCompactTouch = true;+ const observed: string[] = [];+ const record = (kind: string, target: Node) => {+ // The root theme's attribute observer is the theme's, not the sheet's.+ if (target !== document.documentElement) {+ observed.push(kind);+ }+ };+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe(target: Element) {+ record('resize', target);+ }+ unobserve() {}+ disconnect() {}+ },+ );+ vi.stubGlobal(+ 'MutationObserver',+ class {+ observe(target: Node) {+ record('mutation', target);+ }+ disconnect() {}+ takeRecords() {+ return [];+ }+ },+ );+ const viewportListeners: string[] = [];+ const addWindowListener = window.addEventListener.bind(window);+ const recordWindowListener = (+ type: string,+ listener: EventListenerOrEventListenerObject,+ options?: boolean | AddEventListenerOptions,+ ) => {+ if (type === 'resize' || type === 'blur') {+ viewportListeners.push(type);+ }+ addWindowListener(type, listener, options);+ };+ vi.spyOn(window, 'addEventListener').mockImplementation(+ recordWindowListener,+ );++ render(<Filters presentation="adaptive" />);+ // The closed sheet is mounted at rest, in place of the anchored layer.+ await vi.waitFor(() => {+ expect(sheetDialog()).not.toBeNull();+ });+ expect(sheetDialog()).not.toHaveAttribute('open');+ expect(observed).toEqual([]);+ expect(viewportListeners).toEqual([]);++ // Opening attaches them.+ await tapTrigger();+ await vi.waitFor(() => {+ expect(observed.length).toBeGreaterThan(0);+ });+ });++ it('reads the compact-touch query only for an adaptive popover', async () => {+ const {unmount} = render(<Filters />);+ await tapTrigger();+ render(<Filters presentation="bottom-sheet" />);+ expect(compactQueryReads()).toBe(0);+ unmount();+ render(<Filters presentation="adaptive" />);+ expect(compactQueryReads()).toBeGreaterThan(0);+ });++ it('takes compact from the compact definition: a short landscape phone gets the sheet', async () => {+ // FR9 counts a screen shorter than 500 as compact whatever its width.+ expect(COMPACT_TOUCH_QUERY).toContain('height < 500px');+ isCompactTouch = true;+ render(<Filters presentation="adaptive" />);+ await tapTrigger();+ expect(sheetDialog()).not.toBeNull();+ });++ it("styles the sheet's panel with the caller's xstyle, className and style", async () => {+ render(+ <Popover+ label="Filters"+ presentation="bottom-sheet"+ className="caller-popover"+ style={{outlineWidth: 3}}+ content={<button type="button">Apply</button>}>+ <Button label="Filter">Filter</Button>+ </Popover>,+ );+ await tapTrigger();+ const styled = sheetDialog()?.querySelector<HTMLElement>('.caller-popover');+ expect(styled).not.toBeNull();+ expect(styled?.style.outlineWidth).toBe('3px');+ });++ it('stays anchored on a phone by default', async () => {+ isCompactTouch = true;+ render(<Filters />);+ await tapTrigger();+ expect(trigger()).toHaveAttribute('aria-expanded', 'true');+ expect(sheetDialog()).toBeNull();+ expect(openLayer()).not.toBeNull();+ });++ it('adaptive: a phone gets a BottomSheet holding the content, labeled by the popover', async () => {+ isCompactTouch = true;+ const onOpenChange = vi.fn();+ render(<Filters presentation="adaptive" onOpenChange={onOpenChange} />);+ await tapTrigger();+ const dialog = await vi.waitFor(() => {+ const element = sheetDialog();+ expect(element).toHaveAttribute('open');+ return element!;+ });+ expect(dialog.querySelector('button')).toHaveTextContent('Apply');+ expect(onOpenChange).toHaveBeenLastCalledWith(true);+ expect(trigger()).toHaveAttribute('aria-expanded', 'true');+ // The trigger controls the sheet's panel, not the hidden layer.+ const controlled = document.getElementById(+ trigger().getAttribute('aria-controls') ?? '',+ );+ expect(controlled).not.toBeNull();+ expect(dialog.contains(controlled)).toBe(true);+ expect(document.querySelector('[popover]:popover-open')).toBeNull();+ });++ it('a sheet without a label is named by the trigger\u2019s text, never an unnamed dialog (DEC-8)', async () => {+ isCompactTouch = true;+ render(+ <Popover+ presentation="adaptive"+ content={<button type="button">Apply</button>}>+ <Button label="Sort by">Sort by</Button>+ </Popover>,+ );+ await act(async () => {+ fireEvent.click(screen.getByRole('button', {name: 'Sort by'}));+ await Promise.resolve();+ });+ const dialog = await vi.waitFor(() => {+ const element = document.querySelector<HTMLDialogElement>('dialog');+ expect(element).toHaveAttribute('open');+ return element!;+ });+ expect(dialog).toHaveAttribute('aria-label', 'Sort by');+ });++ it('a render-prop trigger without a label names the sheet with its text (DEC-8)', async () => {+ isCompactTouch = true;+ render(+ <Popover+ presentation="adaptive"+ content={<button type="button">Apply</button>}>+ {triggerProps => (+ <button type="button" {...triggerProps}>+ Group by+ </button>+ )}+ </Popover>,+ );+ await act(async () => {+ fireEvent.click(screen.getByRole('button', {name: 'Group by'}));+ await Promise.resolve();+ });+ const dialog = await vi.waitFor(() => {+ const element = document.querySelector<HTMLDialogElement>('dialog');+ expect(element).toHaveAttribute('open');+ return element!;+ });+ expect(dialog).toHaveAttribute('aria-label', 'Group by');+ });++ it('a sheet with hasEscapeDismiss={false} leaves Escape on for a sheet opened inside it', async () => {+ isCompactTouch = true;+ const onInnerOpenChange = vi.fn();+ render(+ <Popover+ label="Filters"+ presentation="adaptive"+ hasEscapeDismiss={false}+ content={+ <BottomSheet+ isOpen+ onOpenChange={onInnerOpenChange}+ label="Inner sheet">+ Inner+ </BottomSheet>+ }>+ <Button label="Filter">Filter</Button>+ </Popover>,+ );+ await tapTrigger();+ const inner = await vi.waitFor(() => {+ const element = document.querySelector<HTMLDialogElement>(+ 'dialog[aria-label="Inner sheet"]',+ );+ expect(element).not.toBeNull();+ return element!;+ });+ act(() => {+ fireEvent.keyDown(inner, {key: 'Escape'});+ });+ expect(onInnerOpenChange).toHaveBeenCalledWith(false);+ });++ it('the sheet focuses the first content control, as the anchored popover does (FR2)', async () => {+ isCompactTouch = true;+ render(+ <Popover+ label="Filters"+ presentation="adaptive"+ content={+ <div>+ <p>Status</p>+ <button type="button">Apply</button>+ </div>+ }>+ <Button label="Filter">Filter</Button>+ </Popover>,+ );+ await tapTrigger();+ await vi.waitFor(() => {+ expect(document.activeElement).toBe(+ screen.getByRole('button', {name: 'Apply'}),+ );+ });+ });++ it('a sheet with read-only content focuses its labelled surface (FR2)', async () => {+ isCompactTouch = true;+ render(+ <Popover+ label="About this filter"+ presentation="adaptive"+ content={<p>Shows open items only.</p>}>+ <Button label="Filter">Filter</Button>+ </Popover>,+ );+ await tapTrigger();+ await vi.waitFor(() => {+ expect(document.activeElement).toBe(+ screen.getByRole('group', {name: 'About this filter'}),+ );+ });+ });++ it('an overflowing sheet still focuses its first content control, not its scroll area (FR2)', async () => {+ isCompactTouch = true;+ render(+ <Popover+ label="Filters"+ presentation="adaptive"+ content={<button type="button">Apply</button>}>+ <Button label="Filter">Filter</Button>+ </Popover>,+ );+ // The closed sheet is mounted at rest. BottomSheet's scroll area becomes a+ // tab stop when its content overflows: make it one before opening.+ const panel = await vi.waitFor(() => {+ const element =+ sheetDialog()?.querySelector<HTMLElement>('[tabindex="-1"]');+ expect(element).toBeTruthy();+ return element!;+ });+ for (const child of Array.from(panel.children)) {+ (child as HTMLElement).tabIndex = 0;+ }+ await tapTrigger();+ await vi.waitFor(() => {+ expect(document.activeElement).toBe(+ screen.getByRole('button', {name: 'Apply'}),+ );+ });+ });++ it('the sheet focuses its first content control again at each opening (FR2)', async () => {+ isCompactTouch = true;+ render(+ <Popover+ label="Filters"+ presentation="bottom-sheet"+ content={<button type="button">Apply</button>}>+ <Button label="Filter">Filter</Button>+ </Popover>,+ );+ const apply = () => screen.getByRole('button', {name: 'Apply'});+ await tapTrigger();+ await vi.waitFor(() => expect(document.activeElement).toBe(apply()));+ // A second tap on the trigger closes the sheet; a third opens it again.+ await tapTrigger();+ // The exit ends on the panel's transform transition, which jsdom never+ // runs: end it by hand.+ const panel = document.querySelector('dialog [tabindex="-1"]');+ if (panel != null) {+ fireEvent.transitionEnd(panel, {propertyName: 'transform'});+ }+ await vi.waitFor(+ () => expect(document.querySelector('dialog[open]')).toBeNull(),+ {timeout: 3000},+ );+ act(() => {+ (document.activeElement as HTMLElement | null)?.blur();+ });+ await tapTrigger();+ await vi.waitFor(() => expect(document.activeElement).toBe(apply()));+ });++ it('adaptive: a desktop keeps the anchored popover', async () => {+ render(<Filters presentation="adaptive" />);+ await tapTrigger();+ expect(trigger()).toHaveAttribute('aria-expanded', 'true');+ expect(sheetDialog()).toBeNull();+ expect(openLayer()).not.toBeNull();+ });++ it('bottom-sheet: the sheet on any screen', async () => {+ render(<Filters presentation="bottom-sheet" />);+ await tapTrigger();+ await vi.waitFor(() => {+ expect(sheetDialog()).toHaveAttribute('open');+ });+ });++ it('closing the sheet reports it and collapses the trigger', async () => {+ isCompactTouch = true;+ const onOpenChange = vi.fn();+ render(<Filters presentation="adaptive" onOpenChange={onOpenChange} />);+ await tapTrigger();+ const dialog = await vi.waitFor(() => {+ const element = sheetDialog();+ expect(element).toHaveAttribute('open');+ return element!;+ });+ act(() => {+ fireEvent.keyDown(dialog, {key: 'Escape'});+ });+ expect(onOpenChange).toHaveBeenLastCalledWith(false);+ expect(trigger()).toHaveAttribute('aria-expanded', 'false');+ });++ it('controlled: isOpen drives the sheet, and the trigger asks to close it', async () => {+ isCompactTouch = true;+ const changes: boolean[] = [];+ function Controlled() {+ const [isOpen, setIsOpen] = useState(false);+ return (+ <>+ <button type="button" onClick={() => setIsOpen(true)}>+ Open from outside+ </button>+ <Popover+ label="Filters"+ presentation="adaptive"+ isOpen={isOpen}+ onOpenChange={next => {+ changes.push(next);+ setIsOpen(next);+ }}+ content={<button type="button">Apply</button>}>+ <Button label="Filter">Filter</Button>+ </Popover>+ </>+ );+ }+ render(<Controlled />);+ await act(async () => {+ fireEvent.click(screen.getByRole('button', {name: 'Open from outside'}));+ await Promise.resolve();+ });+ await vi.waitFor(() => {+ expect(sheetDialog()).toHaveAttribute('open');+ });+ expect(trigger()).toHaveAttribute('aria-expanded', 'true');+ await tapTrigger();+ expect(changes).toEqual([false]);+ expect(trigger()).toHaveAttribute('aria-expanded', 'false');+ });++ it('holds one instance of the content: the sheet\u2019s, while the sheet is the surface', async () => {+ isCompactTouch = true;+ render(<Filters presentation="adaptive" />);+ // Before it opens, the content sits where an open would show it.+ expect(+ screen.getAllByRole('button', {name: 'Apply', hidden: true}),+ ).toHaveLength(1);+ await tapTrigger();+ await vi.waitFor(() => {+ expect(sheetDialog()).toHaveAttribute('open');+ });+ const applies = screen.getAllByRole('button', {+ name: 'Apply',+ hidden: true,+ });+ expect(applies).toHaveLength(1);+ expect(sheetDialog()!.contains(applies[0])).toBe(true);+ });++ it('a sheet light-dismisses whatever hasLightDismiss says: a tap outside closes it (DEC-8)', async () => {+ isCompactTouch = true;+ const onOpenChange = vi.fn();+ render(+ <Filters+ presentation="adaptive"+ hasLightDismiss={false}+ hasEscapeDismiss={false}+ onOpenChange={onOpenChange}+ />,+ );+ await tapTrigger();+ const dialog = await vi.waitFor(() => {+ const element = sheetDialog();+ expect(element).toHaveAttribute('open');+ return element!;+ });+ // Never an alertdialog: the sheet always has a way out.+ expect(dialog).not.toHaveAttribute('role', 'alertdialog');+ // The scrim is the dialog element itself.+ act(() => {+ fireEvent.click(dialog);+ });+ expect(onOpenChange).toHaveBeenLastCalledWith(false);+ expect(trigger()).toHaveAttribute('aria-expanded', 'false');+ });++ it('a swipe down closes a sheet with hasLightDismiss={false} (DEC-8)', async () => {+ isCompactTouch = true;+ const onOpenChange = vi.fn();+ render(+ <Filters+ presentation="adaptive"+ hasLightDismiss={false}+ hasEscapeDismiss={false}+ onOpenChange={onOpenChange}+ />,+ );+ await tapTrigger();+ const handle = await vi.waitFor(() => {+ const element = sheetDialog()?.querySelector<HTMLElement>(+ '.astryx-bottom-sheet [aria-hidden="true"]',+ );+ expect(element).not.toBeNull();+ return element!;+ });+ // jsdom's PointerEvents carry no clientY, so these carry the coordinates+ // the sheet's drag reads.+ act(() => {+ fireEvent.pointerDown(handle, {+ pointerId: 1,+ clientY: 0,+ button: 0,+ isPrimary: true,+ });+ fireEvent.pointerMove(handle, {pointerId: 1, clientY: 40});+ fireEvent.pointerMove(handle, {pointerId: 1, clientY: 120});+ fireEvent.pointerUp(handle, {pointerId: 1, clientY: 120});+ });+ expect(onOpenChange).toHaveBeenLastCalledWith(false);+ });++ it('in a sheet, Escape follows hasEscapeDismiss', async () => {+ isCompactTouch = true;+ const onOpenChange = vi.fn();+ const {unmount} = render(+ <Filters+ presentation="adaptive"+ hasEscapeDismiss={false}+ onOpenChange={onOpenChange}+ />,+ );+ await tapTrigger();+ const blocked = await vi.waitFor(() => {+ const element = sheetDialog();+ expect(element).toHaveAttribute('open');+ return element!;+ });+ onOpenChange.mockClear();+ act(() => {+ fireEvent.keyDown(blocked, {key: 'Escape'});+ fireEvent(blocked, new Event('cancel', {cancelable: true}));+ });+ expect(onOpenChange).not.toHaveBeenCalled();+ unmount();++ render(<Filters presentation="adaptive" onOpenChange={onOpenChange} />);+ await tapTrigger();+ const allowed = await vi.waitFor(() => {+ const element = sheetDialog();+ expect(element).toHaveAttribute('open');+ return element!;+ });+ act(() => {+ fireEvent.keyDown(allowed, {key: 'Escape'});+ });+ expect(onOpenChange).toHaveBeenLastCalledWith(false);+ });++ it('keeps the fallback close control in the sheet, hidden until reached, as the anchored surface does', async () => {+ isCompactTouch = true;+ const onOpenChange = vi.fn();+ render(<Filters presentation="adaptive" onOpenChange={onOpenChange} />);+ await tapTrigger();+ const close = await vi.waitFor(() => {+ const element = sheetDialog()?.querySelector<HTMLElement>(+ 'button[data-astryx-popover-fallback-close]',+ );+ expect(element).not.toBeNull();+ return element!;+ });+ expect(close).toHaveTextContent('Close popover');+ // The Button itself carries the hidden-until-focused styles: no wrapper+ // element (architecture:component-style-authoring INV7).+ expect(+ close.parentElement?.closest('[data-astryx-popover-fallback-close]'),+ ).toBeNull();+ act(() => {+ fireEvent.click(close);+ });+ expect(onOpenChange).toHaveBeenLastCalledWith(false);+ });++ it('controlled: a phone turned past the compact width keeps its sheet until it closes', async () => {+ isCompactTouch = true;+ const changes: boolean[] = [];+ function Controlled() {+ const [isOpen, setIsOpen] = useState(true);+ return (+ <Popover+ label="Filters"+ presentation="adaptive"+ isOpen={isOpen}+ onOpenChange={next => {+ changes.push(next);+ setIsOpen(next);+ }}+ content={<button type="button">Apply</button>}>+ <Button label="Filter">Filter</Button>+ </Popover>+ );+ }+ render(<Controlled />);+ await vi.waitFor(() => {+ expect(sheetDialog()).toHaveAttribute('open');+ });+ // Landscape on a wide phone: no longer a compact touch screen.+ setCompactTouch(false);+ expect(sheetDialog()).toHaveAttribute('open');+ expect(document.querySelector('[popover]:popover-open')).toBeNull();+ expect(changes).toEqual([]);+ expect(trigger()).toHaveAttribute('aria-expanded', 'true');+ });++ it('adaptive: a sheet closed after the screen stops being compact plays its exit and hands focus back to the trigger', async () => {+ isCompactTouch = true;+ const closedWhileConnected: boolean[] = [];+ const close = HTMLDialogElement.prototype.close;+ HTMLDialogElement.prototype.close = vi.fn(function (+ this: HTMLDialogElement,+ ) {+ closedWhileConnected.push(this.isConnected);+ close.call(this);+ });+ render(<Filters presentation="adaptive" />);+ trigger().focus();+ await tapTrigger();+ const dialog = await vi.waitFor(() => {+ const element = sheetDialog();+ expect(element).toHaveAttribute('open');+ return element!;+ });+ // An iPad mini turned to landscape: no longer a compact touch screen.+ setCompactTouch(false);+ act(() => {+ fireEvent.keyDown(dialog, {key: 'Escape'});+ });+ expect(trigger()).toHaveAttribute('aria-expanded', 'false');+ // The sheet that was open stays mounted through its exit.+ expect(dialog.isConnected).toBe(true);+ const panel = dialog.querySelector<HTMLElement>('.astryx-bottom-sheet');+ expect(panel).not.toBeNull();+ act(() => {+ fireEvent.transitionEnd(panel!, {propertyName: 'transform'});+ });+ // Its dialog closes in the document, and focus is back on the trigger.+ expect(dialog).not.toHaveAttribute('open');+ expect(closedWhileConnected).toEqual([true]);+ expect(document.activeElement).toBe(trigger());+ // The next open on the wide screen is the anchored popover, with the+ // content.+ await tapTrigger();+ await vi.waitFor(() => {+ expect(openLayer()).not.toBeNull();+ });+ expect(openLayer()).toHaveTextContent('Apply');+ });++ it('mounts one presentation at a time, with the content once', async () => {+ // The elements a render adds to the document.+ let before = 0;+ const elements = () => document.body.querySelectorAll('*').length - before;+ // A desktop: the anchored layer, at rest and open.+ before = document.body.querySelectorAll('*').length;+ const desktop = render(<Filters presentation="adaptive" />);+ const desktopAtRest = elements();+ await tapTrigger();+ const desktopOpen = elements();+ desktop.unmount();+ // A compact touch screen: the closed sheet stands in place of the+ // anchored layer, holding the content, with no more elements.+ isCompactTouch = true;+ before = document.body.querySelectorAll('*').length;+ render(<Filters presentation="adaptive" />);+ const dialog = await vi.waitFor(() => {+ const element = sheetDialog();+ expect(element).not.toBeNull();+ return element!;+ });+ expect(dialog).not.toHaveAttribute('open');+ expect(document.querySelector('[popover]')).toBeNull();+ expect(+ screen.getAllByRole('button', {name: 'Apply', hidden: true}),+ ).toHaveLength(1);+ const touchAtRest = elements();+ expect(touchAtRest).toBeLessThanOrEqual(desktopAtRest);+ // Open: still the one presentation.+ await tapTrigger();+ await vi.waitFor(() => {+ expect(dialog).toHaveAttribute('open');+ });+ expect(document.querySelector('[popover]')).toBeNull();+ expect(screen.getAllByRole('button', {name: 'Apply'})).toHaveLength(1);+ // Open under touch, the sheet adds at most its edge tint, within the+ // open-layer allowance (spec:AST-017 FR60).+ expect(elements()).toBeLessThanOrEqual(desktopOpen + 1);+ // Closed: the sheet stays, closed, as it was at rest.+ act(() => {+ fireEvent.keyDown(dialog, {key: 'Escape'});+ });+ act(() => {+ fireEvent.transitionEnd(+ dialog.querySelector<HTMLElement>('.astryx-bottom-sheet')!,+ {propertyName: 'transform'},+ );+ });+ expect(dialog).not.toHaveAttribute('open');+ expect(sheetDialog()).toBe(dialog);+ expect(elements()).toBe(touchAtRest);+ });++ it('keeps state in the content across sheet openings, as the anchored popover does', async () => {+ isCompactTouch = true;+ render(+ <Popover+ label="Filters"+ presentation="adaptive"+ content={<input type="checkbox" aria-label="Archived" />}>+ <Button label="Filter">Filter</Button>+ </Popover>,+ );+ await tapTrigger();+ const dialog = await vi.waitFor(() => {+ const element = sheetDialog();+ expect(element).toHaveAttribute('open');+ return element!;+ });+ act(() => {+ fireEvent.click(screen.getByRole('checkbox', {name: 'Archived'}));+ });+ expect(screen.getByRole('checkbox', {name: 'Archived'})).toBeChecked();+ act(() => {+ fireEvent.keyDown(dialog, {key: 'Escape'});+ });+ act(() => {+ fireEvent.transitionEnd(+ dialog.querySelector<HTMLElement>('.astryx-bottom-sheet')!,+ {propertyName: 'transform'},+ );+ });+ await tapTrigger();+ await vi.waitFor(() => {+ expect(sheetDialog()).toHaveAttribute('open');+ });+ expect(screen.getByRole('checkbox', {name: 'Archived'})).toBeChecked();+ });++ it('a trigger whose popover has no dialog role says it opens a dialog while the sheet is the surface', async () => {+ const Menu = () => (+ <Popover+ label="Filters"+ role="none"+ presentation="adaptive"+ content={<button type="button">Apply</button>}>+ <Button label="Filter">Filter</Button>+ </Popover>+ );+ // A desktop: the anchored layer, which is not a dialog.+ const desktop = render(<Menu />);+ expect(trigger()).toHaveAttribute('aria-haspopup', 'true');+ desktop.unmount();+ // A compact touch screen: the sheet, a modal dialog.+ isCompactTouch = true;+ render(<Menu />);+ await vi.waitFor(() => {+ expect(trigger()).toHaveAttribute('aria-haspopup', 'dialog');+ });+ await tapTrigger();+ await vi.waitFor(() => {+ expect(sheetDialog()).toHaveAttribute('open');+ });+ expect(trigger()).toHaveAttribute('aria-haspopup', 'dialog');+ });++ it('a sheet with neither dismissal renders no more elements than the anchored popover', async () => {+ const Required = () => (+ <Popover+ label="Filters"+ presentation="adaptive"+ hasLightDismiss={false}+ hasEscapeDismiss={false}+ content={<p>Showing archived items</p>}>+ <Button label="Filter">Filter</Button>+ </Popover>+ );+ let before = 0;+ const elements = () => document.body.querySelectorAll('*').length - before;+ // A desktop: the anchored popover, open.+ before = document.body.querySelectorAll('*').length;+ const desktop = render(<Required />);+ await tapTrigger();+ const anchoredOpen = elements();+ desktop.unmount();+ // A phone: the sheet, open. BottomSheet's frame (the dialog, the panel,+ // its grab bar, body and content box) matches the anchored layer's+ // (sentinel, layer, surface, content box, fallback wrapper), and the+ // sheet's Close button is the Button itself.+ isCompactTouch = true;+ before = document.body.querySelectorAll('*').length;+ render(<Required />);+ await tapTrigger();+ await vi.waitFor(() => {+ expect(sheetDialog()).toHaveAttribute('open');+ });+ // Plus the edge tint, its own element while presented (spec:AST-017 FR60).+ expect(elements()).toBe(anchoredOpen + 1);+ });++ it('without a Theme provider, adaptive measures compact against the registered root theme', async () => {+ defineTheme({+ name: 'root-popover-points',+ adaptations: {widthBreakpoints: {md: 900}},+ });+ const originalGetAttribute = document.documentElement.getAttribute.bind(+ document.documentElement,+ );+ const rootTheme = vi+ .spyOn(document.documentElement, 'getAttribute')+ .mockImplementation(name =>+ name === 'data-astryx-theme'+ ? 'root-popover-points'+ : originalGetAttribute(name),+ );+ try {+ render(<Filters presentation="adaptive" />);+ expect(window.matchMedia).toHaveBeenCalledWith(+ compactDefinition({md: 900}).coarsePointerQuery,+ );+ expect(window.matchMedia).not.toHaveBeenCalledWith(COMPACT_TOUCH_QUERY);+ } finally {+ rootTheme.mockRestore();+ }+ });++ it('a render-prop trigger gets the sheet state', async () => {+ isCompactTouch = true;+ render(+ <Popover+ label="Filters"+ presentation="adaptive"+ content={<button type="button">Apply</button>}>+ {props => (+ <button type="button" {...props}>+ Filter+ </button>+ )}+ </Popover>,+ );+ await tapTrigger();+ await vi.waitFor(() => {+ expect(sheetDialog()).toHaveAttribute('open');+ });+ expect(trigger()).toHaveAttribute('aria-expanded', 'true');+ expect(+ sheetDialog()!.contains(+ document.getElementById(trigger().getAttribute('aria-controls') ?? ''),+ ),+ ).toBe(true);+ });+});++// Keeps React in scope for the JSX runtime in this file.+void React;diff --git a/packages/core/src/Popover/index.ts b/packages/core/src/Popover/index.tsindex c6c46c0c9f..8338651173 100644--- a/packages/core/src/Popover/index.ts+++ b/packages/core/src/Popover/index.ts@@ -17,4 +17,8 @@ export type {UsePopoverOptions, UsePopoverReturn} from './usePopover';// Popover componentexport {Popover} from './Popover';-export type {PopoverProps, PopoverTriggerRenderProps} from './Popover';+export type {+ PopoverPresentation,+ PopoverProps,+ PopoverTriggerRenderProps,+} from './Popover';diff --git a/packages/core/src/Popover/lazyPopoverBottomSheet.ts b/packages/core/src/Popover/lazyPopoverBottomSheet.tsnew file mode 100644index 0000000000..36ebca56b0--- /dev/null+++ b/packages/core/src/Popover/lazyPopoverBottomSheet.ts@@ -0,0 +1,57 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file lazyPopoverBottomSheet.ts+ * @input Uses React lazy and Suspense, useIsHydrating and BottomSheet+ * @output Exports `PopoverBottomSheet`, a BottomSheet that loads on its first+ * render, and `preloadPopoverBottomSheet`, which loads it without rendering+ * @position Internal to Popover: the surface of its bottom-sheet presentation+ *+ * A Popover only renders a BottomSheet when its presentation asks for one, so+ * the sheet (and its gestures) loads on demand and stays out of pages whose+ * popovers stay anchored, as DropdownMenu's sheet does+ * (DropdownMenu/lazyMenuBottomSheet.ts). It renders nothing until the module+ * loads, and nothing on the server or in the render that hydrates server HTML+ * (spec:AST-013 FR9); the closed sheet has no visible markup.+ */++import {+ createElement,+ lazy,+ Suspense,+ type ComponentProps,+ type ReactElement,+} from 'react';+import type {BottomSheet as EagerBottomSheet} from '../BottomSheet/BottomSheet';+import {useIsHydrating} from '../hooks/useIsHydrating';++const loadBottomSheet = async () => import('../BottomSheet/BottomSheet');++const LazyBottomSheet = lazy(async () =>+ loadBottomSheet().then(module => ({+ default: module.BottomSheet,+ })),+);++/**+ * Loads the sheet's module with nothing rendered, so a Popover whose sheet+ * can be the surface opens it at once.+ */+export function preloadPopoverBottomSheet(): void {+ void loadBottomSheet();+}++export function PopoverBottomSheet(+ props: ComponentProps<typeof EagerBottomSheet>,+): ReactElement | null {+ if (useIsHydrating()) {+ return null;+ }+ return createElement(+ Suspense,+ {fallback: null},+ createElement(LazyBottomSheet, props),+ );+}diff --git a/packages/core/src/theme/useTheme.ts b/packages/core/src/theme/useTheme.tsindex 3ca35ad4bc..a260f20ccf 100644--- a/packages/core/src/theme/useTheme.ts+++ b/packages/core/src/theme/useTheme.ts@@ -239,13 +239,19 @@ export function useThemeName(): string | null {/*** Return the nearest theme object, falling back to the registered root theme- * only when no provider context is available.+ * only when no provider context is available. With `enabled` false it reads+ * nothing and subscribes to nothing, for a consumer that needs the theme only+ * in some configurations.* @internal*/-export function useThemeDefinition(): DefinedTheme | undefined {- const ctx = use(ThemeContext);+export function useThemeDefinition(enabled = true): DefinedTheme | undefined {+ // `use` may be called conditionally, unlike the other hooks.+ const ctx = enabled ? use(ThemeContext) : null;const hasCtx = ctx != null;- const rootThemeName = useRootThemeNameAttr(hasCtx);+ const rootThemeName = useRootThemeNameAttr(hasCtx || !enabled);+ if (!enabled) {+ return undefined;+ }return ctx?.theme ?? getRegisteredTheme(rootThemeName) ?? undefined;}