Skip to content

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

TypeScript

Improve Popover responsive fit and focus behavior (#5373)

rubyycheung191758193820
diff --git a/.changeset/bottom-sheet-modal-edge-tint.md b/.changeset/bottom-sheet-modal-edge-tint.md
new file mode 100644
index 0000000000..b86c60e999
--- /dev/null
+++ b/.changeset/bottom-sheet-modal-edge-tint.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] BottomSheet now keeps the iOS Safari browser-bar edge consistent with the sheet surface for both modal and non-modal presentations.
+
+@rubyycheung
diff --git a/.changeset/popover-responsive-fit.md b/.changeset/popover-responsive-fit.md
new file mode 100644
index 0000000000..d4e20bf7da
--- /dev/null
+++ b/.changeset/popover-responsive-fit.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Popover layers now cap explicit widths and match-trigger sizing to the available viewport with alignment-aware token safe-area gutters, preserving trigger alignment while keeping the painted surface at least one spacing token from both viewport edges. Long content scrolls inside the layer instead of forcing page overflow on narrow viewports. Repeated resize and content-change signals coalesce overflow measurement to once per animation frame. Pointer-activated dialog popovers focus the labeled dialog container so the first action does not appear preselected, while keyboard activation still focuses the first content control. Read-only content uses the same container target without revealing the fallback close button, while preserving Tab access to that fallback escape control.
+
+@rubyycheung
diff --git a/apps/storybook/stories/Popover.stories.tsx b/apps/storybook/stories/Popover.stories.tsx
index c33dd61582..0798a92446 100644
--- a/apps/storybook/stories/Popover.stories.tsx
+++ b/apps/storybook/stories/Popover.stories.tsx
@@ -1,17 +1,22 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import React from 'react';
+import * as stylex from '@stylexjs/stylex';
import type {Meta, StoryObj} from '@storybook/react';
+import {BottomSheet} from '@astryxdesign/core/BottomSheet';
import {Popover} from '@astryxdesign/core/Popover';
import type {PopoverTriggerRenderProps} from '@astryxdesign/core/Popover';
import {Button} from '@astryxdesign/core/Button';
import {Token} from '@astryxdesign/core/Token';
import {Link} from '@astryxdesign/core/Link';
+import {List, ListItem} from '@astryxdesign/core/List';
import {VStack, HStack} from '@astryxdesign/core/Layout';
import {Text, Heading} from '@astryxdesign/core/Text';
import {Switch} from '@astryxdesign/core/Switch';
import {CheckboxInput} from '@astryxdesign/core/CheckboxInput';
import {Divider} from '@astryxdesign/core/Divider';
+import {Section} from '@astryxdesign/core/Section';
+import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';
const meta: Meta<typeof Popover> = {
title: 'Core/Popover',
@@ -37,6 +42,263 @@ const meta: Meta<typeof Popover> = {
export default meta;
type Story = StoryObj<typeof Popover>;
+type PresentationRecipeStory = StoryObj<PresentationRecipeArgs>;
+
+type ProjectAction = 'owner' | 'label' | 'due-date';
+type PresentationChoice = 'popover' | 'bottom-sheet';
+
+interface PresentationRecipeArgs {
+ presentation?: PresentationChoice;
+ touchPresentation?: PresentationChoice;
+}
+
+const PROJECT_ACTIONS: ReadonlyArray<{
+ id: ProjectAction;
+ label: string;
+ description: string;
+}> = [
+ {
+ id: 'owner',
+ label: 'Assign owner',
+ description: 'Route follow-up to a teammate.',
+ },
+ {
+ id: 'label',
+ label: 'Add label',
+ description: 'Group this item with related work.',
+ },
+ {
+ id: 'due-date',
+ label: 'Set due date',
+ description: 'Pick a lightweight reminder for review.',
+ },
+];
+
+const PROJECT_DESTINATIONS = [
+ ['Apollo launch', 'Marketing · 12 open tasks'],
+ ['Customer insights', 'Research · 8 open tasks'],
+ ['Design systems', 'Platform · 24 open tasks'],
+ ['Growth experiments', 'Product · 6 open tasks'],
+ ['Incident review', 'Operations · 4 open tasks'],
+ ['Mobile quality', 'Engineering · 15 open tasks'],
+ ['Quarterly planning', 'Strategy · 9 open tasks'],
+ ['Recruiting plan', 'People · 7 open tasks'],
+ ['Security follow-up', 'Trust · 3 open tasks'],
+ ['Website refresh', 'Brand · 11 open tasks'],
+] as const;
+
+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',
+ },
+ oversizedTrigger: {
+ inlineSize: 640,
+ },
+ boundedPopoverContent: {
+ maxBlockSize: stylex.firstThatWorks(
+ 'min(50dvb, 360px)',
+ 'min(50vh, 360px)',
+ ),
+ },
+ evidenceCopy: {
+ maxInlineSize: 520,
+ overflowWrap: 'anywhere',
+ },
+ actionList: {
+ inlineSize: '100%',
+ },
+});
+
+function ProjectActionList({
+ selectedAction,
+ onSelectAction,
+ onReset,
+ presentation,
+}: {
+ selectedAction: ProjectAction | null;
+ onSelectAction: (action: ProjectAction) => void;
+ onReset: () => void;
+ presentation: PresentationChoice;
+}) {
+ return (
+ <VStack gap={3} xstyle={readinessStyles.actionList}>
+ <List
+ density="compact"
+ hasDividers
+ header={
+ <VStack gap={1}>
+ <Heading level={4} tabIndex={-1}>
+ Project actions
+ </Heading>
+ <Text type="supporting" color="secondary">
+ {presentation === 'popover'
+ ? 'Compact supplemental actions stay anchored to the trigger and keep the surrounding context visible.'
+ : 'The same actions can move into a BottomSheet when a product explicitly wants a bottom-edge touch surface.'}
+ </Text>
+ </VStack>
+ }>
+ {PROJECT_ACTIONS.map(action => (
+ <ListItem
+ key={action.id}
+ label={action.label}
+ description={action.description}
+ isSelected={selectedAction === action.id}
+ onClick={() => onSelectAction(action.id)}
+ />
+ ))}
+ </List>
+ <Divider />
+ <HStack gap={2} hAlign="between">
+ <Text type="supporting" color="secondary">
+ Selected:{' '}
+ {selectedAction == null
+ ? 'none'
+ : PROJECT_ACTIONS.find(action => action.id === selectedAction)
+ ?.label}
+ </Text>
+ <Button label="Reset selection" variant="ghost" onClick={onReset}>
+ Reset
+ </Button>
+ </HStack>
+ </VStack>
+ );
+}
+
+function useOptInTouchPresentation(
+ presentation: PresentationChoice | undefined,
+ touchPresentation: PresentationChoice | undefined,
+): PresentationChoice {
+ const [matchesTouchSurface, setMatchesTouchSurface] = React.useState(false);
+
+ React.useEffect(() => {
+ if (typeof window === 'undefined' || !window.matchMedia) {
+ return;
+ }
+ const query = window.matchMedia(
+ '(max-width: 639px) and (pointer: coarse) and (hover: none)',
+ );
+ const sync = () => setMatchesTouchSurface(query.matches);
+ sync();
+ query.addEventListener('change', sync);
+ return () => query.removeEventListener('change', sync);
+ }, []);
+
+ if (presentation != null) {
+ return presentation;
+ }
+ return touchPresentation === 'bottom-sheet' && matchesTouchSurface
+ ? 'bottom-sheet'
+ : 'popover';
+}
+
+function ProjectActionSurface({
+ presentation = 'popover',
+ touchPresentation = 'bottom-sheet',
+}: PresentationRecipeArgs) {
+ const resolvedPresentation = useOptInTouchPresentation(
+ presentation,
+ touchPresentation,
+ );
+ const [isOpen, setIsOpen] = React.useState(false);
+ const [selectedAction, setSelectedAction] =
+ React.useState<ProjectAction | null>(null);
+ const content = (
+ <ProjectActionList
+ presentation={resolvedPresentation}
+ selectedAction={selectedAction}
+ onSelectAction={setSelectedAction}
+ onReset={() => setSelectedAction(null)}
+ />
+ );
+
+ if (resolvedPresentation === 'bottom-sheet') {
+ return (
+ <div {...stylex.props(readinessStyles.viewportStoryCanvas)}>
+ <Button label="Open project actions" onClick={() => setIsOpen(true)}>
+ Open project actions
+ </Button>
+ <BottomSheet
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ label="Project actions"
+ height="hug">
+ <Section padding={4}>{content}</Section>
+ </BottomSheet>
+ </div>
+ );
+ }
+
+ return (
+ <div {...stylex.props(readinessStyles.viewportStoryCanvas)}>
+ <Popover
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ placement="below"
+ alignment="start"
+ label="Project actions"
+ width={320}
+ content={content}>
+ <Button label="Open project actions">Open project actions</Button>
+ </Popover>
+ </div>
+ );
+}
+
+function TallContentOverflowExample() {
+ const [selectedProject, setSelectedProject] = React.useState<string | null>(
+ null,
+ );
+
+ return (
+ <div {...stylex.props(readinessStyles.viewportStoryCanvas)}>
+ <Popover
+ placement="below"
+ alignment="start"
+ label="Move to project"
+ width={320}
+ data-testid="tall-popover"
+ xstyle={readinessStyles.boundedPopoverContent}
+ content={
+ <List
+ density="compact"
+ hasDividers
+ header={
+ <VStack gap={1}>
+ <Heading level={4} tabIndex={-1}>
+ Move to project
+ </Heading>
+ <Text type="supporting" color="secondary">
+ Choose a destination for this task.
+ </Text>
+ </VStack>
+ }>
+ {PROJECT_DESTINATIONS.map(([label, description]) => (
+ <ListItem
+ key={label}
+ label={label}
+ description={description}
+ isSelected={selectedProject === label}
+ onClick={() => setSelectedProject(label)}
+ />
+ ))}
+ </List>
+ }>
+ <Button label="Move task">Move task</Button>
+ </Popover>
+ </div>
+ );
+}
// =============================================================================
// Settings Panel
@@ -309,7 +571,11 @@ export const Disabled: Story = {
label: 'Disabled popover',
isEnabled: false,
content: <Text type="body">This should not appear.</Text>,
- children: <Button label="Disabled popover">Disabled</Button>,
+ children: (
+ <Button label="Disabled popover" isDisabled>
+ Disabled
+ </Button>
+ ),
},
};
@@ -406,3 +672,282 @@ export const RenderProp: Story = {
</Popover>
),
};
+// =============================================================================
+// Responsive and Interaction Readiness Evidence
+// =============================================================================
+
+export const ViewportFit: Story = {
+ name: 'Viewport Fit',
+ parameters: {
+ layout: 'fullscreen',
+ viewport: {defaultViewport: 'mobile1'},
+ docs: {
+ story: {inline: false, height: '844px'},
+ description: {
+ story:
+ 'Uses the actual Storybook viewport rather than a simulated phone frame. The Popover requests a 640px width and must stay anchored to the trigger while preserving at least 16px safe-area-aware gutters from both viewport edges.',
+ },
+ },
+ },
+ render: () => (
+ <div {...stylex.props(readinessStyles.viewportStoryCanvas)}>
+ <div {...stylex.props(readinessStyles.edgeAnchorRow)}>
+ <Popover
+ placement="below"
+ alignment="end"
+ label="Narrow viewport fit evidence"
+ width={640}
+ content={
+ <VStack gap={3} xstyle={readinessStyles.evidenceCopy}>
+ <Heading level={4} tabIndex={-1}>
+ Narrow viewport fit
+ </Heading>
+ <Text type="body" wordBreak="break-word">
+ This intentionally requests a wider-than-mobile popover. The
+ layer should stay anchored to the trigger, preserve safe gutters
+ on both viewport edges, and allow long content to reflow instead
+ of causing horizontal page overflow.
+ </Text>
+ <Text type="supporting" wordBreak="break-word">
+ Long localized-token-like content:
+ project-settings-notification-delivery-exception-review-queue
+ </Text>
+ </VStack>
+ }>
+ <Button label="Open fit evidence">Open fit evidence</Button>
+ </Popover>
+ </div>
+ </div>
+ ),
+ play: async ({canvasElement}) => {
+ const trigger = canvasElement.querySelector('button');
+ if (trigger instanceof HTMLElement) {
+ trigger.click();
+ }
+ },
+};
+
+export const MatchTriggerViewportFit: Story = {
+ name: 'Match-trigger viewport fit',
+ parameters: {
+ layout: 'fullscreen',
+ viewport: {defaultViewport: 'mobile1'},
+ docs: {
+ story: {inline: false, height: '844px'},
+ description: {
+ story:
+ 'Uses the actual Storybook viewport. The real trigger is intentionally 640px wide, while Popover keeps its default match-trigger sizing; the Popover must cap to the available viewport instead of inheriting the full trigger width.',
+ },
+ },
+ },
+ render: () => (
+ <div {...stylex.props(readinessStyles.viewportStoryCanvas)}>
+ <Popover
+ placement="below"
+ alignment="start"
+ label="Match-trigger viewport evidence"
+ data-testid="match-trigger-popover"
+ content={
+ <VStack gap={2} xstyle={readinessStyles.evidenceCopy}>
+ <Heading level={4} tabIndex={-1}>
+ Match-trigger sizing
+ </Heading>
+ <Text type="body">
+ The anchor is wider than this viewport, but the Popover stays
+ inside the available inline space.
+ </Text>
+ </VStack>
+ }>
+ <Button
+ label="Oversized match-width trigger"
+ xstyle={readinessStyles.oversizedTrigger}>
+ Oversized match-width trigger
+ </Button>
+ </Popover>
+ </div>
+ ),
+ play: async ({canvasElement}) => {
+ const trigger = canvasElement.querySelector('button');
+ if (trigger instanceof HTMLElement) {
+ trigger.click();
+ }
+ },
+};
+
+export const TallContentOverflow: Story = {
+ name: 'Tall content overflow',
+ parameters: {
+ layout: 'fullscreen',
+ viewport: {defaultViewport: 'mobile1'},
+ docs: {
+ story: {inline: false, height: '844px'},
+ description: {
+ story:
+ 'Uses the actual Storybook viewport and a realistic project picker. The product-level 360px/50dvh cap keeps this lightweight anchored surface compact, while Popover detects the overflow and makes its content scrollable. Scrolling demonstrates bounded overflow handling; it does not by itself determine whether another presentation is more appropriate.',
+ },
+ },
+ },
+ render: () => <TallContentOverflowExample />,
+ play: async ({canvasElement}) => {
+ const trigger = canvasElement.querySelector('button');
+ if (trigger instanceof HTMLElement) {
+ trigger.click();
+ }
+ },
+};
+
+export const ReadOnlyDialogFocus: Story = {
+ name: 'Read-only dialog focus',
+ parameters: {
+ layout: 'fullscreen',
+ docs: {
+ story: {inline: false, height: '844px'},
+ description: {
+ story:
+ 'Manual assistive-technology check for a dialog-style Popover with no content controls. On open, the labeled dialog container receives focus without revealing the fallback close button. Confirm the dialog name and role are announced, Tab reaches Close popover, Shift+Tab remains contained, Escape closes, and focus returns to the trigger.',
+ },
+ },
+ },
+ render: () => (
+ <Popover
+ placement="below"
+ label="Deployment status"
+ content={
+ <VStack gap={2}>
+ <Heading level={4}>Deployment status</Heading>
+ <Text type="body">
+ The latest production deployment completed successfully.
+ </Text>
+ </VStack>
+ }>
+ <Button label="View deployment status">View deployment status</Button>
+ </Popover>
+ ),
+ play: async ({canvasElement}) => {
+ const trigger = canvasElement.querySelector('button');
+ if (trigger instanceof HTMLElement) {
+ trigger.click();
+ }
+ },
+};
+
+export const TriggerInteractionEvidence: Story = {
+ name: 'Trigger Interaction Evidence',
+ parameters: {
+ layout: 'fullscreen',
+ docs: {
+ story: {inline: false, height: '844px'},
+ description: {
+ story:
+ 'Desktop Storybook interaction evidence: the native button trigger opens the popover without hover. Use real touch/iOS evidence before claiming mobile Safari behavior.',
+ },
+ },
+ },
+ render: () => (
+ <Popover
+ placement="below"
+ label="Interaction evidence"
+ content={
+ <VStack gap={2}>
+ <Heading level={4} tabIndex={-1}>
+ Interaction evidence
+ </Heading>
+ <Text type="body">
+ Opened by trigger activation; Escape, outside press, and focus
+ return are covered by unit tests.
+ </Text>
+ </VStack>
+ }>
+ <Button label="Open interaction evidence">
+ Open interaction evidence
+ </Button>
+ </Popover>
+ ),
+ play: async ({canvasElement}) => {
+ const trigger = canvasElement.querySelector('button');
+ if (trigger instanceof HTMLElement) {
+ trigger.click();
+ }
+ },
+};
+
+export const KeepPopoverPresentation: Story = {
+ name: 'Keep Popover Presentation',
+ parameters: {
+ layout: 'fullscreen',
+ docs: {
+ story: {inline: false, height: '844px'},
+ description: {
+ story:
+ 'Keep Popover for anchored, compact supplemental details and actions. The trigger is click/tap activated, not hover dependent, and the compact surface keeps context near the trigger.',
+ },
+ },
+ },
+ render: () => <ProjectActionSurface presentation="popover" />,
+ play: async ({canvasElement}) => {
+ const trigger = canvasElement.querySelector('button');
+ if (trigger instanceof HTMLElement) {
+ trigger.click();
+ }
+ },
+};
+
+export const BottomSheetPresentationOption: Story = {
+ name: 'BottomSheet Presentation Option',
+ parameters: {
+ layout: 'fullscreen',
+ docs: {
+ story: {inline: false, height: '844px'},
+ description: {
+ story:
+ 'This story shows BottomSheet as an explicit alternative for the same focused task when a product wants a bottom-edge modal touch surface. It changes the contract: dialog focus ownership, scrim behavior, Escape handling, swipe-to-dismiss, and sheet body scrolling differ from Popover.',
+ },
+ },
+ },
+ render: () => <ProjectActionSurface presentation="bottom-sheet" />,
+ play: async ({canvasElement}) => {
+ const trigger = canvasElement.querySelector('button');
+ if (trigger instanceof HTMLElement) {
+ trigger.click();
+ }
+ },
+};
+
+export const AdaptivePopoverRecipe: PresentationRecipeStory = {
+ name: 'Adaptive Popover Recipe',
+ args: {
+ presentation: 'popover',
+ touchPresentation: 'bottom-sheet',
+ },
+ argTypes: {
+ presentation: {
+ control: 'select',
+ options: ['popover', 'bottom-sheet'],
+ description:
+ 'Deterministic review/test override for the presentation used by this recipe story.',
+ },
+ touchPresentation: {
+ control: 'select',
+ options: ['popover', 'bottom-sheet'],
+ description:
+ 'Opt-in touch presentation. If a consumer omits the deterministic presentation override, the recipe may choose BottomSheet only for compact + coarse pointer + no hover.',
+ },
+ },
+ parameters: {
+ layout: 'fullscreen',
+ docs: {
+ story: {inline: false, height: '844px'},
+ description: {
+ story:
+ 'Story-local recipe only: Core Popover does not silently adapt. Products opt in with touchPresentation="bottom-sheet" and can force presentation="popover" or presentation="bottom-sheet" for review and tests.',
+ },
+ },
+ },
+ render: args => <ProjectActionSurface {...args} />,
+ play: async ({canvasElement}) => {
+ const trigger = canvasElement.querySelector('button');
+ if (trigger instanceof HTMLElement) {
+ trigger.click();
+ }
+ },
+};
diff --git a/packages/cli/assets/templates/blocks/components/Popover/PopoverBottomSheetAlternative.doc.mjs b/packages/cli/assets/templates/blocks/components/Popover/PopoverBottomSheetAlternative.doc.mjs
new file mode 100644
index 0000000000..4b333ecbcf
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Popover/PopoverBottomSheetAlternative.doc.mjs
@@ -0,0 +1,22 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'Popover',
+ name: 'Popover — Bottom Sheet Alternative',
+ displayName: 'Popover — Bottom Sheet Alternative',
+ description:
+ 'Opt-in BottomSheet alternative for compact touch surfaces where actions should use a modal presentation anchored to the bottom edge.',
+ isReady: true,
+ aspectRatio: 4 / 3,
+ componentsUsed: [
+ 'BottomSheet',
+ 'Button',
+ 'Icon',
+ 'Section',
+ 'Layout',
+ 'Text',
+ 'List',
+ ],
+};
diff --git a/packages/cli/assets/templates/blocks/components/Popover/PopoverBottomSheetAlternative.tsx b/packages/cli/assets/templates/blocks/components/Popover/PopoverBottomSheetAlternative.tsx
new file mode 100644
index 0000000000..341ce80936
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Popover/PopoverBottomSheetAlternative.tsx
@@ -0,0 +1,71 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {CalendarIcon, TagIcon, UserIcon} from '@heroicons/react/24/outline';
+import {BottomSheet} from '@astryxdesign/core/BottomSheet';
+import {Button} from '@astryxdesign/core/Button';
+import {Icon} from '@astryxdesign/core/Icon';
+import {List, ListItem} from '@astryxdesign/core/List';
+import {VStack} from '@astryxdesign/core/Layout';
+import {Section} from '@astryxdesign/core/Section';
+import {Heading, Text} from '@astryxdesign/core/Text';
+import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';
+
+const styles = stylex.create({
+ header: {
+ // Match the unchanged spacious ListItem inset so the title and description
+ // align with the action icons.
+ marginInlineStart: spacingVars['--spacing-3'],
+ },
+});
+
+const PROJECT_ACTIONS = [
+ [UserIcon, 'Assign owner', 'Route follow-up to a teammate.'],
+ [TagIcon, 'Add label', 'Group this item with related work.'],
+ [CalendarIcon, 'Set due date', 'Pick a reminder for review.'],
+] as const;
+
+export default function PopoverBottomSheetAlternative() {
+ const [isOpen, setIsOpen] = useState(false);
+
+ return (
+ <>
+ <Button label="Open project actions" onClick={() => setIsOpen(true)}>
+ Open project actions
+ </Button>
+ <BottomSheet
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ label="Project actions"
+ height="hug">
+ <Section paddingBlock={4} paddingInline={1}>
+ <VStack gap={3}>
+ <VStack gap={1} xstyle={styles.header}>
+ <Heading level={3}>Project actions</Heading>
+ <Text type="supporting" color="secondary">
+ Use this modal touch surface when the task should move away from
+ its trigger and stay close to the bottom edge.
+ </Text>
+ </VStack>
+ <List density="spacious">
+ {PROJECT_ACTIONS.map(([icon, label, description]) => (
+ <ListItem
+ key={label}
+ label={label}
+ description={description}
+ startContent={
+ <Icon icon={icon} size="md" color="secondary" />
+ }
+ onClick={() => setIsOpen(false)}
+ />
+ ))}
+ </List>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </>
+ );
+}
diff --git a/packages/core/src/BottomSheet/BottomSheet.tsx b/packages/core/src/BottomSheet/BottomSheet.tsx
index d7b4720715..a98b16949c 100644
--- a/packages/core/src/BottomSheet/BottomSheet.tsx
+++ b/packages/core/src/BottomSheet/BottomSheet.tsx
@@ -385,8 +385,7 @@ function StandaloneBottomSheet({
{children}
</BottomSheetPanel>
</div>
- {/* A modal sheet's ::backdrop already answers Safari's edge sampler. */}
- {hasScrim ? null : <BottomSheetEdgeTint />}
+ <BottomSheetEdgeTint />
</dialog>
);
}
diff --git a/packages/core/src/BottomSheet/BottomSheetEdgeTint.test.tsx b/packages/core/src/BottomSheet/BottomSheetEdgeTint.test.tsx
index 75c1c7f7dd..7922fa0d4e 100644
--- a/packages/core/src/BottomSheet/BottomSheetEdgeTint.test.tsx
+++ b/packages/core/src/BottomSheet/BottomSheetEdgeTint.test.tsx
@@ -101,15 +101,13 @@ describe('BottomSheetEdgeTint', () => {
expect(tints()).toHaveLength(1);
});
- // A modal sheet's ::backdrop is a case WebKit's sampler handles on its own,
- // so a second sampling target there would only fight it.
- it('leaves a modal sheet to its ::backdrop', () => {
+ it('gives a modal sheet the same surface-coloured edge tint', () => {
render(
<BottomSheet isOpen onOpenChange={() => {}} label="Place details">
Content
</BottomSheet>,
);
- expect(tints()).toHaveLength(0);
+ expect(tints()).toHaveLength(1);
});
it('renders the tint inside the dialog, so it unmounts with the sheet', () => {
@@ -148,7 +146,7 @@ describe('BottomSheetEdgeTint', () => {
expect(tints()).toHaveLength(1);
});
- it('leaves a modal switcher flow to its ::backdrop', () => {
+ it('gives a modal switcher flow exactly one tint', () => {
render(
<BottomSheetSwitcher activeSheet="comment" onActiveSheetChange={() => {}}>
<BottomSheet sheetId="comment" label="Add a comment">
@@ -156,7 +154,7 @@ describe('BottomSheetEdgeTint', () => {
</BottomSheet>
</BottomSheetSwitcher>,
);
- expect(tints()).toHaveLength(0);
+ expect(tints()).toHaveLength(1);
});
it('keeps the tint out of the accessibility tree and out of hit testing', async () => {
diff --git a/packages/core/src/BottomSheet/BottomSheetEdgeTint.tsx b/packages/core/src/BottomSheet/BottomSheetEdgeTint.tsx
index 19f18de7ae..1dfa5015d6 100644
--- a/packages/core/src/BottomSheet/BottomSheetEdgeTint.tsx
+++ b/packages/core/src/BottomSheet/BottomSheetEdgeTint.tsx
@@ -6,7 +6,7 @@
* @file BottomSheetEdgeTint.tsx
* @input Uses StyleX and core color tokens
* @output Exports BottomSheetEdgeTint, an internal decorative element
- * @position Private helper rendered inside a non-modal BottomSheet dialog
+ * @position Private helper rendered inside every BottomSheet dialog
*
* iOS 26 Safari dropped `<meta name="theme-color">` and instead derives the
* colour it paints behind its translucent toolbars by sampling the page: it
@@ -14,13 +14,10 @@
* `fixed`/`sticky` ancestor, and extends that element's declared
* `background-color` into the browser chrome.
*
- * A modal sheet is served by that heuristic already — WebKit has a dedicated
- * branch for a dialog's `::backdrop`. A non-modal sheet is not: the nearest
- * fixed ancestor of the panel is the sheet's own full-viewport `<dialog>`,
- * which is transparent and viewport-sized, and WebKit answers a viewport-sized
- * candidate by *keeping the colour it already had* — the host page's. The page
- * then shows through behind the address bar while the sheet covers the screen
- * above it.
+ * WebKit may otherwise extend either the dialog backdrop or the host page into
+ * the browser chrome. Which one wins varies with dialog mode and the page's
+ * own fixed or sticky edge content, so relying on the backdrop makes otherwise
+ * identical BottomSheets produce different toolbar colours.
*
* This element gives the heuristic something unambiguous to sample: fixed,
* full width, flush with the bottom edge, taller than WebKit's 10px minimum
@@ -68,8 +65,8 @@ const styles = stylex.create({
});
/**
- * Colours the iOS Safari toolbar strip below a non-modal sheet. Renders
- * nothing visible; see the file header for why it exists.
+ * Colours the iOS Safari toolbar strip below a sheet. Renders nothing visible;
+ * see the file header for why it exists.
*/
export function BottomSheetEdgeTint() {
return (
diff --git a/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx b/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx
index 8295e93369..3012c53b75 100644
--- a/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx
+++ b/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx
@@ -632,8 +632,7 @@ export function BottomSheetSwitcher({
? {role: 'alertdialog'}
: undefined)}>
{children}
- {/* A modal flow's ::backdrop already answers Safari's edge sampler. */}
- {hasScrim ? null : <BottomSheetEdgeTint />}
+ <BottomSheetEdgeTint />
</dialog>
</BottomSheetSwitcherContext>
);
diff --git a/packages/core/src/Popover/Popover.doc.mjs b/packages/core/src/Popover/Popover.doc.mjs
index 87c54719c1..41c0efedbe 100644
--- a/packages/core/src/Popover/Popover.doc.mjs
+++ b/packages/core/src/Popover/Popover.doc.mjs
@@ -64,7 +64,7 @@ export const docs = {
{
name: 'width',
type: 'number | string',
- description: 'Width of the popover container.',
+ description: 'Width of the popover container. The layer still caps to the viewport with alignment-aware safe-area gutters before scrolling long content.',
default: "'auto'",
},
{
@@ -101,7 +101,7 @@ export const docs = {
{
name: 'hasAutoFocus',
type: 'boolean',
- description: 'Whether to auto-focus the first focusable element when the popover opens. Set to false for inline showcases or documentation previews.',
+ description: 'Whether to move focus into the popover when it opens. Keyboard activation focuses the first content control; pointer activation focuses the labeled dialog container so an action does not appear preselected. Set to false for inline showcases or documentation previews.',
default: 'true',
},
{
@@ -149,8 +149,8 @@ export const docs = {
{ guidance: true, description: 'Keep popover content focused on a single task or piece of information.' },
{ guidance: true, description: 'Provide a clear way to close: either by clicking outside or with an explicit close button.' },
{ guidance: false, description: 'Nest popovers inside other popovers; it creates confusing focus and navigation.' },
- { guidance: false, description: 'Use a popover for content that requires heavy user input; use a Dialog instead.' },
- { guidance: false, description: 'Put too much content in a popover; if it needs scrolling, use a Dialog instead.' },
+ { guidance: false, description: 'Assume input complexity alone determines the presentation; evaluate the task’s focus, space, and interaction requirements.' },
+ { guidance: false, description: 'Assume scrolling alone means Popover is the wrong component; a bounded Popover may scroll while a focused anchored interaction remains appropriate.' },
],
anatomy: [
{name: 'Header', required: true, description: 'Contains the title, optional subheader, and close button.'},
@@ -220,7 +220,7 @@ export const docsZh = {
{
name: 'width',
type: 'number | string',
- description: '弹出框容器的宽度。',
+ description: '弹出框容器的宽度。弹出层仍会限制在视口和安全区域留白内,长内容再滚动。',
default: "'auto'",
},
{
@@ -294,8 +294,8 @@ export const docsZh = {
{ guidance: true, description: 'Keep popover content focused on a single task or piece of information.' },
{ guidance: true, description: 'Provide a clear way to close: either by clicking outside or with an explicit close button.' },
{ guidance: false, description: 'Nest popovers inside other popovers; it creates confusing focus and navigation.' },
- { guidance: false, description: 'Use a popover for content that requires heavy user input; use a Dialog instead.' },
- { guidance: false, description: 'Put too much content in a popover; if it needs scrolling, use a Dialog instead.' },
+ { guidance: false, description: 'Assume input complexity alone determines the presentation; evaluate the task’s focus, space, and interaction requirements.' },
+ { guidance: false, description: 'Assume scrolling alone means Popover is the wrong component; a bounded Popover may scroll while a focused anchored interaction remains appropriate.' },
],
anatomy: [
{name: 'Header', required: true, description: 'Contains the title, optional subheader, and close button.'},
@@ -316,8 +316,8 @@ export const docsDense = {
{ guidance: true, description: 'Keep popover content focused on a single task or piece of information.' },
{ guidance: true, description: 'Provide a clear way to close: either by clicking outside or with an explicit close button.' },
{ guidance: false, description: 'Nest popovers inside other popovers; it creates confusing focus and navigation.' },
- { guidance: false, description: 'Use a popover for content that requires heavy user input; use a Dialog instead.' },
- { guidance: false, description: 'Put too much content in a popover; if it needs scrolling, use a Dialog instead.' },
+ { guidance: false, description: 'Assume input complexity alone determines the presentation; evaluate the task’s focus, space, and interaction requirements.' },
+ { guidance: false, description: 'Assume scrolling alone means Popover is the wrong component; a bounded Popover may scroll while a focused anchored interaction remains appropriate.' },
],
anatomy: [
{name: 'Header', required: true, description: 'Contains the title, optional subheader, and close button.'},
@@ -340,11 +340,11 @@ export const docsDense = {
isOpen: 'Whether popover shown in controlled mode.',
onOpenChange: 'Callback fired when popover visibility changes.',
isEnabled: 'When false, trigger interactions ignored.',
- width: 'Popover container width.',
+ width: 'Popover container width; capped to alignment-aware viewport/safe-area gutters before long content scrolls.',
label: 'Accessible label for popover dialog.',
hasCloseButton: 'Whether to include hidden close button for accessibility.',
closeButtonLabel: 'Label for hidden close button.',
- hasAutoFocus: 'Auto-focus first element on open; false for showcases.',
+ hasAutoFocus: 'Move focus into the popover on open; keyboard targets the first control and pointer targets the dialog container.',
hasLightDismiss: 'Outside click dismisses; false for explicit-dismiss surfaces (coachmarks).',
hasEscapeDismiss: 'Escape dismisses; full effect only with hasLightDismiss=false.',
},
diff --git a/packages/core/src/Popover/Popover.test.tsx b/packages/core/src/Popover/Popover.test.tsx
index 4d86b654ef..90e1a6ca05 100644
--- a/packages/core/src/Popover/Popover.test.tsx
+++ b/packages/core/src/Popover/Popover.test.tsx
@@ -2,7 +2,7 @@
/**
* @file Popover.test.tsx
- * @input Uses vitest, @testing-library/react, Popover, Dialog,
+ * @input Uses vitest, Testing Library, node:fs, Popover, Dialog, and
* SegmentedControl
* @output Unit tests for Popover component behavior
* @position Testing; validates Popover.tsx implementation
@@ -11,7 +11,9 @@
*/
import {describe, it, expect, vi, beforeAll, afterAll} from 'vitest';
-import {render, screen, fireEvent} from '@testing-library/react';
+import {render, screen, fireEvent, waitFor, act} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {readFileSync} from 'node:fs';
import React, {useRef} from 'react';
import {Popover} from './Popover';
import type {UsePopoverReturn} from './usePopover';
@@ -64,8 +66,19 @@ describe('usePopover public return type', () => {
const hasDismissalGuard: 'wasJustDismissed' extends keyof UsePopoverReturn
? true
: false = false;
+ const hasInternalToggle: 'toggleWithOptions' extends keyof UsePopoverReturn
+ ? true
+ : false = false;
+ type PublicShowOptions = NonNullable<
+ Parameters<UsePopoverReturn['show']>[0]
+ >;
+ const hasInternalFocusTarget: 'focusTarget' extends keyof PublicShowOptions
+ ? true
+ : false = false;
expect(hasKeepOpenProps).toBe(false);
expect(hasDismissalGuard).toBe(false);
+ expect(hasInternalToggle).toBe(false);
+ expect(hasInternalFocusTarget).toBe(false);
});
});
@@ -205,6 +218,288 @@ describe('Popover', () => {
expect(screen.getByTestId('my-popover')).toBeInTheDocument();
});
+ it('constrains the layer without clipping content that already fits', () => {
+ render(
+ <Popover
+ content={<span>Content</span>}
+ label="Test"
+ width={640}
+ data-testid="popover-content">
+ <button type="button">Open</button>
+ </Popover>,
+ );
+
+ fireEvent.click(screen.getByRole('button', {name: 'Open'}));
+
+ const layer = document.querySelector('[popover]');
+ expect(layer).toHaveStyle({boxSizing: 'border-box'});
+ expect(layer?.className).toContain('Popover__styles.viewportFit');
+ expect(layer?.className).toContain('Popover__styles.viewportAligned');
+ expect(layer?.className).toContain('Popover__styles.viewportStart');
+ const surface = screen.getByTestId('popover-content').parentElement;
+ expect(surface?.className).toContain('Popover__styles.surfaceViewportFit');
+ const popoverSource = readFileSync(
+ 'packages/core/src/Popover/Popover.tsx',
+ 'utf8',
+ );
+ expect(popoverSource).toMatch(
+ /surfaceViewportFit:[\s\S]*?maxInlineSize: stylex\.firstThatWorks\(\s*POPOVER_MAX_INLINE_SIZE/,
+ );
+ expect(popoverSource).toMatch(
+ /surfaceViewportFit:[\s\S]*?maxBlockSize: stylex\.firstThatWorks\(\s*POPOVER_MAX_BLOCK_SIZE/,
+ );
+ expect(surface?.className).not.toContain(
+ 'Popover__styles.surfaceScrollable',
+ );
+ });
+
+ it('enables internal scrolling only when content exceeds the available space', () => {
+ const clientHeight = vi
+ .spyOn(HTMLElement.prototype, 'clientHeight', 'get')
+ .mockReturnValue(100);
+ const scrollHeight = vi
+ .spyOn(HTMLElement.prototype, 'scrollHeight', 'get')
+ .mockReturnValue(200);
+ const clientWidth = vi
+ .spyOn(HTMLElement.prototype, 'clientWidth', 'get')
+ .mockReturnValue(200);
+ const scrollWidth = vi
+ .spyOn(HTMLElement.prototype, 'scrollWidth', 'get')
+ .mockReturnValue(200);
+
+ try {
+ render(
+ <Popover
+ content={<span>Long content</span>}
+ label="Test"
+ data-testid="popover-content">
+ <button type="button">Open</button>
+ </Popover>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Open'}));
+
+ expect(
+ screen.getByTestId('popover-content').parentElement?.className,
+ ).toContain('Popover__styles.surfaceScrollable');
+ } finally {
+ clientHeight.mockRestore();
+ scrollHeight.mockRestore();
+ clientWidth.mockRestore();
+ scrollWidth.mockRestore();
+ }
+ });
+
+ it('coalesces repeated overflow signals into one animation frame', () => {
+ let resizeCallback: ResizeObserverCallback | undefined;
+ let mutationCallback: MutationCallback | undefined;
+ const frameCallbacks: FrameRequestCallback[] = [];
+
+ class ResizeObserverMock {
+ constructor(callback: ResizeObserverCallback) {
+ resizeCallback = callback;
+ }
+ observe = vi.fn();
+ unobserve = vi.fn();
+ disconnect = vi.fn();
+ }
+
+ class MutationObserverMock {
+ constructor(callback: MutationCallback) {
+ mutationCallback = callback;
+ }
+ observe = vi.fn();
+ disconnect = vi.fn();
+ takeRecords = vi.fn(() => []);
+ }
+
+ const requestFrame = vi.fn((callback: FrameRequestCallback) => {
+ frameCallbacks.push(callback);
+ return frameCallbacks.length;
+ });
+ const cancelFrame = vi.fn();
+ vi.stubGlobal('ResizeObserver', ResizeObserverMock);
+ vi.stubGlobal('MutationObserver', MutationObserverMock);
+ vi.stubGlobal('requestAnimationFrame', requestFrame);
+ vi.stubGlobal('cancelAnimationFrame', cancelFrame);
+
+ const {unmount} = render(
+ <Popover content={<span>Content</span>} label="Test">
+ <button type="button">Open</button>
+ </Popover>,
+ );
+
+ try {
+ fireEvent.click(screen.getByRole('button', {name: 'Open'}));
+ while (frameCallbacks.length > 0) {
+ const pendingFrames = frameCallbacks.splice(0);
+ act(() => pendingFrames.forEach(callback => callback(0)));
+ }
+ requestFrame.mockClear();
+
+ act(() => {
+ resizeCallback?.([], {} as ResizeObserver);
+ mutationCallback?.([], {} as MutationObserver);
+ window.dispatchEvent(new Event('resize'));
+ });
+
+ expect(requestFrame).toHaveBeenCalledTimes(1);
+ expect(frameCallbacks).toHaveLength(1);
+ } finally {
+ unmount();
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it('observes overflow only while the popover is open', () => {
+ const resizeConstructed = vi.fn();
+ const resizeDisconnected = vi.fn();
+ const mutationConstructed = vi.fn();
+ const mutationDisconnected = vi.fn();
+
+ class ResizeObserverMock {
+ constructor() {
+ resizeConstructed();
+ }
+ observe = vi.fn();
+ unobserve = vi.fn();
+ disconnect = resizeDisconnected;
+ }
+
+ class MutationObserverMock {
+ constructor() {
+ mutationConstructed();
+ }
+ observe = vi.fn();
+ disconnect = mutationDisconnected;
+ takeRecords = vi.fn(() => []);
+ }
+
+ vi.stubGlobal('ResizeObserver', ResizeObserverMock);
+ vi.stubGlobal('MutationObserver', MutationObserverMock);
+
+ const {unmount} = render(
+ <Popover content={<span>Content</span>} label="Test">
+ <button type="button">Open</button>
+ </Popover>,
+ );
+
+ try {
+ const trigger = screen.getByRole('button', {name: 'Open'});
+ expect(resizeConstructed).not.toHaveBeenCalled();
+ expect(mutationConstructed).not.toHaveBeenCalled();
+
+ fireEvent.click(trigger);
+ expect(resizeConstructed).toHaveBeenCalledTimes(1);
+ expect(mutationConstructed).toHaveBeenCalledTimes(1);
+
+ fireEvent.click(trigger);
+ expect(resizeDisconnected).toHaveBeenCalledTimes(1);
+ expect(mutationDisconnected).toHaveBeenCalledTimes(1);
+ expect(resizeConstructed).toHaveBeenCalledTimes(1);
+ expect(mutationConstructed).toHaveBeenCalledTimes(1);
+ } finally {
+ unmount();
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it('keeps aligned popovers anchored while applying viewport gutters', () => {
+ render(
+ <Popover content={<span>Content</span>} label="Test">
+ <button type="button">Open</button>
+ </Popover>,
+ );
+
+ fireEvent.click(screen.getByRole('button', {name: 'Open'}));
+
+ const layer = document.querySelector('[popover]');
+ expect(layer?.className).toContain('Popover__styles.viewportAligned');
+ expect(layer?.className).toContain('Popover__styles.viewportStart');
+ expect(layer).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))))',
+ );
+ });
+
+ it('mirrors the far-edge gutter for end-aligned popovers', () => {
+ render(
+ <Popover content={<span>Content</span>} label="Test" alignment="end">
+ <button type="button">Open</button>
+ </Popover>,
+ );
+
+ fireEvent.click(screen.getByRole('button', {name: 'Open'}));
+
+ const layer = document.querySelector('[popover]');
+ expect(layer?.className).toContain('Popover__styles.viewportAligned');
+ expect(layer?.className).toContain('Popover__styles.viewportEnd');
+ expect(layer?.className).not.toContain('Popover__styles.viewportStart');
+ });
+
+ it('reserves both inline gutters only for centered popovers', () => {
+ render(
+ <Popover content={<span>Content</span>} label="Test" alignment="center">
+ <button type="button">Open</button>
+ </Popover>,
+ );
+
+ fireEvent.click(screen.getByRole('button', {name: 'Open'}));
+
+ const layer = document.querySelector('[popover]');
+ expect(layer?.className).toContain('Popover__styles.viewportCentered');
+ expect(layer?.className).not.toContain('Popover__styles.viewportAligned');
+ expect(layer).toHaveStyle(
+ 'min-width: min(anchor-size(width),calc(100vi - max(var(--spacing-4),env(safe-area-inset-left,0px)) - max(var(--spacing-4),env(safe-area-inset-right,0px))))',
+ );
+ });
+
+ it('uses block-axis gutters for side placement', () => {
+ render(
+ <Popover
+ content={<span>Content</span>}
+ label="Test"
+ placement="end"
+ alignment="start">
+ <button type="button">Open</button>
+ </Popover>,
+ );
+
+ fireEvent.click(screen.getByRole('button', {name: 'Open'}));
+
+ const layer = document.querySelector('[popover]');
+ expect(layer?.className).toContain('Popover__styles.viewportBlockStart');
+ expect(layer?.className).not.toContain('Popover__styles.viewportStart');
+ });
+
+ it('preserves the dialog aria-haspopup contract for render-prop triggers', () => {
+ render(
+ <Popover
+ role="none"
+ content={
+ <div role="menu" aria-label="Actions">
+ Menu content
+ </div>
+ }
+ label="Actions">
+ {triggerProps => (
+ <button
+ type="button"
+ ref={triggerProps.ref}
+ onClick={triggerProps.onClick}
+ aria-haspopup={triggerProps['aria-haspopup']}
+ aria-expanded={triggerProps['aria-expanded']}
+ aria-controls={triggerProps['aria-controls']}>
+ Open menu
+ </button>
+ )}
+ </Popover>,
+ );
+
+ expect(screen.getByRole('button', {name: 'Open menu'})).toHaveAttribute(
+ 'aria-haspopup',
+ 'dialog',
+ );
+ });
+
it('supports anchorRef sibling mode', () => {
function AnchorRefTest() {
const ref = useRef<HTMLButtonElement>(null);
@@ -437,6 +732,106 @@ describe('Popover', () => {
});
describe('focus restoration', () => {
+ it('focuses the dialog container without outlining an action after pointer activation', async () => {
+ render(
+ <Popover
+ content={<button type="button">Delete</button>}
+ label="Confirm deletion">
+ <button type="button">Open confirmation</button>
+ </Popover>,
+ );
+
+ fireEvent.click(screen.getByRole('button', {name: 'Open confirmation'}), {
+ detail: 1,
+ });
+
+ const dialog = screen.getByRole('dialog', {
+ name: 'Confirm deletion',
+ hidden: true,
+ });
+ await waitFor(() => expect(dialog).toHaveFocus());
+ expect(dialog).toHaveStyle({outline: 'none'});
+ expect(
+ screen.getByRole('button', {name: 'Delete', hidden: true}),
+ ).not.toHaveFocus();
+ });
+
+ it('focuses the first content control after keyboard activation', async () => {
+ render(
+ <Popover
+ content={<button type="button">Delete</button>}
+ label="Confirm deletion">
+ <button type="button">Open confirmation</button>
+ </Popover>,
+ );
+
+ fireEvent.click(screen.getByRole('button', {name: 'Open confirmation'}), {
+ detail: 0,
+ });
+
+ await waitFor(() =>
+ expect(
+ screen.getByRole('button', {name: 'Delete', hidden: true}),
+ ).toHaveFocus(),
+ );
+ });
+
+ it('focuses the dialog container when content has no controls', async () => {
+ render(
+ <Popover content={<span>Read-only content</span>} label="Read only">
+ <button type="button">Open read only</button>
+ </Popover>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Open read only'}));
+
+ const dialog = screen.getByRole('dialog', {
+ name: 'Read only',
+ hidden: true,
+ });
+ await waitFor(() => expect(dialog).toHaveFocus());
+ expect(
+ screen.getByRole('button', {name: 'Close popover', hidden: true}),
+ ).not.toHaveFocus();
+ });
+
+ it('prefers a genuine content control for initial focus', async () => {
+ render(
+ <Popover
+ content={<button type="button">Content action</button>}
+ label="Action popover">
+ <button type="button">Open action</button>
+ </Popover>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Open action'}));
+
+ await waitFor(() =>
+ expect(
+ screen.getByRole('button', {name: 'Content action', hidden: true}),
+ ).toHaveFocus(),
+ );
+ });
+
+ it('keeps the fallback close button reachable by Tab', async () => {
+ const user = userEvent.setup();
+ render(
+ <Popover content={<span>Read-only content</span>} label="Read only">
+ <button type="button">Open read only</button>
+ </Popover>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Open read only'}));
+ await waitFor(() =>
+ expect(
+ screen.getByRole('dialog', {name: 'Read only', hidden: true}),
+ ).toHaveFocus(),
+ );
+
+ await user.tab();
+
+ expect(
+ screen.getByRole('button', {name: 'Close popover', hidden: true}),
+ ).toHaveFocus();
+ });
+
it('returns focus to the trigger when closed via Escape', () => {
render(
<Popover
diff --git a/packages/core/src/Popover/Popover.tsx b/packages/core/src/Popover/Popover.tsx
index 9a760a7851..12f0425c5e 100644
--- a/packages/core/src/Popover/Popover.tsx
+++ b/packages/core/src/Popover/Popover.tsx
@@ -4,8 +4,8 @@
/**
* @file Popover.tsx
- * @input Uses React, usePopover hook
- * @output Exports Popover component for click-triggered popovers
+ * @input Uses React layout measurement and the usePopover hook
+ * @output Exports Popover with viewport fitting and conditional overflow
* @position Layer component; declarative wrapper around usePopover hook
*
* For hover-triggered overlays, use HoverCard instead.
@@ -20,6 +20,7 @@
import React, {
useCallback,
useRef,
+ useState,
type ReactElement,
type ReactNode,
} from 'react';
@@ -27,7 +28,7 @@ import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import * as stylex from '@stylexjs/stylex';
import {devWarn} from '../utils/devWarning';
import type {BaseProps} from '../BaseProps';
-import {usePopover} from './usePopover';
+import {usePopoverInternal} from './usePopover';
import type {LayerAlignment, LayerPlacement} from '../Layer/useLayer';
import {layerAnimations} from '../Layer/layerAnimations.stylex';
import {spacingVars} from '../theme/tokens.stylex';
@@ -38,6 +39,14 @@ import {InteractiveRoleContext} from '../InteractiveRoleContext/InteractiveRoleC
// =============================================================================
const BUTTON_SELECTOR = 'button, [role="button"]';
+const POPOVER_VIEWPORT_GUTTER = spacingVars['--spacing-4'];
+const POPOVER_MAX_INLINE_SIZE = `calc(100vi - max(${POPOVER_VIEWPORT_GUTTER}, env(safe-area-inset-left, 0px)) - max(${POPOVER_VIEWPORT_GUTTER}, env(safe-area-inset-right, 0px)))`;
+const POPOVER_MAX_INLINE_SIZE_FALLBACK = `calc(100vw - ${POPOVER_VIEWPORT_GUTTER} - ${POPOVER_VIEWPORT_GUTTER})`;
+const POPOVER_MAX_BLOCK_SIZE = `calc(100dvb - max(${POPOVER_VIEWPORT_GUTTER}, env(safe-area-inset-top, 0px)) - max(${POPOVER_VIEWPORT_GUTTER}, env(safe-area-inset-bottom, 0px)))`;
+const POPOVER_MAX_BLOCK_SIZE_FALLBACK = `calc(100vh - ${POPOVER_VIEWPORT_GUTTER} - ${POPOVER_VIEWPORT_GUTTER})`;
+const POPOVER_POSITION_AREA_MAX_INLINE_SIZE = `calc(100% - max(${POPOVER_VIEWPORT_GUTTER}, env(safe-area-inset-left, 0px), env(safe-area-inset-right, 0px)))`;
+const POPOVER_POSITION_AREA_MAX_INLINE_SIZE_FALLBACK = `calc(100% - ${POPOVER_VIEWPORT_GUTTER})`;
+const POPOVER_INLINE_EDGE_GUTTER = `max(${POPOVER_VIEWPORT_GUTTER}, env(safe-area-inset-left, 0px), env(safe-area-inset-right, 0px))`;
/**
* Find the trigger button inside a container element.
@@ -61,9 +70,9 @@ function findTriggerButton(el: HTMLElement): HTMLElement | null {
export interface PopoverTriggerRenderProps {
/** Ref callback — attach to the trigger element for anchor positioning. */
ref: (el: HTMLElement | null) => void;
- /** Toggle the popover open/closed. */
- onClick: () => void;
- /** ARIA attribute: indicates the element triggers a dialog. */
+ /** Toggle the popover open/closed. Pass the click event through so pointer and keyboard focus behavior can differ. */
+ onClick: (event?: {detail: number}) => void;
+ /** ARIA attribute: indicates the trigger opens a dialog-style popover. */
'aria-haspopup': 'dialog';
/** ARIA attribute: whether the popover is currently open. */
'aria-expanded': boolean;
@@ -198,7 +207,9 @@ export interface PopoverProps extends Pick<
closeButtonLabel?: string;
/**
- * Whether to auto-focus the first focusable element when the popover opens.
+ * Whether to move focus into the popover when it opens. Keyboard activation
+ * focuses the first content control; pointer activation focuses the labeled
+ * dialog container so an action does not appear preselected.
* Set to `false` for inline showcases or documentation previews.
* @default true
*/
@@ -241,6 +252,62 @@ const styles = stylex.create({
anchorWrapper: {
display: 'inline-flex',
},
+ viewportFit: {
+ boxSizing: 'border-box',
+ maxBlockSize: stylex.firstThatWorks(
+ POPOVER_MAX_BLOCK_SIZE,
+ POPOVER_MAX_BLOCK_SIZE_FALLBACK,
+ ),
+ },
+ viewportAligned: {
+ maxInlineSize: stylex.firstThatWorks(
+ POPOVER_POSITION_AREA_MAX_INLINE_SIZE,
+ POPOVER_POSITION_AREA_MAX_INLINE_SIZE_FALLBACK,
+ ),
+ },
+ viewportStart: {
+ marginInlineEnd: POPOVER_INLINE_EDGE_GUTTER,
+ },
+ viewportEnd: {
+ marginInlineStart: POPOVER_INLINE_EDGE_GUTTER,
+ },
+ viewportBlockStart: {
+ marginBlockEnd: `max(${POPOVER_VIEWPORT_GUTTER}, env(safe-area-inset-bottom, 0px))`,
+ },
+ viewportBlockEnd: {
+ marginBlockStart: `max(${POPOVER_VIEWPORT_GUTTER}, env(safe-area-inset-top, 0px))`,
+ },
+ viewportCentered: {
+ marginInlineStart: POPOVER_INLINE_EDGE_GUTTER,
+ marginInlineEnd: POPOVER_INLINE_EDGE_GUTTER,
+ maxInlineSize: stylex.firstThatWorks(
+ POPOVER_MAX_INLINE_SIZE,
+ POPOVER_MAX_INLINE_SIZE_FALLBACK,
+ ),
+ },
+ viewportBlockCentered: {
+ marginBlockStart: `max(${POPOVER_VIEWPORT_GUTTER}, env(safe-area-inset-top, 0px))`,
+ marginBlockEnd: `max(${POPOVER_VIEWPORT_GUTTER}, env(safe-area-inset-bottom, 0px))`,
+ maxInlineSize: stylex.firstThatWorks(
+ POPOVER_MAX_INLINE_SIZE,
+ POPOVER_MAX_INLINE_SIZE_FALLBACK,
+ ),
+ },
+ surfaceViewportFit: {
+ boxSizing: 'border-box',
+ maxInlineSize: stylex.firstThatWorks(
+ POPOVER_MAX_INLINE_SIZE,
+ POPOVER_MAX_INLINE_SIZE_FALLBACK,
+ ),
+ maxBlockSize: stylex.firstThatWorks(
+ POPOVER_MAX_BLOCK_SIZE,
+ POPOVER_MAX_BLOCK_SIZE_FALLBACK,
+ ),
+ },
+ surfaceScrollable: {
+ overflow: 'auto',
+ overscrollBehavior: 'contain',
+ },
// Content padding, applied to the popup surface so a theme's `padding`
// replaces it instead of nesting inside it.
contentPadding: {
@@ -252,8 +319,19 @@ const styles = stylex.create({
customWidth: (width: string | number) => ({
width: typeof width === 'number' ? `${width}px` : width,
}),
- matchTrigger: {
- minWidth: 'anchor-size(width)',
+ matchTriggerAligned: {
+ minWidth: stylex.firstThatWorks(
+ `min(anchor-size(width), ${POPOVER_POSITION_AREA_MAX_INLINE_SIZE})`,
+ `min(anchor-size(width), ${POPOVER_POSITION_AREA_MAX_INLINE_SIZE_FALLBACK})`,
+ 'anchor-size(width)',
+ ),
+ },
+ matchTriggerCentered: {
+ minWidth: stylex.firstThatWorks(
+ `min(anchor-size(width), ${POPOVER_MAX_INLINE_SIZE})`,
+ `min(anchor-size(width), ${POPOVER_MAX_INLINE_SIZE_FALLBACK})`,
+ 'anchor-size(width)',
+ ),
},
});
@@ -320,6 +398,8 @@ export function Popover({
'data-testid': testId,
}: PopoverProps): ReactElement {
const wrapperRef = useRef<HTMLDivElement>(null);
+ const measurementFrameRef = useRef<number | null>(null);
+ const [hasOverflow, setHasOverflow] = useState(false);
const isControlled = isOpen !== undefined;
const handlePopoverShow = useCallback(() => {
@@ -330,7 +410,7 @@ export function Popover({
onOpenChange?.(false);
}, [onOpenChange]);
- const popover = usePopover({
+ const popover = usePopoverInternal({
dialogLabel: label,
role,
isModal,
@@ -343,21 +423,113 @@ export function Popover({
// it is the element the `popover` theme target has to sit on — a target on
// the content div inside it styles a box that paints nothing.
surfaceTarget: 'popover',
- xstyle: [styles.contentPadding, xstyle],
+ xstyle: [
+ styles.contentPadding,
+ styles.surfaceViewportFit,
+ hasOverflow && styles.surfaceScrollable,
+ xstyle,
+ ],
className,
style,
onShow: handlePopoverShow,
onHide: handlePopoverHide,
});
- // Shared handler for click events on the trigger button.
- const handleTriggerClick = useCallback(() => {
- if (!isEnabled) {
+ const measureOverflow = useCallback(() => {
+ const surface = popover.contentRef.current;
+ if (!surface) {
+ return;
+ }
+ const nextHasOverflow =
+ surface.scrollHeight > surface.clientHeight + 1 ||
+ surface.scrollWidth > surface.clientWidth + 1;
+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- DOM overflow measurement controls whether this surface becomes a scroll container
+ setHasOverflow(current =>
+ current === nextHasOverflow ? current : nextHasOverflow,
+ );
+ }, [popover.contentRef]);
+
+ const scheduleOverflowMeasurement = useCallback(() => {
+ if (measurementFrameRef.current != null) {
+ return;
+ }
+ measurementFrameRef.current = window.requestAnimationFrame(() => {
+ measurementFrameRef.current = null;
+ measureOverflow();
+ });
+ }, [measureOverflow]);
+
+ useIsomorphicLayoutEffect(() => {
+ if (!popover.isOpen) {
+ return;
+ }
+ const surface = popover.contentRef.current;
+ if (!surface) {
+ return;
+ }
+ measureOverflow();
+ const resizeObserver =
+ typeof ResizeObserver === 'undefined'
+ ? null
+ : new ResizeObserver(scheduleOverflowMeasurement);
+ const mutationObserver =
+ typeof MutationObserver === 'undefined'
+ ? null
+ : new MutationObserver(scheduleOverflowMeasurement);
+ resizeObserver?.observe(surface);
+ mutationObserver?.observe(surface, {
+ childList: true,
+ characterData: true,
+ subtree: true,
+ });
+ surface.addEventListener('load', scheduleOverflowMeasurement, true);
+ window.addEventListener('resize', scheduleOverflowMeasurement);
+ window.visualViewport?.addEventListener(
+ 'resize',
+ scheduleOverflowMeasurement,
+ );
+ return () => {
+ resizeObserver?.disconnect();
+ mutationObserver?.disconnect();
+ surface.removeEventListener('load', scheduleOverflowMeasurement, true);
+ window.removeEventListener('resize', scheduleOverflowMeasurement);
+ window.visualViewport?.removeEventListener(
+ 'resize',
+ scheduleOverflowMeasurement,
+ );
+ if (measurementFrameRef.current != null) {
+ window.cancelAnimationFrame(measurementFrameRef.current);
+ measurementFrameRef.current = null;
+ }
+ };
+ }, [measureOverflow, popover.isOpen, scheduleOverflowMeasurement]);
+
+ useIsomorphicLayoutEffect(() => {
+ if (!popover.isOpen) {
return;
}
- // `toggle` absorbs a click that belongs to its own light dismiss.
- popover.toggle();
- }, [isEnabled, popover]);
+ scheduleOverflowMeasurement();
+ }, [content, popover.isOpen, scheduleOverflowMeasurement]);
+
+ // Shared handler for click events on the trigger button.
+ const handleTriggerClick = useCallback(
+ (event?: {detail: number}) => {
+ if (!isEnabled) {
+ return;
+ }
+ // Pointer/touch activation should not make the first action look
+ // preselected. Keep focus inside the modal dialog by focusing its
+ // labeled container; keyboard and AT activation still focus the first
+ // content control and expose the expected focus ring.
+ popover.toggleWithOptions({
+ focusTarget:
+ role === 'dialog' && event != null && event.detail > 0
+ ? 'container'
+ : 'first',
+ });
+ },
+ [isEnabled, popover, role],
+ );
// Shared handler for keydown events on role="button" elements.
// Native <button> synthesizes click on Enter/Space, but role="button"
@@ -503,7 +675,27 @@ export function Popover({
}, [isOpen, isControlled, popover]);
// Determine popover xstyle
- const popoverXstyle = width ? styles.customWidth(width) : styles.matchTrigger;
+ const popoverSizeXstyle = width
+ ? styles.customWidth(width)
+ : alignment === 'center'
+ ? styles.matchTriggerCentered
+ : styles.matchTriggerAligned;
+ const isSidePlacement = placement === 'start' || placement === 'end';
+ const popoverViewportXstyle =
+ alignment === 'center'
+ ? isSidePlacement
+ ? styles.viewportBlockCentered
+ : styles.viewportCentered
+ : [
+ styles.viewportAligned,
+ isSidePlacement
+ ? alignment === 'start'
+ ? styles.viewportBlockStart
+ : styles.viewportBlockEnd
+ : alignment === 'start'
+ ? styles.viewportStart
+ : styles.viewportEnd,
+ ];
// Sibling mode: render only the popover (no wrapper needed)
if (anchorRef && children == null) {
@@ -513,7 +705,12 @@ export function Popover({
placement,
alignment,
offset: spacingVars['--spacing-1'],
- xstyle: [popoverXstyle, layerAnimations[placement]],
+ xstyle: [
+ styles.viewportFit,
+ popoverViewportXstyle,
+ popoverSizeXstyle,
+ layerAnimations[placement],
+ ],
})}
</>
);
@@ -538,7 +735,12 @@ export function Popover({
placement,
alignment,
offset: spacingVars['--spacing-1'],
- xstyle: [popoverXstyle, layerAnimations[placement]],
+ xstyle: [
+ styles.viewportFit,
+ popoverViewportXstyle,
+ popoverSizeXstyle,
+ layerAnimations[placement],
+ ],
})}
</>
);
@@ -556,7 +758,12 @@ export function Popover({
placement,
alignment,
offset: spacingVars['--spacing-1'],
- xstyle: [popoverXstyle, layerAnimations[placement]],
+ xstyle: [
+ styles.viewportFit,
+ popoverViewportXstyle,
+ popoverSizeXstyle,
+ layerAnimations[placement],
+ ],
})}
</>
);
diff --git a/packages/core/src/Popover/usePopover.tsx b/packages/core/src/Popover/usePopover.tsx
index 6aaae1941e..e0e04f774c 100644
--- a/packages/core/src/Popover/usePopover.tsx
+++ b/packages/core/src/Popover/usePopover.tsx
@@ -28,6 +28,7 @@ import {
shadowVars,
} from '../theme/tokens.stylex';
import {Button} from '../Button';
+import {FOCUSABLE_SELECTOR} from '../hooks/focusableSelector';
import {rtlStyles} from '../utils';
import {useTranslator} from '../i18n';
import {useDevWarning} from '../hooks/useDevWarning';
@@ -35,6 +36,29 @@ import {mergeProps} from '../utils/mergeProps';
import {themeProps} from '../utils/themeProps';
import {stableClassName} from '../naming';
+const FALLBACK_CLOSE_SELECTOR = '[data-astryx-popover-fallback-close]';
+
+function attemptFocus(element: HTMLElement): boolean {
+ try {
+ element.focus();
+ } catch {
+ // Ignore non-focusable elements; the caller will try the next target.
+ }
+ return document.activeElement === element;
+}
+
+function focusFirstContentControl(container: HTMLElement): boolean {
+ const focusable = Array.from(
+ container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),
+ ).filter(element => element.closest(FALLBACK_CLOSE_SELECTOR) == null);
+ for (const element of focusable) {
+ if (attemptFocus(element)) {
+ return true;
+ }
+ }
+ return false;
+}
+
const styles = stylex.create({
// Default popover surface — background, radius, shadow.
// Applied automatically unless hasSurface is false.
@@ -48,6 +72,11 @@ const styles = stylex.create({
// Focus trap container
contentWrapper: {
position: 'relative',
+ // Pointer-open dialog popovers park focus on this wrapper so the first
+ // action does not look selected. The wrapper itself is not an action and
+ // should not receive the browser's default focus ring; interactive
+ // descendants retain their normal focus-visible treatment.
+ outline: 'none',
},
// Hidden close button wrapper - sr-only until focused, then positioned below
// popover. Inline-axis centering (+ the translateY(100%) that drops it below
@@ -296,6 +325,10 @@ export interface UsePopoverReturn {
interface InternalUsePopoverReturn extends UsePopoverReturn {
wasJustDismissed: () => boolean;
+ toggleWithOptions: (options?: {
+ skipAutoFocus?: boolean;
+ focusTarget?: 'first' | 'container';
+ }) => void;
}
/**
@@ -368,6 +401,7 @@ function usePopoverImplementation(
// Track whether to skip auto-focus for the current open event
const skipAutoFocusRef = useRef(false);
+ const focusTargetRef = useRef<'first' | 'container'>('first');
// Core layer for popover positioning
const layer = useLayerInternal({
@@ -385,19 +419,44 @@ function usePopoverImplementation(
onEscape: hasEscapeDismiss || hasLightDismiss ? layer.hide : undefined,
});
+ const focusInitialTarget = useCallback(() => {
+ const container = contentRef.current;
+ if (!container) {
+ return;
+ }
+ if (focusFirstContentControl(container)) {
+ return;
+ }
+ if (role === 'dialog') {
+ attemptFocus(container);
+ return;
+ }
+ focusFirst();
+ }, [contentRef, focusFirst, role]);
+
// Auto-focus first element when popover opens (unless skipped)
useEffect(() => {
if (layer.isOpen && hasAutoFocus && !skipAutoFocusRef.current) {
// Use requestAnimationFrame to ensure DOM is ready
requestAnimationFrame(() => {
- focusFirst();
+ const container = contentRef.current;
+ if (
+ focusTargetRef.current === 'container' &&
+ role === 'dialog' &&
+ container
+ ) {
+ attemptFocus(container);
+ } else {
+ focusInitialTarget();
+ }
});
}
- // Reset the skip flag after the effect runs
+ // Reset per-open focus preferences after the popover closes.
if (!layer.isOpen) {
skipAutoFocusRef.current = false;
+ focusTargetRef.current = 'first';
}
- }, [layer.isOpen, hasAutoFocus, focusFirst]);
+ }, [contentRef, layer.isOpen, hasAutoFocus, focusInitialTarget, role]);
// Combined ref for trigger element (layer anchor + our ref)
const triggerRef = useCallback(
@@ -410,24 +469,35 @@ function usePopoverImplementation(
// Show function with optional skipAutoFocus
const show = useCallback(
- (showOptions?: {skipAutoFocus?: boolean}) => {
+ (showOptions?: {
+ skipAutoFocus?: boolean;
+ focusTarget?: 'first' | 'container';
+ }) => {
skipAutoFocusRef.current = showOptions?.skipAutoFocus ?? false;
+ focusTargetRef.current = showOptions?.focusTarget ?? 'first';
layer.show();
},
[layer],
);
// Toggle function
- const toggle = useCallback(() => {
- if (layer.wasJustDismissed()) {
- return;
- }
- if (layer.isOpen) {
- layer.hide();
- } else {
- show();
- }
- }, [layer, show]);
+ const toggleWithOptions = useCallback(
+ (showOptions?: {
+ skipAutoFocus?: boolean;
+ focusTarget?: 'first' | 'container';
+ }) => {
+ if (layer.wasJustDismissed()) {
+ return;
+ }
+ if (layer.isOpen) {
+ layer.hide();
+ } else {
+ show(showOptions);
+ }
+ },
+ [layer, show],
+ );
+ const toggle = useCallback(() => toggleWithOptions(), [toggleWithOptions]);
// ARIA attributes for the trigger
const triggerProps = {
@@ -465,6 +535,7 @@ function usePopoverImplementation(
role={role === 'dialog' ? 'dialog' : undefined}
aria-modal={role === 'dialog' && isModal ? true : undefined}
aria-label={role === 'dialog' ? dialogLabel : undefined}
+ tabIndex={role === 'dialog' ? -1 : undefined}
{...mergeProps(
{...surfaceProps, className: surfaceClassName},
stylex.props(
@@ -478,6 +549,7 @@ function usePopoverImplementation(
{children}
{hasCloseButton && (
<div
+ data-astryx-popover-fallback-close=""
{...stylex.props(
styles.closeButtonWrapper,
rtlStyles.centerInline('100%'),
@@ -517,6 +589,7 @@ function usePopoverImplementation(
show,
hide: layer.hide,
toggle,
+ toggleWithOptions,
wasJustDismissed: layer.wasJustDismissed,
isOpen: layer.isOpen,
id: layer.id,
@@ -526,7 +599,11 @@ function usePopoverImplementation(
}
export function usePopover(options: UsePopoverOptions = {}): UsePopoverReturn {
- const {wasJustDismissed: _, ...popover} = usePopoverImplementation(options);
+ const {
+ wasJustDismissed: _,
+ toggleWithOptions: __,
+ ...popover
+ } = usePopoverImplementation(options);
return popover;
}
diff --git a/packages/core/src/hooks/useFocusTrap.test.tsx b/packages/core/src/hooks/useFocusTrap.test.tsx
index 394da81b40..b8a652a309 100644
--- a/packages/core/src/hooks/useFocusTrap.test.tsx
+++ b/packages/core/src/hooks/useFocusTrap.test.tsx
@@ -193,6 +193,46 @@ describe('useFocusTrap tabbable model (infra-8)', () => {
expect(screen.getByTestId('first')).toHaveFocus();
});
+ it('moves from a programmatic container focus target into the tabbable cycle', () => {
+ render(
+ <Trap>
+ <button type="button" data-testid="first">
+ First
+ </button>
+ <button type="button" data-testid="last">
+ Last
+ </button>
+ </Trap>,
+ );
+ const trap = screen.getByTestId('trap');
+ trap.tabIndex = -1;
+ trap.focus();
+
+ fireEvent.keyDown(document, {key: 'Tab'});
+
+ expect(screen.getByTestId('first')).toHaveFocus();
+ });
+
+ it('moves backward from a programmatic container focus target to the last tabbable control', () => {
+ render(
+ <Trap>
+ <button type="button" data-testid="first">
+ First
+ </button>
+ <button type="button" data-testid="last">
+ Last
+ </button>
+ </Trap>,
+ );
+ const trap = screen.getByTestId('trap');
+ trap.tabIndex = -1;
+ trap.focus();
+
+ fireEvent.keyDown(document, {key: 'Tab', shiftKey: true});
+
+ expect(screen.getByTestId('last')).toHaveFocus();
+ });
+
it('keeps a programmatic focus target when the trap has no tabbable controls', () => {
render(
<Trap>
diff --git a/packages/core/src/hooks/useFocusTrap.ts b/packages/core/src/hooks/useFocusTrap.ts
index c05638a06c..ce8997599f 100644
--- a/packages/core/src/hooks/useFocusTrap.ts
+++ b/packages/core/src/hooks/useFocusTrap.ts
@@ -375,6 +375,19 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(
const first = focusable[0];
const last = focusable[focusable.length - 1];
+ if (document.activeElement === container) {
+ // Programmatic initial focus can sit on the trap container itself
+ // (for example a dialog panel with no content controls). Move into
+ // the tabbable cycle instead of letting Tab escape to the page.
+ event.preventDefault();
+ if (event.shiftKey) {
+ last.focus();
+ } else {
+ first.focus();
+ }
+ return;
+ }
+
if (event.shiftKey) {
// Shift+Tab: if on first element, wrap to last
if (document.activeElement === first) {