An open source design system that's fully customizable and agent ready
TypeScript
Improve DropdownMenu responsive fit and presentation guidance (#5395)
rubyycheung98dd9837fb6c
diff --git a/.changeset/adaptive-menu-presentation.md b/.changeset/adaptive-menu-presentation.mdnew file mode 100644index 0000000000..33322417c5--- /dev/null+++ b/.changeset/adaptive-menu-presentation.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[component] Add built-in `popover`, `bottom-sheet`, and compact-touch `adaptive` presentation policies to DropdownMenu, MoreMenu, and ContextMenu.++@rubycheungdiff --git a/.changeset/adaptive-selector-presentation.md b/.changeset/adaptive-selector-presentation.mdnew file mode 100644index 0000000000..0d740c16ec--- /dev/null+++ b/.changeset/adaptive-selector-presentation.md@@ -0,0 +1,8 @@+---+'@astryxdesign/core': patch+'@astryxdesign/cli': patch+---++[component] Add popover, bottom-sheet, and adaptive presentation options to Selector and MultiSelector, with docsite examples for both bottom-sheet variants.++@rubyycheungdiff --git a/.changeset/dropdown-menu-responsive-fit.md b/.changeset/dropdown-menu-responsive-fit.mdnew file mode 100644index 0000000000..6e054597c0--- /dev/null+++ b/.changeset/dropdown-menu-responsive-fit.md@@ -0,0 +1,9 @@+---+'@astryxdesign/core': patch+---++[fix] Keep DropdownMenu and submenu flyouts inside the viewport with safe inline gutters and viewport-aware height limits. Only overflowing menus become internal scroll containers, while `menuWidth` keeps its existing minimum-width behavior up to the available space.++[feat] Add an opt-in `presentation` prop for data-driven DropdownMenu instances so products can render the same actions as an anchored popover or a modal bottom sheet according to their own responsive input policy.++@rubycheungdiff --git a/apps/docsite/src/__tests__/data-extraction.test.ts b/apps/docsite/src/__tests__/data-extraction.test.tsindex 80599cb3e6..51ab0a0b1c 100644--- a/apps/docsite/src/__tests__/data-extraction.test.ts+++ b/apps/docsite/src/__tests__/data-extraction.test.ts@@ -969,6 +969,124 @@ describe('Card playground defaults', () => {});});+describe('DropdownMenu adaptive-presentation example', () => {+ it('documents the presentation choice for the Properties tab', () => {+ const dropdownMenu = Object.values(components)+ .flat()+ .find(component => component.name === 'DropdownMenu');+ const presentation = dropdownMenu?.props.find(+ prop => prop.name === 'presentation',+ );++ expect(presentation?.type).toBe("'popover' | 'bottom-sheet' | 'adaptive'");+ expect(presentation?.default).toBe("'popover'");++ const defaults = dropdownMenu?.playground?.defaults as+ Record<string, unknown> | undefined;+ const items = defaults?.items as+ Array<{label?: unknown; icon?: unknown}> | undefined;+ expect(items).toHaveLength(4);+ expect(items?.every(item => typeof item.icon === 'string')).toBe(true);+ });++ it('registers the responsive presentation example on the related component pages', () => {+ const dropdownExamples = exampleRegistry['DropdownMenu'] ?? [];+ const bottomSheetExample = dropdownExamples.find(example =>+ /Adaptive presentation/i.test(example.name),+ );++ expect(bottomSheetExample).toBeDefined();+ expect(bottomSheetExample!.source).toContain('useMediaQuery');+ expect(bottomSheetExample!.source).toContain("'bottom-sheet' : 'popover'");+ expect(bottomSheetExample!.source).toContain('<DropdownMenu');++ const bottomSheetExamples = exampleRegistry['BottomSheet'] ?? [];+ expect(+ bottomSheetExamples.some(+ example => example.source === bottomSheetExample!.source,+ ),+ ).toBe(true);++ const mediaQueryExamples = exampleRegistry['useMediaQuery'] ?? [];+ expect(+ mediaQueryExamples.some(+ example => example.source === bottomSheetExample!.source,+ ),+ ).toBe(true);+ });++ it('registers the ContextMenu BottomSheet example', () => {+ const contextMenuExamples = exampleRegistry['ContextMenu'] ?? [];+ const bottomSheetExample = contextMenuExamples.find(example =>+ /Bottom Sheet/i.test(example.name),+ );++ expect(bottomSheetExample).toBeDefined();+ expect(bottomSheetExample!.source).toContain('presentation="bottom-sheet"');+ expect(bottomSheetExample!.source).toContain(+ 'Long-press on touch or right-click',+ );+ expect(bottomSheetExample!.source).not.toContain("type: 'divider'");+ });++ it('uses adaptive presentation in the primary ContextMenu example', () => {+ const contextMenuExamples = exampleRegistry['ContextMenu'] ?? [];+ const basicExample = contextMenuExamples.find(example =>+ /Basic/i.test(example.name),+ );++ expect(basicExample).toBeDefined();+ expect(basicExample!.source).toContain('presentation="adaptive"');+ expect(basicExample!.source).toContain('Long-press or right-click');+ });++ it('registers the MoreMenu BottomSheet example', () => {+ const moreMenuExamples = exampleRegistry['MoreMenu'] ?? [];+ const bottomSheetExample = moreMenuExamples.find(example =>+ /Bottom Sheet/i.test(example.name),+ );++ expect(bottomSheetExample).toBeDefined();+ expect(bottomSheetExample!.source).toContain('presentation="bottom-sheet"');+ expect(bottomSheetExample!.source).toContain('label="Project actions"');+ expect(bottomSheetExample!.source).not.toContain("type: 'divider'");+ });+});++describe('Selector bottom-sheet examples', () => {+ it.each(['Selector', 'MultiSelector'])(+ 'documents the %s presentation choice',+ componentName => {+ const component = Object.values(components)+ .flat()+ .find(entry => entry.name === componentName);+ const presentation = component?.props.find(+ prop => prop.name === 'presentation',+ );++ expect(presentation?.type).toBe(+ "'popover' | 'bottom-sheet' | 'adaptive'",+ );+ expect(presentation?.default).toBe("'popover'");+ },+ );++ it.each(['Selector', 'MultiSelector'])(+ 'registers the %s BottomSheet example',+ componentName => {+ const examples = exampleRegistry[componentName] ?? [];+ const bottomSheetExample = examples.find(example =>+ /Bottom Sheet/i.test(example.name),+ );++ expect(bottomSheetExample).toBeDefined();+ expect(bottomSheetExample!.source).toContain(+ 'presentation="bottom-sheet"',+ );+ },+ );+});+// ── Vertical ToggleButtonGroup example (#2707) ─────────────────────────────// ToggleButtonGroup supports orientation="vertical", but no docsite example// demonstrated it — the prop was undiscoverable without reading the APIdiff --git a/apps/storybook/stories/ContextMenu.stories.tsx b/apps/storybook/stories/ContextMenu.stories.tsxindex 902dda18b2..9ea22aa8dc 100644--- a/apps/storybook/stories/ContextMenu.stories.tsx+++ b/apps/storybook/stories/ContextMenu.stories.tsx@@ -58,6 +58,12 @@ const meta: Meta<typeof ContextMenu> = {control: 'boolean',description: 'Disable custom context menu',},+ presentation: {+ control: 'select',+ options: ['popover', 'bottom-sheet', 'adaptive'],+ description:+ 'Cursor popover, BottomSheet, or adaptive compact-touch presentation',+ },'data-testid': {control: 'text',description: 'Test ID for testing frameworks',@@ -387,3 +393,88 @@ export const WithSelectableItems: Story = {},},};++export const BottomSheetPresentation: Story = {+ name: 'Presentation / BottomSheet',+ parameters: {+ layout: 'fullscreen',+ viewport: {defaultViewport: 'mobile1'},+ docs: {+ story: {inline: false, height: '560px'},+ description: {+ story:+ 'The real ContextMenu component forced to BottomSheet presentation. Long-press opens this surface on touch; this story opens it with a contextmenu event so the sheet is directly reviewable.',+ },+ },+ },+ render: () => (+ <div style={{padding: 16}}>+ <ContextMenu+ data-testid="bottom-sheet-context-menu"+ presentation="bottom-sheet"+ label="Document actions"+ items={[+ {label: 'Edit', icon: PencilIcon, onClick: () => {}},+ {+ label: 'Duplicate',+ icon: DocumentDuplicateIcon,+ onClick: () => {},+ },+ {label: 'Share', icon: ShareIcon, onClick: () => {}},+ {+ label: 'Delete',+ icon: TrashIcon,+ variant: 'destructive',+ onClick: () => {},+ },+ ]}>+ <div {...stylex.props(triggerStyles.area)}>+ Long-press or right-click for document actions+ </div>+ </ContextMenu>+ </div>+ ),+ play: async ({canvasElement}) => {+ const trigger = canvasElement.querySelector(+ '[data-testid="bottom-sheet-context-menu"]',+ );+ trigger?.dispatchEvent(+ new MouseEvent('contextmenu', {bubbles: true, clientX: 40, clientY: 40}),+ );+ },+};++export const AdaptivePresentation: Story = {+ name: 'Presentation / adaptive',+ parameters: {+ layout: 'fullscreen',+ viewport: {defaultViewport: 'mobile1'},+ docs: {+ description: {+ story:+ 'Uses the built-in adaptive policy: BottomSheet at 768px and below with a coarse primary pointer, cursor-positioned popover otherwise. Important actions still need a visible MoreMenu or equivalent entry point.',+ },+ },+ },+ render: () => (+ <div style={{padding: 16}}>+ <ContextMenu+ presentation="adaptive"+ label="Document actions"+ items={[+ {label: 'Edit', icon: PencilIcon, onClick: () => {}},+ {label: 'Share', icon: ShareIcon, onClick: () => {}},+ {+ label: 'Delete',+ icon: TrashIcon,+ variant: 'destructive',+ onClick: () => {},+ },+ ]}>+ <div {...stylex.props(triggerStyles.area)}>+ Long-press or right-click for document actions+ </div>+ </ContextMenu>+ </div>+ ),+};diff --git a/apps/storybook/stories/DropdownMenu.stories.tsx b/apps/storybook/stories/DropdownMenu.stories.tsxindex a8b8e4394c..f9a4791e65 100644--- a/apps/storybook/stories/DropdownMenu.stories.tsx+++ b/apps/storybook/stories/DropdownMenu.stories.tsx@@ -1,6 +1,7 @@// Copyright (c) Meta Platforms, Inc. and affiliates.import type {Meta, StoryObj} from '@storybook/react';+import * as stylex from '@stylexjs/stylex';import {Badge} from '@astryxdesign/core/Badge';import {useState} from 'react';import {@@ -12,6 +13,7 @@ import {DropdownMenuRadioItem,DropdownMenuSubMenu,} from '@astryxdesign/core/DropdownMenu';+import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';import {PencilIcon,TrashIcon,@@ -41,13 +43,19 @@ const meta: Meta<typeof DropdownMenu> = {items: {description: 'Menu items (items, dividers, or sections)',},+ presentation: {+ control: 'select',+ options: ['popover', 'bottom-sheet'],+ description: 'Surface used to present data-driven menu actions',+ },isMenuOpen: {control: 'boolean',description: 'Controlled open state',},menuWidth: {control: 'text',- description: 'Custom menu width (number for px or CSS string)',+ description:+ 'Minimum menu width for lengths, or preferred width for intrinsic keywords; capped to the available viewport space',},placement: {control: 'select',@@ -69,6 +77,81 @@ const meta: Meta<typeof DropdownMenu> = {export default meta;type Story = StoryObj<typeof DropdownMenu>;+const readinessStyles = stylex.create({+ viewportStoryCanvas: {+ boxSizing: 'border-box',+ inlineSize: '100%',+ minBlockSize: '100dvh',+ paddingBlockStart: spacingVars['--spacing-4'],+ paddingBlockEnd: spacingVars['--spacing-4'],+ paddingInlineStart: spacingVars['--spacing-4'],+ paddingInlineEnd: spacingVars['--spacing-4'],+ overflow: 'clip',+ },+ edgeAnchorRow: {+ display: 'flex',+ justifyContent: 'flex-end',+ },+});++const PROJECT_ACTIONS = [+ {+ label: 'Edit project',+ description: 'Update the project details.',+ icon: PencilIcon,+ },+ {+ label: 'Duplicate project',+ description: 'Create a copy of this project.',+ icon: DocumentDuplicateIcon,+ },+ {+ label: 'Share project',+ description: 'Invite people to collaborate.',+ icon: ShareIcon,+ },+ {+ label: 'Archive project',+ description: 'Move this project out of active work.',+ icon: ArchiveBoxIcon,+ },+] as const;++function CompactDrillInActionSheet() {+ return (+ <DropdownMenu+ button={{label: 'Project actions'}}+ presentation="bottom-sheet"+ items={[+ {label: 'Rename project', icon: PencilIcon},+ {+ label: 'Move to project',+ icon: FolderPlusIcon,+ items: PROJECT_DESTINATIONS.slice(0, 4).map(([label, team]) => ({+ label,+ description: team,+ icon: FolderPlusIcon,+ })),+ },+ {label: 'Archive project', icon: ArchiveBoxIcon},+ ]}+ />+ );+}++const PROJECT_DESTINATIONS = [+ ['Apollo launch', 'Marketing'],+ ['Customer insights', 'Research'],+ ['Design systems', 'Platform'],+ ['Growth experiments', 'Product'],+ ['Incident review', 'Operations'],+ ['Mobile quality', 'Engineering'],+ ['Quarterly planning', 'Strategy'],+ ['Recruiting plan', 'People'],+ ['Security follow-up', 'Trust'],+ ['Website refresh', 'Brand'],+] as const;+// Basic usageexport const Default: Story = {render: () => (@@ -869,3 +952,254 @@ export const ModeParity: Story = {</div>),};++// =============================================================================+// Responsive and Interaction Readiness Evidence+// =============================================================================++export const ActionSheetPresentation: Story = {+ name: 'Presentation / action sheet',+ parameters: {+ layout: 'fullscreen',+ docs: {+ story: {inline: false, height: '560px'},+ description: {+ story:+ 'Forces DropdownMenu’s bottom-sheet presentation for a short, flat set of actions. It uses BottomSheet behavior including dialog focus, a scrim, Escape, and swipe dismissal.',+ },+ },+ },+ globals: {viewport: {value: 'mobile1', isRotated: false}},+ render: () => (+ <div {...stylex.props(readinessStyles.viewportStoryCanvas)}>+ <DropdownMenu+ presentation="bottom-sheet"+ button={{label: 'Project actions'}}+ items={PROJECT_ACTIONS.map(action => ({+ ...action,+ onClick: () => console.log(`${action.label} selected`),+ }))}+ />+ </div>+ ),+ play: async ({canvasElement}) => {+ const trigger = canvasElement.querySelector('button');+ if (trigger instanceof HTMLElement) {+ trigger.click();+ }+ },+};++export const AdaptiveActionPresentation: Story = {+ name: 'Presentation / adaptive action menu',+ parameters: {+ layout: 'fullscreen',+ docs: {+ story: {inline: false, height: '560px'},+ description: {+ story:+ 'Uses DropdownMenu’s adaptive presentation: a BottomSheet on compact coarse-pointer layouts and an anchored popover elsewhere.',+ },+ },+ },+ globals: {viewport: {value: 'mobile1', isRotated: false}},+ render: () => (+ <div {...stylex.props(readinessStyles.viewportStoryCanvas)}>+ <DropdownMenu+ presentation="adaptive"+ button={{label: 'Project actions'}}+ items={PROJECT_ACTIONS.map(action => ({+ ...action,+ onClick: () => console.log(`${action.label} selected`),+ }))}+ />+ </div>+ ),+ play: async ({canvasElement}) => {+ const trigger = canvasElement.querySelector('button');+ if (trigger instanceof HTMLElement) {+ trigger.click();+ }+ },+};++export const CompactDrillInPresentation: Story = {+ name: 'Presentation / compact drill-in hierarchy',+ parameters: {+ layout: 'fullscreen',+ docs: {+ story: {inline: false, height: '560px'},+ description: {+ story:+ 'Uses DropdownMenu’s bottom-sheet presentation for a hierarchy that cannot fit as adjacent flyouts. Move to project drills into a second list with a Back action while BottomSheet owns the modal contract.',+ },+ },+ },+ globals: {viewport: {value: 'mobile1', isRotated: false}},+ render: () => (+ <div {...stylex.props(readinessStyles.viewportStoryCanvas)}>+ <CompactDrillInActionSheet />+ </div>+ ),+ play: async ({canvasElement}) => {+ const trigger = canvasElement.querySelector('button');+ if (trigger instanceof HTMLElement) {+ trigger.click();+ await new Promise<void>(resolve =>+ requestAnimationFrame(() => resolve()),+ );+ const submenuRow = Array.from(canvasElement.querySelectorAll('li')).find(+ item => item.textContent?.includes('Move to project'),+ );+ submenuRow?.querySelector('button')?.click();+ }+ },+};++export const CompactDrillInPresentationRTL: Story = {+ ...CompactDrillInPresentation,+ name: 'Presentation / compact drill-in hierarchy / RTL',+ globals: {+ viewport: {value: 'mobile1', isRotated: false},+ direction: 'rtl',+ },+};++export const ViewportFit: Story = {+ name: 'Readiness / viewport fit',+ parameters: {+ layout: 'fullscreen',+ docs: {+ description: {+ story:+ 'Uses the actual Storybook viewport. The menu requests a 640px minimum width near the inline edge and must keep 16px safe-area-aware gutters instead of widening the page.',+ },+ },+ },+ globals: {viewport: {value: 'mobile1', isRotated: false}},+ render: () => (+ <div {...stylex.props(readinessStyles.viewportStoryCanvas)}>+ <div {...stylex.props(readinessStyles.edgeAnchorRow)}>+ <DropdownMenu+ button={{label: 'Project actions'}}+ alignment="end"+ menuWidth={640}+ items={[+ {label: 'Rename project', onClick: () => {}},+ {label: 'Duplicate project', onClick: () => {}},+ {+ label: 'Share with external collaborators and reviewers',+ onClick: () => {},+ },+ {type: 'divider'},+ {label: 'Archive project', onClick: () => {}},+ ]}+ />+ </div>+ </div>+ ),+ play: async ({canvasElement}) => {+ const trigger = canvasElement.querySelector('button');+ if (trigger instanceof HTMLElement) {+ trigger.click();+ }+ },+};++export const TallContentOverflow: Story = {+ name: 'Readiness / tall content overflow',+ parameters: {+ layout: 'fullscreen',+ docs: {+ description: {+ story:+ 'Uses the actual Storybook viewport and a realistic project list. The anchored menu stays at or below 300px and scrolls internally, so its actions remain reachable without scrolling the page.',+ },+ },+ },+ globals: {viewport: {value: 'mobile1', isRotated: false}},+ render: () => (+ <div {...stylex.props(readinessStyles.viewportStoryCanvas)}>+ <DropdownMenu button={{label: 'Move to project'}} menuWidth={280}>+ {PROJECT_DESTINATIONS.map(([label, team]) => (+ <DropdownMenuItem+ key={label}+ label={label}+ description={team}+ onClick={() => {}}+ />+ ))}+ </DropdownMenu>+ </div>+ ),+ play: async ({canvasElement}) => {+ const trigger = canvasElement.querySelector('button');+ if (trigger instanceof HTMLElement) {+ trigger.click();+ }+ },+};++export const SubmenuViewportFit: Story = {+ name: 'Readiness / submenu edge fit',+ parameters: {+ layout: 'fullscreen',+ docs: {+ description: {+ story:+ 'Uses the actual Storybook viewport with concise parent and child menus that can fit side by side. The submenu flips toward the available side, remains separated from its parent, and stays within viewport gutters. Use the compact drill-in example when the hierarchy cannot fit this contract.',+ },+ },+ },+ globals: {viewport: {value: 'mobile1', isRotated: false}},+ render: () => (+ <div {...stylex.props(readinessStyles.viewportStoryCanvas)}>+ <div {...stylex.props(readinessStyles.edgeAnchorRow)}>+ <DropdownMenu+ button={{label: 'Project actions'}}+ alignment="end"+ menuWidth={140}>+ <DropdownMenuItem label="Rename" onClick={() => {}} />+ <DropdownMenuSubMenu label="Move to" menuWidth={140}>+ <DropdownMenuItem label="Research" onClick={() => {}} />+ <DropdownMenuItem label="Platform" onClick={() => {}} />+ <DropdownMenuItem label="Engineering" onClick={() => {}} />+ </DropdownMenuSubMenu>+ <DropdownMenuItem label="Archive" onClick={() => {}} />+ </DropdownMenu>+ </div>+ </div>+ ),+ play: async ({canvasElement}) => {+ const trigger = canvasElement.querySelector('button');+ if (!(trigger instanceof HTMLElement)) {+ return;+ }+ trigger.click();+ await new Promise<void>(resolve => requestAnimationFrame(() => resolve()));+ const submenuTrigger = canvasElement.querySelector(+ '[role="menuitem"][aria-haspopup="menu"]',+ );+ if (submenuTrigger instanceof HTMLElement) {+ submenuTrigger.click();+ await new Promise<void>(resolve =>+ requestAnimationFrame(() => resolve()),+ );++ const openMenus = Array.from(+ canvasElement.querySelectorAll<HTMLElement>('[role="menu"]'),+ ).filter(menu => menu.getClientRects().length > 0);+ const [parentMenu, submenu] = openMenus;+ if (parentMenu && submenu) {+ const parentRect = parentMenu.getBoundingClientRect();+ const submenuRect = submenu.getBoundingClientRect();+ const isSeparated =+ submenuRect.right <= parentRect.left ||+ submenuRect.left >= parentRect.right;+ if (!isSeparated) {+ throw new Error('Submenu must not overlap its parent menu');+ }+ }+ }+ },+};diff --git a/apps/storybook/stories/MoreMenu.stories.tsx b/apps/storybook/stories/MoreMenu.stories.tsxindex 3a5402397a..ad736177ae 100644--- a/apps/storybook/stories/MoreMenu.stories.tsx+++ b/apps/storybook/stories/MoreMenu.stories.tsx@@ -51,6 +51,12 @@ const meta: Meta<typeof MoreMenu> = {options: ['start', 'center', 'end'],description: 'Alignment of the menu along the placement axis',},+ presentation: {+ control: 'select',+ options: ['popover', 'bottom-sheet', 'adaptive'],+ description:+ 'Popover, BottomSheet, or adaptive compact-touch presentation',+ },'data-testid': {control: 'text',description: 'Test ID for testing frameworks',@@ -258,6 +264,82 @@ export const InToolbar: Story = {),};+export const BottomSheetPresentation: Story = {+ name: 'Presentation / BottomSheet',+ parameters: {+ layout: 'fullscreen',+ viewport: {defaultViewport: 'mobile1'},+ docs: {+ story: {inline: false, height: '560px'},+ description: {+ story:+ 'The real MoreMenu component using DropdownMenu’s BottomSheet presentation. Its visible kebab trigger remains the discoverable mobile entry point.',+ },+ },+ },+ render: () => (+ <div style={{padding: 16, display: 'flex', justifyContent: 'flex-end'}}>+ <MoreMenu+ presentation="bottom-sheet"+ label="Project actions"+ items={[+ {label: 'Edit', icon: PencilIcon, onClick: () => {}},+ {+ label: 'Duplicate',+ icon: DocumentDuplicateIcon,+ onClick: () => {},+ },+ {label: 'Share', icon: ShareIcon, onClick: () => {}},+ {+ label: 'Delete',+ icon: TrashIcon,+ variant: 'destructive',+ onClick: () => {},+ },+ ]}+ />+ </div>+ ),+ play: async ({canvasElement}) => {+ const trigger = canvasElement.querySelector('button');+ if (trigger instanceof HTMLElement) {+ trigger.click();+ }+ },+};++export const AdaptivePresentation: Story = {+ name: 'Presentation / adaptive',+ parameters: {+ layout: 'fullscreen',+ viewport: {defaultViewport: 'mobile1'},+ docs: {+ description: {+ story:+ 'Uses the built-in adaptive policy: BottomSheet at 768px and below with a coarse primary pointer, anchored popover otherwise. Use device emulation to exercise the touch branch.',+ },+ },+ },+ render: () => (+ <div style={{padding: 16, display: 'flex', justifyContent: 'flex-end'}}>+ <MoreMenu+ presentation="adaptive"+ label="Project actions"+ items={[+ {label: 'Edit', icon: PencilIcon, onClick: () => {}},+ {label: 'Share', icon: ShareIcon, onClick: () => {}},+ {+ label: 'Delete',+ icon: TrashIcon,+ variant: 'destructive',+ onClick: () => {},+ },+ ]}+ />+ </div>+ ),+};+// With custom item renderingexport const CustomItemRendering: Story = {render: () => (diff --git a/apps/storybook/stories/MultiSelector.stories.tsx b/apps/storybook/stories/MultiSelector.stories.tsxindex 03fae7dc17..3209214bc5 100644--- a/apps/storybook/stories/MultiSelector.stories.tsx+++ b/apps/storybook/stories/MultiSelector.stories.tsx@@ -27,6 +27,10 @@ const meta: Meta<typeof MultiSelector> = {placeholder: {control: 'text'},size: {control: 'radio', options: ['sm', 'md', 'lg']},variant: {control: 'radio', options: ['input', 'ghost']},+ presentation: {+ control: 'radio',+ options: ['popover', 'bottom-sheet', 'adaptive'],+ },triggerDisplay: {control: 'radio',options: ['count', 'labels', 'badges'],@@ -62,6 +66,22 @@ export const Default: Story = {},};+export const BottomSheetPresentation: Story = {+ render: () => {+ const [value, setValue] = useState<string[]>([]);+ return (+ <MultiSelector+ label="Teams"+ options={['Design', 'Engineering', 'Marketing', 'Operations']}+ value={value}+ onChange={setValue}+ hasSelectAll+ presentation="bottom-sheet"+ />+ );+ },+};+// With sectionsexport const Sections: Story = {render: () => {diff --git a/apps/storybook/stories/Selector.stories.tsx b/apps/storybook/stories/Selector.stories.tsxindex 717cae8961..14060a11c8 100644--- a/apps/storybook/stories/Selector.stories.tsx+++ b/apps/storybook/stories/Selector.stories.tsx@@ -71,6 +71,11 @@ const meta: Meta<typeof Selector> = {description:'Explicit menu placement. Leave unset for selected-item overlay behavior.',},+ presentation: {+ control: 'radio',+ options: ['popover', 'bottom-sheet', 'adaptive'],+ description: 'Popover, bottom sheet, or responsive presentation.',+ },isDisabled: {control: 'boolean',description: 'Whether the selector is disabled',@@ -132,6 +137,21 @@ export const Default: Story = {},};+export const BottomSheetPresentation: Story = {+ render: () => {+ const [value, setValue] = useState<string | undefined>();+ return (+ <Selector+ label="Team"+ options={['Design', 'Engineering', 'Marketing', 'Operations']}+ value={value}+ onChange={setValue}+ presentation="bottom-sheet"+ />+ );+ },+};+// With hidden labelexport const HiddenLabel: Story = {render: args => {diff --git a/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuBasic.doc.mjs b/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuBasic.doc.mjsindex 25b5b2d91a..842fcb7543 100644--- a/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuBasic.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuBasic.doc.mjs@@ -7,7 +7,7 @@ export const doc = {name: 'ContextMenu — Basic',displayName: 'ContextMenu — Basic',description:- 'A right-click area with action items and a divider separating a destructive action. Use to provide contextual actions for a specific element or region.',+ 'An adaptive context area: long-press opens a BottomSheet on compact touch screens, while right-click opens a cursor-positioned menu elsewhere.',isReady: true,aspectRatio: 16 / 9,componentsUsed: ['ContextMenu'],diff --git a/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuBasic.tsx b/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuBasic.tsxindex 0d04542268..b9fb8764e6 100644--- a/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuBasic.tsx+++ b/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuBasic.tsx@@ -7,6 +7,7 @@ import {ContextMenu} from '@astryxdesign/core/ContextMenu';export default function ContextMenuBasic() {return (<ContextMenu+ presentation="adaptive"items={[{label: 'Cut', onClick: () => {}},{label: 'Copy', onClick: () => {}},@@ -25,7 +26,7 @@ export default function ContextMenuBasic() {color: '#6b7280',userSelect: 'none',}}>- Right-click this area+ Long-press or right-click this area</div></ContextMenu>);diff --git a/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuBottomSheet.doc.mjs b/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuBottomSheet.doc.mjsnew file mode 100644index 0000000000..c4eacc4e85--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuBottomSheet.doc.mjs@@ -0,0 +1,14 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */+export const doc = {+ type: 'block',+ exampleFor: 'ContextMenu',+ name: 'ContextMenu — Bottom Sheet',+ displayName: 'ContextMenu — Bottom Sheet',+ description:+ 'A ContextMenu using the explicit BottomSheet presentation. Long-press the target on touch devices or right-click it with a pointer. Keep a visible menu trigger for important mobile actions.',+ isReady: true,+ aspectRatio: 4 / 3,+ componentsUsed: ['ContextMenu'],+};diff --git a/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuBottomSheet.tsx b/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuBottomSheet.tsxnew file mode 100644index 0000000000..fa6b8c5b17--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuBottomSheet.tsx@@ -0,0 +1,59 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {+ DocumentDuplicateIcon,+ PencilIcon,+ ShareIcon,+ TrashIcon,+} from '@heroicons/react/24/outline';+import {ContextMenu} from '@astryxdesign/core/ContextMenu';++export default function ContextMenuBottomSheet() {+ return (+ <ContextMenu+ presentation="bottom-sheet"+ label="Document actions"+ items={[+ {+ label: 'Rename document',+ description: 'Change the title shown to collaborators.',+ icon: PencilIcon,+ onClick: () => {},+ },+ {+ label: 'Duplicate document',+ description: 'Create a copy in the same workspace.',+ icon: DocumentDuplicateIcon,+ onClick: () => {},+ },+ {+ label: 'Share document',+ description: 'Invite people or copy a share link.',+ icon: ShareIcon,+ onClick: () => {},+ },+ {+ label: 'Delete document',+ description: 'Move this document to the trash.',+ icon: TrashIcon,+ variant: 'destructive',+ onClick: () => {},+ },+ ]}>+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ gap: '8px',+ padding: '32px',+ border: '1px solid #d1d5db',+ borderRadius: '12px',+ }}>+ <strong>Quarterly plan</strong>+ <span>Long-press on touch or right-click for document actions.</span>+ </div>+ </ContextMenu>+ );+}diff --git a/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuShowcase.doc.mjs b/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuShowcase.doc.mjsindex 3e60f5f835..8cd2ea75b0 100644--- a/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuShowcase.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuShowcase.doc.mjs@@ -6,7 +6,7 @@ export const doc = {name: 'ContextMenu',displayName: 'Context Menu',description:- 'A right-click area that opens a context menu with action items.',+ 'An adaptive context area that supports long-press on compact touch screens and right-click elsewhere.',isReady: true,isShowcase: true,aspectRatio: 1,diff --git a/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuShowcase.tsx b/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuShowcase.tsxindex 3280c57414..a8f2fb0ecb 100644--- a/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuShowcase.tsx+++ b/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuShowcase.tsx@@ -6,6 +6,7 @@ import {ContextMenu} from '@astryxdesign/core/ContextMenu';export default function ContextMenuShowcase() {return (<ContextMenu+ presentation="adaptive"items={[{label: 'Cut', onClick: () => {}},{label: 'Copy', onClick: () => {}},@@ -22,7 +23,7 @@ export default function ContextMenuShowcase() {color: '#6b7280',userSelect: 'none',}}>- Right-click this area+ Long-press or right-click this area</div></ContextMenu>);diff --git a/packages/cli/assets/templates/blocks/components/DropdownMenu/DropdownMenuBottomSheet.doc.mjs b/packages/cli/assets/templates/blocks/components/DropdownMenu/DropdownMenuBottomSheet.doc.mjsnew file mode 100644index 0000000000..ec7b7e0e85--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/DropdownMenu/DropdownMenuBottomSheet.doc.mjs@@ -0,0 +1,15 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */+export const doc = {+ type: 'block',+ exampleFor: 'DropdownMenu',+ alsoExampleFor: ['BottomSheet', 'useMediaQuery'],+ name: 'DropdownMenu — Adaptive presentation',+ displayName: 'DropdownMenu — Adaptive presentation',+ description:+ 'Chooses a bottom sheet for compact touch surfaces and an anchored popover otherwise. The media query is product policy, while DropdownMenu owns both presentations.',+ isReady: true,+ aspectRatio: 3 / 4,+ componentsUsed: ['DropdownMenu', 'Stack', 'Text', 'useMediaQuery'],+};diff --git a/packages/cli/assets/templates/blocks/components/DropdownMenu/DropdownMenuBottomSheet.tsx b/packages/cli/assets/templates/blocks/components/DropdownMenu/DropdownMenuBottomSheet.tsxnew file mode 100644index 0000000000..31981d8d37--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/DropdownMenu/DropdownMenuBottomSheet.tsx@@ -0,0 +1,49 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {useState} from 'react';+import {+ ArchiveBoxIcon,+ DocumentDuplicateIcon,+ PencilIcon,+ ShareIcon,+} from '@heroicons/react/24/outline';+import {DropdownMenu} from '@astryxdesign/core/DropdownMenu';+import {VStack} from '@astryxdesign/core/Stack';+import {Text} from '@astryxdesign/core/Text';+import {useMediaQuery} from '@astryxdesign/core/hooks';++const COMPACT_TOUCH_QUERY =+ '(max-width: 639px) and (pointer: coarse) and (hover: none)';++const ACTIONS = [+ {label: 'Edit project', icon: PencilIcon},+ {label: 'Duplicate project', icon: DocumentDuplicateIcon},+ {label: 'Share project', icon: ShareIcon},+ {label: 'Archive project', icon: ArchiveBoxIcon},+] as const;++export default function DropdownMenuBottomSheet() {+ const [lastAction, setLastAction] = useState<string | null>(null);+ const isCompactTouchSurface = useMediaQuery(COMPACT_TOUCH_QUERY);++ return (+ <VStack gap={3}>+ <DropdownMenu+ button={{label: 'Project actions'}}+ presentation={isCompactTouchSurface ? 'bottom-sheet' : 'popover'}+ items={ACTIONS.map(({label, icon}) => ({+ label,+ icon,+ onClick: () => setLastAction(label),+ }))}+ />+ {lastAction && (+ <Text type="supporting" color="secondary">+ Last action: {lastAction}+ </Text>+ )}+ </VStack>+ );+}diff --git a/packages/cli/assets/templates/blocks/components/MoreMenu/MoreMenuBottomSheet.doc.mjs b/packages/cli/assets/templates/blocks/components/MoreMenu/MoreMenuBottomSheet.doc.mjsnew file mode 100644index 0000000000..cec5baa4bf--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/MoreMenu/MoreMenuBottomSheet.doc.mjs@@ -0,0 +1,14 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */+export const doc = {+ type: 'block',+ exampleFor: 'MoreMenu',+ name: 'MoreMenu — Bottom Sheet',+ displayName: 'MoreMenu — Bottom Sheet',+ description:+ 'A visible overflow trigger that opens actions in a BottomSheet. Use this presentation for short action sets on compact touch surfaces.',+ isReady: true,+ aspectRatio: 4 / 3,+ componentsUsed: ['MoreMenu'],+};diff --git a/packages/cli/assets/templates/blocks/components/MoreMenu/MoreMenuBottomSheet.tsx b/packages/cli/assets/templates/blocks/components/MoreMenu/MoreMenuBottomSheet.tsxnew file mode 100644index 0000000000..45b4002937--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/MoreMenu/MoreMenuBottomSheet.tsx@@ -0,0 +1,63 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {+ DocumentDuplicateIcon,+ PencilIcon,+ ShareIcon,+ TrashIcon,+} from '@heroicons/react/24/outline';+import {MoreMenu} from '@astryxdesign/core/MoreMenu';++export default function MoreMenuBottomSheet() {+ return (+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ gap: '16px',+ width: 'min(100%, 360px)',+ padding: '16px',+ border: '1px solid #d1d5db',+ borderRadius: '12px',+ }}>+ <div style={{display: 'flex', flexDirection: 'column', gap: '4px'}}>+ <strong>Quarterly plan</strong>+ <span>Updated a few minutes ago</span>+ </div>+ <MoreMenu+ presentation="bottom-sheet"+ label="Project actions"+ items={[+ {+ label: 'Rename project',+ description: 'Update the project title.',+ icon: PencilIcon,+ onClick: () => {},+ },+ {+ label: 'Duplicate project',+ description: 'Create a copy in this workspace.',+ icon: DocumentDuplicateIcon,+ onClick: () => {},+ },+ {+ label: 'Share project',+ description: 'Invite people to collaborate.',+ icon: ShareIcon,+ onClick: () => {},+ },+ {+ label: 'Delete project',+ description: 'Move this project to the trash.',+ icon: TrashIcon,+ variant: 'destructive',+ onClick: () => {},+ },+ ]}+ />+ </div>+ );+}diff --git a/packages/cli/assets/templates/blocks/components/MultiSelector/MultiSelectorBottomSheet.doc.mjs b/packages/cli/assets/templates/blocks/components/MultiSelector/MultiSelectorBottomSheet.doc.mjsnew file mode 100644index 0000000000..3b727e5a49--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/MultiSelector/MultiSelectorBottomSheet.doc.mjs@@ -0,0 +1,15 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */+export const doc = {+ type: 'block',+ exampleFor: 'MultiSelector',+ alsoExampleFor: ['BottomSheet'],+ name: 'MultiSelector — Bottom Sheet',+ displayName: 'MultiSelector — Bottom Sheet',+ description:+ 'Keeps a multi-selection list open in a bottom sheet while choices are toggled.',+ isReady: true,+ aspectRatio: 3 / 4,+ componentsUsed: ['MultiSelector'],+};diff --git a/packages/cli/assets/templates/blocks/components/MultiSelector/MultiSelectorBottomSheet.tsx b/packages/cli/assets/templates/blocks/components/MultiSelector/MultiSelectorBottomSheet.tsxnew file mode 100644index 0000000000..4e39f085b2--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/MultiSelector/MultiSelectorBottomSheet.tsx@@ -0,0 +1,26 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {useState} from 'react';+import {MultiSelector} from '@astryxdesign/core/MultiSelector';++const OPTIONS = ['Design', 'Engineering', 'Marketing', 'Operations'];++export default function MultiSelectorBottomSheet() {+ const [value, setValue] = useState<string[]>([]);++ return (+ <div style={{width: 320, maxWidth: '100%'}}>+ <MultiSelector+ label="Teams"+ options={OPTIONS}+ value={value}+ onChange={setValue}+ placeholder="Choose teams"+ hasSelectAll+ presentation="bottom-sheet"+ />+ </div>+ );+}diff --git a/packages/cli/assets/templates/blocks/components/Selector/SelectorBottomSheet.doc.mjs b/packages/cli/assets/templates/blocks/components/Selector/SelectorBottomSheet.doc.mjsnew file mode 100644index 0000000000..54aafb44f4--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/Selector/SelectorBottomSheet.doc.mjs@@ -0,0 +1,15 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */+export const doc = {+ type: 'block',+ exampleFor: 'Selector',+ alsoExampleFor: ['BottomSheet'],+ name: 'Selector — Bottom Sheet',+ displayName: 'Selector — Bottom Sheet',+ description:+ 'Presents a single-selection list in a bottom sheet for compact touch interfaces.',+ isReady: true,+ aspectRatio: 3 / 4,+ componentsUsed: ['Selector'],+};diff --git a/packages/cli/assets/templates/blocks/components/Selector/SelectorBottomSheet.tsx b/packages/cli/assets/templates/blocks/components/Selector/SelectorBottomSheet.tsxnew file mode 100644index 0000000000..e60b3d3388--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/Selector/SelectorBottomSheet.tsx@@ -0,0 +1,30 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {useState} from 'react';+import {Selector} from '@astryxdesign/core/Selector';++const OPTIONS = [+ {value: 'design', label: 'Design'},+ {value: 'engineering', label: 'Engineering'},+ {value: 'marketing', label: 'Marketing'},+ {value: 'operations', label: 'Operations'},+];++export default function SelectorBottomSheet() {+ const [value, setValue] = useState<string | undefined>();++ return (+ <div style={{width: 320, maxWidth: '100%'}}>+ <Selector+ label="Team"+ options={OPTIONS}+ value={value}+ onChange={setValue}+ placeholder="Choose a team"+ presentation="bottom-sheet"+ />+ </div>+ );+}diff --git a/packages/core/locales/en.json b/packages/core/locales/en.jsonindex 98c365b9fc..7fe56b23a7 100644--- a/packages/core/locales/en.json+++ b/packages/core/locales/en.json@@ -415,6 +415,10 @@"defaultMessage": "Menu","description": "Screen-reader-only fallback name for a dropdown menu popover. Very generic; consumers usually override. Noun (\"a menu\"), not the imperative."},+ "@astryx.dropdownMenu.back": {+ "defaultMessage": "Back",+ "description": "Button label that returns from a nested action list to its parent inside a DropdownMenu bottom sheet. Imperative navigation action."+ },"@astryx.lightbox.close": {"defaultMessage": "Close","description": "\"Close\" = shut/dismiss (not \"nearby\"). Screen-reader-only label on the X button that dismisses a Lightbox."diff --git a/packages/core/src/BottomSheet/BottomSheet.doc.mjs b/packages/core/src/BottomSheet/BottomSheet.doc.mjsindex aa6f4ab669..b273433628 100644--- a/packages/core/src/BottomSheet/BottomSheet.doc.mjs+++ b/packages/core/src/BottomSheet/BottomSheet.doc.mjs@@ -71,6 +71,12 @@ export const docs = {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.',},+ {+ 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.',+ },{name: 'purpose',type: "'required' | 'form' | 'info'",diff --git a/packages/core/src/BottomSheet/BottomSheet.test.tsx b/packages/core/src/BottomSheet/BottomSheet.test.tsxindex 03e607fa46..c5cfd21c37 100644--- a/packages/core/src/BottomSheet/BottomSheet.test.tsx+++ b/packages/core/src/BottomSheet/BottomSheet.test.tsx@@ -2319,6 +2319,35 @@ describe('BottomSheet', () => {expect(document.activeElement).toBe(opener);});++ it('prefers an explicit final focus target', () => {+ const finalFocusRef = createRef<HTMLButtonElement>();+ function ExplicitFocusHarness() {+ const [isOpen, setIsOpen] = useState(true);+ return (+ <>+ <button ref={finalFocusRef} type="button">+ Adaptive trigger+ </button>+ <BottomSheet+ isOpen={isOpen}+ onOpenChange={setIsOpen}+ finalFocusRef={finalFocusRef}+ label="Filters">+ <button type="button" onClick={() => setIsOpen(false)}>+ Done+ </button>+ </BottomSheet>+ </>+ );+ }++ render(<ExplicitFocusHarness />);+ fireEvent.click(screen.getByRole('button', {name: 'Done'}));+ finishSheetExit();++ expect(document.activeElement).toBe(finalFocusRef.current);+ });});describe('initial focus', () => {diff --git a/packages/core/src/BottomSheet/BottomSheet.tsx b/packages/core/src/BottomSheet/BottomSheet.tsxindex a98b16949c..d7d6e20595 100644--- a/packages/core/src/BottomSheet/BottomSheet.tsx+++ b/packages/core/src/BottomSheet/BottomSheet.tsx@@ -32,6 +32,7 @@ import {useLayoutEffect,useRef,useState,+ type RefObject,type ReactNode,} from 'react';import * as stylex from '@stylexjs/stylex';@@ -162,6 +163,8 @@ interface StandaloneBottomSheetProps extends BottomSheetSharedProps {isOpen: boolean;onOpenChange: (isOpen: boolean) => void;hasScrim?: boolean;+ /** Element that receives focus after the sheet closes. */+ finalFocusRef?: RefObject<HTMLElement | null>;sheetId?: never;}@@ -221,6 +224,7 @@ function StandaloneBottomSheet({height = 'capped',snapPoints,hasScrim = true,+ finalFocusRef,purpose = 'info',xstyle,...props@@ -298,10 +302,10 @@ function StandaloneBottomSheet({dialog.close();}setIsPresented(false);- triggerRef.current?.focus();+ (finalFocusRef?.current ?? triggerRef.current)?.focus();triggerRef.current = null;},- [isOpen],+ [finalFocusRef, isOpen],);useScrollLock(shouldPresent && hasScrim);diff --git a/packages/core/src/ContextMenu/ContextMenu.doc.mjs b/packages/core/src/ContextMenu/ContextMenu.doc.mjsindex f041ca9fdb..b60fd37725 100644--- a/packages/core/src/ContextMenu/ContextMenu.doc.mjs+++ b/packages/core/src/ContextMenu/ContextMenu.doc.mjs@@ -32,7 +32,7 @@ export const docs = {{name: 'items',type: 'ContextMenuOption[]',- description: 'Array of menu entries. Each entry is one of: an action item `{label, onClick?, icon?, isDisabled?, variant?}` (variant `"destructive"` renders it in the error color), a divider `{type: "divider"}`, or a section `{type: "section", title?, items: [...action items]}`.',+ description: 'Array of menu entries. Each entry is one of: an action item `{label, onClick?, icon?, isDisabled?, variant?, items?}` (nested `items` open a flyout in popover presentation and drill into a new view in bottom-sheet presentation; variant `"destructive"` renders it in the error color), a divider `{type: "divider"}`, or a section `{type: "section", title?, items: [...action items]}`.',required: true,},{@@ -63,6 +63,12 @@ export const docs = {type: '(isOpen: boolean) => void',description: 'Callback fired when the menu opens or closes.',},+ {+ name: 'presentation',+ type: "'popover' | 'bottom-sheet' | 'adaptive'",+ description: 'Presentation policy. `popover` opens at the pointer position, `bottom-sheet` always uses an action sheet, and `adaptive` uses the BottomSheet at 768px and below when the primary pointer is coarse.',+ default: "'popover'",+ },{name: 'isDisabled',type: 'boolean',@@ -78,7 +84,9 @@ export const docs = {bestPractices: [{ guidance: true, description: 'Keep menu items concise and action-oriented; users expect quick access to contextual actions.' },{ guidance: true, description: 'Use sections and dividers to group related actions when the menu has many items.' },+ { guidance: true, description: 'Use `presentation="adaptive"` when right-click should remain cursor-positioned on desktop while long-press opens a reachable BottomSheet on compact touch devices.' },{ guidance: true, description: 'Ensure all context menu actions are also accessible via other UI elements for keyboard-only users.' },+ { guidance: true, description: 'Keep a visible MoreMenu or equivalent trigger for important mobile actions; long-press must not be the only route.' },{ guidance: false, description: 'Use a ContextMenu as the only way to access important actions; not all users know to right-click.' },{ guidance: false, description: 'Place more than 10–12 items in a single menu without grouping them into sections.' },],@@ -107,7 +115,9 @@ export const docsZh = {bestPractices: [{ guidance: true, description: '保持菜单项简洁和面向操作。' },{ guidance: true, description: '有很多项时使用分组和分隔线。' },+ { guidance: true, description: '在桌面端需要光标定位、紧凑触控设备上需要 BottomSheet 时,使用 `presentation="adaptive"`。' },{ guidance: true, description: '确保所有上下文菜单操作也可通过其他 UI 元素访问。' },+ { guidance: true, description: '重要的移动端操作还应提供可见的 MoreMenu 或同等入口,不要只依赖长按。' },{ guidance: false, description: '将上下文菜单作为访问重要操作的唯一方式。' },{ guidance: false, description: '在单个菜单中放置超过 10-12 个项而不分组。' },],@@ -122,7 +132,9 @@ export const docsDense = {bestPractices: [{ guidance: true, description: 'Keep items concise and action-oriented.' },{ guidance: true, description: 'Group related actions with sections and dividers.' },+ { guidance: true, description: 'Use adaptive presentation for cursor popover on desktop and BottomSheet on compact touch.' },{ guidance: true, description: 'Ensure actions are also accessible via other UI elements.' },+ { guidance: true, description: 'Keep a visible mobile entry point for important actions.' },{ guidance: false, description: 'Use as the only way to access important actions.' },{ guidance: false, description: 'Place more than 10–12 items without grouping.' },],diff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsxindex 30a15f60c0..143ce1ca08 100644--- a/packages/core/src/ContextMenu/ContextMenu.test.tsx+++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx@@ -9,8 +9,9 @@*/import {describe, it, expect, vi, beforeEach} from 'vitest';-import {render, screen, fireEvent, act} from '@testing-library/react';+import {render, screen, fireEvent, act, waitFor} from '@testing-library/react';import userEvent from '@testing-library/user-event';+import {readFileSync} from 'node:fs';import {ContextMenu} from './ContextMenu';import {ContextMenuItem,@@ -23,6 +24,30 @@ import {DropdownMenuItem} from '../DropdownMenu/DropdownMenuItem';import {Divider} from '../Divider';beforeEach(() => {+ 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');+ });+ vi.stubGlobal(+ 'matchMedia',+ vi.fn().mockImplementation((query: string) => ({+ matches: false,+ media: query,+ onchange: null,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),+ );HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {this.setAttribute('popover-open', '');const event = new Event('toggle', {bubbles: false});@@ -123,6 +148,100 @@ describe('ContextMenu', () => {expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();});+ it('opens the real menu content in a BottomSheet when requested', async () => {+ render(+ <ContextMenu+ presentation="bottom-sheet"+ label="Row actions"+ items={[{label: 'Edit'}]}>+ <div>Right-click me</div>+ </ContextMenu>,+ );++ fireEvent.contextMenu(screen.getByText('Right-click me'));+ await waitFor(() =>+ expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalledOnce(),+ );+ const dialog = screen.getByRole('dialog', {name: 'Row actions'});+ const actionList = dialog.querySelector('[data-autofocus]');+ expect(actionList).not.toBeNull();+ await waitFor(() => expect(actionList).toHaveFocus());+ expect(screen.getByRole('button', {name: 'Edit'})).not.toHaveFocus();+ expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled();+ });++ it('drills into nested data items inside the BottomSheet', async () => {+ const user = userEvent.setup();+ const onMove = vi.fn();++ render(+ <ContextMenu+ presentation="bottom-sheet"+ label="Row actions"+ items={[+ {+ label: 'Move to project',+ items: [{label: 'Apollo launch', onClick: onMove}],+ },+ ]}>+ <div>Right-click me</div>+ </ContextMenu>,+ );++ fireEvent.contextMenu(screen.getByText('Right-click me'));+ await user.click(screen.getByRole('button', {name: 'Move to project'}));++ const submenuHeading = screen.getByRole('heading', {+ name: 'Move to project',+ });+ expect(submenuHeading).toBeInTheDocument();+ await waitFor(() => expect(submenuHeading).toHaveFocus());+ expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled();++ await user.click(screen.getByRole('button', {name: 'Apollo launch'}));+ expect(onMove).toHaveBeenCalledOnce();+ await waitFor(() =>+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument(),+ );+ });++ it('keeps only the top content padding in a menu BottomSheet', () => {+ const source = readFileSync(+ 'packages/core/src/DropdownMenu/MenuBottomSheet.tsx',+ 'utf8',+ );++ expect(source).toContain('paddingBlockStart={4}');+ expect(source).toContain('paddingBlockEnd={0}');+ });++ it('uses the BottomSheet for adaptive presentation on compact touch', async () => {+ vi.stubGlobal(+ 'matchMedia',+ vi.fn().mockImplementation((query: string) => ({+ matches: query === '(max-width: 768px) and (pointer: coarse)',+ media: query,+ onchange: null,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),+ );+ render(+ <ContextMenu presentation="adaptive" items={[{label: 'Edit'}]}>+ <div>Right-click me</div>+ </ContextMenu>,+ );++ fireEvent.contextMenu(screen.getByText('Right-click me'));+ await waitFor(() =>+ expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalledOnce(),+ );+ expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled();+ });+it('closes on Escape even when opened without auto-focus', () => {render(<ContextMenu items={[{label: 'Item 1'}]}>@@ -273,6 +392,17 @@ describe('ContextMenu', () => {}});+ it('suppresses native text selection on the long-press trigger', () => {+ const source = readFileSync(+ 'packages/core/src/ContextMenu/ContextMenu.tsx',+ 'utf8',+ );++ expect(source).toMatch(+ /trigger:[\s\S]*?WebkitTouchCallout: 'none',[\s\S]*?WebkitUserSelect: 'none',[\s\S]*?userSelect: 'none'/,+ );+ });+it('cancels the long-press when the finger moves past the threshold', () => {vi.useFakeTimers();try {diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsxindex 37c5c4572b..e6cccc7496 100644--- a/packages/core/src/ContextMenu/ContextMenu.tsx+++ b/packages/core/src/ContextMenu/ContextMenu.tsx@@ -3,8 +3,9 @@/*** @file ContextMenu.tsx- * @input Uses React, StyleX, useLayer (context mode), useListFocus- * @output Exports ContextMenu component+ * @input Uses React, StyleX, useLayer, BottomSheet, useListFocus, and the+ * shared menu-presentation resolver+ * @output Exports ContextMenu with cursor-popover and touch-sheet presentations* @position Core implementation; consumed by index.ts** Right-click context menu positioned at the cursor. The cursor point is@@ -34,13 +35,19 @@ import React, {useCallback,useEffect,useId,+ lazy,useMemo,useRef,useState,+ Suspense,} from 'react';import type {ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';+import {Button} from '../Button';+import {Heading} from '../Heading';+import {Icon} from '../Icon';import {useLayer} from '../Layer/useLayer';+import {MenuBottomSheetActionList} from '../DropdownMenu/MenuBottomSheetActionList';import {renderDropdownItems} from '../DropdownMenu/renderDropdownItems';import {DropdownMenuContext,@@ -63,7 +70,7 @@ import {easeVars,shadowVars,} from '../theme/tokens.stylex';-import {mergeProps, isImeKeyEvent} from '../utils';+import {mergeProps, isImeKeyEvent, rtlStyles} from '../utils';import type {BaseProps} from '../BaseProps';import type {StyleXStyles} from '../theme/types';import {themeProps} from '../utils/themeProps';@@ -76,6 +83,16 @@ import type {} from '../DropdownMenu/DropdownMenu';import {useMergedRefs} from '../hooks/useMergedRefs';+import {+ useAdaptivePresentation,+ type AdaptivePresentation,+} from '../hooks/useAdaptivePresentation';++const LazyMenuBottomSheet = lazy(async () =>+ import('../DropdownMenu/MenuBottomSheet').then(module => ({+ default: module.MenuBottomSheet,+ })),+);const styles = stylex.create({// Trigger wrapper: suppress the iOS long-press callout/selection so the// long-press opens our context menu instead of the native text/callout UI.@@ -85,6 +102,8 @@ const styles = stylex.create({trigger: {position: 'relative',WebkitTouchCallout: 'none',+ WebkitUserSelect: 'none',+ userSelect: 'none',},// Zero-size anchor placed at the cursor point within the trigger. The menu// is anchored to this element, so it sits under the cursor yet is positioned@@ -121,6 +140,33 @@ const styles = stylex.create({popoverCustomWidth: (width: string | number) => ({minWidth: typeof width === 'number' ? `${width}px` : width,}),+ sheetMenu: {+ boxSizing: 'border-box',+ display: 'flex',+ flexDirection: 'column',+ gap: spacingVars['--spacing-0-5'],+ width: '100%',+ '--_dropdown-menu-radius': radiusVars['--radius-container'],+ '--_dropdown-menu-padding': spacingVars['--spacing-1'],+ padding: spacingVars['--spacing-1'],+ borderRadius: 'var(--_dropdown-menu-radius)',+ backgroundColor: colorVars['--color-background-surface'],+ outline: 'none',+ userSelect: 'none',+ },+ sheetHeader: {+ display: 'flex',+ flexDirection: 'row',+ alignItems: 'center',+ gap: spacingVars['--spacing-1'],+ marginBottom: spacingVars['--spacing-2'],+ },+ sheetRootHeading: {+ marginInlineStart: spacingVars['--spacing-3'],+ },+ sheetViewHeading: {+ outline: 'none',+ },});// =============================================================================@@ -164,6 +210,15 @@ interface ContextMenuBaseProps extends BaseProps {isDisabled?: boolean;/** Called when the menu opens or closes. */onOpenChange?: (isOpen: boolean) => void;+ /**+ * Presentation policy for the menu.+ * - `popover`: open beside the pointer position.+ * - `bottom-sheet`: open as an action sheet.+ * - `adaptive`: use a BottomSheet on compact coarse-pointer viewports and+ * the cursor-positioned popover elsewhere.+ * @default 'popover'+ */+ presentation?: AdaptivePresentation;'data-testid'?: string;}@@ -215,6 +270,7 @@ export function ContextMenu({label: labelFromProps,isDisabled = false,onOpenChange,+ presentation = 'popover',ref,className,style,@@ -225,6 +281,9 @@ export function ContextMenu({}: ContextMenuProps) {const t = useTranslator();const label = labelFromProps ?? t('@astryx.contextMenu.label');+ const backLabel = t('@astryx.dropdownMenu.back');+ const resolvedPresentation = useAdaptivePresentation(presentation);+ const usesBottomSheet = resolvedPresentation === 'bottom-sheet';// Separate content props (union discriminant) from DOM pass-through attrs.// The union means exactly one of items/menuContent exists in rest; destructure// both so triggerProps contains only DOM-safe attributes.@@ -250,8 +309,25 @@ export function ContextMenu({// Element focused before the menu opened, restored when it closes so focus// does not fall to <body> after Escape or outside-click dismissal.const triggerFocusRef = useRef<HTMLElement | null>(null);+ const sheetHeadingRef = useRef<HTMLHeadingElement>(null);const [isOpen, setIsOpen] = useState(false);+ const [submenuPath, setSubmenuPath] = useState<ContextMenuItemData[]>([]);+ const currentSubmenu = submenuPath.at(-1);+ const currentItems = currentSubmenu?.items ?? items;+ const currentTitle = currentSubmenu?.label ?? label;+ const sheetLabel = typeof currentTitle === 'string' ? currentTitle : label;++ const updateOpenState = useCallback(+ (nextIsOpen: boolean) => {+ if (!nextIsOpen) {+ setSubmenuPath([]);+ }+ setIsOpen(nextIsOpen);+ onOpenChange?.(nextIsOpen);+ },+ [onOpenChange],+ );const layer = useLayer({mode: 'context',@@ -273,8 +349,35 @@ export function ContextMenu({});const closeMenu = useCallback(() => {- layer.hide();- }, [layer]);+ if (usesBottomSheet) {+ updateOpenState(false);+ } else {+ layer.hide();+ }+ }, [layer, updateOpenState, usesBottomSheet]);++ const handleBottomSheetSelect = useCallback(+ (item: ContextMenuItemData) => {+ if (item.isDisabled) {+ return;+ }+ item.onClick?.();+ if (item.hasCloseOnSelect !== false) {+ closeMenu();+ }+ },+ [closeMenu],+ );++ useEffect(() => {+ if (!isOpen || submenuPath.length === 0) {+ return;+ }+ const frame = requestAnimationFrame(() => {+ sheetHeadingRef.current?.focus({preventScroll: true});+ });+ return () => cancelAnimationFrame(frame);+ }, [isOpen, submenuPath.length]);const {listRef,@@ -308,7 +411,7 @@ export function ContextMenu({// opening right-click as a dismiss event. Handling it ourselves via// mousedown avoids that race.useEffect(() => {- if (!isOpen) {+ if (!isOpen || usesBottomSheet) {return;}const handleClickOutside = (e: MouseEvent) => {@@ -321,14 +424,14 @@ export function ContextMenu({return () => {document.removeEventListener('mousedown', handleClickOutside);};- }, [isOpen, closeMenu, listRef]);+ }, [isOpen, closeMenu, listRef, usesBottomSheet]);// Dismiss on Escape from anywhere while open. The menu div's own onKeyDown// only fires when focus is inside the menu; a document-level listener is// kept as a reliable fallback Escape path (e.g. if focus has moved out of// the menu). Guards against IME composition-cancel.useEffect(() => {- if (!isOpen) {+ if (!isOpen || usesBottomSheet) {return;}const handleEscape = (e: KeyboardEvent) => {@@ -347,7 +450,7 @@ export function ContextMenu({return () => {document.removeEventListener('keydown', handleEscape);};- }, [isOpen, closeMenu]);+ }, [isOpen, closeMenu, usesBottomSheet]);const listKeyDown = useCallback((e: React.KeyboardEvent) => {@@ -404,10 +507,14 @@ export function ContextMenu({document.activeElement instanceof HTMLElement? document.activeElement: focusEl;- layer.show();- requestAnimationFrame(() => focusFirst());+ if (usesBottomSheet) {+ updateOpenState(true);+ } else {+ layer.show();+ requestAnimationFrame(() => focusFirst());+ }},- [layer, focusFirst],+ [layer, focusFirst, updateOpenState, usesBottomSheet],);const handleContextMenu = useCallback(@@ -465,6 +572,74 @@ export function ContextMenu({const resolvedMenuContent =itemsProp !== undefined ? renderDropdownItems(items) : menuContent;+ const renderedMenu = (+ <div+ ref={listRef}+ id={menuId}+ role="menu"+ data-autofocus={usesBottomSheet ? '' : undefined}+ tabIndex={usesBottomSheet ? 0 : -1}+ aria-label={label}+ onKeyDown={listKeyDown}+ onContextMenu={e => e.preventDefault()}+ {...mergeProps(+ themeProps('context-menu'),+ stylex.props(usesBottomSheet ? styles.sheetMenu : styles.menu, xstyle),+ className,+ style,+ )}>+ <DropdownMenuContext value={contextValue}>+ {resolvedMenuContent}+ </DropdownMenuContext>+ </div>+ );++ const renderedBottomSheetContent =+ itemsProp !== undefined ? (+ <div+ ref={listRef}+ data-autofocus=""+ tabIndex={0}+ {...mergeProps(+ themeProps('context-menu'),+ stylex.props(styles.sheetMenu, xstyle),+ className,+ style,+ )}>+ <div {...stylex.props(styles.sheetHeader)}>+ {submenuPath.length > 0 && (+ <Button+ label={backLabel}+ variant="ghost"+ size="sm"+ icon={+ <Icon icon="chevronLeft" size="sm" xstyle={rtlStyles.mirror} />+ }+ isIconOnly+ onClick={() => setSubmenuPath(path => path.slice(0, -1))}+ />+ )}+ <Heading+ ref={sheetHeadingRef}+ level={3}+ tabIndex={-1}+ xstyle={[+ styles.sheetViewHeading,+ submenuPath.length === 0 && styles.sheetRootHeading,+ ]}>+ {currentTitle}+ </Heading>+ </div>+ <MenuBottomSheetActionList+ items={currentItems}+ onSelect={handleBottomSheetSelect}+ onOpenSubmenu={item => setSubmenuPath(path => [...path, item])}+ />+ </div>+ ) : (+ renderedMenu+ );+return (<><div@@ -494,29 +669,21 @@ export function ContextMenu({/></div>- {layer.render(- <div- ref={listRef}- id={menuId}- role="menu"- aria-label={label}- onKeyDown={listKeyDown}- onContextMenu={e => e.preventDefault()}- {...mergeProps(- themeProps('context-menu'),- stylex.props(styles.menu, xstyle),- className,- style,- )}>- <DropdownMenuContext value={contextValue}>- {resolvedMenuContent}- </DropdownMenuContext>- </div>,- {+ {usesBottomSheet ? (+ <Suspense fallback={null}>+ <LazyMenuBottomSheet+ isOpen={isOpen}+ onOpenChange={updateOpenState}+ label={sheetLabel}>+ {renderedBottomSheetContent}+ </LazyMenuBottomSheet>+ </Suspense>+ ) : (+ layer.render(renderedMenu, {placement: 'below',alignment: 'start',xstyle: [popoverXstyle, layerAnimations.below],- },+ }))}</>);diff --git a/packages/core/src/ContextMenu/index.ts b/packages/core/src/ContextMenu/index.tsindex d2b60036d8..cb3cfb3629 100644--- a/packages/core/src/ContextMenu/index.ts+++ b/packages/core/src/ContextMenu/index.ts@@ -15,6 +15,7 @@ export {type ContextMenuSection,type ContextMenuOption,} from './ContextMenu';+export type {AdaptivePresentation as MenuPresentation} from '../hooks/useAdaptivePresentation';export {DropdownMenuItem as ContextMenuItem,diff --git a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjsindex ac1d053261..cdd67dad3e 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs+++ b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs@@ -7,24 +7,42 @@ export const docs = {displayName: 'Dropdown Menu',group: 'DropdownMenu',category: 'Action',- keywords: ["dropdown","menu","popover","select","actions","contextmenu","overflow","kebab","menubutton"],+ keywords: [+ 'dropdown',+ 'menu',+ 'popover',+ 'select',+ 'actions',+ 'contextmenu',+ 'overflow',+ 'kebab',+ 'menubutton',+ ],playground: {// `items` is required; without seeded entries the properties-tab preview// renders an empty trigger button. Provide a few actions so the preview// is meaningful.defaults: {button: {label: 'Actions'},+ presentation: 'popover',items: [- {label: 'Edit'},- {label: 'Duplicate'},- {label: 'Delete'},+ {label: 'Edit project', icon: 'wrench'},+ {label: 'Duplicate project', icon: 'copy'},+ {label: 'Share project', icon: 'externalLink'},+ {label: 'Archive project', icon: 'stop'},],},},theming: {targets: [- {className: 'astryx-dropdown-menu'},- {className: 'astryx-dropdown-menu-item', visualProps: ['size', 'variant']},+ {+ className: 'astryx-dropdown-menu',+ visualProps: ['presentation'],+ },+ {+ className: 'astryx-dropdown-menu-item',+ visualProps: ['size', 'variant'],+ },{className: 'astryx-dropdown-menu-radio',visualProps: ['size'],@@ -35,28 +53,48 @@ export const docs = {{className: 'astryx-dropdown-menu-indicator-icon'},],vars: [- {name: '--_dropdown-menu-radius', description: 'Border radius of the menu popup', default: 'var(--radius-element)', private: true},- {name: '--_dropdown-menu-padding', description: 'Inner padding of the menu popup', default: 'var(--spacing-1)', private: true},+ {+ name: '--_dropdown-menu-radius',+ description: 'Border radius of the menu popup',+ default: 'var(--radius-element)',+ private: true,+ },+ {+ name: '--_dropdown-menu-padding',+ description: 'Inner padding of the menu popup',+ default: 'var(--spacing-1)',+ private: true,+ },],derived: [{property: 'borderRadius', vars: ['--_dropdown-menu-radius']},{property: 'padding', vars: ['--_dropdown-menu-padding']},],},- description: 'Main dropdown menu component with a trigger button and popup item list.',+ description:+ 'Action menu with a trigger button and anchored, bottom-sheet, or adaptive presentation.',props: [{name: 'button',type: 'DropdownMenuButtonProps',- description: 'Props for the trigger button (Button props except onClick).',+ description:+ 'Props for the trigger button (Button props except onClick).',default: "{ label: 'Menu' }",},{name: 'items',type: 'DropdownMenuOption[]',- description: 'Array of menu entries. Each entry is one of: an action item `{label, onClick?, icon?, description?, endContent?, isDisabled?, variant?, hasCloseOnSelect?, id?}` (variant `"destructive"` renders it in the error color; `endContent` holds trailing content such as a keyboard-shortcut hint; `id` is the row\'s stable React key, needed only when the array reorders or filters), a divider `{type: "divider"}`, or a section `{type: "section", title?, id?, items: [...action items]}`.',+ description:+ 'Array of menu entries. Each entry is one of: an action item `{label, onClick?, icon?, description?, endContent?, isDisabled?, variant?, hasCloseOnSelect?, id?}` (variant `"destructive"` renders it in the error color; `endContent` holds trailing content such as a keyboard-shortcut hint; `id` is the row\'s stable React key, needed only when the array reorders or filters), a divider `{type: "divider"}`, or a section `{type: "section", title?, id?, items: [...action items]}`.',required: true,},+ {+ name: 'presentation',+ type: "'popover' | 'bottom-sheet' | 'adaptive'",+ description:+ "Presentation surface for data-driven items. 'popover' stays anchored, 'bottom-sheet' always renders the actions in a modal BottomSheet, and 'adaptive' uses a BottomSheet on compact coarse-pointer layouts while remaining anchored elsewhere. Compound children currently support popover only.",+ default: "'popover'",+ },{name: 'isMenuOpen',type: 'boolean',@@ -70,18 +108,21 @@ export const docs = {{name: 'menuWidth',type: 'number | string',- description: 'Custom menu width; defaults to matching the trigger button width.',+ description:+ 'Minimum width for the popover presentation. Length values may grow for content; intrinsic and CSS-wide keywords select the preferred inline size. Every form is capped to the available viewport space. Defaults to matching the trigger width up to that cap.',},{name: 'placement',type: "'above' | 'below' | 'start' | 'end'",- description: "Position placement relative to the trigger. Logical: start/end resolve against the menu's own inherited direction (RTL mirrors).",+ description:+ "Popover placement relative to the trigger. Ignored by the bottom-sheet presentation. Logical: start/end resolve against the menu's own inherited direction (RTL mirrors).",default: "'below'",},{name: 'alignment',type: "'start' | 'center' | 'end'",- description: "Alignment along the placement axis. Logical: start/end follow the menu's own inherited direction (RTL mirrors).",+ description:+ "Popover alignment along the placement axis. Ignored by the bottom-sheet presentation. Logical: start/end follow the menu's own inherited direction (RTL mirrors).",default: "'start'",},{@@ -89,34 +130,70 @@ export const docs = {type: '() => void',description: 'Callback fired when the trigger button is clicked.',},- {- name: 'placement',- type: "'above' | 'below' | 'start' | 'end'",- description: 'Position placement for the menu popover relative to the trigger button.',- default: "'below'",- },{name: 'hasChevron',type: 'boolean',- description: 'Whether to show a chevron icon on the trigger button. Set to false for icon-only triggers.',+ description:+ 'Whether to show a chevron icon on the trigger button. Set to false for icon-only triggers.',default: 'true',- }, {+ },+ {name: 'children',type: 'ReactNode',description:'Compound-mode menu content: DropdownMenuItem, DropdownMenuDivider, DropdownMenuSubMenu, and the selectable items. Mutually exclusive with `items`.',},],- components: [- {name: 'DropdownMenuItem'},- ],+ components: [{name: 'DropdownMenuItem'}],usage: {- description: 'A dropdown menu that displays a list of actionable items in a popup triggered by a button. Use to present action options as a next step in a process, or to offer contextual actions without cluttering the interface.',+ description:+ 'A dropdown menu that displays a list of actionable items in a popup triggered by a button. Use to present action options as a next step in a process, or to offer contextual actions without cluttering the interface.',bestPractices: [- { guidance: true, description: 'Keep menu items concise and action-oriented so users can scan options quickly.' },- { guidance: true, description: 'Use sections and dividers to group related actions when the menu has many items.' },- { guidance: false, description: 'Use a DropdownMenu for navigation; use a navigation component instead.' },- { guidance: false, description: 'Place more than 10–12 items in a single menu without grouping them into sections.' },+ {+ guidance: true,+ description:+ 'Keep menu items concise and action-oriented so users can scan options quickly.',+ },+ {+ guidance: true,+ description:+ 'Use sections and dividers to group related actions when the menu has many items.',+ },+ {+ guidance: true,+ description:+ 'For a short, flat action set, use presentation="bottom-sheet" when product policy calls for a modal touch surface.',+ },+ {+ guidance: true,+ description:+ 'Use presentation="adaptive" when the same short action set should remain anchored on pointer layouts and become a BottomSheet on compact coarse-pointer layouts.',+ },+ {+ guidance: true,+ description:+ 'For a hierarchy that cannot fit as adjacent flyouts on a compact touch surface, a product may explicitly use a drill-in interaction with a Back action.',+ },+ {+ guidance: true,+ description:+ 'Choose presentation explicitly in product code. A compact, coarse-pointer, hover-free media query is one useful policy, but DropdownMenu does not impose a universal device breakpoint.',+ },+ {+ guidance: true,+ description:+ 'When the content is no longer a short list of immediate actions, reevaluate the interaction and choose a component that matches the actual task; content traits alone do not determine the component.',+ },+ {+ guidance: false,+ description:+ 'Use a DropdownMenu for navigation; use a navigation component instead.',+ },+ {+ guidance: false,+ description:+ 'Place more than 10–12 items in a single menu without grouping them into sections.',+ },],},};@@ -124,12 +201,54 @@ export const docs = {/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */export const docsZh = {usage: {- description: 'A dropdown menu that displays a list of actionable items in a popup triggered by a button. Use to present action options as a next step in a process, or to offer contextual actions without cluttering the interface.',+ description:+ 'A dropdown menu that displays a list of actionable items in a popup triggered by a button. Use to present action options as a next step in a process, or to offer contextual actions without cluttering the interface.',bestPractices: [- { guidance: true, description: 'Keep menu items concise and action-oriented so users can scan options quickly.' },- { guidance: true, description: 'Use sections and dividers to group related actions when the menu has many items.' },- { guidance: false, description: 'Use a DropdownMenu for navigation; use a navigation component instead.' },- { guidance: false, description: 'Place more than 10–12 items in a single menu without grouping them into sections.' },+ {+ guidance: true,+ description:+ 'Keep menu items concise and action-oriented so users can scan options quickly.',+ },+ {+ guidance: true,+ description:+ 'Use sections and dividers to group related actions when the menu has many items.',+ },+ {+ guidance: true,+ description:+ 'For a short, flat action set, use presentation="bottom-sheet" when product policy calls for a modal touch surface.',+ },+ {+ guidance: true,+ description:+ 'Use presentation="adaptive" when the same short action set should remain anchored on pointer layouts and become a BottomSheet on compact coarse-pointer layouts.',+ },+ {+ guidance: true,+ description:+ 'For a hierarchy that cannot fit as adjacent flyouts on a compact touch surface, a product may explicitly use a drill-in interaction with a Back action.',+ },+ {+ guidance: true,+ description:+ 'Choose presentation explicitly in product code. A compact, coarse-pointer, hover-free media query is one useful policy, but DropdownMenu does not impose a universal device breakpoint.',+ },+ {+ guidance: true,+ description:+ 'When the content is no longer a short list of immediate actions, reevaluate the interaction and choose a component that matches the actual task; content traits alone do not determine the component.',+ },+ {+ guidance: false,+ description:+ 'Use a DropdownMenu for navigation; use a navigation component instead.',+ },+ {+ guidance: false,+ description:+ 'Place more than 10–12 items in a single menu without grouping them into sections.',+ },],},};@@ -138,12 +257,54 @@ export const docsZh = {export const docsDense = {description: 'dropdown menu for actionable items in popup',usage: {- description: 'A dropdown menu that displays a list of actionable items in a popup triggered by a button. Use to present action options as a next step in a process, or to offer contextual actions without cluttering the interface.',+ description:+ 'A dropdown menu that displays a list of actionable items in a popup triggered by a button. Use to present action options as a next step in a process, or to offer contextual actions without cluttering the interface.',bestPractices: [- { guidance: true, description: 'Keep menu items concise and action-oriented so users can scan options quickly.' },- { guidance: true, description: 'Use sections and dividers to group related actions when the menu has many items.' },- { guidance: false, description: 'Use a DropdownMenu for navigation; use a navigation component instead.' },- { guidance: false, description: 'Place more than 10–12 items in a single menu without grouping them into sections.' },+ {+ guidance: true,+ description:+ 'Keep menu items concise and action-oriented so users can scan options quickly.',+ },+ {+ guidance: true,+ description:+ 'Use sections and dividers to group related actions when the menu has many items.',+ },+ {+ guidance: true,+ description:+ 'For a short, flat action set, use presentation="bottom-sheet" when product policy calls for a modal touch surface.',+ },+ {+ guidance: true,+ description:+ 'Use presentation="adaptive" when the same short action set should remain anchored on pointer layouts and become a BottomSheet on compact coarse-pointer layouts.',+ },+ {+ guidance: true,+ description:+ 'For a hierarchy that cannot fit as adjacent flyouts on a compact touch surface, a product may explicitly use a drill-in interaction with a Back action.',+ },+ {+ guidance: true,+ description:+ 'Choose presentation explicitly in product code. A compact, coarse-pointer, hover-free media query is one useful policy, but DropdownMenu does not impose a universal device breakpoint.',+ },+ {+ guidance: true,+ description:+ 'When the content is no longer a short list of immediate actions, reevaluate the interaction and choose a component that matches the actual task; content traits alone do not determine the component.',+ },+ {+ guidance: false,+ description:+ 'Use a DropdownMenu for navigation; use a navigation component instead.',+ },+ {+ guidance: false,+ description:+ 'Place more than 10–12 items in a single menu without grouping them into sections.',+ },],},};diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsxindex 13582f5374..d0500a54e1 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx@@ -10,16 +10,43 @@*/import {describe, it, expect, vi, beforeEach} from 'vitest';+import {readFileSync} from 'node:fs';import {render, screen, fireEvent, waitFor, act} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {useState} from 'react';+import * as stylex from '@stylexjs/stylex';import {DropdownMenu} from './DropdownMenu';import {DropdownMenuItem} from './DropdownMenuItem';import {DropdownMenuDivider} from './DropdownMenuDivider';import {Divider} from '../Divider';+import {rtlStyles} from '../utils';+import {__resetInteractionModalityForTest} from '../utils/interactionModality';+import {focusOutlineStyles} from '../utils/focusOutline.stylex';// Mock showPopover and hidePopover methods since they're not implemented in jsdombeforeEach(() => {+ __resetInteractionModalityForTest();+ HTMLDialogElement.prototype.showModal = vi.fn(function (+ this: HTMLDialogElement,+ ) {+ this.setAttribute('open', '');+ });+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {+ this.removeAttribute('open');+ });+ vi.stubGlobal(+ 'matchMedia',+ vi.fn().mockImplementation((query: string) => ({+ matches: false,+ media: query,+ onchange: null,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),+ );HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {this.setAttribute('popover-open', '');const event = new Event('toggle', {bubbles: false});@@ -83,6 +110,334 @@ describe('DropdownMenu', () => {).not.toBeInTheDocument();});+ it('renders data-driven actions in a bottom sheet when requested', async () => {+ const user = userEvent.setup();+ const onEdit = vi.fn();++ render(+ <DropdownMenu+ button={{label: 'Project actions'}}+ presentation="bottom-sheet"+ items={[{label: 'Edit project', onClick: onEdit}]}+ />,+ );++ const trigger = screen.getByRole('button', {name: /Project actions/});+ expect(trigger).toHaveAttribute('aria-haspopup', 'dialog');+ expect(screen.queryByRole('menu', {hidden: true})).not.toBeInTheDocument();++ await user.click(trigger);++ expect(+ screen.getByRole('dialog', {name: 'Project actions'}),+ ).toBeInTheDocument();+ const editAction = screen.getByRole('button', {name: 'Edit project'});+ await waitFor(() =>+ expect(+ screen.getByRole('dialog', {name: 'Project actions'}),+ ).toContainElement(document.activeElement as HTMLElement),+ );+ expect(editAction).not.toHaveFocus();+ await user.click(editAction);++ expect(onEdit).toHaveBeenCalledTimes(1);+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ });++ it('aligns the bottom-sheet heading with the item content edge and keeps item padding', async () => {+ const user = userEvent.setup();++ render(+ <DropdownMenu+ button={{label: 'Project actions'}}+ presentation="bottom-sheet"+ items={[{label: 'Edit project', icon: <span aria-hidden="true" />}]}+ />,+ );++ await user.click(screen.getByRole('button', {name: /Project actions/}));++ const heading = screen.getByRole('heading', {name: 'Project actions'});+ expect(heading).toHaveStyle({marginInlineStart: 'var(--spacing-3)'});+ expect(heading.closest('.astryx-section')).toHaveStyle({+ paddingInlineStart: 'var(--spacing-1)',+ paddingInlineEnd: 'var(--spacing-1)',+ });+ expect(+ screen.getByRole('button', {name: 'Edit project'}).closest('li'),+ ).toHaveStyle({paddingInline: 'var(--spacing-3)'});+ });++ it('drills into nested data items in bottom-sheet presentation', async () => {+ const user = userEvent.setup();++ render(+ <DropdownMenu+ button={{label: 'Project actions'}}+ presentation="bottom-sheet"+ items={[+ {+ label: 'Move to project',+ items: [{label: 'Apollo launch'}],+ },+ ]}+ />,+ );++ await user.click(screen.getByRole('button', {name: /Project actions/}));+ await user.click(screen.getByRole('button', {name: 'Move to project'}));++ const submenuHeading = screen.getByRole('heading', {+ name: 'Move to project',+ });+ expect(submenuHeading).toBeInTheDocument();+ await waitFor(() => expect(submenuHeading).toHaveFocus());+ expect(+ screen.getByRole('button', {name: 'Apollo launch'}),+ ).toBeInTheDocument();++ const backButton = screen.getByRole('button', {name: 'Back'});+ expect(backButton).toHaveAttribute('aria-label', 'Back');+ expect(backButton).not.toHaveTextContent('Back');+ await user.click(backButton);+ const rootHeading = screen.getByRole('heading', {+ name: 'Project actions',+ });+ expect(rootHeading).toBeInTheDocument();+ await waitFor(() => expect(rootHeading).toHaveFocus());+ });++ it('returns to the root after a controlled bottom sheet closes externally', async () => {+ const user = userEvent.setup();++ function ControlledDropdownMenu() {+ const [isOpen, setIsOpen] = useState(false);++ return (+ <>+ <button type="button" onClick={() => setIsOpen(false)}>+ Close externally+ </button>+ <DropdownMenu+ button={{label: 'Project actions'}}+ presentation="bottom-sheet"+ isMenuOpen={isOpen}+ onOpenChange={setIsOpen}+ items={[+ {+ label: 'Move to project',+ items: [{label: 'Apollo launch'}],+ },+ ]}+ />+ </>+ );+ }++ render(<ControlledDropdownMenu />);++ await user.click(screen.getByRole('button', {name: /Project actions/}));+ await user.click(screen.getByRole('button', {name: 'Move to project'}));+ expect(+ screen.getByRole('heading', {name: 'Move to project'}),+ ).toBeInTheDocument();++ await user.click(screen.getByRole('button', {name: 'Close externally'}));+ await user.click(screen.getByRole('button', {name: /Project actions/}));++ expect(+ screen.getByRole('heading', {name: 'Project actions'}),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole('button', {name: 'Apollo launch'}),+ ).not.toBeInTheDocument();+ });++ it('mirrors bottom-sheet drill-in affordances under RTL', async () => {+ const user = userEvent.setup();+ const {className: mirrorClassName} = stylex.props(rtlStyles.mirror);+ const mirrorClasses = mirrorClassName?.split(' ') ?? [];+ expect(mirrorClasses.length).toBeGreaterThan(0);++ render(+ <div dir="rtl">+ <DropdownMenu+ button={{label: 'Project actions'}}+ presentation="bottom-sheet"+ items={[+ {+ label: 'Move to project',+ items: [{label: 'Apollo launch'}],+ },+ ]}+ />+ </div>,+ );++ await user.click(screen.getByRole('button', {name: /Project actions/}));+ const submenuButton = screen.getByRole('button', {+ name: 'Move to project',+ });+ const forwardIcon = submenuButton+ .closest('li')+ ?.querySelector('.astryx-icon');+ expect(forwardIcon).not.toBeNull();+ for (const className of mirrorClasses) {+ expect(forwardIcon).toHaveClass(className);+ }++ await user.click(submenuButton);+ const backButton = screen.getByRole('button', {name: 'Back'});+ const backIcon = backButton.querySelector('.astryx-icon');+ expect(backIcon).not.toBeNull();+ for (const className of mirrorClasses) {+ expect(backIcon).toHaveClass(className);+ }+ });++ it('uses the BottomSheet for adaptive presentation on compact touch', async () => {+ vi.stubGlobal(+ 'matchMedia',+ vi.fn().mockImplementation((query: string) => ({+ matches: query === '(max-width: 768px) and (pointer: coarse)',+ media: query,+ onchange: null,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),+ );+ const user = userEvent.setup();+ render(+ <DropdownMenu+ button={{label: 'Actions'}}+ presentation="adaptive"+ items={[{label: 'Edit'}]}+ />,+ );++ await user.click(screen.getByRole('button', {name: /Actions/}));+ expect(screen.getByRole('dialog', {name: 'Actions'})).toBeInTheDocument();+ expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled();+ });++ it('uses the shared menu BottomSheet frame', () => {+ const source = readFileSync(+ 'packages/core/src/DropdownMenu/DropdownMenu.tsx',+ 'utf8',+ );++ expect(source).toContain('<MenuBottomSheet');+ expect(source).not.toContain("import {BottomSheet} from '../BottomSheet'");+ expect(source).not.toContain("import {Section} from '../Section'");+ });++ it('keeps adaptive presentation anchored without compact touch', async () => {+ const user = userEvent.setup();+ render(+ <DropdownMenu+ button={{label: 'Actions'}}+ presentation="adaptive"+ items={[{label: 'Edit'}]}+ />,+ );++ await user.click(screen.getByRole('button', {name: /Actions/}));+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalledOnce();+ expect(HTMLDialogElement.prototype.showModal).not.toHaveBeenCalled();+ });++ it('preserves uncontrolled open state when adaptive presentation changes', async () => {+ let matches = false;+ const listeners = new Set<() => void>();+ vi.stubGlobal(+ 'matchMedia',+ vi.fn().mockImplementation((query: string) => ({+ get matches() {+ return matches;+ },+ media: query,+ onchange: null,+ addEventListener: (_type: string, listener: () => void) =>+ listeners.add(listener),+ removeEventListener: (_type: string, listener: () => void) =>+ listeners.delete(listener),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),+ );+ const user = userEvent.setup();+ render(+ <DropdownMenu+ button={{label: 'Actions'}}+ presentation="adaptive"+ items={[{label: 'Edit'}]}+ />,+ );++ await user.click(screen.getByRole('button', {name: /Actions/}));+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalledOnce();++ matches = true;+ act(() => listeners.forEach(listener => listener()));++ expect(screen.getByRole('dialog', {name: 'Actions'})).toBeInTheDocument();+ expect(screen.getByRole('button', {name: /Actions/})).toHaveAttribute(+ 'aria-expanded',+ 'true',+ );+ });++ it('focuses the first action when a bottom sheet opens from the keyboard', async () => {+ const user = userEvent.setup();+ render(+ <DropdownMenu+ button={{label: 'Actions'}}+ presentation="bottom-sheet"+ items={[{label: 'Edit'}, {label: 'Delete'}]}+ />,+ );++ const trigger = screen.getByRole('button', {name: /Actions/});+ trigger.focus();+ await user.keyboard('{Enter}');++ await waitFor(() =>+ expect(screen.getByRole('button', {name: 'Edit'})).toHaveFocus(),+ );+ });++ it('restores touch focus without painting a trigger focus ring', async () => {+ render(+ <DropdownMenu+ button={{label: 'Actions'}}+ presentation="bottom-sheet"+ items={[{label: 'Edit'}]}+ />,+ );++ const trigger = screen.getByRole('button', {name: /Actions/});+ fireEvent.pointerDown(trigger, {pointerType: 'touch'});+ fireEvent.click(trigger, {detail: 1});++ const action = screen.getByRole('button', {name: 'Edit'});+ action.focus();+ fireEvent.pointerDown(action, {pointerType: 'touch'});+ fireEvent.click(action, {detail: 1});++ expect(action).not.toHaveFocus();+ trigger.focus();+ expect(trigger).toHaveFocus();+ await waitFor(() =>+ expect(trigger).toHaveClass(+ stylex.props(focusOutlineStyles.suppressed).className!,+ ),+ );+ });+it('defaults menu placement below', () => {render(<DropdownMenu button={{label: 'Actions'}} items={[{label: 'Item 1'}]} />,@@ -127,6 +482,26 @@ describe('DropdownMenu', () => {);});+ it('uses block-axis viewport gutters for side placement', () => {+ render(+ <DropdownMenu+ button={{label: 'Actions'}}+ placement="end"+ alignment="start"+ items={[{label: 'Item 1'}]}+ />,+ );+ const popover = screen+ .getByRole('menu', {hidden: true})+ .closest('[popover]');+ expect(popover?.className).toContain(+ 'DropdownMenu__styles.popoverViewportBlockStart',+ );+ expect(popover?.className).not.toContain(+ 'DropdownMenu__styles.popoverViewportStart',+ );+ });+it('emits the direction-independent logical mapping under an RTL ancestor (#3389)', async () => {// The self-* position-area keywords resolve against the popover's own// inherited direction in the browser, so RTL emits the same string as@@ -147,6 +522,104 @@ describe('DropdownMenu', () => {);});+ it('caps default and custom widths to the available viewport', () => {+ const {unmount} = render(+ <DropdownMenu button={{label: 'Actions'}} items={[{label: 'Item 1'}]} />,+ );+ let menu = screen.getByRole('menu', {hidden: true});+ let popover = menu.closest('[popover]');+ expect(popover?.className).toContain(+ 'DropdownMenu__styles.popoverViewport',+ );+ expect(popover?.className).toContain('DropdownMenu__styles.popoverAligned');+ expect(popover).toHaveStyle(+ 'min-width: min(anchor-size(width),calc(100% - max(var(--spacing-4),env(safe-area-inset-left,0px),env(safe-area-inset-right,0px))))',+ );++ unmount();+ render(+ <DropdownMenu+ button={{label: 'Wide actions'}}+ menuWidth={640}+ items={[{label: 'Item 1'}]}+ />,+ );+ menu = screen.getByRole('menu', {hidden: true});+ popover = menu.closest('[popover]');+ expect(popover?.className).toContain(+ 'DropdownMenu__styles.popoverViewport',+ );+ expect(popover).toHaveStyle({minWidth: 'var(--x-minWidth)'});+ expect(popover?.getAttribute('style')).toContain('min(640px, calc(100%');+ });++ it.each(['max-content', 'fit-content', 'auto'])(+ 'preserves the valid %s menuWidth while retaining the viewport cap',+ menuWidth => {+ render(+ <DropdownMenu+ button={{label: 'Actions'}}+ menuWidth={menuWidth}+ items={[{label: 'Item 1'}]}+ />,+ );++ const popover = screen+ .getByRole('menu', {hidden: true})+ .closest('[popover]');+ expect(popover?.className).toContain(+ 'DropdownMenu__styles.popoverCustomIntrinsicWidth',+ );+ expect(popover?.getAttribute('style')).toContain(menuWidth);+ expect(popover?.className).toContain(+ 'DropdownMenu__styles.popoverViewportAligned',+ );+ expect(popover?.getAttribute('style')).not.toContain(`min(${menuWidth},`);+ },+ );++ it('caps menu height and only scrolls when content overflows', async () => {+ const clientHeightSpy = vi+ .spyOn(HTMLElement.prototype, 'clientHeight', 'get')+ .mockReturnValue(300);+ const scrollHeightSpy = vi+ .spyOn(HTMLElement.prototype, 'scrollHeight', 'get')+ .mockReturnValue(300);++ try {+ render(+ <DropdownMenu+ button={{label: 'Actions'}}+ items={[{label: 'Item 1'}]}+ />,+ );+ const menu = screen.getByRole('menu', {hidden: true});+ fireEvent.click(screen.getByRole('button', {name: /Actions/}));+ await waitFor(() => {+ expect(screen.getByRole('button', {name: /Actions/})).toHaveAttribute(+ 'aria-expanded',+ 'true',+ );+ });+ expect(menu).toHaveStyle(+ 'max-height: min(300px,calc(100dvb - max(var(--spacing-4),env(safe-area-inset-top,0px)) - max(var(--spacing-4),env(safe-area-inset-bottom,0px))))',+ );+ expect(menu).not.toHaveStyle({overflowY: 'auto'});+ expect(menu).toHaveAttribute('tabindex', '-1');++ scrollHeightSpy.mockReturnValue(480);+ fireEvent(window, new Event('resize'));++ await waitFor(() => {+ expect(menu).toHaveStyle({overflowY: 'auto'});+ expect(menu).toHaveStyle({overflowX: 'hidden'});+ });+ } finally {+ clientHeightSpy.mockRestore();+ scrollHeightSpy.mockRestore();+ }+ });+it('has aria-haspopup and aria-expanded attributes', () => {render(<DropdownMenu button={{label: 'Actions'}} items={[{label: 'Item 1'}]} />,@@ -196,7 +669,7 @@ describe('DropdownMenu', () => {);});- it('restores focus to the trigger after native light dismiss', async () => {+ it('restores focus to the trigger after keyboard dismissal', async () => {const raf = vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => {@@ -215,17 +688,16 @@ describe('DropdownMenu', () => {const trigger = screen.getByRole('button', {name: /Actions/});trigger.focus();- await user.click(trigger);- // Pointer opens focus the menu container, not the first item (#4477).- expect(screen.getByRole('menu', {hidden: true})).toHaveFocus();+ await user.keyboard('{Enter}');+ expect(+ screen.getByRole('menuitem', {name: 'Edit', hidden: true}),+ ).toHaveFocus();const popoverEl = screen.getByRole('menu', {hidden: true}).closest('[popover]');expect(popoverEl).not.toBeNull();- popoverEl?.addEventListener('toggle', () => {- trigger.blur();- });+ trigger.blur();const toggleEvent = new Event('toggle');Object.defineProperty(toggleEvent, 'newState', {value: 'closed'});fireEvent(popoverEl as HTMLElement, toggleEvent);@@ -236,6 +708,44 @@ describe('DropdownMenu', () => {}});+ it('does not leave focus on the trigger after pointer dismissal', async () => {+ const raf = vi+ .spyOn(window, 'requestAnimationFrame')+ .mockImplementation(callback => {+ callback(0);+ return 0;+ });++ try {+ render(+ <DropdownMenu+ button={{label: 'Actions'}}+ items={[{label: 'Edit'}, {label: 'Delete'}]}+ />,+ );++ const trigger = screen.getByRole('button', {name: /Actions/});+ fireEvent.pointerDown(trigger, {pointerType: 'touch'});+ fireEvent.click(trigger, {detail: 1});+ expect(screen.getByRole('menu', {hidden: true})).toHaveFocus();++ const popoverEl = screen+ .getByRole('menu', {hidden: true})+ .closest('[popover]');+ expect(popoverEl).not.toBeNull();+ // Simulate native popover focus restoration occurring before React's+ // toggle handler; pointer dismissal should remove that focus again.+ trigger.focus();+ const toggleEvent = new Event('toggle');+ Object.defineProperty(toggleEvent, 'newState', {value: 'closed'});+ fireEvent(popoverEl as HTMLElement, toggleEvent);++ expect(trigger).not.toHaveFocus();+ } finally {+ raf.mockRestore();+ }+ });+it('closes the menu when Tab is pressed inside it (APG menu-button)', async () => {const user = userEvent.setup();render(@@ -1267,6 +1777,7 @@ describe('DropdownMenu open focus follows input modality (#4477)', () => {const menu = screen.getByRole('menu', {hidden: true});await waitFor(() => expect(menu).toHaveFocus());+ expect(menu).toHaveStyle({outline: 'none'});expect(screen.getByRole('menuitem', {name: 'Edit', hidden: true}),).not.toHaveFocus();diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsxindex 105dc1ca29..9907099729 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx@@ -4,8 +4,10 @@/*** @file DropdownMenu.tsx- * @input Uses React, StyleX, usePopover, Button, Icon, useListFocus- * @output Exports DropdownMenu component+ * @input Uses React, StyleX, usePopover, MenuBottomSheet, Button, List,+ * useListFocus, and the shared viewport-safe menu-width resolver+ * @output Exports DropdownMenu with caller-selected popover or bottom-sheet+ * presentation* @position Core implementation; consumed by index.ts** Supports two modes with a single keyboard/focus path:@@ -39,6 +41,7 @@ import React, {import * as stylex from '@stylexjs/stylex';import {usePopoverInternal} from '../Popover/usePopover';import {Button, type ButtonProps} from '../Button';+import {Heading} from '../Heading';import {Icon} from '../Icon';import {renderDropdownItems} from './renderDropdownItems';@@ -54,27 +57,65 @@ import {} from './DropdownMenuContext';import {useListFocus} from '../hooks/useListFocus';import {useTypeahead} from '../hooks/useTypeahead';+import {useFocusReturnVisibility} from '../hooks/useFocusReturnVisibility';+import {useMenuOverflow} from './useMenuOverflow';+import {resolveMenuWidth} from './menuWidth';+import {+ useAdaptivePresentation,+ type AdaptivePresentation,+} from '../hooks/useAdaptivePresentation';+import {MenuBottomSheet} from './MenuBottomSheet';+import {MenuBottomSheetActionList} from './MenuBottomSheetActionList';import {layerAnimations} from '../Layer/layerAnimations.stylex';import type {LayerAlignment, LayerPlacement} from '../Layer/useLayer';import {spacingVars,+ colorVars,radiusVars,durationVars,easeVars,} from '../theme/tokens.stylex';-import {mergeProps} from '../utils';+import {mergeProps, rtlStyles} from '../utils';import type {BaseProps} from '../BaseProps';import {themeProps} from '../utils/themeProps';+import {+ getInteractionModality,+ trackInteractionModality,+} from '../utils/interactionModality';import {useTranslator} from '../i18n';+import {focusOutlineStyles} from '../utils/focusOutline.stylex';++const MENU_VIEWPORT_GUTTER = spacingVars['--spacing-4'];+const MENU_MAX_INLINE_SIZE = `calc(100vi - max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-left, 0px)) - max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-right, 0px)))`;+const MENU_MAX_INLINE_SIZE_FALLBACK = `calc(100vw - ${MENU_VIEWPORT_GUTTER} - ${MENU_VIEWPORT_GUTTER})`;+const MENU_MAX_BLOCK_SIZE = `min(300px, calc(100dvb - max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-top, 0px)) - max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-bottom, 0px))))`;+const MENU_MAX_BLOCK_SIZE_FALLBACK = `min(300px, calc(100vh - ${MENU_VIEWPORT_GUTTER} - ${MENU_VIEWPORT_GUTTER}))`;+const MENU_POSITION_AREA_MAX_INLINE_SIZE = `calc(100% - max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-left, 0px), env(safe-area-inset-right, 0px)))`;+const MENU_POSITION_AREA_MAX_INLINE_SIZE_FALLBACK = `calc(100% - ${MENU_VIEWPORT_GUTTER})`;+const MENU_INLINE_EDGE_GUTTER = `max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-left, 0px), env(safe-area-inset-right, 0px))`;+const MENU_TRIGGER_OPEN_BACKGROUND = `linear-gradient(${colorVars['--color-overlay-pressed']}, ${colorVars['--color-overlay-pressed']})`;const styles = stylex.create({+ triggerOpen: {+ backgroundImage: MENU_TRIGGER_OPEN_BACKGROUND,+ },dropdown: {boxSizing: 'border-box',display: 'flex',flexDirection: 'column',gap: spacingVars['--spacing-0-5'],- maxHeight: '300px',- overflowY: 'auto',+ // Pointer opens focus this container so subsequent arrow keys and Escape+ // stay owned by the menu. It is an internal focus target, not a control,+ // so suppress the browser ring; keyboard focus moves to an item instead.+ outline: 'none',+ maxInlineSize: stylex.firstThatWorks(+ MENU_MAX_INLINE_SIZE,+ MENU_MAX_INLINE_SIZE_FALLBACK,+ ),+ maxHeight: stylex.firstThatWorks(+ MENU_MAX_BLOCK_SIZE,+ MENU_MAX_BLOCK_SIZE_FALLBACK,+ ),'--_dropdown-menu-radius': radiusVars['--radius-container'],'--_dropdown-menu-padding': spacingVars['--spacing-1'],padding: spacingVars['--spacing-1'],@@ -84,14 +125,95 @@ const styles = stylex.create({transitionDuration: durationVars['--duration-fast'],transitionTimingFunction: easeVars['--ease-standard'],},- popover: {- minWidth: 'anchor-size(width)',+ scrollable: {+ overflowY: 'auto',+ overflowX: 'hidden',+ overscrollBehavior: 'contain',+ },+ popoverViewport: {+ boxSizing: 'border-box',+ maxBlockSize: stylex.firstThatWorks(+ MENU_MAX_BLOCK_SIZE,+ MENU_MAX_BLOCK_SIZE_FALLBACK,+ ),+ },+ popoverViewportAligned: {+ maxInlineSize: stylex.firstThatWorks(+ MENU_POSITION_AREA_MAX_INLINE_SIZE,+ MENU_POSITION_AREA_MAX_INLINE_SIZE_FALLBACK,+ ),+ },+ popoverViewportStart: {+ marginInlineEnd: MENU_INLINE_EDGE_GUTTER,+ },+ popoverViewportEnd: {+ marginInlineStart: MENU_INLINE_EDGE_GUTTER,+ },+ popoverViewportBlockStart: {+ marginBlockEnd: `max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-bottom, 0px))`,+ },+ popoverViewportBlockEnd: {+ marginBlockStart: `max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-top, 0px))`,+ },+ popoverViewportCentered: {+ marginInlineStart: MENU_INLINE_EDGE_GUTTER,+ marginInlineEnd: MENU_INLINE_EDGE_GUTTER,+ maxInlineSize: stylex.firstThatWorks(+ MENU_MAX_INLINE_SIZE,+ MENU_MAX_INLINE_SIZE_FALLBACK,+ ),+ },+ popoverViewportBlockCentered: {+ marginBlockStart: `max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-top, 0px))`,+ marginBlockEnd: `max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-bottom, 0px))`,+ maxInlineSize: stylex.firstThatWorks(+ MENU_MAX_INLINE_SIZE,+ MENU_MAX_INLINE_SIZE_FALLBACK,+ ),+ },+ popoverAligned: {+ minWidth: stylex.firstThatWorks(+ `min(anchor-size(width), ${MENU_POSITION_AREA_MAX_INLINE_SIZE})`,+ `min(anchor-size(width), ${MENU_POSITION_AREA_MAX_INLINE_SIZE_FALLBACK})`,+ 'anchor-size(width)',+ ),},- popoverCustomWidth: (width: string | number) => ({- minWidth: typeof width === 'number' ? `${width}px` : width,+ popoverCentered: {+ minWidth: stylex.firstThatWorks(+ `min(anchor-size(width), ${MENU_MAX_INLINE_SIZE})`,+ `min(anchor-size(width), ${MENU_MAX_INLINE_SIZE_FALLBACK})`,+ 'anchor-size(width)',+ ),+ },+ popoverCustomWidth: (width: string) => ({+ minWidth: width,+ }),+ popoverCustomIntrinsicWidth: (width: string) => ({+ inlineSize: width,}),});+const bottomSheetStyles = stylex.create({+ content: {+ width: '100%',+ },+ header: {+ display: 'flex',+ flexDirection: 'row',+ alignItems: 'center',+ gap: spacingVars['--spacing-1'],+ marginBottom: spacingVars['--spacing-2'],+ },+ rootHeading: {+ // Match the content edge of a spacious ListItem. Icon-bearing rows place+ // their icon here; rows without an icon place their label here.+ marginInlineStart: spacingVars['--spacing-3'],+ },+ viewHeading: {+ outline: 'none',+ },+});+// =============================================================================// Types// =============================================================================@@ -157,22 +279,31 @@ export type DropdownMenuOption =export type DropdownMenuButtonProps = Omit<ButtonProps, 'onClick'>;+export type DropdownMenuPresentation = AdaptivePresentation;+interface DropdownMenuBaseProps extends BaseProps {button?: DropdownMenuButtonProps;isMenuOpen?: boolean;onOpenChange?: (isOpen: boolean) => void;+ /**+ * Minimum popover width. The menu may grow for its content but is capped to+ * the available viewport space. Ignored by bottom-sheet presentation.+ * Defaults to the trigger width.+ */menuWidth?: number | string;onClick?: () => void;hasChevron?: boolean;/**- * Position placement relative to the trigger.+ * Popover position relative to the trigger. Ignored by bottom-sheet+ * presentation.* Uses the same placement values as other Astryx layer-based components.* @default 'below'*/placement?: LayerPlacement;/**- * Alignment along the placement axis.+ * Popover alignment along the placement axis. Ignored by bottom-sheet+ * presentation.* Uses the same alignment values as other Astryx layer-based components.* @default 'start'*/@@ -182,11 +313,19 @@ interface DropdownMenuBaseProps extends BaseProps {}interface DropdownMenuDataProps extends DropdownMenuBaseProps {+ /**+ * Surface used to present the actions. Pass a value selected by product+ * policy (for example, a compact-touch media query) when the presentation+ * should adapt. Bottom-sheet presentation is intended for short action sets.+ * @default 'popover'+ */+ presentation?: DropdownMenuPresentation;items: DropdownMenuOption[];children?: undefined;}interface DropdownMenuCompoundProps extends DropdownMenuBaseProps {+ presentation?: 'popover';items?: undefined;children: ReactNode;}@@ -202,15 +341,16 @@ export type DropdownMenuProps =* A dropdown menu component that displays a list of actionable items.** Supports two modes:- * - **Data-driven**: pass `items` for static menus with optional custom rendering- * - **Compound-component**: pass JSX children for dynamic, stateful, or lazy-loaded menus- *- * Both modes share the same DOM-based keyboard navigation via useListFocus.+ * - **Data-driven**: pass `items` and choose either the default anchored+ * popover or the modal bottom-sheet presentation.+ * - **Compound-component**: pass JSX children for dynamic, stateful, or+ * lazy-loaded anchored popover menus.** @example* ```* <DropdownMenu* button={{ label: 'Actions' }}+ * presentation={useBottomSheet ? 'bottom-sheet' : 'popover'}* items={[* { label: 'Edit', onClick: () => handleEdit() },* { label: 'Delete', onClick: () => handleDelete() },@@ -223,7 +363,210 @@ export type DropdownMenuProps =// locale.const DEFAULT_BUTTON_I18N_KEY = '@astryx.dropdownMenu.label' as const;-export function DropdownMenu({+function DropdownMenuBottomSheet({+ button: buttonFromProps,+ isMenuOpen: controlledIsOpen,+ onOpenChange,+ onClick,+ hasChevron = true,+ items,+ presentation: _presentation,+ menuWidth: _menuWidth,+ placement: _placement,+ alignment: _alignment,+ className,+ style,+ xstyle,+ 'data-testid': testId,+ ...rest+}: DropdownMenuDataProps & {presentation: 'bottom-sheet'}) {+ const t = useTranslator();+ const button = buttonFromProps ?? {label: t(DEFAULT_BUTTON_I18N_KEY)};+ const backLabel = t('@astryx.dropdownMenu.back');+ const buttonRef = useRef<HTMLButtonElement>(null);+ const actionListRef = useRef<HTMLDivElement>(null);+ const openModalityRef = useRef<'keyboard' | 'pointer'>('pointer');+ const {+ isFocusRingSuppressed,+ onFocusReturnTargetFocus,+ prepareFocusReturn,+ resetFocusReturn,+ } = useFocusReturnVisibility();+ const viewHeadingRef = useRef<HTMLHeadingElement>(null);+ const previousSubmenuDepthRef = useRef(0);+ const [internalIsOpen, setInternalIsOpen] = useState(false);+ const [submenuPath, setSubmenuPath] = useState<DropdownMenuItemData[]>([]);+ const isControlled = controlledIsOpen !== undefined;+ const isOpen = isControlled ? controlledIsOpen : internalIsOpen;+ const [previousIsOpen, setPreviousIsOpen] = useState(isOpen);+ if (previousIsOpen !== isOpen) {+ setPreviousIsOpen(isOpen);+ if (!isOpen && submenuPath.length > 0) {+ setSubmenuPath([]);+ }+ }+ const currentSubmenu = submenuPath.at(-1);+ const currentItems = currentSubmenu?.items ?? items;+ const currentTitle = currentSubmenu?.label ?? button.label;+ const sheetLabel =+ typeof currentTitle === 'string' ? currentTitle : button.label;++ const setOpen = useCallback(+ (nextIsOpen: boolean) => {+ if (!nextIsOpen) {+ setSubmenuPath([]);+ prepareFocusReturn();+ } else {+ resetFocusReturn();+ }+ onOpenChange?.(nextIsOpen);+ if (!isControlled) {+ setInternalIsOpen(nextIsOpen);+ }+ },+ [isControlled, onOpenChange, prepareFocusReturn, resetFocusReturn],+ );++ const handleSelect = useCallback(+ (item: DropdownMenuItemData) => {+ if (item.isDisabled) {+ return;+ }+ item.onClick?.();+ if (item.hasCloseOnSelect !== false) {+ setOpen(false);+ }+ },+ [setOpen],+ );++ const isIconOnly = button.isIconOnly === true;+ const resolvedEndContent =+ button.endContent ??+ (hasChevron && !isIconOnly ? (+ <Icon icon="chevronDown" size="sm" color="inherit" />+ ) : undefined);++ useEffect(() => {+ if (!isOpen || openModalityRef.current !== 'keyboard') {+ return;+ }+ const frame = requestAnimationFrame(() => {+ actionListRef.current+ ?.querySelector<HTMLElement>('button:not(:disabled), a[href]')+ ?.focus({preventScroll: true});+ });+ return () => cancelAnimationFrame(frame);+ }, [currentItems, isOpen]);++ useEffect(() => {+ if (!isOpen) {+ previousSubmenuDepthRef.current = 0;+ return;+ }+ if (submenuPath.length === previousSubmenuDepthRef.current) {+ return;+ }+ previousSubmenuDepthRef.current = submenuPath.length;+ const frame = requestAnimationFrame(() => {+ viewHeadingRef.current?.focus({preventScroll: true});+ });+ return () => cancelAnimationFrame(frame);+ }, [isOpen, submenuPath.length]);++ return (+ <>+ <Button+ {...button}+ ref={buttonRef}+ xstyle={[+ isOpen && styles.triggerOpen,+ button.xstyle,+ isFocusRingSuppressed && focusOutlineStyles.suppressed,+ ]}+ tooltip={isOpen ? undefined : button.tooltip}+ endContent={resolvedEndContent}+ onPointerDown={event => {+ button.onPointerDown?.(event);+ openModalityRef.current = 'pointer';+ }}+ onKeyDown={event => {+ button.onKeyDown?.(event);+ if (+ event.key === 'ArrowDown' ||+ event.key === 'Enter' ||+ event.key === ' '+ ) {+ openModalityRef.current = 'keyboard';+ }+ }}+ onFocus={event => {+ button.onFocus?.(event);+ onFocusReturnTargetFocus();+ }}+ onClick={() => {+ onClick?.();+ setOpen(!isOpen);+ }}+ aria-haspopup="dialog"+ aria-expanded={isOpen}+ data-testid={testId}+ />++ <MenuBottomSheet+ isOpen={isOpen}+ onOpenChange={setOpen}+ finalFocusRef={buttonRef}+ label={sheetLabel}>+ <div+ ref={actionListRef}+ {...rest}+ {...mergeProps(+ themeProps('dropdown-menu', {presentation: 'bottom-sheet'}),+ stylex.props(bottomSheetStyles.content, xstyle),+ className,+ style,+ )}>+ <div {...stylex.props(bottomSheetStyles.header)}>+ {submenuPath.length > 0 && (+ <Button+ label={backLabel}+ variant="ghost"+ size="sm"+ icon={+ <Icon+ icon="chevronLeft"+ size="sm"+ xstyle={rtlStyles.mirror}+ />+ }+ isIconOnly+ onClick={() => setSubmenuPath(path => path.slice(0, -1))}+ />+ )}+ <Heading+ ref={viewHeadingRef}+ level={3}+ tabIndex={-1}+ xstyle={[+ bottomSheetStyles.viewHeading,+ submenuPath.length === 0 && bottomSheetStyles.rootHeading,+ ]}>+ {currentTitle}+ </Heading>+ </div>+ <MenuBottomSheetActionList+ items={currentItems}+ onSelect={handleSelect}+ onOpenSubmenu={item => setSubmenuPath(path => [...path, item])}+ />+ </div>+ </MenuBottomSheet>+ </>+ );+}++function DropdownMenuPopover({button: buttonFromProps,isMenuOpen: controlledIsOpen,onOpenChange,@@ -232,6 +575,7 @@ export function DropdownMenu({hasChevron = true,placement = 'below',alignment = 'start',+ presentation: _presentation,className,style,xstyle,@@ -261,13 +605,25 @@ export function DropdownMenu({const isControlled = controlledIsOpen !== undefined;const isOpen = isControlled ? controlledIsOpen : internalIsOpen;- // Close menu + return focus to trigger+ useEffect(() => {+ trackInteractionModality();+ }, []);++ // Keyboard dismissal returns focus to the trigger. Pointer dismissal leaves+ // focus where the browser put it; Safari can otherwise paint a focus-visible+ // ring on the trigger after a touch selection. Native popover restoration+ // can happen before `toggle`, so explicitly blur that pointer-restored case.const handleLayerHide = useCallback(() => {onOpenChange?.(false);if (!isControlled) {setInternalIsOpen(false);}- buttonRef.current?.focus();+ const trigger = buttonRef.current;+ if (getInteractionModality() === 'keyboard') {+ trigger?.focus();+ } else if (document.activeElement === trigger) {+ trigger?.blur();+ }}, [isControlled, onOpenChange]);// Defer item focus until the layer has committed open, so focus restore@@ -469,9 +825,21 @@ export function DropdownMenu({<Icon icon="chevronDown" size="sm" color="inherit" />) : undefined);- const popoverXstyle = menuWidth- ? styles.popoverCustomWidth(menuWidth)- : styles.popover;+ const requestedWidthLimit =+ alignment === 'center'+ ? MENU_MAX_INLINE_SIZE_FALLBACK+ : MENU_POSITION_AREA_MAX_INLINE_SIZE_FALLBACK;+ const resolvedMenuWidth = menuWidth+ ? resolveMenuWidth(menuWidth, requestedWidthLimit)+ : null;+ const popoverXstyle = resolvedMenuWidth+ ? resolvedMenuWidth.property === 'inlineSize'+ ? styles.popoverCustomIntrinsicWidth(resolvedMenuWidth.value)+ : styles.popoverCustomWidth(resolvedMenuWidth.value)+ : alignment === 'center'+ ? styles.popoverCentered+ : styles.popoverAligned;+ const isSidePlacement = placement === 'start' || placement === 'end';// Context for compound itemsconst contextValue = useMemo<DropdownMenuContextValue>(() => ({closeMenu, menuSize}),@@ -481,6 +849,7 @@ export function DropdownMenu({// Resolve menu content: data-driven items become componentsconst menuContent =props.items !== undefined ? renderDropdownItems(items) : children;+ const hasOverflow = useMenuOverflow(listRef, menuContent, popover.isOpen);return (<>@@ -498,6 +867,7 @@ export function DropdownMenu({/* eslint-enable react-compiler/react-compiler */}}}+ xstyle={[isOpen && styles.triggerOpen, button.xstyle]}tooltip={isOpen ? undefined : button.tooltip}endContent={resolvedEndContent}onClick={handleButtonClick}@@ -514,11 +884,11 @@ export function DropdownMenu({ref={listRef}id={menuId}role="menu"- // Focus target for pointer opens (not in the Tab order): holding- // focus on the container keeps key events (arrows, typeahead,- // Escape, Tab) inside the menu without highlighting any item.- // Mirrors the DropdownMenuSubMenu flyout container.- tabIndex={-1}+ // Pointer opens focus the container so arrows, typeahead, Escape and+ // Tab remain owned by the menu without pre-highlighting an item.+ // An overflowing menu joins the Tab order so its scrollable region is+ // keyboard-accessible; Tab still dismisses through listKeyDown.+ tabIndex={hasOverflow ? 0 : -1}// Give the menu an accessible name from its trigger's label, so// screen readers announce e.g. "Actions menu" rather than an unnamed// menu (menus-13).@@ -526,7 +896,11 @@ export function DropdownMenu({onKeyDown={listKeyDown}{...mergeProps(themeProps('dropdown-menu'),- stylex.props(styles.dropdown, xstyle),+ stylex.props(+ styles.dropdown,+ hasOverflow && styles.scrollable,+ xstyle,+ ),className,style,)}>@@ -538,11 +912,68 @@ export function DropdownMenu({placement,alignment,offset: spacingVars['--spacing-1'],- xstyle: [popoverXstyle, layerAnimations[placement]],+ xstyle: [+ styles.popoverViewport,+ alignment === 'center'+ ? isSidePlacement+ ? styles.popoverViewportBlockCentered+ : styles.popoverViewportCentered+ : [+ styles.popoverViewportAligned,+ isSidePlacement+ ? alignment === 'start'+ ? styles.popoverViewportBlockStart+ : styles.popoverViewportBlockEnd+ : alignment === 'start'+ ? styles.popoverViewportStart+ : styles.popoverViewportEnd,+ ],+ popoverXstyle,+ layerAnimations[placement],+ ],},)}</>);}+export function DropdownMenu(props: DropdownMenuProps) {+ const {onOpenChange} = props;+ const requestedPresentation =+ 'items' in props ? (props.presentation ?? 'popover') : 'popover';+ const resolvedPresentation = useAdaptivePresentation(requestedPresentation);+ const isControlled = props.isMenuOpen !== undefined;+ const [internalIsOpen, setInternalIsOpen] = useState(false);+ const isOpen = isControlled ? props.isMenuOpen : internalIsOpen;+ const handleOpenChange = useCallback(+ (nextIsOpen: boolean) => {+ onOpenChange?.(nextIsOpen);+ if (!isControlled) {+ setInternalIsOpen(nextIsOpen);+ }+ },+ [isControlled, onOpenChange],+ );+ const sharedProps = {+ ...props,+ isMenuOpen: isOpen,+ onOpenChange: handleOpenChange,+ };++ if (+ resolvedPresentation === 'bottom-sheet' &&+ 'items' in props &&+ props.items !== undefined+ ) {+ return (+ <DropdownMenuBottomSheet+ {...(sharedProps as DropdownMenuDataProps)}+ presentation="bottom-sheet"+ />+ );+ }++ return <DropdownMenuPopover {...sharedProps} presentation="popover" />;+}+DropdownMenu.displayName = 'DropdownMenu';diff --git a/packages/core/src/DropdownMenu/DropdownMenuContext.tsx b/packages/core/src/DropdownMenu/DropdownMenuContext.tsxindex b5bfe316b3..5408259167 100644--- a/packages/core/src/DropdownMenu/DropdownMenuContext.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenuContext.tsx@@ -18,7 +18,7 @@ import {createContext, use} from 'react';export type DropdownMenuSize = 'sm' | 'md' | 'lg';export interface DropdownMenuContextValue {- /** Close the menu and return focus to trigger */+ /** Close the menu; keyboard dismissal returns focus to the trigger. */closeMenu: () => void;/** Menu size derived from button size */menuSize: DropdownMenuSize;diff --git a/packages/core/src/DropdownMenu/DropdownMenuItem.tsx b/packages/core/src/DropdownMenu/DropdownMenuItem.tsxindex 21bad6a7f0..3fad1b4afb 100644--- a/packages/core/src/DropdownMenu/DropdownMenuItem.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenuItem.tsx@@ -52,6 +52,8 @@ const menuItemStyles = stylex.create({backgroundColor: {default: 'transparent',':focus': colorVars['--color-overlay-hover'],+ ':active:where(:not(:disabled,[aria-disabled="true"]))':+ colorVars['--color-overlay-pressed'],},border: 'none',cursor: {diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.doc.mjsindex 97d9b5e58a..e0f1768a1b 100644--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.doc.mjs+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.doc.mjs@@ -52,7 +52,8 @@ export const docs = {{name: 'menuWidth',type: 'number | string',- description: 'Fixed flyout width. Defaults to sizing to its content (min 160px).',+ description:+ 'Minimum flyout width. The flyout may grow for its content, but it is capped to the available viewport space. Defaults to intrinsic sizing (min 160px).',},{name: 'onOpenChange',@@ -81,7 +82,8 @@ export const docsDense = {children: 'flyout menu items (same components as top level)',isDisabled: 'renders trigger but never opens',hasSpinner: 'spinner instead of caret for async children',- menuWidth: 'fixed flyout width (default: content, min 160px)',+ menuWidth:+ 'minimum flyout width, capped to the viewport (default: content, min 160px)',onOpenChange: 'called when flyout opens/closes',xstyle: 'StyleX styles for the trigger row',},diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsxindex 87ecec6e5d..8ac517a5e2 100644--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx@@ -10,9 +10,11 @@ import {describe, it, expect, vi, beforeEach} from 'vitest';import {useState} from 'react';import {render, screen, waitFor, fireEvent, act} from '@testing-library/react';import userEvent from '@testing-library/user-event';+import * as stylex from '@stylexjs/stylex';import {DropdownMenu} from './DropdownMenu';import {DropdownMenuItem} from './DropdownMenuItem';import {DropdownMenuSubMenu} from './DropdownMenuSubMenu';+import {rtlStyles} from '../utils';beforeEach(() => {HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {@@ -81,6 +83,82 @@ describe('DropdownMenuSubMenu', () => {).toBeInTheDocument();});+ it('caps the flyout width and height to the available viewport', async () => {+ const user = userEvent.setup();+ render(+ <DropdownMenu button={{label: 'Actions'}}>+ <DropdownMenuSubMenu label="Move to" menuWidth={640}>+ <DropdownMenuItem label="Folder A" onClick={() => {}} />+ </DropdownMenuSubMenu>+ </DropdownMenu>,+ );+ await user.click(screen.getByRole('button', {name: /Actions/}));+ const trigger = screen.getByRole('menuitem', {+ name: /Move to/,+ hidden: true,+ });+ await user.click(trigger);++ const flyout = screen.getByRole('menu', {name: /Move to/, hidden: true});+ const popover = flyout.closest('[popover]');+ expect(popover?.className).toContain(+ 'DropdownMenuSubMenu__flyoutStyles.popoverViewport',+ );+ expect(popover).not.toHaveStyle(+ 'margin-inline-start: max(var(--spacing-2),env(safe-area-inset-left,0px))',+ );+ expect(popover).not.toHaveStyle(+ 'margin-inline-end: max(var(--spacing-2),env(safe-area-inset-right,0px))',+ );+ expect(popover).toHaveStyle({minWidth: 'var(--x-minWidth)'});+ expect(popover?.getAttribute('style')).toContain('min(640px, calc(100vw');+ expect(flyout).toHaveStyle(+ 'max-height: min(300px,calc(100dvb - max(var(--spacing-4),env(safe-area-inset-top,0px)) - max(var(--spacing-4),env(safe-area-inset-bottom,0px))))',+ );+ expect(flyout).not.toHaveStyle({overflowY: 'auto'});+ expect(flyout).toHaveAttribute('tabindex', '-1');++ Object.defineProperties(flyout, {+ clientHeight: {configurable: true, value: 300},+ scrollHeight: {configurable: true, value: 480},+ });+ fireEvent(window, new Event('resize'));++ await waitFor(() => {+ expect(flyout).toHaveStyle({overflowY: 'auto'});+ expect(flyout).toHaveAttribute('tabindex', '0');+ });+ });++ it.each(['max-content', 'fit-content', 'auto'])(+ 'preserves the valid %s flyout width while retaining the viewport cap',+ async menuWidth => {+ const user = userEvent.setup();+ render(+ <DropdownMenu button={{label: 'Actions'}}>+ <DropdownMenuSubMenu label="Move to" menuWidth={menuWidth}>+ <DropdownMenuItem label="Folder A" onClick={() => {}} />+ </DropdownMenuSubMenu>+ </DropdownMenu>,+ );+ await user.click(screen.getByRole('button', {name: /Actions/}));+ await user.click(+ screen.getByRole('menuitem', {name: /Move to/, hidden: true}),+ );++ const flyout = screen.getByRole('menu', {name: /Move to/, hidden: true});+ const popover = flyout.closest('[popover]');+ expect(popover?.className).toContain(+ 'DropdownMenuSubMenu__flyoutStyles.popoverCustomIntrinsicWidth',+ );+ expect(popover?.getAttribute('style')).toContain(menuWidth);+ expect(popover?.className).toContain(+ 'DropdownMenuSubMenu__flyoutStyles.popoverViewport',+ );+ expect(popover?.getAttribute('style')).not.toContain(`min(${menuWidth},`);+ },+ );+it('opens on ArrowRight and returns focus to the trigger on ArrowLeft', async () => {const user = userEvent.setup();render(<MoveMenu />);@@ -115,6 +193,52 @@ describe('DropdownMenuSubMenu', () => {expect(trigger).toHaveFocus();});+ it('mirrors its indicator and keyboard directions under RTL', async () => {+ const user = userEvent.setup();+ const {className: mirrorClassName} = stylex.props(rtlStyles.mirror);+ const mirrorClasses = mirrorClassName?.split(' ') ?? [];+ expect(mirrorClasses.length).toBeGreaterThan(0);+ render(+ <div dir="rtl" style={{direction: 'rtl'}}>+ <MoveMenu />+ </div>,+ );++ await user.click(screen.getByRole('button', {name: /Actions/}));+ const trigger = screen.getByRole('menuitem', {+ name: /Move to/,+ hidden: true,+ });+ const indicator = trigger.querySelector('.astryx-icon');+ expect(indicator).not.toBeNull();+ for (const className of mirrorClasses) {+ expect(indicator).toHaveClass(className);+ }++ await waitFor(() => {+ expect(+ screen.getByRole('menu', {name: 'Actions', hidden: true}),+ ).toHaveFocus();+ });+ // jsdom does not propagate the ancestor's computed direction, so set the+ // same RTL direction directly on each keyboard event owner.+ trigger.style.direction = 'rtl';+ trigger.focus();+ await user.keyboard('{ArrowLeft}');+ const flyout = screen.getByRole('menu', {name: /Move to/, hidden: true});+ flyout.style.direction = 'rtl';+ await waitFor(() => {+ expect(+ screen.getByRole('menuitem', {name: 'Folder A', hidden: true}),+ ).toHaveFocus();+ });+ await user.keyboard('{ArrowRight}');+ await waitFor(() => {+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ });+ expect(trigger).toHaveFocus();+ });+it('names the flyout from its trigger via aria-labelledby', async () => {const user = userEvent.setup();render(<MoveMenu />);diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsxindex 9cce4450a6..9132a2dbb6 100644--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx@@ -5,7 +5,8 @@/*** @file DropdownMenuSubMenu.tsx* @input React, stylex, useLayer (context mode), useListFocus, useMenuHover,- * useTypeahead, Item, Icon, Spinner, DropdownMenu context + item roles.+ * useTypeahead, the shared viewport-safe menu-width resolver, Item, Icon,+ * Spinner, and DropdownMenu context + item roles* @output Exports DropdownMenuSubMenu — a single menu row that reveals a nested* flyout menu of its own children/items.* @position Sub-component; place inside a DropdownMenu (or ContextMenu)@@ -56,6 +57,8 @@ import {layerAnimations} from '../Layer/layerAnimations.stylex';import {useListFocus} from '../hooks/useListFocus';import {useMenuHover} from '../hooks/useMenuHover';import {useTypeahead} from '../hooks/useTypeahead';+import {useMenuOverflow} from './useMenuOverflow';+import {resolveMenuWidth} from './menuWidth';import {colorVars,spacingVars,@@ -66,7 +69,7 @@ import {typographyVars,typeScaleVars,} from '../theme/tokens.stylex';-import {mergeProps} from '../utils';+import {mergeProps, rtlStyles} from '../utils';import {themeProps} from '../utils/themeProps';import type {BaseProps} from '../BaseProps';import {@@ -81,6 +84,14 @@ import {} from './DropdownMenuContext';import {focusMenuItemOnHover} from './menuItemHover';+const MENU_VIEWPORT_GUTTER = spacingVars['--spacing-4'];+// `useLayer` adds 4px of anchor clearance. An 8px collision margin resolves+// to a 4px visible gap after the browser flips the flyout.+const MENU_MAX_INLINE_SIZE = `calc(100vi - max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-left, 0px)) - max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-right, 0px)))`;+const MENU_MAX_INLINE_SIZE_FALLBACK = `calc(100vw - ${MENU_VIEWPORT_GUTTER} - ${MENU_VIEWPORT_GUTTER})`;+const MENU_MAX_BLOCK_SIZE = `min(300px, calc(100dvb - max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-top, 0px)) - max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-bottom, 0px))))`;+const MENU_MAX_BLOCK_SIZE_FALLBACK = `min(300px, calc(100vh - ${MENU_VIEWPORT_GUTTER} - ${MENU_VIEWPORT_GUTTER}))`;+const triggerStyles = stylex.create({root: {boxSizing: 'border-box',@@ -135,8 +146,14 @@ const flyoutStyles = stylex.create({display: 'flex',flexDirection: 'column',gap: spacingVars['--spacing-0-5'],- maxHeight: '300px',- overflowY: 'auto',+ maxInlineSize: stylex.firstThatWorks(+ MENU_MAX_INLINE_SIZE,+ MENU_MAX_INLINE_SIZE_FALLBACK,+ ),+ maxHeight: stylex.firstThatWorks(+ MENU_MAX_BLOCK_SIZE,+ MENU_MAX_BLOCK_SIZE_FALLBACK,+ ),'--_dropdown-menu-radius': radiusVars['--radius-container'],'--_dropdown-menu-padding': spacingVars['--spacing-1'],padding: spacingVars['--spacing-1'],@@ -148,11 +165,33 @@ const flyoutStyles = stylex.create({transitionDuration: durationVars['--duration-fast'],transitionTimingFunction: easeVars['--ease-standard'],},+ scrollable: {+ overflowY: 'auto',+ overflowX: 'hidden',+ overscrollBehavior: 'contain',+ },+ popoverViewport: {+ boxSizing: 'border-box',+ // Keep the inline viewport cap on the menu surface above. Applying it to+ // the anchor-positioned popover itself prevents Chromium from selecting+ // `flip-inline` and instead shifts the flyout back across its parent.+ maxBlockSize: stylex.firstThatWorks(+ MENU_MAX_BLOCK_SIZE,+ MENU_MAX_BLOCK_SIZE_FALLBACK,+ ),+ },popover: {- minWidth: '160px',+ minWidth: stylex.firstThatWorks(+ `min(160px, ${MENU_MAX_INLINE_SIZE})`,+ `min(160px, ${MENU_MAX_INLINE_SIZE_FALLBACK})`,+ '160px',+ ),},- popoverCustomWidth: (width: string | number) => ({- minWidth: typeof width === 'number' ? `${width}px` : width,+ popoverCustomWidth: (width: string) => ({+ minWidth: width,+ }),+ popoverCustomIntrinsicWidth: (width: string) => ({+ inlineSize: width,}),});@@ -178,7 +217,10 @@ interface DropdownMenuSubMenuBaseProps extends Pick<* @default false*/hasSpinner?: boolean;- /** Fixed flyout width. Defaults to sizing to its content (min 160px). */+ /**+ * Minimum flyout width. The flyout may grow for its content but is capped to+ * the available viewport space. Defaults to intrinsic sizing (min 160px).+ */menuWidth?: number | string;/** Called when the flyout opens or closes. */onOpenChange?: (isOpen: boolean) => void;@@ -289,6 +331,7 @@ export function DropdownMenuSubMenu(wrap: false,onEscape: () => close({focusTrigger: true}),});+ const hasOverflow = useMenuOverflow(menuRef, children, isOpen);const typeahead = useTypeahead({getItemLabels: () => getItems().map(el => el.textContent),@@ -485,13 +528,19 @@ export function DropdownMenuSubMenu(icon="chevronRight"size="sm"color="secondary"+ xstyle={rtlStyles.mirror}{...themeProps('dropdown-menu-indicator-icon')}/></span>);- const popoverXstyle = menuWidth- ? flyoutStyles.popoverCustomWidth(menuWidth)+ const resolvedMenuWidth = menuWidth+ ? resolveMenuWidth(menuWidth, MENU_MAX_INLINE_SIZE_FALLBACK)+ : null;+ const popoverXstyle = resolvedMenuWidth+ ? resolvedMenuWidth.property === 'inlineSize'+ ? flyoutStyles.popoverCustomIntrinsicWidth(resolvedMenuWidth.value)+ : flyoutStyles.popoverCustomWidth(resolvedMenuWidth.value): flyoutStyles.popover;return (@@ -537,11 +586,10 @@ export function DropdownMenuSubMenu(ref={menuRef}id={contentId}role="menu"- // Focusable as a fallback target so an empty/loading flyout (e.g.- // hasSpinner with only a disabled row) can still receive keyboard- // focus and own arrow/Escape keys instead of leaving focus on the- // parent list.- tabIndex={-1}+ // Focusable as a fallback target so an empty/loading flyout can own+ // arrow/Escape keys. An overflowing flyout joins the Tab order so its+ // scrollable region is keyboard-accessible.+ tabIndex={hasOverflow ? 0 : -1}aria-labelledby={triggerId}onKeyDown={handleContentKeyDown}onMouseEnter={contentProps.onMouseEnter}@@ -549,7 +597,10 @@ export function DropdownMenuSubMenu(data-testid={menuDataTestId}{...mergeProps(themeProps('dropdown-menu'),- stylex.props(flyoutStyles.menu),+ stylex.props(+ flyoutStyles.menu,+ hasOverflow && flyoutStyles.scrollable,+ ),)}><DropdownMenuContext value={nestedMenuContext}>{children}@@ -559,7 +610,11 @@ export function DropdownMenuSubMenu(placement: 'end',alignment: 'start',offset: spacingVars['--spacing-1'],- xstyle: [popoverXstyle, layerAnimations.end],+ xstyle: [+ flyoutStyles.popoverViewport,+ popoverXstyle,+ layerAnimations.end,+ ],},)}</>diff --git a/packages/core/src/DropdownMenu/MenuBottomSheet.tsx b/packages/core/src/DropdownMenu/MenuBottomSheet.tsxnew file mode 100644index 0000000000..9399dced90--- /dev/null+++ b/packages/core/src/DropdownMenu/MenuBottomSheet.tsx@@ -0,0 +1,46 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file MenuBottomSheet.tsx+ * @input Uses BottomSheet and Section+ * @output Internal action-sheet host for menu content+ * @position Shared by DropdownMenu and ContextMenu adaptive presentations+ */++import type {ReactNode, RefObject} from 'react';+import {BottomSheet} from '../BottomSheet/BottomSheet';+import {Section} from '../Section/Section';++interface MenuBottomSheetProps {+ finalFocusRef?: RefObject<HTMLElement | null>;+ isOpen: boolean;+ onOpenChange: (isOpen: boolean) => void;+ label: string;+ children: ReactNode;+}++export function MenuBottomSheet({+ finalFocusRef,+ isOpen,+ onOpenChange,+ label,+ children,+}: MenuBottomSheetProps) {+ return (+ <BottomSheet+ finalFocusRef={finalFocusRef}+ isOpen={isOpen}+ onOpenChange={onOpenChange}+ label={label}+ height="hug"+ purpose="info">+ <Section paddingBlockStart={4} paddingBlockEnd={0} paddingInline={1}>+ {children}+ </Section>+ </BottomSheet>+ );+}++MenuBottomSheet.displayName = 'MenuBottomSheet';diff --git a/packages/core/src/DropdownMenu/MenuBottomSheetActionList.tsx b/packages/core/src/DropdownMenu/MenuBottomSheetActionList.tsxnew file mode 100644index 0000000000..8169d9c50c--- /dev/null+++ b/packages/core/src/DropdownMenu/MenuBottomSheetActionList.tsx@@ -0,0 +1,141 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file MenuBottomSheetActionList.tsx+ * @input Uses menu data entries and callbacks for selection and drill-in+ * @output Internal touch-friendly action list shared by DropdownMenu and ContextMenu+ * @position Shared implementation for menu bottom-sheet presentations+ */++import type {ReactElement} from 'react';+import * as stylex from '@stylexjs/stylex';+import {Divider} from '../Divider';+import {Heading} from '../Heading';+import {Icon, renderIconSlot} from '../Icon';+import {List, ListItem} from '../List';+import {colorVars, spacingVars} from '../theme/tokens.stylex';+import {rtlStyles} from '../utils';+import {getInteractionModality} from '../utils/interactionModality';+import type {DropdownMenuItemData, DropdownMenuOption} from './DropdownMenu';++const styles = stylex.create({+ destructiveAction: {+ '--_item-label-color': colorVars['--color-error'],+ '--_item-description-color': colorVars['--color-error'],+ color: colorVars['--color-error'],+ },+ structuralItem: {+ listStyleType: 'none',+ },+ divider: {+ marginBlock: spacingVars['--spacing-1'],+ },+ section: {+ display: 'flex',+ flexDirection: 'column',+ gap: spacingVars['--spacing-1'],+ },+});++function getItemKey(item: DropdownMenuItemData, index: number): string {+ return `item-${item.id ?? index}`;+}++export function MenuBottomSheetActionList({+ items,+ onSelect,+ onOpenSubmenu,+}: {+ items: DropdownMenuOption[];+ onSelect: (item: DropdownMenuItemData) => void;+ onOpenSubmenu: (item: DropdownMenuItemData) => void;+}) {+ const renderItem = (+ item: DropdownMenuItemData,+ index: number,+ ): ReactElement => {+ const isSubmenu = item.items != null && item.items.length > 0;+ const isDestructive = item.variant === 'destructive';++ return (+ <ListItem+ key={getItemKey(item, index)}+ label={item.label}+ description={item.description}+ startContent={+ item.icon+ ? renderIconSlot(item.icon, {+ size: 'sm',+ color: isDestructive ? 'error' : 'secondary',+ })+ : undefined+ }+ endContent={+ isSubmenu ? (+ <Icon+ icon="chevronRight"+ size="sm"+ color="secondary"+ xstyle={rtlStyles.mirror}+ />+ ) : (+ item.endContent+ )+ }+ isDisabled={item.isDisabled}+ onClick={event => {+ if (getInteractionModality() === 'pointer') {+ (event.currentTarget as HTMLElement).blur();+ }+ if (isSubmenu) {+ onOpenSubmenu(item);+ } else {+ onSelect(item);+ }+ }}+ xstyle={isDestructive && styles.destructiveAction}+ />+ );+ };++ return (+ <List density="spacious">+ {items.map((option, index) => {+ if ('type' in option && option.type === 'divider') {+ return (+ <li+ // eslint-disable-next-line @eslint-react/no-array-index-key+ key={`divider-${index}`}+ role="presentation"+ {...stylex.props(styles.structuralItem)}>+ <Divider xstyle={styles.divider} />+ </li>+ );+ }++ if ('type' in option && option.type === 'section') {+ return (+ <li+ key={`section-${option.id ?? index}`}+ role="presentation"+ {...stylex.props(styles.structuralItem)}>+ <div+ role="group"+ aria-label={option.title}+ {...stylex.props(styles.section)}>+ {option.title && <Heading level={4}>{option.title}</Heading>}+ <List density="spacious">{option.items.map(renderItem)}</List>+ </div>+ </li>+ );+ }++ return renderItem(option, index);+ })}+ </List>+ );+}++MenuBottomSheetActionList.displayName = 'MenuBottomSheetActionList';diff --git a/packages/core/src/DropdownMenu/index.ts b/packages/core/src/DropdownMenu/index.tsindex f59ce8a8f5..7cdcdb0c19 100644--- a/packages/core/src/DropdownMenu/index.ts+++ b/packages/core/src/DropdownMenu/index.ts@@ -20,12 +20,14 @@export {DropdownMenu,type DropdownMenuProps,+ type DropdownMenuPresentation,type DropdownMenuButtonProps,type DropdownMenuItemData,type DropdownMenuDividerData,type DropdownMenuSection,type DropdownMenuOption,} from './DropdownMenu';+export type {AdaptivePresentation as MenuPresentation} from '../hooks/useAdaptivePresentation';export {DropdownMenuItem, type DropdownMenuItemProps} from './DropdownMenuItem';diff --git a/packages/core/src/DropdownMenu/menuWidth.ts b/packages/core/src/DropdownMenu/menuWidth.tsnew file mode 100644index 0000000000..2b4740e68c--- /dev/null+++ b/packages/core/src/DropdownMenu/menuWidth.ts@@ -0,0 +1,51 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file menuWidth.ts+ * @input Accepts the public DropdownMenu menuWidth value and a viewport limit+ * @output Resolves whether the value belongs on min-width or inline-size+ * @position Shared width compatibility logic for root menus and submenu flyouts+ */++const INTRINSIC_AND_CSS_WIDE_WIDTHS = new Set([+ 'auto',+ 'contain',+ 'fit-content',+ 'inherit',+ 'initial',+ 'max-content',+ 'min-content',+ 'revert',+ 'revert-layer',+ 'stretch',+ 'unset',+]);++export type ResolvedMenuWidth =+ | {property: 'inlineSize'; value: string}+ | {property: 'minWidth'; value: string};++/**+ * CSS intrinsic and CSS-wide keywords cannot be arguments to `min()`. Apply+ * those values as the preferred inline size so max-inline-size can still cap+ * the menu. Lengths retain the existing minimum-width growth contract.+ */+export function resolveMenuWidth(+ menuWidth: number | string,+ maximum: string,+): ResolvedMenuWidth {+ if (typeof menuWidth === 'number') {+ return {property: 'minWidth', value: `min(${menuWidth}px, ${maximum})`};+ }++ const width = menuWidth.trim();+ const normalizedWidth = width.toLowerCase();+ if (+ INTRINSIC_AND_CSS_WIDE_WIDTHS.has(normalizedWidth) ||+ normalizedWidth.startsWith('fit-content(')+ ) {+ return {property: 'inlineSize', value: width};+ }++ return {property: 'minWidth', value: `min(${width}, ${maximum})`};+}diff --git a/packages/core/src/DropdownMenu/useMenuOverflow.ts b/packages/core/src/DropdownMenu/useMenuOverflow.tsnew file mode 100644index 0000000000..5e6dbdcb8f--- /dev/null+++ b/packages/core/src/DropdownMenu/useMenuOverflow.ts@@ -0,0 +1,77 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useMenuOverflow.ts+ * @input Menu element ref, rendered content, and open state+ * @output Returns whether the open menu overflows its block-size constraint+ * @position Shared responsive helper for DropdownMenu and DropdownMenuSubMenu+ */++import {useCallback, useState, type ReactNode, type RefObject} from 'react';+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';++/** Detect block-axis overflow without making a fitting menu a scroll container. */+export function useMenuOverflow(+ menuRef: RefObject<HTMLElement | null>,+ content: ReactNode,+ isOpen: boolean,+): boolean {+ const [hasOverflow, setHasOverflow] = useState(false);++ const measureOverflow = useCallback(() => {+ const menu = menuRef.current;+ if (!menu) {+ return;+ }+ const nextHasOverflow = menu.scrollHeight > menu.clientHeight + 1;+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- DOM overflow measurement controls whether this menu becomes a scroll container+ setHasOverflow(current =>+ current === nextHasOverflow ? current : nextHasOverflow,+ );+ }, [menuRef]);++ useIsomorphicLayoutEffect(() => {+ if (!isOpen) {+ return;+ }+ const menu = menuRef.current;+ if (!menu) {+ return;+ }+ measureOverflow();+ const resizeObserver =+ typeof ResizeObserver === 'undefined'+ ? null+ : new ResizeObserver(measureOverflow);+ const mutationObserver =+ typeof MutationObserver === 'undefined'+ ? null+ : new MutationObserver(measureOverflow);+ resizeObserver?.observe(menu);+ mutationObserver?.observe(menu, {+ childList: true,+ characterData: true,+ subtree: true,+ });+ menu.addEventListener('load', measureOverflow, true);+ window.addEventListener('resize', measureOverflow);+ window.visualViewport?.addEventListener('resize', measureOverflow);+ return () => {+ resizeObserver?.disconnect();+ mutationObserver?.disconnect();+ menu.removeEventListener('load', measureOverflow, true);+ window.removeEventListener('resize', measureOverflow);+ window.visualViewport?.removeEventListener('resize', measureOverflow);+ };+ }, [isOpen, measureOverflow, menuRef]);++ useIsomorphicLayoutEffect(() => {+ if (isOpen) {+ measureOverflow();+ }+ }, [content, isOpen, measureOverflow]);++ return hasOverflow;+}diff --git a/packages/core/src/MoreMenu/MoreMenu.doc.mjs b/packages/core/src/MoreMenu/MoreMenu.doc.mjsindex 1d52c38013..7ee0c5f57c 100644--- a/packages/core/src/MoreMenu/MoreMenu.doc.mjs+++ b/packages/core/src/MoreMenu/MoreMenu.doc.mjs@@ -61,6 +61,12 @@ export const docs = {"Alignment along the placement axis. Use 'end' to align the menu with the trigger's trailing edge, which is usually what an overflow menu wants.",default: "'start'",},+ {+ name: 'presentation',+ type: "'popover' | 'bottom-sheet' | 'adaptive'",+ description: 'Presentation policy forwarded to DropdownMenu. `adaptive` keeps the anchored popover on pointer-based layouts and uses a BottomSheet at 768px and below when the primary pointer is coarse.',+ default: "'popover'",+ },{name: 'onOpenChange',type: '(isOpen: boolean) => void',@@ -93,6 +99,7 @@ export const docs = {bestPractices: [{ guidance: true, description: 'Use for overflow or secondary actions; keep primary actions visible outside the menu.' },{ guidance: true, description: 'Use dividers or sections to group related actions when the menu has many items.' },+ { guidance: true, description: 'Use `presentation="adaptive"` when the visible overflow trigger should open a thumb-reachable BottomSheet on compact touch devices.' },{ guidance: false, description: 'Hide primary actions inside a MoreMenu; they should be directly visible.' },],},@@ -153,6 +160,12 @@ export const docsZh = {"沿放置轴的对齐方式。使用 'end' 让菜单与触发器的尾部边缘对齐,这通常是溢出菜单所需的效果。",default: "'start'",},+ {+ name: 'presentation',+ type: "'popover' | 'bottom-sheet' | 'adaptive'",+ description: '菜单呈现策略。`adaptive` 在指针布局中使用锚定浮层,在主指针为粗略指针且宽度不超过 768px 时使用 BottomSheet。',+ default: "'popover'",+ },{name: 'xstyle',type: 'StyleXStyles',@@ -171,6 +184,7 @@ export const docsZh = {bestPractices: [{ guidance: true, description: 'Use for overflow or secondary actions; keep primary actions visible outside the menu.' },{ guidance: true, description: 'Use dividers or sections to group related actions when the menu has many items.' },+ { guidance: true, description: 'Use `presentation="adaptive"` when the visible overflow trigger should open a thumb-reachable BottomSheet on compact touch devices.' },{ guidance: false, description: 'Hide primary actions inside a MoreMenu; they should be directly visible.' },],},@@ -186,6 +200,7 @@ export const docsDense = {bestPractices: [{ guidance: true, description: 'Use for overflow or secondary actions; keep primary actions visible outside the menu.' },{ guidance: true, description: 'Use dividers or sections to group related actions when the menu has many items.' },+ { guidance: true, description: 'Use `presentation="adaptive"` when the visible overflow trigger should open a thumb-reachable BottomSheet on compact touch devices.' },{ guidance: false, description: 'Hide primary actions inside a MoreMenu; they should be directly visible.' },],},@@ -199,6 +214,8 @@ export const docsDense = {placement: 'Menu position relative to trigger. Logical (RTL mirrors).',alignment:"Alignment along the placement axis. 'end' aligns with the trigger's trailing edge.",+ presentation:+ 'Popover, BottomSheet, or adaptive compact-touch presentation.',xstyle:'StyleX styles for layout customization (margins, positioning, sizing). Must be stylex.create() value.',},diff --git a/packages/core/src/MoreMenu/MoreMenu.test.tsx b/packages/core/src/MoreMenu/MoreMenu.test.tsxindex e7b9e2a722..5195124564 100644--- a/packages/core/src/MoreMenu/MoreMenu.test.tsx+++ b/packages/core/src/MoreMenu/MoreMenu.test.tsx@@ -17,6 +17,30 @@ import {DropdownMenu} from '../DropdownMenu/DropdownMenu';// Mock showPopover and hidePopover methods since they're not implemented in jsdombeforeEach(() => {+ 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');+ });+ vi.stubGlobal(+ 'matchMedia',+ vi.fn().mockImplementation((query: string) => ({+ matches: false,+ media: query,+ onchange: null,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),+ );HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {this.setAttribute('popover-open', '');const event = new Event('toggle', {bubbles: false});@@ -85,6 +109,29 @@ describe('MoreMenu', () => {expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();});+ it('keeps the trigger visually pressed while the menu is open', async () => {+ const user = userEvent.setup();+ render(<MoreMenu items={defaultItems} />);++ const trigger = screen.getByRole('button', {name: 'More options'});+ expect(trigger.className).not.toContain('DropdownMenu__styles.triggerOpen');++ await user.click(trigger);++ expect(trigger.className).toContain('DropdownMenu__styles.triggerOpen');+ });++ it('forwards BottomSheet presentation to DropdownMenu', async () => {+ const user = userEvent.setup();+ render(<MoreMenu items={defaultItems} presentation="bottom-sheet" />);++ await user.click(screen.getByRole('button', {name: 'More options'}));+ await waitFor(() =>+ expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalledOnce(),+ );+ expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled();+ });+it('calls onClick when item is clicked', async () => {const handleEdit = vi.fn();const items = [diff --git a/packages/core/src/MoreMenu/MoreMenu.tsx b/packages/core/src/MoreMenu/MoreMenu.tsxindex 0166dba502..5d56b05c47 100644--- a/packages/core/src/MoreMenu/MoreMenu.tsx+++ b/packages/core/src/MoreMenu/MoreMenu.tsx@@ -22,7 +22,10 @@ import type {ReactNode} from 'react';import {useIcon} from '../Icon';import {DropdownMenu} from '../DropdownMenu/DropdownMenu';import {useSize} from '../SizeContext/SizeContext';-import type {DropdownMenuOption} from '../DropdownMenu';+import type {+ DropdownMenuOption,+ DropdownMenuPresentation,+} from '../DropdownMenu';import type {LayerAlignment, LayerPlacement} from '../Layer';import type {ButtonVariant, ButtonSize} from '../Button';import type {BaseProps} from '../BaseProps';@@ -87,6 +90,13 @@ export interface MoreMenuProps extends Pick<*/alignment?: LayerAlignment;+ /**+ * Menu presentation policy. `adaptive` uses a BottomSheet on compact+ * coarse-pointer viewports and an anchored popover elsewhere.+ * @default 'popover'+ */+ presentation?: DropdownMenuPresentation;+/*** Controlled open state for the menu.*/@@ -125,6 +135,7 @@ export function MoreMenu({isDisabled = false,placement,alignment,+ presentation,isMenuOpen,onOpenChange,xstyle,@@ -151,6 +162,7 @@ export function MoreMenu({onOpenChange={onOpenChange}placement={placement}alignment={alignment}+ presentation={presentation}button={{label,icon: icon ?? moreIcon,diff --git a/packages/core/src/MultiSelector/MultiSelector.doc.mjs b/packages/core/src/MultiSelector/MultiSelector.doc.mjsindex dda0742333..7717523467 100644--- a/packages/core/src/MultiSelector/MultiSelector.doc.mjs+++ b/packages/core/src/MultiSelector/MultiSelector.doc.mjs@@ -224,6 +224,13 @@ export const docs = {'Which edge of the option row carries the checkbox. end pushes it to the far edge of the row, including on the select-all row.',default: "'start'",},+ {+ name: 'presentation',+ type: "'popover' | 'bottom-sheet' | 'adaptive'",+ description:+ 'How the option list is presented. adaptive uses a bottom sheet on compact touch screens and an anchored popover otherwise.',+ default: "'popover'",+ },{name: 'width',type: 'SizeValue',@@ -290,6 +297,11 @@ export const docs = {description:'Use variant="ghost" when a multi-selector sits in a toolbar with ghost buttons. If validation status is needed there, prefer statusVariant="tooltip" so the toolbar height stays compact.',},+ {+ guidance: true,+ description:+ 'Use presentation="adaptive" when the multi-selector should become a bottom sheet on compact touch screens.',+ },{guidance: false,description: 'Use for single-value selection; use Selector instead.',@@ -349,6 +361,8 @@ export const docsZh = {'状态消息的放置方式:attached 直接叠加在输入框下方;detached 作为独立元素浮于下方并留有间距。',renderOption:'每个可选选项的自定义渲染函数。不会用于分隔线、分组或全选行。',+ presentation:+ '选项列表的呈现方式:锚定弹出框、底部抽屉,或根据紧凑触控屏自适应。',xstyle: '布局自定义的 StyleX 样式,必须是 stylex.create() 值。',},},@@ -487,6 +501,8 @@ export const docsDense = {'status message placement; ghost detaches attached by default; use tooltip for compact toolbars.',renderOption:'custom render fn per selectable option; not dividers/sections/select-all',+ presentation:+ 'popover, bottom-sheet, or compact-touch adaptive presentation',xstyle: 'StyleX layout styles; stylex.create() only',},},diff --git a/packages/core/src/MultiSelector/MultiSelector.test.tsx b/packages/core/src/MultiSelector/MultiSelector.test.tsxindex ca801038bd..7baa04d63b 100644--- a/packages/core/src/MultiSelector/MultiSelector.test.tsx+++ b/packages/core/src/MultiSelector/MultiSelector.test.tsx@@ -19,12 +19,15 @@ import {within,} from '@testing-library/react';import userEvent from '@testing-library/user-event';+import * as stylex from '@stylexjs/stylex';import {MultiSelector} from './MultiSelector';import {Icon} from '../Icon';import {InternationalizationProvider} from '../i18n';import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';+import {__resetInteractionModalityForTest} from '../utils/interactionModality';import {defineTheme} from '../theme/defineTheme';import {generateThemeCSS} from '../theme/generateThemeRules';+import {selectorPresentationStyles} from '../Selector/selectorPresentation.stylex';function generateThemeTestCSS(theme: Parameters<typeof generateThemeCSS>[0]) {const {prose, component} = generateThemeCSS(theme);@@ -40,6 +43,28 @@ function politeRegion(): HTMLElement | null {// Mock showPopover and hidePopover methods since they're not implemented in jsdombeforeEach(() => {+ __resetInteractionModalityForTest();+ HTMLDialogElement.prototype.showModal = vi.fn(function (+ this: HTMLDialogElement,+ ) {+ this.setAttribute('open', '');+ });+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {+ this.removeAttribute('open');+ });+ vi.stubGlobal(+ 'matchMedia',+ vi.fn().mockImplementation((query: string) => ({+ matches: false,+ media: query,+ onchange: null,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),+ );HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {this.setAttribute('popover-open', '');const event = new Event('toggle', {bubbles: false});@@ -75,6 +100,108 @@ const h = {hidden: true} as const;describe('MultiSelector', () => {const defaultOptions = ['Apple', 'Banana', 'Orange'];+ it('uses a bottom sheet and stays open while toggling options', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <MultiSelector+ label="Fruit"+ options={defaultOptions}+ value={[]}+ onChange={onChange}+ presentation="bottom-sheet"+ />,+ );++ const trigger = screen.getByRole('combobox');+ await user.click(trigger);++ expect(+ await screen.findByRole('dialog', {name: 'Fruit'}),+ ).toBeInTheDocument();+ expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled();++ await user.click(screen.getByRole('option', {name: 'Banana'}));+ expect(onChange).toHaveBeenCalledWith(['Banana']);+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ });++ it('uses a bottom sheet for adaptive presentation on compact touch', async () => {+ vi.stubGlobal(+ 'matchMedia',+ vi.fn().mockImplementation((query: string) => ({+ matches: query === '(max-width: 768px) and (pointer: coarse)',+ media: query,+ onchange: null,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),+ );+ const user = userEvent.setup();+ render(+ <MultiSelector+ label="Fruit"+ options={defaultOptions}+ value={[]}+ onChange={() => {}}+ presentation="adaptive"+ />,+ );++ await user.click(screen.getByRole('combobox'));+ expect(+ await screen.findByRole('dialog', {name: 'Fruit'}),+ ).toBeInTheDocument();+ expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled();+ });++ it('moves keyboard focus into a bottom-sheet listbox', async () => {+ const user = userEvent.setup();+ render(+ <MultiSelector+ label="Fruit"+ options={defaultOptions}+ value={[]}+ onChange={() => {}}+ presentation="bottom-sheet"+ />,+ );++ const trigger = screen.getByRole('combobox');+ trigger.focus();+ await user.keyboard('{Enter}');++ await waitFor(() => expect(screen.getByRole('listbox')).toHaveFocus());+ });++ it('restores touch focus without painting a trigger focus ring', async () => {+ render(+ <MultiSelector+ label="Fruit"+ options={defaultOptions}+ value={[]}+ onChange={() => {}}+ presentation="bottom-sheet"+ />,+ );++ const trigger = screen.getByRole('combobox');+ fireEvent.pointerDown(trigger, {pointerType: 'touch'});+ fireEvent.click(trigger, {detail: 1});+ const dialog = await screen.findByRole('dialog', {name: 'Fruit'});+ fireEvent.pointerDown(dialog, {pointerType: 'touch'});+ fireEvent.click(dialog, {detail: 1});++ trigger.focus();+ expect(trigger).toHaveFocus();+ expect(trigger.parentElement).toHaveClass(+ stylex.props(selectorPresentationStyles.pointerRestoredFocus).className!,+ );+ });+it('renders with label', () => {render(<MultiSelectordiff --git a/packages/core/src/MultiSelector/MultiSelector.tsx b/packages/core/src/MultiSelector/MultiSelector.tsxindex bb16c43cd2..08a5c76b4e 100644--- a/packages/core/src/MultiSelector/MultiSelector.tsx+++ b/packages/core/src/MultiSelector/MultiSelector.tsx@@ -28,7 +28,6 @@ import React, {type ReactNode,} from 'react';import * as stylex from '@stylexjs/stylex';-import {usePopoverInternal} from '../Popover/usePopover';import {useTooltip} from '../Tooltip';import {Icon, renderIconSlot, type IconType} from '../Icon';import type {IconName} from '../Icon';@@ -57,7 +56,6 @@ import {typographyVars,fontWeightVars,typeScaleVars,- borderVars,} from '../theme/tokens.stylex';import type {MultiSelectorOptionType,@@ -86,6 +84,10 @@ import {groupStyles} from '../InputGroup/groupStyles';import {useInputGroup} from '../InputGroup/InputGroupContext';import {VisuallyHidden} from '../VisuallyHidden';import {useTranslator} from '../i18n';+import type {AdaptivePresentation} from '../hooks/useAdaptivePresentation';+import {SelectorBottomSheet} from '../Selector/SelectorBottomSheet';+import {useSelectorPresentation} from '../Selector/useSelectorPresentation';+import {selectorPresentationStyles} from '../Selector/selectorPresentation.stylex';// Sentinel value for the select-all item in keyboard navigationconst SELECT_ALL_VALUE = '__xds_select_all__';@@ -245,6 +247,9 @@ const styles = stylex.create({overflowY: 'auto',padding: spacingVars['--spacing-1'],},+ listbox: {+ outline: 'none',+ },// Popover container (for anchor positioning)popover: {@@ -415,6 +420,8 @@ export type MultiSelectorSize = 'sm' | 'md' | 'lg';export type MultiSelectorVariant = 'input' | 'ghost';+export type MultiSelectorPresentation = AdaptivePresentation;+export type MultiSelectorStatusType = 'warning' | 'error' | 'success';export type {MultiSelectorStatus};@@ -658,6 +665,15 @@ export interface MultiSelectorProps<*/indicatorPosition?: IndicatorPosition;+ /**+ * How the option list is presented.+ * - 'popover': anchored to the trigger+ * - 'bottom-sheet': modal sheet suited to compact touch screens+ * - 'adaptive': bottom sheet on compact coarse-pointer screens, otherwise popover+ * @default 'popover'+ */+ presentation?: MultiSelectorPresentation;+/*** Whether the dropdown starts open on mount.* Useful for showcases and previews.@@ -747,6 +763,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({maxBadges = 3,renderOption,indicatorPosition = 'start',+ presentation = 'popover',isDefaultOpen = false,'data-testid': testId,htmlName,@@ -754,6 +771,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({xstyle,className,style,+ onFocus,}: MultiSelectorProps<T>) {const t = useTranslator();const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});@@ -780,6 +798,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({const searchId = useId();const triggerRef = useRef<HTMLButtonElement>(null);const searchRef = useRef<HTMLInputElement>(null);+ const listboxRef = useRef<HTMLDivElement>(null);const inputGroup = useInputGroup();const [searchQuery, setSearchQuery] = useState('');@@ -935,27 +954,31 @@ export function MultiSelector<T extends MultiSelectorOptionType>({// Clear any lingering result count when the popover closes so stale status// text does not linger in the a11y tree.announce('');- triggerRef.current?.focus();}, [announce]);- const popover = usePopoverInternal({- hasLightDismiss: true,+ const surface = useSelectorPresentation({+ presentation,onHide: handleLayerHide,- hasCloseButton: false,- hasAutoFocus: false,- // The popup's own role="listbox" is the exposed semantics; the trigger- // keeps DOM focus, so wrapping it in a modal dialog would misrepresent it.- role: 'none',- // The theme target belongs on the SURFACE that paints the popup, which- // `usePopover` owns — not on the scrolling list inside it.- surfaceTarget: 'multi-selector-popup',+ triggerRef,+ popoverOptions: {+ hasLightDismiss: true,+ hasCloseButton: false,+ hasAutoFocus: false,+ // The popup's own role="listbox" is the exposed semantics; the trigger+ // keeps DOM focus, so wrapping it in a modal dialog would misrepresent it.+ role: 'none',+ // The theme target belongs on the SURFACE that paints the popup, which+ // `usePopover` owns — not on the scrolling list inside it.+ surfaceTarget: 'multi-selector-popup',+ },});+ const {popover} = surface;const keepOpenProps = useKeepLayerOpenProps(popover.id, popover.isOpen);// Open dropdown on mount when isDefaultOpen is trueuseEffect(() => {if (isDefaultOpen) {- popover.show();+ surface.show();}// eslint-disable-next-line @eslint-react/exhaustive-deps -- mount-only: isDefaultOpen is not reactive}, []);@@ -999,7 +1022,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({const announcedEmptyRef = useRef<string | null>(null);useEffect(() => {const isPanelEmpty =- popover.isOpen &&+ surface.isOpen &&!isLoading &&searchQuery === '' &&selectableItems.length === 0;@@ -1013,7 +1036,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({announcedEmptyRef.current = emptyAnnouncement;announce(emptyAnnouncement);}, [- popover.isOpen,+ surface.isOpen,isLoading,searchQuery,selectableItems.length,@@ -1158,24 +1181,24 @@ export function MultiSelector<T extends MultiSelectorOptionType>({onKeyDown,onItemMouseEnter,} = useMultiCombobox({- wasJustDismissed: popover.wasJustDismissed,+ wasJustDismissed: surface.wasJustDismissed,selectableItems: sortedItems,isDisabled,- isOpen: popover.isOpen,+ isOpen: surface.isOpen,hasSearch,onOpen: useCallback(() => {// Snapshot which items are selected at open time — sort is frozen until closesetSelectedAtOpen(new Set(optimisticValue));- popover.show();+ surface.show();if (hasSearch) {// Focus search after popover opensrequestAnimationFrame(() => {searchRef.current?.focus();});}- }, [popover, hasSearch, optimisticValue]),- onClose: popover.hide,+ }, [surface, hasSearch, optimisticValue]),+ onClose: surface.hide,onToggle: handleNavigableToggle,onClear: hasClear ? clearValues : undefined,hasValue,@@ -1187,13 +1210,13 @@ export function MultiSelector<T extends MultiSelectorOptionType>({// cursor walks off-screen once navigation passes the visible window. Mirrors// CommandPaletteItem's scrollIntoView({block: 'nearest'}) behavior.useEffect(() => {- if (!popover.isOpen || highlightedIndex < 0) {+ if (!surface.isOpen || highlightedIndex < 0) {return;}document.getElementById(getItemId(highlightedIndex))?.scrollIntoView?.({block: 'nearest'});- }, [popover.isOpen, highlightedIndex, getItemId]);+ }, [surface.isOpen, highlightedIndex, getItemId]);// Build trigger display contentconst selectedItems = useMemo(() => {@@ -1288,11 +1311,11 @@ export function MultiSelector<T extends MultiSelectorOptionType>({// not the trigger — must be the combobox reporting the highlighted// option via aria-activedescendant (comboboxes-4).role="combobox"- aria-expanded={popover.isOpen}+ aria-expanded={surface.isOpen}aria-controls={listboxId}aria-autocomplete="list"aria-activedescendant={- popover.isOpen && highlightedIndex >= 0+ surface.isOpen && highlightedIndex >= 0? getItemId(highlightedIndex): undefined}@@ -1355,7 +1378,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({searchPlaceholder,handleSearchChange,onKeyDown,- popover.isOpen,+ surface.isOpen,highlightedIndex,getItemId,t,@@ -1608,6 +1631,64 @@ export function MultiSelector<T extends MultiSelectorOptionType>({const showStatusTooltip =status != null && effectiveStatusVariant === 'tooltip' && !!status.message;+ const panelContent = hasSearch ? (+ <div>+ {renderSearch()}+ <Divider />+ <div {...stylex.props(styles.dropdown)}>+ <div+ ref={listboxRef}+ id={listboxId}+ role="listbox"+ aria-multiselectable="true"+ aria-labelledby={triggerId}+ {...stylex.props(styles.listbox)}>+ {renderOptions()}+ </div>+ </div>+ </div>+ ) : (+ <div {...stylex.props(styles.dropdown)}>+ <div+ ref={listboxRef}+ id={listboxId}+ role="listbox"+ aria-multiselectable="true"+ aria-labelledby={triggerId}+ aria-activedescendant={+ surface.isOpen && highlightedIndex >= 0+ ? getItemId(highlightedIndex)+ : undefined+ }+ tabIndex={surface.activePresentation === 'bottom-sheet' ? 0 : undefined}+ onKeyDown={+ surface.activePresentation === 'bottom-sheet' ? onKeyDown : undefined+ }+ {...stylex.props(styles.listbox)}>+ {renderOptions()}+ </div>+ </div>+ );++ const selectionSurface =+ surface.activePresentation === 'bottom-sheet' ? (+ <SelectorBottomSheet+ isOpen={surface.isSheetOpen}+ onOpenChange={surface.onSheetOpenChange}+ finalFocusRef={triggerRef}+ initialFocusRef={hasSearch ? searchRef : listboxRef}+ label={label}>+ {panelContent}+ </SelectorBottomSheet>+ ) : (+ popover.render(panelContent, {+ placement: 'below',+ alignment: 'start',+ offset: spacingVars['--spacing-1'],+ xstyle: styles.popover,+ })+ );+const multiSelectorContent = (<><div@@ -1634,6 +1715,8 @@ export function MultiSelector<T extends MultiSelectorOptionType>({variant === 'ghost' && styles.triggerGhost,variant === 'ghost' && interactionOverlayStyles.backgroundImage,variant === 'ghost' && focusOutlineStyles.focusWithin,+ surface.isTriggerFocusRingSuppressed &&+ selectorPresentationStyles.pointerRestoredFocus,isDisabled && inputWrapperStyles.disabled,variant === 'ghost' && isDisabled && styles.triggerGhostDisabled,optimisticValue.length === 0 && styles.triggerPlaceholder,@@ -1663,11 +1746,13 @@ export function MultiSelector<T extends MultiSelectorOptionType>({// focus + aria-activedescendant, comboboxes-4), so the trigger is a// plain button that opens the listbox — not a second combobox.role={hasSearch ? undefined : 'combobox'}- aria-haspopup="listbox"- aria-expanded={popover.isOpen}+ aria-haspopup={+ surface.activePresentation === 'bottom-sheet' ? 'dialog' : 'listbox'+ }+ aria-expanded={surface.isOpen}aria-controls={listboxId}aria-activedescendant={- !hasSearch && popover.isOpen && highlightedIndex >= 0+ !hasSearch && surface.isOpen && highlightedIndex >= 0? getItemId(highlightedIndex): undefined}@@ -1682,6 +1767,10 @@ export function MultiSelector<T extends MultiSelectorOptionType>({disabled={isDisabled && !showsDisabledMessage}aria-disabled={showsDisabledMessage ? 'true' : undefined}onKeyDown={onKeyDown}+ onFocus={event => {+ onFocus?.(event);+ surface.onTriggerFocus(event);+ }}tabIndex={isDisabled && !showsDisabledMessage ? -1 : 0}{...stylex.props(styles.trigger)}><span {...stylex.props(styles.triggerContent)}>@@ -1754,7 +1843,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({xstyle={[styles.triggerIcon,styles.triggerIconRotation,- popover.isOpen && styles.triggerIconOpen,+ surface.isOpen && styles.triggerIconOpen,]}// Stable theme target on the chevron glyph itself, so a theme can// restyle just this icon (color, size, hover) — and its@@ -1762,54 +1851,13 @@ export function MultiSelector<T extends MultiSelectorOptionType>({// @layer astryx-theme win over the icon's own base color/size,// which a button-level target could not reach.{...themeProps('multi-selector-indicator-icon', {- state: popover.isOpen ? 'expanded' : 'collapsed',+ state: surface.isOpen ? 'expanded' : 'collapsed',})}/>)}</div>- {popover.render(- hasSearch ? (- // With a search row the panel splits: the header stays put while the- // options scroll under it, so the field does not slide out of reach- // in a long list. Without one the panel is a single scroll container,- // exactly as before.- <div>- {renderSearch()}- {/*- Separates the header from the options and spans the panel: the- search row and the option list each hold their own inline- padding, the line does not, so it reads as the panel's own edge.- */}- <Divider />- <div {...stylex.props(styles.dropdown)}>- <div- id={listboxId}- role="listbox"- aria-multiselectable="true"- aria-labelledby={triggerId}>- {renderOptions()}- </div>- </div>- </div>- ) : (- <div {...stylex.props(styles.dropdown)}>- <div- id={listboxId}- role="listbox"- aria-multiselectable="true"- aria-labelledby={triggerId}>- {renderOptions()}- </div>- </div>- ),- {- placement: 'below',- alignment: 'start',- offset: spacingVars['--spacing-1'],- xstyle: styles.popover,- },- )}+ {selectionSurface}{showStatusTooltip && statusTooltip.renderTooltip(status?.message ?? '')}diff --git a/packages/core/src/MultiSelector/index.ts b/packages/core/src/MultiSelector/index.tsindex 6f48bb5359..9859cb5c46 100644--- a/packages/core/src/MultiSelector/index.ts+++ b/packages/core/src/MultiSelector/index.ts@@ -11,6 +11,7 @@export {MultiSelector,type MultiSelectorProps,+ type MultiSelectorPresentation,type MultiSelectorSize,type MultiSelectorStatusType,type MultiSelectorSelectedItem,diff --git a/packages/core/src/Selector/Selector.doc.mjs b/packages/core/src/Selector/Selector.doc.mjsindex 4dcb87304d..d8d62937bc 100644--- a/packages/core/src/Selector/Selector.doc.mjs+++ b/packages/core/src/Selector/Selector.doc.mjs@@ -194,6 +194,13 @@ export const docs = {'Which edge of the option row carries the selected mark. start reserves a mark column ahead of every label so they stay aligned, the way a native menu does; end is the house convention shared with Typeahead and CommandPalette.',default: "'end'",},+ {+ name: 'presentation',+ type: "'popover' | 'bottom-sheet' | 'adaptive'",+ description:+ 'How the option list is presented. adaptive uses a bottom sheet on compact touch screens and an anchored popover otherwise.',+ default: "'popover'",+ },{name: 'width',type: 'SizeValue',@@ -253,6 +260,11 @@ export const docs = {description:'Use variant="ghost" when a selector sits in a toolbar with ghost buttons. If validation status is needed there, prefer statusVariant="tooltip" so the toolbar height stays compact.',},+ {+ guidance: true,+ description:+ 'Use presentation="adaptive" when the selector should become a bottom sheet on compact touch screens.',+ },{guidance: false,description:diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsxindex 899a615999..874690d793 100644--- a/packages/core/src/Selector/Selector.test.tsx+++ b/packages/core/src/Selector/Selector.test.tsx@@ -10,6 +10,7 @@*/import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';+import {readFileSync} from 'node:fs';import {act,render,@@ -19,6 +20,7 @@ import {within,} from '@testing-library/react';import userEvent from '@testing-library/user-event';+import * as stylex from '@stylexjs/stylex';import {useState} from 'react';import type {ReactNode} from 'react';import {Selector} from './Selector';@@ -35,6 +37,7 @@ import {defineTheme} from '../theme/defineTheme';import {Theme} from '../theme/Theme';import {generateThemeCSS} from '../theme/generateThemeRules';import {spacingVars} from '../theme/tokens.stylex';+import {selectorPresentationStyles} from './selectorPresentation.stylex';function generateThemeTestCSS(theme: Parameters<typeof generateThemeCSS>[0]) {const {prose, component} = generateThemeCSS(theme);@@ -45,6 +48,28 @@ function generateThemeTestCSS(theme: Parameters<typeof generateThemeCSS>[0]) {beforeEach(() => {// The live regions are a document-level singleton; start each test clean.__resetLiveRegionsForTest();+ __resetInteractionModalityForTest();+ HTMLDialogElement.prototype.showModal = vi.fn(function (+ this: HTMLDialogElement,+ ) {+ this.setAttribute('open', '');+ });+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {+ this.removeAttribute('open');+ });+ vi.stubGlobal(+ 'matchMedia',+ vi.fn().mockImplementation((query: string) => ({+ matches: false,+ media: query,+ onchange: null,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),+ );HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {this.setAttribute('popover-open', '');const event = new Event('toggle', {bubbles: false});@@ -228,6 +253,116 @@ function mockSelectorRects({}describe('Selector', () => {+ it('uses a bottom sheet and closes after a selection when requested', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <Selector+ label="Fruit"+ options={OPTIONS}+ onChange={onChange}+ presentation="bottom-sheet"+ />,+ );++ const trigger = screen.getByRole('combobox');+ await user.click(trigger);++ expect(+ await screen.findByRole('dialog', {name: 'Fruit'}),+ ).toBeInTheDocument();+ expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled();++ await user.click(screen.getByRole('option', {name: /Banana/}));+ expect(onChange).toHaveBeenCalledWith('Banana');+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ });++ it('restores touch focus without painting a trigger focus ring', async () => {+ render(+ <Selector+ label="Fruit"+ options={OPTIONS}+ onChange={() => {}}+ presentation="bottom-sheet"+ />,+ );++ const trigger = screen.getByRole('combobox');+ fireEvent.pointerDown(trigger, {pointerType: 'touch'});+ fireEvent.click(trigger, {detail: 1});+ const option = await screen.findByRole('option', {name: /Banana/});+ fireEvent.pointerDown(option, {pointerType: 'touch'});+ fireEvent.click(option, {detail: 1});++ trigger.focus();+ expect(trigger).toHaveFocus();+ expect(trigger.parentElement).toHaveClass(+ stylex.props(selectorPresentationStyles.pointerRestoredFocus).className!,+ );+ });++ it('uses content-hugging height without extra bottom content padding', () => {+ const source = readFileSync(+ 'packages/core/src/Selector/SelectorBottomSheet.tsx',+ 'utf8',+ );++ expect(source).toContain('height="hug"');+ expect(source).toContain('paddingBlockStart={4}');+ expect(source).toContain('paddingBlockEnd={0}');+ });++ it('moves keyboard focus into a bottom-sheet listbox', async () => {+ const user = userEvent.setup();+ render(+ <Selector label="Fruit" options={OPTIONS} presentation="bottom-sheet" />,+ );++ const trigger = screen.getByRole('combobox');+ trigger.focus();+ await user.keyboard('{Enter}');++ await waitFor(() => expect(screen.getByRole('listbox')).toHaveFocus());+ });++ it('uses a bottom sheet for adaptive presentation on compact touch', async () => {+ vi.stubGlobal(+ 'matchMedia',+ vi.fn().mockImplementation((query: string) => ({+ matches: query === '(max-width: 768px) and (pointer: coarse)',+ media: query,+ onchange: null,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),+ );+ const user = userEvent.setup();+ render(+ <Selector label="Fruit" options={OPTIONS} presentation="adaptive" />,+ );++ await user.click(screen.getByRole('combobox'));+ expect(+ await screen.findByRole('dialog', {name: 'Fruit'}),+ ).toBeInTheDocument();+ expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled();+ });++ it('keeps adaptive presentation anchored without compact touch', async () => {+ const user = userEvent.setup();+ render(+ <Selector label="Fruit" options={OPTIONS} presentation="adaptive" />,+ );++ await user.click(screen.getByRole('combobox'));+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalledOnce();+ expect(HTMLDialogElement.prototype.showModal).not.toHaveBeenCalled();+ });+it('renders with placeholder when no value', () => {render(<Selector label="Fruit" options={OPTIONS} placeholder="Pick one" />);expect(screen.getByRole('combobox')).toHaveTextContent('Pick one');diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsxindex c8df8997cd..50b9c6434f 100644--- a/packages/core/src/Selector/Selector.tsx+++ b/packages/core/src/Selector/Selector.tsx@@ -29,7 +29,6 @@ import React, {type ReactNode,} from 'react';import * as stylex from '@stylexjs/stylex';-import {usePopoverInternal} from '../Popover/usePopover';import {useTooltip} from '../Tooltip';import {Icon, renderIconSlot, type IconType} from '../Icon';import {useIndicator} from '../Indicator';@@ -86,6 +85,10 @@ import {groupStyles} from '../InputGroup/groupStyles';import {useInputGroup} from '../InputGroup/InputGroupContext';import {VisuallyHidden} from '../VisuallyHidden';import {useTranslator} from '../i18n';+import type {AdaptivePresentation} from '../hooks/useAdaptivePresentation';+import {SelectorBottomSheet} from './SelectorBottomSheet';+import {useSelectorPresentation} from './useSelectorPresentation';+import {selectorPresentationStyles} from './selectorPresentation.stylex';const styles = stylex.create({// Trigger container — the enhanced click target wrapping the combobox button and clear button as siblings@@ -265,6 +268,7 @@ const styles = stylex.create({boxSizing: 'border-box',maxHeight: '300px',overflowY: 'auto',+ outline: 'none',paddingBlock: spacingVars['--spacing-1'],paddingInline: spacingVars['--spacing-1'],opacity: 1,@@ -450,6 +454,8 @@ export type SelectorSize = 'sm' | 'md' | 'lg';export type SelectorVariant = 'input' | 'ghost';+export type SelectorPresentation = AdaptivePresentation;+export type SelectorStatusType = 'warning' | 'error' | 'success';export interface SelectorStatus {@@ -672,6 +678,15 @@ interface SelectorPropsBase<*/placement?: LayerPlacement;+ /**+ * How the option list is presented.+ * - 'popover': anchored to the trigger+ * - 'bottom-sheet': modal sheet suited to compact touch screens+ * - 'adaptive': bottom sheet on compact coarse-pointer screens, otherwise popover+ * @default 'popover'+ */+ presentation?: SelectorPresentation;+/*** Whether the dropdown starts open on mount.* Useful for showcases and previews.@@ -811,12 +826,14 @@ export function Selector<T extends SelectorOptionType>(emptyText: emptyTextFromProps,emptySearchText: emptySearchTextFromProps,placement,+ presentation = 'popover',isDefaultOpen = false,'data-testid': testId,width,xstyle,className,style,+ onFocus,hasClear: hasClearProp,id,...rest@@ -949,27 +966,31 @@ export function Selector<T extends SelectorOptionType>(// Clear any lingering result count when the popover closes so stale status// text does not linger in the a11y tree.announce('');- triggerRef.current?.focus();}, [announce]);- const popover = usePopoverInternal({+ const surface = useSelectorPresentation({+ presentation,onHide: handleLayerHide,- hasLightDismiss: true,- hasCloseButton: false,- hasAutoFocus: false,- // The popup's own role="listbox" is the exposed semantics; the trigger- // keeps DOM focus, so wrapping it in a modal dialog would misrepresent it.- role: 'none',- // The theme target belongs on the SURFACE that paints the popup, which- // `usePopover` owns — not on the scrolling list inside it.- surfaceTarget: 'selector-popup',+ triggerRef,+ popoverOptions: {+ hasLightDismiss: true,+ hasCloseButton: false,+ hasAutoFocus: false,+ // The popup's own role="listbox" is the exposed semantics; the trigger+ // keeps DOM focus, so wrapping it in a modal dialog would misrepresent it.+ role: 'none',+ // The theme target belongs on the SURFACE that paints the popup, which+ // `usePopover` owns — not on the scrolling list inside it.+ surfaceTarget: 'selector-popup',+ },});+ const {popover} = surface;const keepOpenProps = useKeepLayerOpenProps(popover.id, popover.isOpen);// Open dropdown on mount when isDefaultOpen is trueuseEffect(() => {if (isDefaultOpen) {- popover.show();+ surface.show();}// eslint-disable-next-line @eslint-react/exhaustive-deps -- mount-only: isDefaultOpen is not reactive}, []);@@ -1022,7 +1043,7 @@ export function Selector<T extends SelectorOptionType>(const announcedEmptyRef = useRef<string | null>(null);useEffect(() => {const isPanelEmpty =- popover.isOpen &&+ surface.isOpen &&!isLoading &&searchQuery === '' &&selectableItems.length === 0;@@ -1036,7 +1057,7 @@ export function Selector<T extends SelectorOptionType>(announcedEmptyRef.current = emptyAnnouncement;announce(emptyAnnouncement);}, [- popover.isOpen,+ surface.isOpen,isLoading,searchQuery,selectableItems.length,@@ -1118,17 +1139,17 @@ export function Selector<T extends SelectorOptionType>(onItemMouseEnter,} = useCombobox({selectableItems: filteredItems,- wasJustDismissed: popover.wasJustDismissed,+ wasJustDismissed: surface.wasJustDismissed,// The optimistic value, not the raw prop: with a pending changeAction the// prop still holds the old selection, so the popup would open with the// highlight on it and Delete/Backspace could clear a value the action has// already replaced.value: optimisticValue,isDisabled,- isOpen: popover.isOpen,+ isOpen: surface.isOpen,hasSearch,onOpen: useCallback(() => {- popover.show();+ surface.show();if (hasSearch) {requestAnimationFrame(() => {const input = searchRef.current;@@ -1140,8 +1161,8 @@ export function Selector<T extends SelectorOptionType>(}});}- }, [popover, hasSearch]),- onClose: popover.hide,+ }, [surface, hasSearch]),+ onClose: surface.hide,onSelect: commitValue,onClear: hasClear ? clearValue : undefined,onSearchSeed: appendSearchQuery,@@ -1161,10 +1182,10 @@ export function Selector<T extends SelectorOptionType>(// cycling on the first match. -1 means nothing is selected or highlighted,// which the hook reads as "search from the top".getCurrentIndex: () =>- popover.isOpen ? highlightedIndex : selectedItemIndex,+ surface.isOpen ? highlightedIndex : selectedItemIndex,onMatch: index => {const item = selectableItems[index];- if (popover.isOpen) {+ if (surface.isOpen) {setHighlightedIndex(index);} else if (item.value !== optimisticValue) {commitValue(item.value);@@ -1191,13 +1212,13 @@ export function Selector<T extends SelectorOptionType>(// cursor walks off-screen once navigation passes the visible window. Mirrors// CommandPaletteItem's scrollIntoView({block: 'nearest'}) behavior.useEffect(() => {- if (!popover.isOpen || highlightedIndex < 0) {+ if (!surface.isOpen || highlightedIndex < 0) {return;}document.getElementById(getItemId(highlightedIndex))?.scrollIntoView?.({block: 'nearest'});- }, [popover.isOpen, highlightedIndex, getItemId]);+ }, [surface.isOpen, highlightedIndex, getItemId]);// Handle clear button clickconst handleClear = useCallback(@@ -1229,17 +1250,21 @@ export function Selector<T extends SelectorOptionType>(label: t('@astryx.selector.searchOptions'),})}{...themeProps('selector-search')}- xstyle={variant !== 'ghost' && styles.searchRowInput}+ xstyle={+ surface.activePresentation === 'popover' &&+ variant !== 'ghost' &&+ styles.searchRowInput+ }// When hasSearch is set, focus moves into this input on open, so it —// not the trigger — must be the combobox that reports the highlighted// option via aria-activedescendant (comboboxes-4). A bare searchbox// left the highlight silent to screen readers.role="combobox"- aria-expanded={popover.isOpen}+ aria-expanded={surface.isOpen}aria-controls={listboxId}aria-autocomplete="list"aria-activedescendant={- popover.isOpen && highlightedIndex >= 0+ surface.isOpen && highlightedIndex >= 0? getItemId(highlightedIndex): undefined}@@ -1302,7 +1327,8 @@ export function Selector<T extends SelectorOptionType>(searchPlaceholder,handleSearchChange,onKeyDown,- popover.isOpen,+ surface.isOpen,+ surface.activePresentation,highlightedIndex,getItemId,variant,@@ -1554,6 +1580,79 @@ export function Selector<T extends SelectorOptionType>(</>);+ const panelContent = hasSearch ? (+ <div>+ {renderSearch()}+ <Divider />+ <div+ ref={listboxRef}+ id={listboxId}+ role="listbox"+ aria-labelledby={triggerId}+ {...stylex.props(+ styles.dropdown,+ surface.activePresentation === 'popover' &&+ variant !== 'ghost' &&+ styles.dropdownInput,+ )}>+ {renderOptions()}+ </div>+ </div>+ ) : (+ <div+ ref={listboxRef}+ id={listboxId}+ role="listbox"+ aria-labelledby={triggerId}+ aria-activedescendant={+ surface.isOpen && highlightedIndex >= 0+ ? getItemId(highlightedIndex)+ : undefined+ }+ tabIndex={surface.activePresentation === 'bottom-sheet' ? 0 : undefined}+ onKeyDown={+ surface.activePresentation === 'bottom-sheet'+ ? handleTriggerKeyDown+ : undefined+ }+ {...stylex.props(+ styles.dropdown,+ surface.activePresentation === 'popover' &&+ variant !== 'ghost' &&+ styles.dropdownInput,+ surface.activePresentation === 'popover' &&+ !isPositioned &&+ styles.dropdownHidden,+ )}>+ {renderOptions()}+ </div>+ );++ const selectionSurface =+ surface.activePresentation === 'bottom-sheet' ? (+ <SelectorBottomSheet+ isOpen={surface.isSheetOpen}+ onOpenChange={surface.onSheetOpenChange}+ finalFocusRef={triggerRef}+ initialFocusRef={hasSearch ? searchRef : listboxRef}+ label={label}>+ {panelContent}+ </SelectorBottomSheet>+ ) : (+ popover.render(panelContent, {+ placement: popoverPlacement,+ alignment: 'start',+ // The system's standard menu clearance, except in overlay mode:+ // there the measured negative margin owns the block geometry and+ // the menu is meant to sit on the trigger, not clear it.+ offset: shouldOverlaySelectedItem+ ? undefined+ : spacingVars['--spacing-1'],+ xstyle: [styles.popover, layerAnimations[popoverPlacement]],+ style: popoverOffsetStyle,+ })+ );+const selectorContent = (<><div@@ -1581,6 +1680,8 @@ export function Selector<T extends SelectorOptionType>(variant === 'ghost' && styles.triggerGhost,variant === 'ghost' && interactionOverlayStyles.backgroundImage,variant === 'ghost' && focusOutlineStyles.focusWithin,+ surface.isTriggerFocusRingSuppressed &&+ selectorPresentationStyles.pointerRestoredFocus,isDisabled && inputWrapperStyles.disabled,variant === 'ghost' && isDisabled && styles.triggerGhostDisabled,!selectedItem && styles.triggerPlaceholder,@@ -1612,11 +1713,13 @@ export function Selector<T extends SelectorOptionType>(// plain button that opens the listbox — not a second combobox.role={hasSearch ? undefined : 'combobox'}{...rest}- aria-haspopup="listbox"- aria-expanded={popover.isOpen}+ aria-haspopup={+ surface.activePresentation === 'bottom-sheet' ? 'dialog' : 'listbox'+ }+ aria-expanded={surface.isOpen}aria-controls={listboxId}aria-activedescendant={- !hasSearch && popover.isOpen && highlightedIndex >= 0+ !hasSearch && surface.isOpen && highlightedIndex >= 0? getItemId(highlightedIndex): undefined}@@ -1631,6 +1734,10 @@ export function Selector<T extends SelectorOptionType>(disabled={isDisabled && !showsDisabledMessage}aria-disabled={showsDisabledMessage ? 'true' : undefined}onKeyDown={handleTriggerKeyDown}+ onFocus={event => {+ onFocus?.(event);+ surface.onTriggerFocus(event);+ }}tabIndex={isDisabled && !showsDisabledMessage ? -1 : 0}{...stylex.props(styles.trigger,@@ -1702,7 +1809,7 @@ export function Selector<T extends SelectorOptionType>(xstyle={[styles.triggerIcon,styles.triggerIconRotation,- popover.isOpen && styles.triggerIconOpen,+ surface.isOpen && styles.triggerIconOpen,]}// Stable theme target on the chevron glyph itself, so a theme can// restyle just this icon (color, size, hover) — and its@@ -1710,61 +1817,13 @@ export function Selector<T extends SelectorOptionType>(// @layer astryx-theme win over the icon's own base color/size,// which a button-level target could not reach.{...themeProps('selector-indicator-icon', {- state: popover.isOpen ? 'expanded' : 'collapsed',+ state: surface.isOpen ? 'expanded' : 'collapsed',})}/>)}</div>- {popover.render(- hasSearch ? (- <div>- {renderSearch()}- {/*- Separates the header from the options and spans the panel: the- search row and the listbox each hold their own inline padding,- the line does not, so it reads as the panel's own edge.- */}- <Divider />- <div- ref={listboxRef}- id={listboxId}- role="listbox"- aria-labelledby={triggerId}- {...stylex.props(- styles.dropdown,- variant !== 'ghost' && styles.dropdownInput,- )}>- {renderOptions()}- </div>- </div>- ) : (- <div- ref={listboxRef}- id={listboxId}- role="listbox"- aria-labelledby={triggerId}- {...stylex.props(- styles.dropdown,- variant !== 'ghost' && styles.dropdownInput,- !isPositioned && styles.dropdownHidden,- )}>- {renderOptions()}- </div>- ),- {- placement: popoverPlacement,- alignment: 'start',- // The system's standard menu clearance, except in overlay mode:- // there the measured negative margin owns the block geometry and- // the menu is meant to sit on the trigger, not clear it.- offset: shouldOverlaySelectedItem- ? undefined- : spacingVars['--spacing-1'],- xstyle: [styles.popover, layerAnimations[popoverPlacement]],- style: popoverOffsetStyle,- },- )}+ {selectionSurface}{showStatusTooltip && statusTooltip.renderTooltip(status?.message ?? '')}diff --git a/packages/core/src/Selector/SelectorBottomSheet.tsx b/packages/core/src/Selector/SelectorBottomSheet.tsxnew file mode 100644index 0000000000..7f3715f9cd--- /dev/null+++ b/packages/core/src/Selector/SelectorBottomSheet.tsx@@ -0,0 +1,97 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file SelectorBottomSheet.tsx+ * @input Uses BottomSheet, Section, and Heading+ * @output Shared mobile listbox sheet for Selector and MultiSelector+ * @position Internal presentation primitive for selection controls+ */++import {lazy, Suspense, useEffect, type ReactNode, type RefObject} from 'react';+import * as stylex from '@stylexjs/stylex';+import {Heading} from '../Heading';+import {Section} from '../Section';+import {spacingVars} from '../theme/tokens.stylex';++const LazyBottomSheet = lazy(async () =>+ import('../BottomSheet/BottomSheet').then(module => ({+ default: module.BottomSheet,+ })),+);++const styles = stylex.create({+ content: {+ width: '100%',+ },+ heading: {+ marginBlockEnd: spacingVars['--spacing-2'],+ marginInline: spacingVars['--spacing-3'],+ },+});++interface SelectorBottomSheetProps {+ children: ReactNode;+ finalFocusRef: RefObject<HTMLElement | null>;+ initialFocusRef: RefObject<HTMLElement | null>;+ isOpen: boolean;+ label: string;+ onOpenChange: (isOpen: boolean) => void;+}++function SelectorBottomSheetInitialFocus({+ isOpen,+ targetRef,+}: {+ isOpen: boolean;+ targetRef: RefObject<HTMLElement | null>;+}) {+ useEffect(() => {+ if (!isOpen) {+ return;+ }+ const frame = requestAnimationFrame(() => {+ targetRef.current?.focus({preventScroll: true});+ });+ return () => cancelAnimationFrame(frame);+ }, [isOpen, targetRef]);++ return null;+}++export function SelectorBottomSheet({+ children,+ finalFocusRef,+ initialFocusRef,+ isOpen,+ label,+ onOpenChange,+}: SelectorBottomSheetProps) {+ return (+ <Suspense fallback={null}>+ <LazyBottomSheet+ isOpen={isOpen}+ onOpenChange={onOpenChange}+ finalFocusRef={finalFocusRef}+ label={label}+ height="hug"+ purpose="info">+ <Section paddingBlockStart={4} paddingBlockEnd={0} paddingInline={1}>+ <div {...stylex.props(styles.content)}>+ <Heading level={3} xstyle={styles.heading}>+ {label}+ </Heading>+ {children}+ <SelectorBottomSheetInitialFocus+ isOpen={isOpen}+ targetRef={initialFocusRef}+ />+ </div>+ </Section>+ </LazyBottomSheet>+ </Suspense>+ );+}++SelectorBottomSheet.displayName = 'SelectorBottomSheet';diff --git a/packages/core/src/Selector/index.ts b/packages/core/src/Selector/index.tsindex 1c027a222e..26bda3cc4b 100644--- a/packages/core/src/Selector/index.ts+++ b/packages/core/src/Selector/index.ts@@ -11,6 +11,7 @@export {Selector,type SelectorProps,+ type SelectorPresentation,type SelectorSize,type SelectorStatus,type SelectorStatusType,diff --git a/packages/core/src/Selector/selectorPresentation.stylex.ts b/packages/core/src/Selector/selectorPresentation.stylex.tsnew file mode 100644index 0000000000..cb6c220952--- /dev/null+++ b/packages/core/src/Selector/selectorPresentation.stylex.ts@@ -0,0 +1,20 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file selectorPresentation.stylex.ts+ * @input Uses field border tokens+ * @output Shared focus-return styles for Selector and MultiSelector+ * @position Internal visual policy for selector presentation changes+ */++import * as stylex from '@stylexjs/stylex';+import {colorVars} from '../theme/tokens.stylex';++export const selectorPresentationStyles = stylex.create({+ pointerRestoredFocus: {+ borderColor: colorVars['--color-border-emphasized'],+ boxShadow: 'none',+ outlineWidth: '0',+ outlineStyle: 'none',+ },+});diff --git a/packages/core/src/Selector/useSelectorPresentation.ts b/packages/core/src/Selector/useSelectorPresentation.tsnew file mode 100644index 0000000000..2bbd0c9ee4--- /dev/null+++ b/packages/core/src/Selector/useSelectorPresentation.ts@@ -0,0 +1,147 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useSelectorPresentation.ts+ * @input Uses the shared adaptive presentation policy and usePopover+ * @output Coordinates popover and bottom-sheet disclosure state+ * @position Internal presentation controller shared by Selector and MultiSelector+ */++import {+ useCallback,+ useRef,+ useState,+ type FocusEvent,+ type RefObject,+} from 'react';+import {+ usePopoverInternal,+ type UsePopoverOptions,+ type UsePopoverReturn,+} from '../Popover/usePopover';+import {+ useAdaptivePresentation,+ type AdaptivePresentation,+ type ResolvedAdaptivePresentation,+} from '../hooks/useAdaptivePresentation';+import {useFocusReturnVisibility} from '../hooks/useFocusReturnVisibility';++interface UseSelectorPresentationOptions {+ presentation: AdaptivePresentation;+ onHide: () => void;+ popoverOptions: Omit<UsePopoverOptions, 'onHide'>;+ triggerRef: RefObject<HTMLElement | null>;+}++interface SelectorPresentationController {+ activePresentation: ResolvedAdaptivePresentation;+ hide: () => void;+ isOpen: boolean;+ isSheetOpen: boolean;+ isTriggerFocusRingSuppressed: boolean;+ onSheetOpenChange: (isOpen: boolean) => void;+ onTriggerFocus: (event: FocusEvent<HTMLElement>) => void;+ popover: UsePopoverReturn & {wasJustDismissed: () => boolean};+ show: () => void;+ wasJustDismissed: () => boolean;+}++export function useSelectorPresentation({+ presentation,+ onHide,+ popoverOptions,+ triggerRef,+}: UseSelectorPresentationOptions): SelectorPresentationController {+ const resolvedPresentation = useAdaptivePresentation(presentation);+ const activePresentationRef =+ useRef<ResolvedAdaptivePresentation>(resolvedPresentation);+ const [isSheetOpen, setIsSheetOpen] = useState(false);+ const isSheetOpenRef = useRef(false);+ const onHideRef = useRef(onHide);+ const {+ isFocusRingSuppressed,+ onFocusReturnTargetFocus,+ prepareFocusReturn,+ resetFocusReturn,+ } = useFocusReturnVisibility();+ onHideRef.current = onHide;++ const handlePopoverHide = useCallback(() => {+ prepareFocusReturn();+ onHideRef.current();+ triggerRef.current?.focus();+ }, [prepareFocusReturn, triggerRef]);+ const popover = usePopoverInternal({+ ...popoverOptions,+ onHide: handlePopoverHide,+ });+ const {+ hide: hidePopover,+ show: showPopover,+ wasJustDismissed: wasPopoverJustDismissed,+ } = popover;++ const show = useCallback(() => {+ resetFocusReturn();+ activePresentationRef.current = resolvedPresentation;+ if (resolvedPresentation === 'bottom-sheet') {+ isSheetOpenRef.current = true;+ setIsSheetOpen(true);+ } else {+ showPopover();+ }+ }, [resetFocusReturn, resolvedPresentation, showPopover]);++ const hide = useCallback(() => {+ if (isSheetOpenRef.current) {+ prepareFocusReturn();+ isSheetOpenRef.current = false;+ setIsSheetOpen(false);+ onHideRef.current();+ } else {+ hidePopover();+ }+ }, [hidePopover, prepareFocusReturn]);++ const handleTriggerFocus = useCallback(+ (_event: FocusEvent<HTMLElement>) => onFocusReturnTargetFocus(),+ [onFocusReturnTargetFocus],+ );++ const handleSheetOpenChange = useCallback(+ (nextIsOpen: boolean) => {+ if (nextIsOpen) {+ show();+ } else {+ hide();+ }+ },+ [hide, show],+ );++ const isOpen = popover.isOpen || isSheetOpen;+ const activePresentation = isOpen+ ? activePresentationRef.current+ : resolvedPresentation;++ const wasJustDismissed = useCallback(+ () =>+ activePresentationRef.current === 'popover' && wasPopoverJustDismissed(),+ [wasPopoverJustDismissed],+ );++ return {+ activePresentation,+ hide,+ isOpen,+ isSheetOpen,+ isTriggerFocusRingSuppressed: isFocusRingSuppressed,+ onSheetOpenChange: handleSheetOpenChange,+ onTriggerFocus: handleTriggerFocus,+ popover,+ show,+ wasJustDismissed,+ };+}diff --git a/packages/core/src/hooks/useAdaptivePresentation.ts b/packages/core/src/hooks/useAdaptivePresentation.tsnew file mode 100644index 0000000000..199be1186d--- /dev/null+++ b/packages/core/src/hooks/useAdaptivePresentation.ts@@ -0,0 +1,35 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useAdaptivePresentation.ts+ * @input Uses the shared SSR-safe media-query hook+ * @output Resolves popover/bottom-sheet presentation policy+ * @position Internal overlay policy shared across component families+ */++import {useMediaQuery} from './useMediaQuery';++export type AdaptivePresentation = 'popover' | 'bottom-sheet' | 'adaptive';+export type ResolvedAdaptivePresentation = Exclude<+ AdaptivePresentation,+ 'adaptive'+>;++// Width keeps desktop-class tablets and large touch displays anchored by+// default. Pointer capability, rather than `hover: none`, avoids excluding+// touch browsers that also report hover capability.+export const COMPACT_TOUCH_PRESENTATION_QUERY =+ '(max-width: 768px) and (pointer: coarse)';++export function useAdaptivePresentation(+ presentation: AdaptivePresentation,+): ResolvedAdaptivePresentation {+ const isCompactTouch = useMediaQuery(COMPACT_TOUCH_PRESENTATION_QUERY);+ return presentation === 'adaptive'+ ? isCompactTouch+ ? 'bottom-sheet'+ : 'popover'+ : presentation;+}diff --git a/packages/core/src/hooks/useFocusReturnVisibility.ts b/packages/core/src/hooks/useFocusReturnVisibility.tsnew file mode 100644index 0000000000..fec50a1e6d--- /dev/null+++ b/packages/core/src/hooks/useFocusReturnVisibility.ts@@ -0,0 +1,45 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useFocusReturnVisibility.ts+ * @input Uses the shared interaction-modality tracker+ * @output Preserves returned focus while suppressing pointer-only focus rings+ * @position Internal focus-return policy for adaptive overlays+ */++import {useCallback, useEffect, useState} from 'react';+import {+ getInteractionModality,+ trackInteractionModality,+} from '../utils/interactionModality';++export function useFocusReturnVisibility() {+ const [isFocusRingSuppressed, setIsFocusRingSuppressed] = useState(false);++ useEffect(() => {+ trackInteractionModality();+ }, []);++ const prepareFocusReturn = useCallback(() => {+ setIsFocusRingSuppressed(getInteractionModality() === 'pointer');+ }, []);++ const resetFocusReturn = useCallback(() => {+ setIsFocusRingSuppressed(false);+ }, []);++ const onFocusReturnTargetFocus = useCallback(() => {+ if (getInteractionModality() === 'keyboard') {+ setIsFocusRingSuppressed(false);+ }+ }, []);++ return {+ isFocusRingSuppressed,+ onFocusReturnTargetFocus,+ prepareFocusReturn,+ resetFocusReturn,+ };+}