Skip to content

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

TypeScript

fix(Popover): unify opening and focus behavior (#6101)

Cindy Zhang79935d45ea5e
diff --git a/.changeset/popover-opening-focus.md b/.changeset/popover-opening-focus.md
new file mode 100644
index 0000000000..629322660c
--- /dev/null
+++ b/.changeset/popover-opening-focus.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Popover: apply same-gesture reopen protection through every opening path, focus genuine caller content regardless of activation modality, and keep the generated fallback close control hidden until keyboard users reach it.
+
+@cixzhang
diff --git a/apps/storybook/rtl-audit/targets.json b/apps/storybook/rtl-audit/targets.json
index c3e69a50cb..44b70b8aec 100644
--- a/apps/storybook/rtl-audit/targets.json
+++ b/apps/storybook/rtl-audit/targets.json
@@ -350,6 +350,34 @@
"overlayRoot": "button:has-text(\"Settings\")"
}
},
+ {
+ "component": "Selector",
+ "storyId": "core-selector--default",
+ "dims": [
+ "D4"
+ ],
+ "setup": {
+ "click": "[role=\"combobox\"]"
+ },
+ "selectors": {
+ "overlay": ".astryx-selector-popup",
+ "overlayRoot": "[role=\"combobox\"]"
+ }
+ },
+ {
+ "component": "MultiSelector",
+ "storyId": "core-multiselector--default",
+ "dims": [
+ "D4"
+ ],
+ "setup": {
+ "click": "[role=\"combobox\"]"
+ },
+ "selectors": {
+ "overlay": ".astryx-multi-selector-popup",
+ "overlayRoot": "[role=\"combobox\"]"
+ }
+ },
{
"component": "SideNav",
"storyId": "core-sidenav--default",
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
index 5b3a95477f..fb03508737 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
+++ b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
@@ -231,7 +231,8 @@ export const docs = {
{
name: 'onClick',
type: '() => void',
- description: 'Callback fired when the trigger button is clicked.',
+ description:
+ 'Callback fired for accepted trigger activation. The trailing click from the same press that light-dismissed the menu is ignored.',
},
{
name: 'hasChevron',
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
index bdfc0c4989..595dadcb34 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
@@ -825,12 +825,13 @@ describe('DropdownMenu', () => {
});
describe('DropdownMenu light-dismiss race', () => {
- function openMenu() {
+ function openMenu(onClick?: () => void) {
render(
<DropdownMenu
button={{label: 'Actions'}}
items={[{label: 'Edit'}]}
data-testid="astryx-dropdown-menu"
+ onClick={onClick}
/>,
);
const trigger = screen.getByTestId('astryx-dropdown-menu');
@@ -857,14 +858,17 @@ describe('DropdownMenu light-dismiss race', () => {
});
}
- it('does not re-open when the trigger click follows its own light dismiss', () => {
- const trigger = openMenu();
+ it('does not re-open or notify on the click from its own light dismiss', () => {
+ const onClick = vi.fn();
+ const trigger = openMenu(onClick);
+ expect(onClick).toHaveBeenCalledTimes(1);
fireEvent.pointerDown(trigger);
lightDismiss();
fireEvent.click(trigger);
expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1);
+ expect(onClick).toHaveBeenCalledTimes(1);
});
it('re-opens on a press of its own after a light dismiss', () => {
@@ -1058,7 +1062,11 @@ describe('DropdownMenu controlled mode', () => {
);
await user.click(screen.getByRole('button', {name: /Actions/}));
- expect(handleToggle).toHaveBeenCalledWith(true);
+ expect(handleToggle.mock.calls).toEqual([[true]]);
+ expect(screen.getByRole('button', {name: /Actions/})).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ );
});
});
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsx
index 78bfc6d013..75a05f7aec 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx
@@ -39,7 +39,7 @@ import React, {
type ReactNode,
} from 'react';
import * as stylex from '@stylexjs/stylex';
-import {usePopoverInternal} from '../Popover/usePopover';
+import {usePopover} from '../Popover/usePopover';
import {Button, type ButtonProps} from '../Button';
import {Heading} from '../Heading';
import {Icon} from '../Icon';
@@ -55,6 +55,7 @@ import {
DropdownMenuContext,
type DropdownMenuContextValue,
} from './DropdownMenuContext';
+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import {useListFocus} from '../hooks/useListFocus';
import {useTypeahead} from '../hooks/useTypeahead';
import {useFocusReturnVisibility} from '../hooks/useFocusReturnVisibility';
@@ -604,6 +605,10 @@ function DropdownMenuPopover({
const [internalIsOpen, setInternalIsOpen] = useState(false);
const isControlled = controlledIsOpen !== undefined;
const isOpen = isControlled ? controlledIsOpen : internalIsOpen;
+ const acceptedOpenRef = useRef(false);
+ const notifyClickOnShowRef = useRef(false);
+ const pendingControlledOpenRef = useRef(false);
+ const suppressControlledRollbackHideRef = useRef(false);
useInteractionModalityTracking();
@@ -612,6 +617,11 @@ function DropdownMenuPopover({
// 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(() => {
+ if (suppressControlledRollbackHideRef.current) {
+ suppressControlledRollbackHideRef.current = false;
+ return;
+ }
+ pendingControlledOpenRef.current = false;
onOpenChange?.(false);
if (!isControlled) {
setInternalIsOpen(false);
@@ -636,13 +646,18 @@ function DropdownMenuPopover({
const openModalityRef = useRef<'keyboard' | 'pointer'>('keyboard');
const handleLayerShow = useCallback(() => {
+ acceptedOpenRef.current = true;
+ if (notifyClickOnShowRef.current) {
+ notifyClickOnShowRef.current = false;
+ onClick?.();
+ }
onOpenChange?.(true);
if (!isControlled) {
setInternalIsOpen(true);
}
- }, [isControlled, onOpenChange]);
+ }, [isControlled, onClick, onOpenChange]);
- const popover = usePopoverInternal({
+ const popover = usePopover({
onHide: handleLayerHide,
onShow: handleLayerShow,
hasLightDismiss: true,
@@ -696,17 +711,27 @@ function DropdownMenuPopover({
// menu, so every later open follows the modality rules above.
const isMountedOpenRef = useRef(isControlled && controlledIsOpen === true);
- // Sync controlled open state → popover.
- useEffect(() => {
- if (isControlled) {
- if (controlledIsOpen && !popover.isOpen) {
+ // Sync controlled open state → popover. A trigger open is committed first so
+ // Popover can reject the dismissing gesture before notifying the controller.
+ // If the controller has not accepted by the next layout pass, roll the DOM
+ // state back before paint without emitting a second change request.
+ useIsomorphicLayoutEffect(() => {
+ if (!isControlled) {
+ return;
+ }
+ if (controlledIsOpen) {
+ pendingControlledOpenRef.current = false;
+ if (!popover.isOpen) {
shouldFocusOnOpenRef.current = !isMountedOpenRef.current;
popover.show();
- } else if (!controlledIsOpen) {
- isMountedOpenRef.current = false;
- if (popover.isOpen) {
- popover.hide();
- }
+ }
+ } else {
+ isMountedOpenRef.current = false;
+ if (popover.isOpen) {
+ suppressControlledRollbackHideRef.current =
+ pendingControlledOpenRef.current;
+ pendingControlledOpenRef.current = false;
+ popover.hide();
}
}
}, [controlledIsOpen, isControlled, popover]);
@@ -771,36 +796,46 @@ function DropdownMenuPopover({
);
const openAndFocus = useCallback(
- (modality: 'keyboard' | 'pointer' = 'keyboard') => {
+ (
+ modality: 'keyboard' | 'pointer' = 'keyboard',
+ notifyClick = false,
+ ): boolean => {
+ acceptedOpenRef.current = false;
+ notifyClickOnShowRef.current = notifyClick;
+ pendingControlledOpenRef.current = isControlled;
openModalityRef.current = modality;
shouldFocusOnOpenRef.current = true;
popover.show();
+ if (!acceptedOpenRef.current) {
+ notifyClickOnShowRef.current = false;
+ pendingControlledOpenRef.current = false;
+ openModalityRef.current = 'keyboard';
+ shouldFocusOnOpenRef.current = false;
+ return false;
+ }
+ return true;
},
- [popover],
+ [isControlled, popover],
);
const handleButtonClick = useCallback(
(e: React.MouseEvent<HTMLButtonElement>) => {
- // The click that light-dismissed the menu is not a request to reopen it.
- if (popover.wasJustDismissed()) {
- return;
- }
- onClick?.();
// detail === 0 marks a synthesized click (screen reader / AT
// activation): treat it as keyboard so those users still land on the
// first item. Real pointer clicks report detail >= 1.
const modality = e.detail === 0 ? 'keyboard' : 'pointer';
if (isControlled) {
- if (!controlledIsOpen) {
- openModalityRef.current = modality;
- }
- onOpenChange?.(!controlledIsOpen);
- } else {
- if (popover.isOpen) {
- popover.hide();
+ if (controlledIsOpen) {
+ onClick?.();
+ onOpenChange?.(false);
} else {
- openAndFocus(modality);
+ openAndFocus(modality, true);
}
+ } else if (popover.isOpen) {
+ onClick?.();
+ popover.hide();
+ } else {
+ openAndFocus(modality, true);
}
},
[
diff --git a/packages/core/src/MultiSelector/MultiSelector.test.tsx b/packages/core/src/MultiSelector/MultiSelector.test.tsx
index 9f8281fa63..15fc130ced 100644
--- a/packages/core/src/MultiSelector/MultiSelector.test.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.test.tsx
@@ -3123,5 +3123,8 @@ describe('MultiSelector popup theme target', () => {
fireEvent.click(trigger);
expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(trigger.parentElement).toHaveClass(
+ stylex.props(selectorPresentationStyles.pointerRestoredFocus).className!,
+ );
});
});
diff --git a/packages/core/src/MultiSelector/MultiSelector.tsx b/packages/core/src/MultiSelector/MultiSelector.tsx
index 3bde456130..091772a5f8 100644
--- a/packages/core/src/MultiSelector/MultiSelector.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.tsx
@@ -981,9 +981,21 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
announce('');
}, [announce]);
+ const handleLayerShow = useCallback(() => {
+ // Snapshot selection only after the surface actually opens; a same-gesture
+ // rejection must not prepare state for an opening that never happened.
+ setSelectedAtOpen(new Set(optimisticValue));
+ if (hasSearch) {
+ requestAnimationFrame(() => {
+ searchRef.current?.focus();
+ });
+ }
+ }, [hasSearch, optimisticValue]);
+
const surface = useSelectorPresentation({
presentation,
onHide: handleLayerHide,
+ onShow: handleLayerShow,
triggerRef,
popoverOptions: {
hasLightDismiss: true,
@@ -1217,23 +1229,11 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
onKeyDown,
onItemMouseEnter,
} = useMultiCombobox({
- wasJustDismissed: surface.wasJustDismissed,
selectableItems: sortedItems,
isDisabled: isDisabled || isEffectivelyReadOnly,
isOpen: surface.isOpen,
hasSearch,
- onOpen: useCallback(() => {
- // Snapshot which items are selected at open time — sort is frozen until close
- setSelectedAtOpen(new Set(optimisticValue));
-
- surface.show();
- if (hasSearch) {
- // Focus search after popover opens
- requestAnimationFrame(() => {
- searchRef.current?.focus();
- });
- }
- }, [surface, hasSearch, optimisticValue]),
+ onOpen: useCallback(() => surface.show(), [surface]),
onClose: surface.hide,
onToggle: handleNavigableToggle,
onClear: hasClear ? clearValues : undefined,
diff --git a/packages/core/src/MultiSelector/hooks.ts b/packages/core/src/MultiSelector/hooks.ts
index cd0644b2f9..fe6a2c97d3 100644
--- a/packages/core/src/MultiSelector/hooks.ts
+++ b/packages/core/src/MultiSelector/hooks.ts
@@ -20,7 +20,7 @@ interface UseMultiComboboxOptions {
isDisabled?: boolean;
isOpen: boolean;
hasSearch?: boolean;
- onOpen: () => void;
+ onOpen: () => unknown;
onClose: () => void;
onToggle: (itemValue: string) => void;
/**
@@ -34,12 +34,6 @@ interface UseMultiComboboxOptions {
* The Delete/Backspace clear path is skipped when false.
*/
hasValue?: boolean;
- /**
- * Whether the browser's light dismiss just closed the popup. The trigger
- * click that follows belongs to that same press, so acting on it would
- * reopen the popup the user just closed.
- */
- wasJustDismissed?: () => boolean;
listboxId: string;
}
@@ -68,7 +62,6 @@ export function useMultiCombobox({
onToggle,
onClear,
hasValue = false,
- wasJustDismissed,
listboxId,
}: UseMultiComboboxOptions): UseMultiComboboxResult {
const [highlightedIndex, setHighlightedIndex] = useState<number>(-1);
@@ -94,18 +87,18 @@ export function useMultiCombobox({
}, [onClose]);
const onTriggerClick = useCallback(() => {
- if (isDisabled || wasJustDismissed?.()) {
+ if (isDisabled) {
return;
}
if (isOpen) {
closeAndReset();
} else {
- onOpen();
- if (!hasSearch) {
+ const didOpen = onOpen() !== false;
+ if (didOpen && !hasSearch) {
setHighlightedIndex(0);
}
}
- }, [isDisabled, wasJustDismissed, isOpen, onOpen, closeAndReset, hasSearch]);
+ }, [isDisabled, isOpen, onOpen, closeAndReset, hasSearch]);
const onItemMouseEnter = useCallback(
(item: MultiSelectorOptionData, index: number) => {
@@ -128,8 +121,9 @@ export function useMultiCombobox({
case 'ArrowDown':
e.preventDefault();
if (!isOpen) {
- onOpen();
- setHighlightedIndex(0);
+ if (onOpen() !== false) {
+ setHighlightedIndex(0);
+ }
} else {
const currentEnabledPos = enabledIndices.indexOf(highlightedIndex);
const nextPos = Math.min(
@@ -143,8 +137,9 @@ export function useMultiCombobox({
case 'ArrowUp':
e.preventDefault();
if (!isOpen) {
- onOpen();
- setHighlightedIndex(selectableItems.length - 1);
+ if (onOpen() !== false) {
+ setHighlightedIndex(selectableItems.length - 1);
+ }
} else {
const currentEnabledPos = enabledIndices.indexOf(highlightedIndex);
const prevPos = Math.max(currentEnabledPos - 1, 0);
@@ -165,8 +160,8 @@ export function useMultiCombobox({
onToggle(item.value);
}
} else if (!isOpen) {
- onOpen();
- if (!hasSearch) {
+ const didOpen = onOpen() !== false;
+ if (didOpen && !hasSearch) {
setHighlightedIndex(0);
}
}
@@ -232,25 +227,23 @@ export function useMultiCombobox({
// Typeahead only when search is not present
if (!hasSearch && e.key.length === 1 && !e.ctrlKey && !e.metaKey) {
const newTypeahead = typeahead + e.key.toLowerCase();
- setTypeahead(newTypeahead);
-
- if (typeaheadTimeoutRef.current) {
- clearTimeout(typeaheadTimeoutRef.current);
- }
- typeaheadTimeoutRef.current = setTimeout(() => {
- setTypeahead('');
- }, 500);
-
const matchIndex = selectableItems.findIndex(
item =>
!item.disabled &&
item.label?.toLowerCase().startsWith(newTypeahead),
);
- if (matchIndex >= 0) {
- if (!isOpen) {
- onOpen();
+ const didOpen = isOpen || matchIndex < 0 || onOpen() !== false;
+ if (didOpen) {
+ setTypeahead(newTypeahead);
+ if (typeaheadTimeoutRef.current) {
+ clearTimeout(typeaheadTimeoutRef.current);
+ }
+ typeaheadTimeoutRef.current = setTimeout(() => {
+ setTypeahead('');
+ }, 500);
+ if (matchIndex >= 0) {
+ setHighlightedIndex(matchIndex);
}
- setHighlightedIndex(matchIndex);
}
}
break;
diff --git a/packages/core/src/Popover/Popover.doc.mjs b/packages/core/src/Popover/Popover.doc.mjs
index b3226e25b6..5ec1ff2d05 100644
--- a/packages/core/src/Popover/Popover.doc.mjs
+++ b/packages/core/src/Popover/Popover.doc.mjs
@@ -125,7 +125,7 @@ export const docs = {
name: 'hasAutoFocus',
type: 'boolean',
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.',
+ 'Whether to move focus into the popover when it opens. Focus enters the first genuine content control; dialogs with none fall back to the labeled surface. The generated fallback close control stays hidden until reached through keyboard navigation. Set to false for input-owned focus, inline showcases, or documentation previews.',
default: 'true',
},
{
@@ -347,7 +347,7 @@ export const docsZh = {
name: 'hasAutoFocus',
type: 'boolean',
description:
- '弹出框打开时是否自动聚焦第一个可聚焦元素。内联展示或文档预览设为 false。',
+ '弹出框打开时是否将焦点移入其中。优先聚焦调用方内容中的第一个控件;若对话框没有此类控件,则聚焦带标签的表面。生成的关闭按钮仅在键盘导航到达时显示。',
default: 'true',
},
{
@@ -541,7 +541,7 @@ export const docsDense = {
'Whether to include hidden close button for accessibility.',
closeButtonLabel: 'Label for hidden close button.',
hasAutoFocus:
- 'Move focus into the popover on open; keyboard targets the first control and pointer targets the dialog container.',
+ 'Move focus into genuine popover content on open, with a labeled-surface fallback; the generated close control stays hidden until reached by keyboard.',
hasLightDismiss:
'Outside click dismisses; false for explicit-dismiss surfaces (coachmarks).',
hasEscapeDismiss:
diff --git a/packages/core/src/Popover/Popover.spec.md b/packages/core/src/Popover/Popover.spec.md
index 71b97b7fac..233804b609 100644
--- a/packages/core/src/Popover/Popover.spec.md
+++ b/packages/core/src/Popover/Popover.spec.md
@@ -7,7 +7,7 @@ authority: current
archive_reason: null
superseded_by: null
approved_by: cixzhang
-approved_at: 2026-08-31
+approved_at: 2026-09-07
owners: [cixzhang]
review_triggers: [public-api, behavior, layout, theming, accessibility]
verified_by:
@@ -44,12 +44,13 @@ surface. The component owns the standard trigger-to-surface composition;
and rendering contract for custom compositions.
This contract records the behavior present after
-[PR #5373](https://github.com/facebook/astryx/pull/5373) and the Popover target
-direction settled by Cindy Zhang on 2026-08-31. It does not change runtime
-behavior, public API, emitted classes, or release status. Consumer syntax and
-complete signatures remain owned by `Popover.doc.mjs` and
-`usePopover.doc.mjs`; automatic canonical-target emission and compatibility
-removal require separately reviewed runtime work.
+[PR #5373](https://github.com/facebook/astryx/pull/5373), the Popover target
+direction settled by Cindy Zhang on 2026-08-31, and the focus/opening correction
+approved by Cindy Zhang on 2026-09-07. Public API signatures, emitted classes,
+and release status remain unchanged. Consumer syntax and complete signatures
+remain owned by `Popover.doc.mjs` and `usePopover.doc.mjs`; automatic canonical-
+target emission and compatibility removal require separately reviewed runtime
+work.
## Compatibility and migration
@@ -114,23 +115,18 @@ full Popover public surface. The backward-compatible Layer entry point re-export
surface, not the Layer entry point. There is no installable
`Popover/usePopover` implementation subpath.
-The source-level internal hook is a package implementation seam used by Popover
-and related presentation components. Its dismissal guard and wider focus-opening
-controls are not installable consumer API. Source-file exports do not promote
-those concepts into the package contract.
-
## Public concepts
-| Concept | Closed values or states | Meaning | Availability | Default | Owner | Stability | Invalid or unsupported behavior |
-| ------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------------------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Trigger composition | Wrapped trigger, render-prop trigger, or referenced anchor | Supplies the anchor and the control that opens or closes the standard component | Popover | Wrapped trigger when children are supplied | `component:Popover` | Current public behavior | A referenced or wrapped anchor without a button or button role warns in development and receives no trigger handler; it does not throw. |
-| Visibility ownership | Uncontrolled or externally controlled | Chooses whether Popover stores visibility or synchronizes to caller state | Popover | Uncontrolled | `component:Popover` | Current public behavior | Controlled changes are synchronized through show/hide; dismissal requests are reported to the caller rather than redefining the external source of truth. |
-| Popup semantics | Dialog or neutral wrapper | Exposes dialog semantics or lets child menu/listbox semantics own the popup | Popover and hook | Dialog | `component:Popover` | Current public behavior | A dialog without a label warns in development. Neutral mode omits dialog role and modal semantics. |
-| Focus entry | Automatic or caller-preserved | Moves focus according to the matrix below or leaves current focus unchanged | Popover and hook | Automatic | `component:Popover` | Current public behavior | A request to skip autofocus affects that opening only. |
-| Dismissal | Outside/Escape enabled or disabled within native constraints | Controls light dismiss and explicit Escape participation | Popover and hook | Both enabled | `component:Popover`; `family:overlay-dismissal` owns Escape/platform-close ordering | Current public behavior | Disabling Escape alone cannot override the native Escape behavior of an auto popover; explicit-dismiss behavior requires light dismiss to be disabled too. |
-| Surface treatment | Default surface or caller-owned treatment | Applies the shared painted surface and optional consumer styling | Popover and hook | Default surface | `component:Popover` | Current public behavior | Custom styling does not change lifecycle, focus, or dismissal semantics. |
-| Surface target ownership | Shared baseline or component-specific refinement | Assigns `popover` as the broad surface owner and lets a composed component add its own target on that same element | Popover and hook | `popover` baseline; no component-specific refinement | `component:Popover`; the composed component owns its refinement target | Accepted contract; runtime alignment pending | `popover-surface` is compatibility output, not a new target for consumers or a second anatomy owner. |
-| Placement and fit | Logical placement/alignment plus preferred width | Positions the anchor surface and constrains it to available space | Popover and hook renderer | Below/start; Popover matches trigger minimum width when no width is supplied | `component:Popover` above `architecture:layer-runtime` | Current public behavior | Preferred width and trigger matching remain capped by viewport and safe-area availability. |
+| Concept | Closed values or states | Meaning | Availability | Default | Owner | Stability | Invalid or unsupported behavior |
+| ------------------------ | ------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- | ------------------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Trigger composition | Wrapped trigger, render-prop trigger, or referenced anchor | Supplies the anchor and the control that opens or closes the standard component | Popover | Wrapped trigger when children are supplied | `component:Popover` | Current public behavior | A referenced or wrapped anchor without a button or button role warns in development and receives no trigger handler; it does not throw. |
+| Visibility ownership | Uncontrolled or externally controlled | Chooses whether Popover stores visibility or synchronizes to caller state | Popover | Uncontrolled | `component:Popover` | Current public behavior | Controlled changes are synchronized through show/hide; dismissal requests are reported to the caller rather than redefining the external source of truth. |
+| Popup semantics | Dialog or neutral wrapper | Exposes dialog semantics or lets child menu/listbox semantics own the popup | Popover and hook | Dialog | `component:Popover` | Current public behavior | A dialog without a label warns in development. Neutral mode omits dialog role and modal semantics. |
+| Focus entry | Automatic or caller-preserved | Focuses genuine caller content, falls back to the labeled dialog surface when none exists, or preserves current focus | Popover and hook | Automatic | `component:Popover` | Current public behavior | The injected fallback close control is excluded from initial-focus candidates and reveals only when reached sequentially. |
+| Dismissal | Outside/Escape enabled or disabled within native constraints | Controls light dismiss and explicit Escape participation | Popover and hook | Both enabled | `component:Popover`; `family:overlay-dismissal` owns Escape/platform-close ordering | Current public behavior | Disabling Escape alone cannot override the native Escape behavior of an auto popover; explicit-dismiss behavior requires light dismiss to be disabled too. |
+| Surface treatment | Default surface or caller-owned treatment | Applies the shared painted surface and optional consumer styling | Popover and hook | Default surface | `component:Popover` | Current public behavior | Custom styling does not change lifecycle, focus, or dismissal semantics. |
+| Surface target ownership | Shared baseline or component-specific refinement | Assigns `popover` as the broad surface owner and lets a composed component add its own target on that same element | Popover and hook | `popover` baseline; no component-specific refinement | `component:Popover`; the composed component owns its refinement target | Accepted contract; runtime alignment pending | `popover-surface` is compatibility output, not a new target for consumers or a second anatomy owner. |
+| Placement and fit | Logical placement/alignment plus preferred width | Positions the anchor surface and constrains it to available space | Popover and hook renderer | Below/start; Popover matches trigger minimum width when no width is supplied | `component:Popover` above `architecture:layer-runtime` | Current public behavior | Preferred width and trigger matching remain capped by viewport and safe-area availability. |
### Public `usePopover` semantic inputs
@@ -142,7 +138,7 @@ table owns their semantic effect.
| Show and hide notifications | Absent | Fire after the hook updates its visibility for an imperative or reconciled browser transition. They remain active for the mounted hook instance. | No callback is fired when no transition occurs. Callers own any focus return they add in a hide notification. |
| Surface styling | No consumer override | Merges consumer StyleX, class, and inline styles onto the painted surface for every rendered lifetime. | Styling cannot move ownership to the positioned outer layer; positioning styles belong to the renderer's layer props. |
| Light and Escape dismissal | Enabled | Escape dismissal registers through the focus trap when enabled; outside light dismiss uses native `popover="auto"` and is not shared-stack coordinated. | Escape disablement is only complete when native light dismiss is also disabled. |
-| Automatic focus | Enabled | Runs once for each successful open unless that opening requests preservation. | If no genuine content control exists, dialog mode falls back to the surface container. |
+| Automatic focus | Enabled | Focuses the first genuine caller content control for each accepted opening unless that opening requests preservation; a dialog with none falls back to its surface. | The injected fallback close control is never an initial-focus candidate. |
| Fallback close control and label | Included; “Close popover” | Appends an end-of-trap close control for each rendered surface. | When omitted, the hook does not synthesize another close affordance. |
| Popup role, label, and modality | Dialog, modal, no implicit label | Stamps semantics on the painted surface for its rendered lifetime. | Neutral role suppresses dialog and modal semantics. Missing dialog label warns in development rather than throwing. |
| Default surface | Enabled | Applies the shared background, radius, and elevation treatment while rendered. | Turning it off delegates painting to caller content but does not turn `usePopover` into a different lifecycle primitive. |
@@ -153,7 +149,7 @@ table owns their semantic effect.
| Output concept | Meaning and lifetime |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Trigger binding | A ref binding establishes the anchor while attached; ARIA trigger state tracks the current role and open state; a stable anchor identifier supports advanced composition. Detaching the trigger removes its anchor association. |
-| Visibility operations | `show`, `hide`, and `toggle` are the canonical operations for the mounted hook instance. Show may preserve current focus for one opening; hide and toggle add no separate caller-owned focus destination. |
+| Visibility operations | `show`, `hide`, and `toggle` are the canonical operations for the mounted hook instance. Public signatures remain unchanged, and every opening path inherits same-gesture reopen protection. |
| Open state | Reflects the hook's reconciled visibility. Browser-initiated close is observed on the queued native toggle event, so DOM visibility may lead React state briefly. |
| Surface binding | A content ref identifies the focus-trap surface while mounted. |
| Renderer | Produces the positioned layer and painted surface around caller content, including focus containment and the optional fallback close control. The renderer must remain in the React tree for the surface to exist. |
@@ -163,6 +159,8 @@ table owns their semantic effect.
- Attaching the trigger ref assigns and removes the CSS anchor name used by the
Layer runtime.
+- Every opening path applies same-gesture reopen protection before changing
+ visibility. A rejected opening does not invoke `onShow`.
- Successful visibility operations call the browser popover methods when
available, update hook state, and invoke the corresponding lifecycle
notification. Native close events reconcile back into that same state model.
@@ -175,15 +173,15 @@ table owns their semantic effect.
## Behavioral and layout contract
-| ID | Invariant | Basis | Acceptance and implementation state |
-| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
-| FR1 | Popover and public `usePopover` expose one visibility lifecycle with canonical show, hide, and toggle operations. Options that refine opening remain part of that operation; an internal need does not create a durable parallel toggle concept. | Current public package surface plus owner direction on 2026-08-31 | Direction settled; current internal helper naming remains a verification gap, not a second API decision |
-| FR2 | Focus destination is derived from popup role, activation style, content, and autofocus policy. Callers do not choose a public focus target. | PR #5373, current source, and current tests | Settled current component behavior |
-| FR3 | The preferred surface size is capped to logical viewport and safe-area availability before overflow is enabled. | PR #5373, current source, tests, and Storybook fixtures | Verified in unit/style evidence; real rendered viewport evidence remains a gap |
-| FR4 | Popover enables internal scrolling only after measured overflow exceeds the current tolerance. Fitting content does not become a scroll container. | PR #5373 and current tests | Verified current behavior |
-| FR5 | Overflow signals while open coalesce into at most one measurement per animation frame, and Popover owns no measurement observers while closed. | PR #5373 and current tests | Verified current resource behavior |
-| FR6 | Component anatomy contains the caller trigger and content, one painted Popover surface, and the optional fallback close control. Popover owns no Header, Body, or separate shared-hook surface part. | Current source, docs target inventory, and tests | Accepted anatomy; stale consumer anatomy corrected by this contract |
-| FR7 | The painted surface has one broad canonical target, `popover`. `popover-surface` is a deprecated compatibility alias on that same part; composed components may add one authoritative component-specific refinement target. | Owner direction on 2026-08-31 plus current target inventory | Accepted semantic contract; automatic hook-wide emission and compatibility removal remain separately reviewed runtime work |
+| ID | Invariant | Basis | Acceptance and implementation state |
+| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
+| FR1 | Popover and public `usePopover` expose one visibility lifecycle with canonical show, hide, and toggle operations. Every opening path inherits same-gesture reopen protection without changing public signatures. | Current public package surface, `architecture:layer-runtime/INV7`, and owner approval on 2026-09-07 | Accepted; implemented and covered by focused Popover-family tests |
+| FR2 | Popover derives semantic focus entry identically across activation modalities: first genuine caller content, then labeled dialog-surface fallback. The injected close control is excluded. Shared interaction modality controls focus indication, not destination. | PR #5373, `architecture:interaction-modality`, and owner approval on 2026-09-07 | Accepted; implemented and covered by Popover focus tests |
+| FR3 | The preferred surface size is capped to logical viewport and safe-area availability before overflow is enabled. | PR #5373, current source, tests, and Storybook fixtures | Verified in unit/style evidence; real rendered viewport evidence remains a gap |
+| FR4 | Popover enables internal scrolling only after measured overflow exceeds the current tolerance. Fitting content does not become a scroll container. | PR #5373 and current tests | Verified current behavior |
+| FR5 | Overflow signals while open coalesce into at most one measurement per animation frame, and Popover owns no measurement observers while closed. | PR #5373 and current tests | Verified current resource behavior |
+| FR6 | Component anatomy contains the caller trigger and content, one painted Popover surface, and the optional fallback close control. Popover owns no Header, Body, or separate shared-hook surface part. | Current source, docs target inventory, and tests | Accepted anatomy; stale consumer anatomy corrected by this contract |
+| FR7 | The painted surface has one broad canonical target, `popover`. `popover-surface` is a deprecated compatibility alias on that same part; composed components may add one authoritative component-specific refinement target. | Owner direction on 2026-08-31 plus current target inventory | Accepted semantic contract; automatic hook-wide emission and compatibility removal remain separately reviewed runtime work |
### Allowed variation
@@ -202,24 +200,26 @@ table owns their semantic effect.
### Representative focus and dismissal states
-| State | Required invariant | Allowed variation |
-| ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
-| Pointer or touch activation of dialog Popover | Initial focus moves to the labeled dialog container so an action does not appear preselected. | The trigger and content may vary. |
-| Keyboard or AT-style activation of dialog Popover | Initial focus moves to the first genuine content control; when none exists, it moves to the dialog container. | Activation with absent or zero event detail follows this path. Named AT announcement remains unverified. |
-| Read-only dialog | The dialog container receives initial focus; the fallback close control remains reachable by Tab but is not selected as initial content. | Caller content may contain no tabbable control. |
-| Neutral-role popup | The neutral wrapper is not selected as a dialog focus target; automatic entry prefers genuine content focus, or callers may disable autofocus for trigger-retained patterns. | Child menu, listbox, or other semantics own their focus model. |
-| Automatic focus disabled | Opening does not move focus. | May be persistent configuration or a one-opening show preference. |
-| Controlled open | External open state invokes the no-activation opening path: first genuine content control, then dialog-container fallback. | The caller remains the visibility source of truth. |
-| Tab from a focused container | Focus enters the first tabbable descendant. | If none exists, focus remains inside. |
-| Shift+Tab from a focused container | Focus enters the last tabbable descendant. | If none exists, focus remains inside. |
-| Escape | The topmost eligible Popover closes according to shared dismissal policy. | Explicit-dismiss surfaces may disable both light and Escape dismissal. |
-| Close after focus entered the popup | Focus returns to the trigger when removal would otherwise strand focus. | A caller may additionally own focus return through its hide notification. |
+| State | Required invariant | Allowed variation |
+| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
+| Pointer or touch activation of dialog Popover | Initial focus enters the first genuine content control, with dialog-surface fallback when none exists. Shared modality-aware indication suppresses keyboard-only rings after pointer input. | The trigger and content may vary. |
+| Keyboard or AT-style activation of dialog Popover | Initial focus enters the first genuine content control, with dialog-surface fallback when none exists. The eligible destination paints the shared keyboard focus indication. | Activation with absent or zero event detail follows this path. Named AT announcement remains unverified. |
+| Read-only dialog | With no genuine caller control, the dialog surface receives initial focus. The injected fallback close control remains hidden and reachable by Tab but is never selected initially. | Caller content may contain no tabbable control. |
+| Neutral-role popup | The neutral wrapper is not selected as a dialog focus target; automatic entry prefers genuine content focus, or callers may disable autofocus for trigger-retained patterns. | Child menu, listbox, or other semantics own their focus model. |
+| Automatic focus disabled | Opening does not move focus. | May be persistent configuration or a one-opening show preference. |
+| Controlled open | External open state invokes the no-activation opening path: first genuine content control, then dialog-container fallback. | The caller remains the visibility source of truth. |
+| Tab from a focused container | Focus enters the first tabbable descendant. | If none exists, focus remains inside. |
+| Shift+Tab from a focused container | Focus enters the last tabbable descendant. | If none exists, focus remains inside. |
+| Escape | The topmost eligible Popover closes according to shared dismissal policy. | Explicit-dismiss surfaces may disable both light and Escape dismissal. |
+| Close after focus entered the popup | Focus returns to the trigger when removal would otherwise strand focus. | A caller may additionally own focus return through its hide notification. |
### Transformation and precedence order
- **ORD1 — Visibility operation.** `toggle` selects the existing `show` or `hide`
- transition; it is not a second lifecycle. Opening preferences refine `show`.
- Popover derives any internal focus destination before invoking that operation.
+ transition; it is not a second lifecycle. Every opening path applies same-
+ gesture protection before visibility changes. Public `show` retains its existing
+ one-opening `skipAutoFocus` preference; otherwise Popover derives genuine
+ content focus and its safe surface fallback.
- **ORD2 — Preferred inline size.** An explicit width wins over trigger matching.
Without explicit width, Popover prefers trigger minimum width. Either preferred
size remains capped by available viewport and safe-area space.
@@ -248,9 +248,11 @@ table owns their semantic effect.
- **AR2 — Dialog naming.** Dialog mode requires a caller-provided accessible
label and places dialog/modal semantics on the painted surface. Missing naming
warns in development but does not synthesize a label.
-- **AR3 — Focus containment.** Automatic entry and Tab/Shift+Tab behavior follow
- the matrix above; a trapped surface with no tabbable descendant does not let
- focus escape.
+- **AR3 — Focus containment and indication.** Automatic entry and
+ Tab/Shift+Tab behavior follow the matrix above; a trapped surface with no
+ tabbable descendant does not let focus escape. Eligible focus destinations use
+ the shared modality-aware focus indication rather than changing semantic focus
+ placement to suppress pointer outlines.
- **AR4 — Focus return.** Dismissal returns focus to the trigger when focus had
entered the closing Popover and would otherwise be lost.
- **AR5 — Evidence boundary.** Current automated tests establish DOM roles, ARIA
@@ -320,8 +322,8 @@ or release guidance.
Popover owns the component-specific fit, overflow, and focus composition above
that runtime.
- `architecture:interaction-modality` owns shared modality classification and
- evidence expectations. Popover owns the destination matrix and derives the
- internal focus choice from activation and role.
+ focus-indicator visibility. Popover owns semantic focus entry and fallback;
+ pointer input does not select a different destination merely to hide an outline.
- `architecture:component-theming-surface` owns anatomy qualification and target
placement. `popover` is the one broad target on the painted surface;
`popover-surface` is only its deprecated compatibility alias. Caller content
@@ -335,8 +337,8 @@ or release guidance.
| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
-| Public boundary, FR1 | `Popover.test.tsx` compile-time public-surface assertions plus package/barrel inspection | Public component/hook imports and package-internal seam | Promoting internal controls or changing public operations fails type assertions or package review. | `audit:Popover/api` |
-| FR2, AR2–AR4 | `Popover.test.tsx` focus/role suites and `useFocusTrap.test.tsx` container-entry suites | Pointer, keyboard/AT-style, read-only, neutral role, no autofocus, controlled, Tab/Shift+Tab, Escape, focus return | Changing a destination, selecting fallback close initially, or allowing focus escape fails focus assertions. | `audit:Popover/accessibility` |
+| Public boundary, FR1 | `Popover.test.tsx` compile-time public-surface assertions plus package/barrel inspection | Unchanged public signatures and same-gesture rejection across Popover-family openings | A public type changes or a same-gesture request reaches visibility state. | `audit:Popover/api` |
+| FR2, AR2–AR4 | `Popover.test.tsx` focus/role suites and `useFocusTrap.test.tsx` container-entry suites | Pointer, keyboard/AT-style, read-only, neutral role, no autofocus, controlled, Tab/Shift+Tab, Escape, focus return | Changing semantic destination by modality, selecting fallback close initially, losing shared indication, or allowing focus escape fails assertions. | `audit:Popover/accessibility` |
| FR3, FR4 | `Popover.test.tsx` sizing/overflow suites; `Popover.stories.tsx` real-viewport scenarios for manual/browser evidence | Explicit width, trigger matching, all alignments, fitting and overflowing content | Removing a cap, reversing width precedence, or always enabling scroll fails emitted-style or overflow assertions. | `audit:Popover/layout` |
| FR5 | `Popover.test.tsx` scheduling and observer-lifecycle suites | Closed, opened, repeated signals, cleanup | Constructing observers while closed or measuring more than once per pending frame fails lifecycle assertions. | `audit:Popover/resources` |
| FR6, FR7 and theming anatomy | `Popover.test.tsx`, `Popover.doc.mjs`, `usePopover.doc.mjs`, `astryx theme targets Popover --json`, and `scripts/check-knowledge.mjs` | One real surface with canonical `popover`; deprecated alias on that element; composed-component refinements | A fake anatomy part, loss of compatibility output, missing deprecation metadata, or an active target without a real owner fails review or validation. | `audit:Popover/theming` |
@@ -350,16 +352,13 @@ or release guidance.
**Decider:** Cindy Zhang, 2026-08-31
-Showing, hiding, and toggling are one visibility lifecycle. Options may refine the
-opening half of toggle, but a package-internal need for a derived focus destination
-does not establish a durable parallel toggle API. Popover derives focus placement
-from activation, role, content, and autofocus policy; consumers are not asked to
-choose it.
+Showing, hiding, and toggling are one visibility lifecycle. Every opening path
+inherits same-gesture reopen protection. Popover derives semantic focus entry;
+public `show({skipAutoFocus: true})` remains the existing escape for a custom
+composition that owns focus outside the Popover. Public signatures are unchanged.
-Rejected: preserving a separate `toggleWithOptions` concept or exposing
-`focusTarget` as durable API. Both describe implementation choices within the
-same caller operation, and public focus selection would let callers create
-inconsistent or inaccessible destinations.
+Rejected: making interaction modality a focus-destination option. Modality owns
+focus indication, while Popover owns semantic focus placement.
### DEC-2 — One canonical Popover surface target
@@ -384,23 +383,39 @@ or inventing a “Shared hook surface” anatomy part to satisfy inventory cover
Both make one painted element look like two design concepts and preserve an
accidental implementation name as permanent public structure.
+### DEC-3 — Focus indication does not change semantic focus placement
+
+**Reference:** `component:Popover/DEC-3`
+
+**Decider:** Cindy Zhang, 2026-09-07
+
+Popover uses one content-first semantic focus policy across pointer, keyboard,
+and assistive-technology activation. The shared interaction-modality system owns
+whether the eligible destination paints a keyboard focus indicator. The injected
+fallback close control is excluded from initial focus and reveals only when
+reached through sequential keyboard navigation; a labeled dialog surface is the
+fallback when caller content has no genuine control.
+
+Every Popover-family opening inherits same-gesture reopen protection through the
+visibility lifecycle. Public API signatures remain unchanged.
+
+Rejected: moving focus to the dialog surface on every pointer opening solely to
+avoid a keyboard-looking outline. That mixes visual modality with semantic focus
+placement and bypasses the shared focus-indication owner.
+
## Verification gaps
These implementation and evidence items remain required follow-up, but they do
not block acceptance of the semantic contract above.
-- **VG1 — Internal operation naming.** Current source still names a
- package-internal wider toggle helper separately. This contract treats it as an
- implementation seam to reconcile in future runtime work, not as public or
- durable package API. This documentation-only PR does not rename it.
-- **VG2 — Real browser behavior.** Unit tests assert emitted sizing styles and
+- **VG1 — Real browser behavior.** Unit tests assert emitted sizing styles and
synthetic dimensions, not rendered viewport layout. Native popover light
- dismiss, top-layer ordering, anchor geometry, and rendered focus behavior still
- require real Chromium/WebKit evidence when changed.
-- **VG3 — AT announcement.** The current story provides manual instructions, but
+ dismiss, top-layer ordering, anchor geometry, rendered focus behavior, and
+ focus-indicator modality still require real Chromium/WebKit evidence when changed.
+- **VG2 — AT announcement.** The current story provides manual instructions, but
named NVDA + Chrome and VoiceOver + Safari results are absent. No announcement
outcome is claimed.
-- **VG4 — Target migration.** Current runtime still emits `popover-surface` as
+- **VG3 — Target migration.** Current runtime still emits `popover-surface` as
the automatic shared class and reaches `popover` through Popover's explicit
`surfaceTarget`. A separate implementation must make `popover` automatic for
every public hook surface while preserving the alias, then verify direct-hook
@@ -408,10 +423,10 @@ not block acceptance of the semantic contract above.
## Open questions
-None. DEC-1 settles the visibility model and derived focus destination; DEC-2
-settles canonical target ownership and compatibility direction. The remaining
-items are verification or separately reviewed implementation work, not human API
-questions.
+None. DEC-1 settles the visibility model, DEC-2 settles canonical target
+ownership, and DEC-3 settles semantic focus versus modality-aware indication.
+The remaining items are verification or separately reviewed implementation work,
+not human API questions.
## Content boundary
diff --git a/packages/core/src/Popover/Popover.test.tsx b/packages/core/src/Popover/Popover.test.tsx
index 600b83e290..11edfc5ce7 100644
--- a/packages/core/src/Popover/Popover.test.tsx
+++ b/packages/core/src/Popover/Popover.test.tsx
@@ -13,12 +13,14 @@
import {describe, it, expect, vi, beforeAll, afterAll} from 'vitest';
import {render, screen, fireEvent, waitFor, act} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import * as stylex from '@stylexjs/stylex';
import {readFileSync} from 'node:fs';
import React, {useRef} from 'react';
import {Popover} from './Popover';
import type {UsePopoverReturn} from './usePopover';
import {Dialog} from '../Dialog';
import {SegmentedControl, SegmentedControlItem} from '../SegmentedControl';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
// Store original matches to restore later
const originalMatches = HTMLElement.prototype.matches;
@@ -618,6 +620,35 @@ describe('Popover', () => {
expect(trigger).toHaveAttribute('aria-expanded', 'false');
});
+ it('does not reopen when the trigger click belongs to its own light dismiss', () => {
+ render(
+ <Popover content={<span>Content</span>} label="Test">
+ <button type="button">Open</button>
+ </Popover>,
+ );
+ const trigger = screen.getByRole('button', {name: 'Open'});
+ const showPopover = vi.mocked(HTMLElement.prototype.showPopover);
+ const callsBeforeOpen = showPopover.mock.calls.length;
+
+ fireEvent.pointerDown(trigger);
+ fireEvent.click(trigger);
+ expect(showPopover).toHaveBeenCalledTimes(callsBeforeOpen + 1);
+
+ fireEvent.pointerDown(trigger);
+ const popover = document.querySelector('[popover]') as HTMLElement;
+ act(() => {
+ popover.dispatchEvent(
+ Object.assign(new Event('toggle'), {
+ oldState: 'open',
+ newState: 'closed',
+ }),
+ );
+ });
+ fireEvent.click(trigger);
+
+ expect(showPopover).toHaveBeenCalledTimes(callsBeforeOpen + 1);
+ });
+
it('dismisses on Escape pressed inside a roving-focus list', () => {
render(
<Popover
@@ -733,7 +764,7 @@ describe('Popover', () => {
});
describe('focus restoration', () => {
- it('focuses the dialog container without outlining an action after pointer activation', async () => {
+ it('focuses the first content control after pointer activation', async () => {
render(
<Popover
content={<button type="button">Delete</button>}
@@ -746,15 +777,11 @@ describe('Popover', () => {
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();
+ await waitFor(() =>
+ expect(
+ screen.getByRole('button', {name: 'Delete', hidden: true}),
+ ).toHaveFocus(),
+ );
});
it('focuses the first content control after keyboard activation', async () => {
@@ -790,6 +817,11 @@ describe('Popover', () => {
hidden: true,
});
await waitFor(() => expect(dialog).toHaveFocus());
+ for (const className of stylex
+ .props(focusOutlineStyles.focusVisible)
+ .className!.split(' ')) {
+ expect(dialog).toHaveClass(className);
+ }
expect(
screen.getByRole('button', {name: 'Close popover', hidden: true}),
).not.toHaveFocus();
diff --git a/packages/core/src/Popover/Popover.tsx b/packages/core/src/Popover/Popover.tsx
index b04f35222c..475103e685 100644
--- a/packages/core/src/Popover/Popover.tsx
+++ b/packages/core/src/Popover/Popover.tsx
@@ -5,7 +5,7 @@
/**
* @file Popover.tsx
* @input Uses React layout measurement and the usePopover hook
- * @output Exports Popover with viewport fitting, conditional overflow, and trigger-aware focus
+ * @output Exports Popover with viewport fitting, conditional overflow, and content-first focus
* @position Layer component; declarative wrapper around usePopover hook
*
* For hover-triggered overlays, use HoverCard instead.
@@ -28,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 {usePopoverInternal} from './usePopover';
+import {usePopover} from './usePopover';
import type {LayerAlignment, LayerPlacement} from '../Layer/useLayer';
import {layerAnimations} from '../Layer/layerAnimations.stylex';
import {spacingVars} from '../theme/tokens.stylex';
@@ -207,10 +207,12 @@ export interface PopoverProps extends Pick<
closeButtonLabel?: string;
/**
- * 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.
+ * Whether to move focus into the popover when it opens. Focus enters the
+ * first genuine caller content control; dialogs with none fall back to the
+ * labeled surface. The generated fallback close control is excluded from
+ * initial focus and reveals only when reached through keyboard navigation.
+ * Set to `false` for input-owned focus, inline showcases, or documentation
+ * previews.
* @default true
*/
hasAutoFocus?: boolean;
@@ -410,7 +412,7 @@ export function Popover({
onOpenChange?.(false);
}, [onOpenChange]);
- const popover = usePopoverInternal({
+ const popover = usePopover({
dialogLabel: label,
role,
isModal,
@@ -512,24 +514,12 @@ export function Popover({
}, [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.toggle({
- focusTarget:
- role === 'dialog' && event != null && event.detail > 0
- ? 'container'
- : 'first',
- });
- },
- [isEnabled, popover, role],
- );
+ const handleTriggerClick = useCallback(() => {
+ if (!isEnabled) {
+ return;
+ }
+ popover.toggle();
+ }, [isEnabled, popover]);
// Shared handler for keydown events on role="button" elements.
// Native <button> synthesizes click on Enter/Space, but role="button"
diff --git a/packages/core/src/Popover/usePopover.doc.mjs b/packages/core/src/Popover/usePopover.doc.mjs
index 82c3f75634..612e04f3e4 100644
--- a/packages/core/src/Popover/usePopover.doc.mjs
+++ b/packages/core/src/Popover/usePopover.doc.mjs
@@ -50,7 +50,7 @@ export const docs = {
name: 'hasAutoFocus',
type: 'boolean',
description:
- 'Whether to automatically focus the first focusable element when opened.',
+ 'Whether to focus the first genuine content control when opened. Dialogs with none fall back to the labeled surface; the generated close control is excluded from initial focus.',
default: 'true',
},
{
@@ -205,7 +205,8 @@ export const docsDense = {
hasLightDismiss: 'whether outside click dismisses popover.',
hasEscapeDismiss:
'whether Escape dismisses; full effect only w/ hasLightDismiss false.',
- hasAutoFocus: 'whether first focusable element receives focus on open.',
+ hasAutoFocus:
+ 'focus genuine content on open; dialog surface fallback; generated close excluded.',
hasCloseButton: 'whether hidden keyboard close button is included.',
closeButtonLabel: 'label for hidden close button.',
dialogLabel: 'accessible label for popover dialog (role="dialog" only).',
diff --git a/packages/core/src/Popover/usePopover.tsx b/packages/core/src/Popover/usePopover.tsx
index a6e4d58496..60eedb6cca 100644
--- a/packages/core/src/Popover/usePopover.tsx
+++ b/packages/core/src/Popover/usePopover.tsx
@@ -5,7 +5,7 @@
/**
* @file usePopover.tsx
* @input Uses useLayer, useFocusTrap, React hooks
- * @output Exports usePopover and a package-internal variant with refined open options.
+ * @output Exports the public usePopover hook with derived focus and guarded opening.
* @position Higher-level layer utility; used by DatePicker, Combobox, etc.
*
* Combines popover layer behavior with focus trap for dialog-like popovers.
@@ -17,7 +17,7 @@
import React, {useCallback, useEffect, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
-import {useLayerInternal, type ContextRenderProps} from '../Layer/useLayer';
+import {useLayer, type ContextRenderProps} from '../Layer/useLayer';
import {useFocusTrap} from '../hooks/useFocusTrap';
import {LayerDepthProvider} from '../Layer/LayerDepthContext';
import type {StyleXStyles} from '@stylexjs/stylex';
@@ -32,6 +32,7 @@ import {FOCUSABLE_SELECTOR} from '../hooks/focusableSelector';
import {rtlStyles} from '../utils';
import {useTranslator} from '../i18n';
import {useDevWarning} from '../hooks/useDevWarning';
+import {focusOutlineProps} from '../utils/focusOutline.stylex';
import {mergeProps} from '../utils/mergeProps';
import {themeProps} from '../utils/themeProps';
import {stableClassName} from '../naming';
@@ -69,14 +70,10 @@ const styles = stylex.create({
borderRadius: 'var(--_popover-radius)',
boxShadow: shadowVars['--shadow-low'],
},
- // Focus trap container
+ // Focus trap container. Shared :focus-visible styling keeps semantic focus
+ // placement independent of pointer/keyboard indication.
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
@@ -323,16 +320,6 @@ export interface UsePopoverReturn {
};
}
-interface InternalPopoverOpenOptions {
- skipAutoFocus?: boolean;
- focusTarget?: 'first' | 'container';
-}
-
-interface InternalUsePopoverReturn extends UsePopoverReturn {
- toggle: (options?: InternalPopoverOpenOptions) => void;
- wasJustDismissed: () => boolean;
-}
-
/**
* Hook for creating popover dialogs with focus trapping.
*
@@ -375,7 +362,7 @@ interface InternalUsePopoverReturn extends UsePopoverReturn {
*/
function usePopoverImplementation(
options: UsePopoverOptions = {},
-): InternalUsePopoverReturn {
+): UsePopoverReturn {
const {
onShow,
onHide,
@@ -403,10 +390,9 @@ 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({
+ const layer = useLayer({
mode: 'context',
lightDismiss: hasLightDismiss,
onShow,
@@ -440,25 +426,13 @@ function usePopoverImplementation(
useEffect(() => {
if (layer.isOpen && hasAutoFocus && !skipAutoFocusRef.current) {
// Use requestAnimationFrame to ensure DOM is ready
- requestAnimationFrame(() => {
- const container = contentRef.current;
- if (
- focusTargetRef.current === 'container' &&
- role === 'dialog' &&
- container
- ) {
- attemptFocus(container);
- } else {
- focusInitialTarget();
- }
- });
+ requestAnimationFrame(focusInitialTarget);
}
- // Reset per-open focus preferences after the popover closes.
+ // Reset the per-open focus preference after the popover closes.
if (!layer.isOpen) {
skipAutoFocusRef.current = false;
- focusTargetRef.current = 'first';
}
- }, [contentRef, layer.isOpen, hasAutoFocus, focusInitialTarget, role]);
+ }, [layer.isOpen, hasAutoFocus, focusInitialTarget]);
// Combined ref for trigger element (layer anchor + our ref)
const triggerRef = useCallback(
@@ -469,30 +443,24 @@ function usePopoverImplementation(
[layer],
);
- // Show function with optional open preferences
+ // Show function with optional focus preservation
const show = useCallback(
- (showOptions?: InternalPopoverOpenOptions) => {
+ (showOptions?: {skipAutoFocus?: boolean}) => {
skipAutoFocusRef.current = showOptions?.skipAutoFocus ?? false;
- focusTargetRef.current = showOptions?.focusTarget ?? 'first';
layer.show();
},
[layer],
);
- // Toggle function
- const toggle = useCallback(
- (showOptions?: InternalPopoverOpenOptions) => {
- if (layer.wasJustDismissed()) {
- return;
- }
- if (layer.isOpen) {
- layer.hide();
- } else {
- show(showOptions);
- }
- },
- [layer, show],
- );
+ // Toggle function. Opening delegates to show so every route inherits the
+ // same-gesture reopen guard owned by Layer.
+ const toggle = useCallback(() => {
+ if (layer.isOpen) {
+ layer.hide();
+ } else {
+ show();
+ }
+ }, [layer, show]);
// ARIA attributes for the trigger
const triggerProps = {
@@ -533,7 +501,7 @@ function usePopoverImplementation(
tabIndex={role === 'dialog' ? -1 : undefined}
{...mergeProps(
{...surfaceProps, className: surfaceClassName},
- stylex.props(
+ focusOutlineProps.focusVisible(
styles.contentWrapper,
hasSurface && styles.surface,
xstyle,
@@ -584,7 +552,6 @@ function usePopoverImplementation(
show,
hide: layer.hide,
toggle,
- wasJustDismissed: layer.wasJustDismissed,
isOpen: layer.isOpen,
id: layer.id,
render,
@@ -593,13 +560,5 @@ function usePopoverImplementation(
}
export function usePopover(options: UsePopoverOptions = {}): UsePopoverReturn {
- const {wasJustDismissed: _, ...popover} = usePopoverImplementation(options);
- return popover;
-}
-
-/** @internal Used by trigger components; not exported from package barrels. */
-export function usePopoverInternal(
- options: UsePopoverOptions = {},
-): InternalUsePopoverReturn {
return usePopoverImplementation(options);
}
diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsx
index 85cf686438..b49029226b 100644
--- a/packages/core/src/Selector/Selector.test.tsx
+++ b/packages/core/src/Selector/Selector.test.tsx
@@ -3791,6 +3791,9 @@ describe('Selector popup theme target', () => {
fireEvent.click(trigger);
expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(trigger.parentElement).toHaveClass(
+ stylex.props(selectorPresentationStyles.pointerRestoredFocus).className!,
+ );
});
});
diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsx
index 4d7ad3de4c..b7dc04aa42 100644
--- a/packages/core/src/Selector/Selector.tsx
+++ b/packages/core/src/Selector/Selector.tsx
@@ -993,9 +993,24 @@ export function Selector<T extends SelectorOptionType>(
announce('');
}, [announce]);
+ const handleLayerShow = useCallback(() => {
+ if (hasSearch) {
+ requestAnimationFrame(() => {
+ const input = searchRef.current;
+ if (input) {
+ input.focus();
+ // When typing seeded the query, place the caret after it so the user
+ // keeps typing where they left off.
+ input.setSelectionRange(input.value.length, input.value.length);
+ }
+ });
+ }
+ }, [hasSearch]);
+
const surface = useSelectorPresentation({
presentation,
onHide: handleLayerHide,
+ onShow: handleLayerShow,
triggerRef,
popoverOptions: {
hasLightDismiss: true,
@@ -1175,7 +1190,6 @@ export function Selector<T extends SelectorOptionType>(
onItemMouseEnter,
} = useCombobox({
selectableItems: filteredItems,
- 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
@@ -1184,20 +1198,7 @@ export function Selector<T extends SelectorOptionType>(
isDisabled: isDisabled || isEffectivelyReadOnly,
isOpen: surface.isOpen,
hasSearch,
- onOpen: useCallback(() => {
- surface.show();
- if (hasSearch) {
- requestAnimationFrame(() => {
- const input = searchRef.current;
- if (input) {
- input.focus();
- // When typing seeded the query, place the caret after it so the
- // user keeps typing where they left off.
- input.setSelectionRange(input.value.length, input.value.length);
- }
- });
- }
- }, [surface, hasSearch]),
+ onOpen: useCallback(() => surface.show(), [surface]),
onClose: surface.hide,
onSelect: commitValue,
onClear: hasClear ? clearValue : undefined,
diff --git a/packages/core/src/Selector/hooks.ts b/packages/core/src/Selector/hooks.ts
index 648ff1e0c3..4ba16b95d6 100644
--- a/packages/core/src/Selector/hooks.ts
+++ b/packages/core/src/Selector/hooks.ts
@@ -159,7 +159,7 @@ interface UseComboboxOptions {
isDisabled?: boolean;
isOpen: boolean;
hasSearch?: boolean;
- onOpen: () => void;
+ onOpen: () => unknown;
onClose: () => void;
onSelect?: (value: string) => void;
/**
@@ -176,12 +176,6 @@ interface UseComboboxOptions {
* lands in the search input, which then owns its own typing.
*/
onSearchSeed?: (char: string) => void;
- /**
- * Whether the browser's light dismiss just closed the popup. The trigger
- * click that follows belongs to that same press, so acting on it would
- * reopen the popup the user just closed.
- */
- wasJustDismissed?: () => boolean;
listboxId: string;
}
@@ -214,7 +208,6 @@ export function useCombobox({
onSelect,
onClear,
onSearchSeed,
- wasJustDismissed,
listboxId,
}: UseComboboxOptions): UseComboboxResult {
const [highlightedIndex, setHighlightedIndex] = useState<number>(-1);
@@ -251,27 +244,19 @@ export function useCombobox({
);
const onTriggerClick = useCallback(() => {
- if (isDisabled || wasJustDismissed?.()) {
+ if (isDisabled) {
return;
}
if (isOpen) {
closeAndReset();
} else {
- onOpen();
- if (!hasSearch) {
+ const didOpen = onOpen() !== false;
+ if (didOpen && !hasSearch) {
const selectedIndex = findSelectedIndex();
setHighlightedIndex(selectedIndex >= 0 ? selectedIndex : 0);
}
}
- }, [
- isDisabled,
- wasJustDismissed,
- isOpen,
- onOpen,
- closeAndReset,
- findSelectedIndex,
- hasSearch,
- ]);
+ }, [isDisabled, isOpen, onOpen, closeAndReset, findSelectedIndex, hasSearch]);
const onItemMouseEnter = useCallback(
(item: SelectorOptionData, index: number) => {
@@ -294,8 +279,9 @@ export function useCombobox({
case 'ArrowDown':
e.preventDefault();
if (!isOpen) {
- onOpen();
- setHighlightedIndex(0);
+ if (onOpen() !== false) {
+ setHighlightedIndex(0);
+ }
} else {
const currentEnabledPos = enabledIndices.indexOf(highlightedIndex);
const nextPos = Math.min(
@@ -309,8 +295,9 @@ export function useCombobox({
case 'ArrowUp':
e.preventDefault();
if (!isOpen) {
- onOpen();
- setHighlightedIndex(selectableItems.length - 1);
+ if (onOpen() !== false) {
+ setHighlightedIndex(selectableItems.length - 1);
+ }
} else {
const currentEnabledPos = enabledIndices.indexOf(highlightedIndex);
const prevPos = Math.max(currentEnabledPos - 1, 0);
@@ -333,8 +320,8 @@ export function useCombobox({
selectItem(item);
}
} else if (!isOpen) {
- onOpen();
- if (!hasSearch) {
+ const didOpen = onOpen() !== false;
+ if (didOpen && !hasSearch) {
const selectedIndex = findSelectedIndex();
setHighlightedIndex(selectedIndex >= 0 ? selectedIndex : 0);
}
@@ -409,10 +396,9 @@ export function useCombobox({
!e.ctrlKey &&
!e.metaKey
) {
- if (!isOpen) {
- onOpen();
+ if (isOpen || onOpen() !== false) {
+ onSearchSeed(e.key);
}
- onSearchSeed(e.key);
}
break;
}
diff --git a/packages/core/src/Selector/useSelectorPresentation.ts b/packages/core/src/Selector/useSelectorPresentation.ts
index d153fb0e0a..ab9be1ba04 100644
--- a/packages/core/src/Selector/useSelectorPresentation.ts
+++ b/packages/core/src/Selector/useSelectorPresentation.ts
@@ -17,7 +17,7 @@ import {
type RefObject,
} from 'react';
import {
- usePopoverInternal,
+ usePopover,
type UsePopoverOptions,
type UsePopoverReturn,
} from '../Popover/usePopover';
@@ -31,7 +31,8 @@ import {useFocusReturnVisibility} from '../hooks/useFocusReturnVisibility';
interface UseSelectorPresentationOptions {
presentation: AdaptivePresentation;
onHide: () => void;
- popoverOptions: Omit<UsePopoverOptions, 'onHide'>;
+ onShow: () => void;
+ popoverOptions: Omit<UsePopoverOptions, 'onHide' | 'onShow'>;
triggerRef: RefObject<HTMLElement | null>;
}
@@ -44,14 +45,14 @@ interface SelectorPresentationController {
isTriggerFocusRingSuppressed: boolean;
onSheetOpenChange: (isOpen: boolean) => void;
onTriggerFocus: (event: FocusEvent<HTMLElement>) => void;
- popover: UsePopoverReturn & {wasJustDismissed: () => boolean};
- show: () => void;
- wasJustDismissed: () => boolean;
+ popover: UsePopoverReturn;
+ show: () => boolean;
}
export function useSelectorPresentation({
presentation,
onHide,
+ onShow,
popoverOptions,
triggerRef,
}: UseSelectorPresentationOptions): SelectorPresentationController {
@@ -65,6 +66,8 @@ export function useSelectorPresentation({
// trigger, then consumers may remove the hidden surface tree.
const [isSheetPresented, setIsSheetPresented] = useState(false);
const onHideRef = useRef(onHide);
+ const onShowRef = useRef(onShow);
+ const didShowPopoverRef = useRef(false);
const {
isFocusRingSuppressed,
onFocusReturnTargetFocus,
@@ -72,33 +75,39 @@ export function useSelectorPresentation({
resetFocusReturn,
} = useFocusReturnVisibility();
onHideRef.current = onHide;
+ onShowRef.current = onShow;
const handlePopoverHide = useCallback(() => {
prepareFocusReturn();
onHideRef.current();
triggerRef.current?.focus();
}, [prepareFocusReturn, triggerRef]);
- const popover = usePopoverInternal({
+ const handlePopoverShow = useCallback(() => {
+ didShowPopoverRef.current = true;
+ resetFocusReturn();
+ onShowRef.current();
+ }, [resetFocusReturn]);
+ const popover = usePopover({
...popoverOptions,
onHide: handlePopoverHide,
+ onShow: handlePopoverShow,
});
- const {
- hide: hidePopover,
- show: showPopover,
- wasJustDismissed: wasPopoverJustDismissed,
- } = popover;
+ const {hide: hidePopover, show: showPopover} = popover;
- const show = useCallback(() => {
- resetFocusReturn();
+ const show = useCallback((): boolean => {
activePresentationRef.current = resolvedPresentation;
if (resolvedPresentation === 'bottom-sheet') {
+ resetFocusReturn();
+ onShowRef.current();
isSheetOpenRef.current = true;
setIsSheetPresented(true);
setIsSheetOpen(true);
- } else {
- setIsSheetPresented(false);
- showPopover();
+ return true;
}
+ setIsSheetPresented(false);
+ didShowPopoverRef.current = false;
+ showPopover();
+ return didShowPopoverRef.current;
}, [resetFocusReturn, resolvedPresentation, showPopover]);
const hide = useCallback(() => {
@@ -145,12 +154,6 @@ export function useSelectorPresentation({
? activePresentationRef.current
: resolvedPresentation;
- const wasJustDismissed = useCallback(
- () =>
- activePresentationRef.current === 'popover' && wasPopoverJustDismissed(),
- [wasPopoverJustDismissed],
- );
-
return {
activePresentation,
hide,
@@ -162,6 +165,5 @@ export function useSelectorPresentation({
onTriggerFocus: handleTriggerFocus,
popover,
show,
- wasJustDismissed,
};
}