Skip to content

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

TypeScript

fix(HoverCard): focusTrigger="auto" decides when focus arrives, through Tooltip's shared check (#9597)

Cindy Zhangf88f5dc65c6b
diff --git a/.changeset/hovercard-focus-trigger-auto.md b/.changeset/hovercard-focus-trigger-auto.md
new file mode 100644
index 0000000000..a4e7583b29
--- /dev/null
+++ b/.changeset/hovercard-focus-trigger-auto.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Under `focusTrigger="auto"`, a `HoverCard` now decides whether focus opens it when the focus arrives, as `Tooltip` does. A roving-tabindex trigger that was `tabindex="-1"` when the card attached, such as a toolbar member, opens on arrow-key focus, and a focusable trigger such as a `<summary>` or an SVG link opens on focus.
+
+@cixzhang @duytbp
diff --git a/docs/specs/components/HoverCard/HoverCard.spec.md b/docs/specs/components/HoverCard/HoverCard.spec.md
index 7fef60ad33..b74cb630f0 100644
--- a/docs/specs/components/HoverCard/HoverCard.spec.md
+++ b/docs/specs/components/HoverCard/HoverCard.spec.md
@@ -45,7 +45,7 @@ system_specs: [spec:AST-003, spec:AST-017]
| Behavior | A floating card of rich, possibly interactive content anchored to a trigger. It opens on hover after `delay`, on focus, and on a tap that `touchTrigger` allows, stays open while the pointer is on the trigger or card, and closes on leave, Escape, or a tap outside. With `label` it is a named dialog the trigger advertises; without, a group that describes the trigger. With `touchTrigger="none"`, touch never opens it. |
| End-user impact | Mouse, keyboard, and touch users can open the preview, move into it to use its actions, and dismiss it; screen-reader users hear it as a named popup dialog or as the trigger's description. Under the default `touchTrigger="auto"`, a tap on a trigger that performs an action performs only that action. |
| Builder impact | `touchTrigger` answers whether it is safe to consume a tap to show the card (DEC-1): keep the default `auto` on a trigger that performs an action, pass `tap` where a tap only reveals the card, and pass `none` where a tap must never show it. |
-| Compatibility/readiness | No public API change: `touchTrigger` keeps its released values and its default `auto`. Six implementation gaps (see Current-state impact). |
+| Compatibility/readiness | No public API change: `touchTrigger` keeps its released values and its default `auto`. Five implementation gaps (see Current-state impact). |
| Review checks | Reject an unnamed `dialog`, a card that cannot be hovered or dismissed (WCAG 1.4.13), Escape in the page that also closes a layer underneath, `aria-expanded` set on a trigger whose role does not support it, or a tap under `touchTrigger="auto"` that both performs the trigger's action and shows the card. |
| Governing rules | WCAG 1.4.13, 2.1.1; `family:overlay-dismissal`; `spec:AST-003` FR4; `spec:AST-017` (lifecycle); `architecture:public-component-api` INV9, INV21; `architecture:layer-runtime`; `architecture:interaction-modality`; `architecture:component-theming-surface`. |
@@ -81,13 +81,6 @@ Consumer migration instructions belong in consumer docs and release notes.
- **Hover timing does not use the shared hover recognizer.** The card runs its
own show and hide timers. `architecture:interaction-modality` INV11 has
`useHoverCard` take its hover timing from the shared hover recognizer.
-- **A roving trigger may not open on focus.** Under `focusTrigger="auto"` the
- card reads the tab order only when the trigger's listeners attach, so a
- trigger rendered with `tabindex="-1"` opens only on mouse hover after it takes
- keyboard focus, until a re-render re-attaches them. A focusable trigger
- `auto` does not recognize, such as a `<summary>` or an SVG link, never opens
- on focus. `architecture:interaction-modality` INV4 keeps hover from being the
- only discovery path.
- **Escape cannot close a card in another document.** HoverCard listens for
Escape only in the page's document, so a card rendered into an iframe or a
Picture-in-Picture window with no layer beneath it is never closed by
@@ -124,22 +117,22 @@ Consumer migration instructions belong in consumer docs and release notes.
| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
| ------------- | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | ------- | --------------------- | --------- | -------------------------------- |
| Popup role | named dialog, group | `label` makes the card a named `dialog`; without it the card is a `group`. | Every card. | group | `component:HoverCard` | Stable | Not applicable. |
-| Focus trigger | `auto`, `always`, `never` | Whether focus opens the card: on focusable triggers (FR4's gap), always, or never. | Every trigger. | `auto` | `component:HoverCard` | Stable | TypeScript rejects other values. |
+| Focus trigger | `auto`, `always`, `never` | Whether focus opens the card: on focusable triggers, judged when focus arrives (FR4), always, or never. | Every trigger. | `auto` | `component:HoverCard` | Stable | TypeScript rejects other values. |
| Touch trigger | `auto`, `tap`, `none` | Whether it is safe to consume a tap to show the card (DEC-1): `auto` shows it on a tap unless the trigger itself performs an action, a disabled control excepted (FR5); `tap` shows it on every tap; `none` on no tap. | Touch without hover. | `auto` | `component:HoverCard` | Stable | TypeScript rejects other values. |
## Behavioral and layout contract
-| ID | Invariant | Basis |
-| ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
-| FR1 | The open card is one surface carrying only the `hover-card` target, padded on every logical edge, with `content` inside and the theme's body font. `xstyle`, `className`, and `style` apply to the card. | Current source and tests |
-| FR2 | Trigger wiring: a single string or number child is wrapped in a focusable inline span; element `children` attach to their first element inside an inline-safe wrapper, and a first element replaced after mount, by new children or by a child that swaps its own root, is wired in place of the old one. | Current source and tests |
-| FR3 | With `label`, the card is `role="dialog"` named by `label`; the trigger gets `aria-haspopup="dialog"` and, only when its role supports it, `aria-expanded`, each replacing the trigger's own value while the card is wired, plus `aria-controls` naming the card while open, merged with the trigger's own; the trigger's own values return on cleanup. Without `label`, the card is `role="group"` and the trigger's `aria-describedby` gains the card's id. | Current source and tests |
-| FR4 | On a hover-capable pointer, entering the trigger opens the card after `delay` ms; leaving the trigger or the card closes it after `hideDelay` ms, and moving between them keeps it open. Any focus on the trigger, keyboard, pointer, or programmatic, opens it per `focusTrigger`, except the focus a tap leaves behind, the refocus after an Escape dismiss (FR6), and the refocus after a controlled close (FR7). Implementation gap: under `auto` the tab order is read only when the trigger's listeners attach, on mount and on a re-render that re-attaches them, so a trigger rendered with `tabindex="-1"` does not open on focus until such a re-render follows its move into the tab order (Current-state impact). | WCAG 1.4.13; tests |
-| FR5 | On touch, a completed tap opens the card per `touchTrigger` when the finger lifts; a touch that becomes a scroll does not. Under `auto`, a tap opens it unless the trigger itself performs an action; an `aria-disabled` control, or a label for a disabled control, is not an action, so a disabled control's reason opens on a tap (DEC-1). Under `tap`, every tap opens it; under `none`, no tap does. A tap on the card's own content keeps it open; a second tap on the trigger, a tap outside, or a scroll starting outside closes it. Whether `auto` also leaves the card shut when the tap acts on a control around the trigger is open (`component:Tooltip` OQ1). | Current source and tests |
-| FR6 | Escape closes a visible card through the shared dismissal stack when it is the topmost layer in the page, so a layer underneath stays open. Implementation gap: a card rendered into another document, such as an iframe or a Picture-in-Picture window, with no layer beneath it is never closed by Escape (Current-state impact). When focus was inside the card, it returns to the trigger, and that refocus does not reopen the card. | WCAG 1.4.13; tests |
-| FR7 | `isOpen` forces the card shown or hidden, and `isOpen={true}` suppresses hover and focus hiding; a controlled card answers Escape by calling `onOpenChange(false)` without hiding, and setting `isOpen={false}` while focus is inside the card returns focus to the trigger. `isDefaultOpen` opens it on mount, still dismissible. Implementation gap: with `isOpen={false}`, focus on the trigger still opens the card, and Escape then only reports `onOpenChange(false)` (Current-state impact). `isEnabled={false}` disables the triggers. `onOpenChange` reports each show and hide. | Current source and tests |
-| FR8 | Content renders only while open; server markup and the first client render match, including a default-open card. `hasHoverIndication` (`auto`: a single string or number child) adds a hover cue to the inline trigger. | Current source and tests |
-| FR11 | A press inside an open HoverCard surface acts only within that surface: it never activates the trigger, a clickable container around it, or the control a label names. Interactive content inside the card (a link, a button) keeps its own activation. The press still reaches page-level listeners, so a menu or Typeahead inside the surface keeps working. `architecture:layer-runtime` INV17 states this stop for every layer root. | `component:Tooltip` FR11; `architecture:layer-runtime` INV17 |
+| ID | Invariant | Basis |
+| ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
+| FR1 | The open card is one surface carrying only the `hover-card` target, padded on every logical edge, with `content` inside and the theme's body font. `xstyle`, `className`, and `style` apply to the card. | Current source and tests |
+| FR2 | Trigger wiring: a single string or number child is wrapped in a focusable inline span; element `children` attach to their first element inside an inline-safe wrapper, and a first element replaced after mount, by new children or by a child that swaps its own root, is wired in place of the old one. | Current source and tests |
+| FR3 | With `label`, the card is `role="dialog"` named by `label`; the trigger gets `aria-haspopup="dialog"` and, only when its role supports it, `aria-expanded`, each replacing the trigger's own value while the card is wired, plus `aria-controls` naming the card while open, merged with the trigger's own; the trigger's own values return on cleanup. Without `label`, the card is `role="group"` and the trigger's `aria-describedby` gains the card's id. | Current source and tests |
+| FR4 | On a hover-capable pointer, entering the trigger opens the card after `delay` ms; leaving the trigger or the card closes it after `hideDelay` ms, and moving between them keeps it open. Any focus on the trigger, keyboard, pointer, or programmatic, opens it per `focusTrigger`, except the focus a tap leaves behind, the refocus after an Escape dismiss (FR6), and the refocus after a controlled close (FR7). Under `auto`, whether focus counts is judged when it arrives: focus on the trigger itself, or within a trigger that is focusable at that moment, so a roving-tabindex member opens when the arrow keys reach it. | WCAG 1.4.13; tests |
+| FR5 | On touch, a completed tap opens the card per `touchTrigger` when the finger lifts; a touch that becomes a scroll does not. Under `auto`, a tap opens it unless the trigger itself performs an action; an `aria-disabled` control, or a label for a disabled control, is not an action, so a disabled control's reason opens on a tap (DEC-1). Under `tap`, every tap opens it; under `none`, no tap does. A tap on the card's own content keeps it open; a second tap on the trigger, a tap outside, or a scroll starting outside closes it. Whether `auto` also leaves the card shut when the tap acts on a control around the trigger is open (`component:Tooltip` OQ1). | Current source and tests |
+| FR6 | Escape closes a visible card through the shared dismissal stack when it is the topmost layer in the page, so a layer underneath stays open. Implementation gap: a card rendered into another document, such as an iframe or a Picture-in-Picture window, with no layer beneath it is never closed by Escape (Current-state impact). When focus was inside the card, it returns to the trigger, and that refocus does not reopen the card. | WCAG 1.4.13; tests |
+| FR7 | `isOpen` forces the card shown or hidden, and `isOpen={true}` suppresses hover and focus hiding; a controlled card answers Escape by calling `onOpenChange(false)` without hiding, and setting `isOpen={false}` while focus is inside the card returns focus to the trigger. `isDefaultOpen` opens it on mount, still dismissible. Implementation gap: with `isOpen={false}`, focus on the trigger still opens the card, and Escape then only reports `onOpenChange(false)` (Current-state impact). `isEnabled={false}` disables the triggers. `onOpenChange` reports each show and hide. | Current source and tests |
+| FR8 | Content renders only while open; server markup and the first client render match, including a default-open card. `hasHoverIndication` (`auto`: a single string or number child) adds a hover cue to the inline trigger. | Current source and tests |
+| FR11 | A press inside an open HoverCard surface acts only within that surface: it never activates the trigger, a clickable container around it, or the control a label names. Interactive content inside the card (a link, a button) keeps its own activation. The press still reaches page-level listeners, so a menu or Typeahead inside the surface keeps working. `architecture:layer-runtime` INV17 states this stop for every layer root. | `component:Tooltip` FR11; `architecture:layer-runtime` INV17 |
### Allowed variation
@@ -215,14 +208,14 @@ Consumer migration instructions belong in consumer docs and release notes.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |
-| FR1, FR2, FR8 | `HoverCard.test.tsx` render, wrapper, portal, theme font, SSR, replaced-trigger, and card `xstyle`/`className`/`style` tests; `HoverCardAudit` Chromium frames of `HoverCard / Open States` for the single target, equal padding on every logical edge, and the text trigger's dashed hover cue | Text and element triggers; default open | A stray target, lost font, or hydration mismatch fails, and so do card `xstyle`, `className`, or `style` that do not reach the card, missing or unequal card padding, or a lost dashed cue on a text trigger. | `audit:HoverCard/anatomy` |
-| FR3, AR1 | `HoverCard.test.tsx` role, trigger-attribute, and attribute-restore tests; `HoverCardAudit` frames and the audit axe pass on `HoverCard / Open States` | Labelled and unlabelled; supported and unsupported roles | Wrong role, trigger attributes that are not replaced and restored as stated, or a new axe violation on an open card, fail. | `audit:HoverCard/accessibility` |
-| FR4–FR6, AR2 | `HoverCard.test.tsx` hover, delay and hide-delay timing, trigger-to-card hold, Escape, refocus, and touch tests; `HoverCardAudit` hover-and-keyboard pass in Chromium; `useTouchTrigger.test.ts` and `touchTriggerTargets.test.tsx` disabled-control cases | Hover, focus, tap, Escape from trigger and content; `touchTrigger` `auto`, `tap`, and `none`; an action trigger; a disabled control inside a clickable row | A card that cannot be reached or dismissed, that opens before `delay` or closes before `hideDelay`, that closes while the pointer moves from the trigger into it, or that opens on a tap on a trigger that performs an action under `auto` or on any tap under `none`, fails. | `audit:HoverCard/behavior` |
-| FR7 | `HoverCard.test.tsx` isEnabled, isDefaultOpen, onOpenChange, `isOpen` forcing, and controlled-close focus-return tests; `layerDismissalFamilies.test.tsx` controlled HoverCard case | Disabled, default open, held open, held closed, closed by the caller with focus inside | Wrong state reporting, a hover that hides a card held open or opens one held closed, or focus left inside a card the caller closes, fails. | `audit:HoverCard/behavior` |
-| FR11 | `HoverCard.test.tsx` surface-press suite | A card inside a clickable container and inside a `<label>`; a button inside the card | A click on card content that runs the container's click handler or activates a labelled control, or a card button that stops working, fails. | — |
-| Theming anatomy map | `scripts/check-knowledge.mjs` | Consumer anatomy and current target | Missing, extra, or stale mappings fail validation. | `audit:HoverCard/theming` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |
+| FR1, FR2, FR8 | `HoverCard.test.tsx` render, wrapper, portal, theme font, SSR, replaced-trigger, and card `xstyle`/`className`/`style` tests; `HoverCardAudit` Chromium frames of `HoverCard / Open States` for the single target, equal padding on every logical edge, and the text trigger's dashed hover cue | Text and element triggers; default open | A stray target, lost font, or hydration mismatch fails, and so do card `xstyle`, `className`, or `style` that do not reach the card, missing or unequal card padding, or a lost dashed cue on a text trigger. | `audit:HoverCard/anatomy` |
+| FR3, AR1 | `HoverCard.test.tsx` role, trigger-attribute, and attribute-restore tests; `HoverCardAudit` frames and the audit axe pass on `HoverCard / Open States` | Labelled and unlabelled; supported and unsupported roles | Wrong role, trigger attributes that are not replaced and restored as stated, or a new axe violation on an open card, fail. | `audit:HoverCard/accessibility` |
+| FR4–FR6, AR2 | `HoverCard.test.tsx` hover, delay and hide-delay timing, trigger-to-card hold, Escape, refocus, and touch tests, and its `focusTrigger="auto"` roving, `<summary>`, wrapper, left-the-tab-order, and focus-inside-a-focusable-trigger cases; `HoverCardAudit` hover-and-keyboard pass in Chromium; `useTouchTrigger.test.ts` and `touchTriggerTargets.test.tsx` disabled-control cases | Hover, focus, tap, Escape from trigger and content; `touchTrigger` `auto`, `tap`, and `none`; an action trigger; a disabled control inside a clickable row | A card that cannot be reached or dismissed, that opens before `delay` or closes before `hideDelay`, that closes while the pointer moves from the trigger into it, or that opens on a tap on a trigger that performs an action under `auto` or on any tap under `none`, fails. | `audit:HoverCard/behavior` |
+| FR7 | `HoverCard.test.tsx` isEnabled, isDefaultOpen, onOpenChange, `isOpen` forcing, and controlled-close focus-return tests; `layerDismissalFamilies.test.tsx` controlled HoverCard case | Disabled, default open, held open, held closed, closed by the caller with focus inside | Wrong state reporting, a hover that hides a card held open or opens one held closed, or focus left inside a card the caller closes, fails. | `audit:HoverCard/behavior` |
+| FR11 | `HoverCard.test.tsx` surface-press suite | A card inside a clickable container and inside a `<label>`; a button inside the card | A click on card content that runs the container's click handler or activates a labelled control, or a card button that stops working, fails. | — |
+| Theming anatomy map | `scripts/check-knowledge.mjs` | Consumer anatomy and current target | Missing, extra, or stale mappings fail validation. | `audit:HoverCard/theming` |
Read from source, with no focused test yet:
diff --git a/packages/core/src/HoverCard/HoverCard.doc.mjs b/packages/core/src/HoverCard/HoverCard.doc.mjs
index 53dbf2a127..0a1da40e16 100644
--- a/packages/core/src/HoverCard/HoverCard.doc.mjs
+++ b/packages/core/src/HoverCard/HoverCard.doc.mjs
@@ -98,7 +98,8 @@ export const docs = {
{
name: 'focusTrigger',
type: "'auto' | 'always' | 'never'",
- description: 'Controls when focus events trigger the hover card.',
+ description:
+ 'When focus should open the hover card. auto opens when the trigger itself takes focus, or focus lands inside a trigger that is focusable at that moment, so a roving-tabindex member opens when the arrow keys reach it.',
default: "'auto'",
},
{
@@ -303,7 +304,8 @@ export const docsZh = {
{
name: 'focusTrigger',
type: "'auto' | 'always' | 'never'",
- description: '控制焦点事件何时触发悬浮卡片。',
+ description:
+ '焦点何时打开悬浮卡片。auto 在触发元素自身获得焦点,或焦点落在当时可聚焦的触发元素内部时打开,因此方向键到达漫游 tabindex 成员时也会打开。',
default: "'auto'",
},
{
diff --git a/packages/core/src/HoverCard/HoverCard.test.tsx b/packages/core/src/HoverCard/HoverCard.test.tsx
index 0d74fd06d1..ce170dd69c 100644
--- a/packages/core/src/HoverCard/HoverCard.test.tsx
+++ b/packages/core/src/HoverCard/HoverCard.test.tsx
@@ -170,6 +170,118 @@ describe('useHoverCard closing while the pointer is on the card', () => {
});
});
+describe('useHoverCard — focusTrigger="auto" decides when focus arrives', () => {
+ it('opens on focus of a trigger that was tabindex="-1" when it attached', async () => {
+ const onShow = vi.fn();
+ function RovingMember() {
+ const card = useHoverCard({onShow, delay: 0});
+ return (
+ <div>
+ {/* A roving-tabindex member that is not the tab stop when the
+ card attaches. */}
+ <button type="button" tabIndex={-1} ref={card.ref}>
+ Filter
+ </button>
+ {card.renderHoverCard(<span>Card</span>)}
+ </div>
+ );
+ }
+ render(<RovingMember />);
+ const member = screen.getByRole('button', {name: 'Filter'});
+ // The roving hook moves the tab stop, then focus, as an arrow key does.
+ member.setAttribute('tabindex', '0');
+ fireEvent.focusIn(member);
+ await waitFor(() => expect(onShow).toHaveBeenCalledTimes(1));
+ });
+
+ it('opens on focus of a focusable trigger it does not list, such as a summary', async () => {
+ const onShow = vi.fn();
+ function SummaryTrigger() {
+ const card = useHoverCard({onShow, delay: 0});
+ return (
+ <details>
+ <summary ref={card.ref}>More</summary>
+ {card.renderHoverCard(<span>Card</span>)}
+ </details>
+ );
+ }
+ render(<SummaryTrigger />);
+ fireEvent.focusIn(screen.getByText('More'));
+ await waitFor(() => expect(onShow).toHaveBeenCalledTimes(1));
+ });
+
+ it('ignores focus inside a plain wrapper trigger', async () => {
+ const onShow = vi.fn();
+ function WrapperTrigger() {
+ const card = useHoverCard({onShow, delay: 0});
+ return (
+ <div>
+ <div ref={card.ref}>
+ <input aria-label="Amount" />
+ </div>
+ {card.renderHoverCard(<span>Card</span>)}
+ </div>
+ );
+ }
+ render(<WrapperTrigger />);
+ fireEvent.focusIn(screen.getByRole('textbox', {name: 'Amount'}));
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 20));
+ });
+ expect(onShow).not.toHaveBeenCalled();
+ });
+
+ it('hides on blur from inside a focusable trigger that left the tab order', async () => {
+ const onShow = vi.fn();
+ const onHide = vi.fn();
+ function FocusableRow() {
+ const card = useHoverCard({onShow, onHide, delay: 0, hideDelay: 0});
+ return (
+ <div>
+ <div tabIndex={0} ref={card.ref} data-testid="row">
+ <button type="button">Inside</button>
+ </div>
+ {card.renderHoverCard(<span>Card</span>)}
+ </div>
+ );
+ }
+ render(<FocusableRow />);
+ const inside = screen.getByRole('button', {name: 'Inside'});
+ // Focus inside a focusable trigger counts.
+ fireEvent.focusIn(inside);
+ await waitFor(() => expect(onShow).toHaveBeenCalledTimes(1));
+ // The trigger leaves the tab order before focus moves on: the focus that
+ // counted still hides the card.
+ screen.getByTestId('row').setAttribute('tabindex', '-1');
+ fireEvent.focusOut(inside);
+ await waitFor(() => expect(onHide).toHaveBeenCalledTimes(1));
+ });
+
+ it('hides on blur of a trigger that left the tab order while focused', async () => {
+ const onShow = vi.fn();
+ const onHide = vi.fn();
+ function RovingMember() {
+ const card = useHoverCard({onShow, onHide, delay: 0, hideDelay: 0});
+ return (
+ <div>
+ <button type="button" ref={card.ref}>
+ Filter
+ </button>
+ {card.renderHoverCard(<span>Card</span>)}
+ </div>
+ );
+ }
+ render(<RovingMember />);
+ const member = screen.getByRole('button', {name: 'Filter'});
+ fireEvent.focusIn(member);
+ await waitFor(() => expect(onShow).toHaveBeenCalledTimes(1));
+ // The roving hook takes the tab stop away before focus moves on.
+ member.setAttribute('tabindex', '-1');
+ fireEvent.focusOut(member);
+ await waitFor(() => expect(onHide).toHaveBeenCalledTimes(1));
+ });
+});
+
describe('HoverCard', () => {
it('renders trigger element', () => {
render(
diff --git a/packages/core/src/HoverCard/HoverCard.tsx b/packages/core/src/HoverCard/HoverCard.tsx
index c99250ecfd..8737fd18f4 100644
--- a/packages/core/src/HoverCard/HoverCard.tsx
+++ b/packages/core/src/HoverCard/HoverCard.tsx
@@ -155,9 +155,10 @@ export interface HoverCardProps extends Pick<
/**
* When to trigger on focus:
- * - `auto`: Only if element is naturally focusable
- * - `always`: Always attach focus listeners
- * - `never`: Never attach focus listeners (for composite widgets)
+ * - `auto`: focus on the trigger itself, or within a trigger that is
+ * focusable when focus arrives
+ * - `always`: focus on the trigger or anything inside it
+ * - `never`: never on focus (for composite widgets)
*
* @default 'auto'
*/
diff --git a/packages/core/src/HoverCard/useHoverCard.doc.mjs b/packages/core/src/HoverCard/useHoverCard.doc.mjs
index 0623a46cff..efb866da60 100644
--- a/packages/core/src/HoverCard/useHoverCard.doc.mjs
+++ b/packages/core/src/HoverCard/useHoverCard.doc.mjs
@@ -5,37 +5,159 @@ export const docs = {
name: 'useHoverCard',
displayName: 'useHoverCard',
group: 'HoverCard',
- keywords: ['hovercard', 'hover', 'preview', 'card', 'tooltip', 'popup', 'floating', 'anchor'],
+ keywords: [
+ 'hovercard',
+ 'hover',
+ 'preview',
+ 'card',
+ 'tooltip',
+ 'popup',
+ 'floating',
+ 'anchor',
+ ],
params: [
- {name: 'placement', type: "'above' | 'below' | 'start' | 'end'", description: "Position relative to the trigger. Logical: start/end resolve against the popover\'s own inherited direction (RTL mirrors in pure CSS).", default: "'above'"},
- {name: 'alignment', type: "'start' | 'center' | 'end'", description: "Alignment along the placement axis. Logical: start/end resolve against the popover\'s own inherited direction (RTL mirrors in pure CSS).", default: "'center'"},
- {name: 'delay', type: 'number', description: 'Delay before showing the hover card on hover, in milliseconds.', default: '300'},
- {name: 'hideDelay', type: 'number', description: 'Delay before hiding after mouse or focus leaves, in milliseconds.', default: '200'},
- {name: 'focusTrigger', type: "'auto' | 'always' | 'never'", description: 'When focus should open the hover card. auto only attaches focus listeners to naturally focusable elements.', default: "'auto'"},
- {name: 'touchTrigger', type: "'auto' | 'tap' | 'none'", description: 'What a tap does where there is no hover. auto opens on tap unless the trigger performs an action of its own (an aria-disabled control performs none); tap always opens; none never opens on touch.', default: "'auto'"},
- {name: 'isEnabled', type: 'boolean', description: 'Whether hover and focus triggers are enabled.', default: 'true'},
- {name: 'label', type: 'string', description: 'Accessible name for the hover card popup. When provided, the popup is exposed as a named role="dialog"; when omitted, it falls back to role="group" (a group may validly be unnamed).'},
- {name: 'isOpen', type: 'boolean', description: 'Controlled open state. true force-shows, false force-hides, undefined lets hover/focus manage visibility.'},
- {name: 'isDefaultOpen', type: 'boolean', description: 'Whether the hover card should be shown on mount.', default: 'false'},
- {name: 'onShow', type: '() => void', description: 'Callback fired when the hover card becomes visible.'},
- {name: 'onHide', type: '() => void', description: 'Callback fired when the hover card is hidden.'},
+ {
+ name: 'placement',
+ type: "'above' | 'below' | 'start' | 'end'",
+ description:
+ "Position relative to the trigger. Logical: start/end resolve against the popover\'s own inherited direction (RTL mirrors in pure CSS).",
+ default: "'above'",
+ },
+ {
+ name: 'alignment',
+ type: "'start' | 'center' | 'end'",
+ description:
+ "Alignment along the placement axis. Logical: start/end resolve against the popover\'s own inherited direction (RTL mirrors in pure CSS).",
+ default: "'center'",
+ },
+ {
+ name: 'delay',
+ type: 'number',
+ description:
+ 'Delay before showing the hover card on hover, in milliseconds.',
+ default: '300',
+ },
+ {
+ name: 'hideDelay',
+ type: 'number',
+ description:
+ 'Delay before hiding after mouse or focus leaves, in milliseconds.',
+ default: '200',
+ },
+ {
+ name: 'focusTrigger',
+ type: "'auto' | 'always' | 'never'",
+ description:
+ 'When focus should open the hover card. auto opens when the trigger itself takes focus, or focus lands inside a trigger that is focusable at that moment, so a roving-tabindex member opens when the arrow keys reach it.',
+ default: "'auto'",
+ },
+ {
+ name: 'touchTrigger',
+ type: "'auto' | 'tap' | 'none'",
+ description:
+ 'What a tap does where there is no hover. auto opens on tap unless the trigger performs an action of its own (an aria-disabled control performs none); tap always opens; none never opens on touch.',
+ default: "'auto'",
+ },
+ {
+ name: 'isEnabled',
+ type: 'boolean',
+ description: 'Whether hover and focus triggers are enabled.',
+ default: 'true',
+ },
+ {
+ name: 'label',
+ type: 'string',
+ description:
+ 'Accessible name for the hover card popup. When provided, the popup is exposed as a named role="dialog"; when omitted, it falls back to role="group" (a group may validly be unnamed).',
+ },
+ {
+ name: 'isOpen',
+ type: 'boolean',
+ description:
+ 'Controlled open state. true force-shows, false force-hides, undefined lets hover/focus manage visibility.',
+ },
+ {
+ name: 'isDefaultOpen',
+ type: 'boolean',
+ description: 'Whether the hover card should be shown on mount.',
+ default: 'false',
+ },
+ {
+ name: 'onShow',
+ type: '() => void',
+ description: 'Callback fired when the hover card becomes visible.',
+ },
+ {
+ name: 'onHide',
+ type: '() => void',
+ description: 'Callback fired when the hover card is hidden.',
+ },
],
returns: [
- {name: 'ref', type: 'RefCallback<HTMLElement>', description: 'Combined ref that sets both position and interaction on the same trigger element.'},
- {name: 'positionRef', type: 'RefCallback<HTMLElement>', description: 'Ref for the positioning anchor element. Use when position and interaction live on different elements.'},
- {name: 'interactionRef', type: 'RefCallback<HTMLElement>', description: 'Ref for the hover/focus interaction element. Use with positionRef for split trigger patterns.'},
- {name: 'anchorId', type: 'string', description: 'CSS anchor name for advanced positioning cases.'},
- {name: 'describedBy', type: 'string', description: 'ID to compose into aria-describedby on the trigger.'},
- {name: 'renderHoverCard', type: "(children: ReactNode, props?: Omit<ContextRenderProps, 'positioning'>) => ReactNode", description: 'Render function for the anchor-positioned hover card content. The positioning opt-out is excluded: the hover card always derives its position from placement/alignment.'},
- {name: 'show', type: '() => void', description: 'Imperatively show the hover card immediately.'},
- {name: 'hide', type: '() => void', description: 'Imperatively hide the hover card immediately.'},
+ {
+ name: 'ref',
+ type: 'RefCallback<HTMLElement>',
+ description:
+ 'Combined ref that sets both position and interaction on the same trigger element.',
+ },
+ {
+ name: 'positionRef',
+ type: 'RefCallback<HTMLElement>',
+ description:
+ 'Ref for the positioning anchor element. Use when position and interaction live on different elements.',
+ },
+ {
+ name: 'interactionRef',
+ type: 'RefCallback<HTMLElement>',
+ description:
+ 'Ref for the hover/focus interaction element. Use with positionRef for split trigger patterns.',
+ },
+ {
+ name: 'anchorId',
+ type: 'string',
+ description: 'CSS anchor name for advanced positioning cases.',
+ },
+ {
+ name: 'describedBy',
+ type: 'string',
+ description: 'ID to compose into aria-describedby on the trigger.',
+ },
+ {
+ name: 'renderHoverCard',
+ type: "(children: ReactNode, props?: Omit<ContextRenderProps, 'positioning'>) => ReactNode",
+ description:
+ 'Render function for the anchor-positioned hover card content. The positioning opt-out is excluded: the hover card always derives its position from placement/alignment.',
+ },
+ {
+ name: 'show',
+ type: '() => void',
+ description: 'Imperatively show the hover card immediately.',
+ },
+ {
+ name: 'hide',
+ type: '() => void',
+ description: 'Imperatively hide the hover card immediately.',
+ },
],
usage: {
- description: 'Headless hook for hover-triggered floating cards. Builds on useLayer with hover/focus intent detection, configurable delays, safe hover behavior, and accessible aria-describedby linking. Use for rich previews on hover when you need full control over the trigger or rendered content.',
+ description:
+ 'Headless hook for hover-triggered floating cards. Builds on useLayer with hover/focus intent detection, configurable delays, safe hover behavior, and accessible aria-describedby linking. Use for rich previews on hover when you need full control over the trigger or rendered content.',
bestPractices: [
- {guidance: true, description: 'Use for rich content previews such as user profiles, entity summaries, and link previews.'},
- {guidance: true, description: 'Prefer the HoverCard component for standard trigger-content pairs; use the hook for custom trigger patterns.'},
- {guidance: false, description: 'Use for simple text hints: use Tooltip or useTooltip instead.'},
+ {
+ guidance: true,
+ description:
+ 'Use for rich content previews such as user profiles, entity summaries, and link previews.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Prefer the HoverCard component for standard trigger-content pairs; use the hook for custom trigger patterns.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use for simple text hints: use Tooltip or useTooltip instead.',
+ },
],
},
relatedComponents: ['HoverCard', 'Tooltip', 'Popover'],
@@ -46,17 +168,24 @@ export const docs = {
/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */
export const docsDense = {
- description: 'Headless hover-triggered floating cards. Builds on useLayer w/ hover/focus intent, delays, safe hover behavior, aria-describedby. Use for rich previews when trigger/content rendering needs full control.',
+ description:
+ 'Headless hover-triggered floating cards. Builds on useLayer w/ hover/focus intent, delays, safe hover behavior, aria-describedby. Use for rich previews when trigger/content rendering needs full control.',
paramDescriptions: {
- placement: 'position relative to trigger. logical: start/end follow the popover\'s inherited direction (RTL mirrors).',
- alignment: 'alignment along placement axis. logical: start/end follow the popover\'s inherited direction (RTL mirrors).',
+ placement:
+ "position relative to trigger. logical: start/end follow the popover's inherited direction (RTL mirrors).",
+ alignment:
+ "alignment along placement axis. logical: start/end follow the popover's inherited direction (RTL mirrors).",
delay: 'show delay in ms.',
hideDelay: 'hide delay after mouse/focus leave in ms.',
- focusTrigger: 'when focus opens hover card; auto = naturally focusable elements only.',
- touchTrigger: 'tap behavior with no hover; auto = tap unless trigger acts, tap = always, none = never.',
+ focusTrigger:
+ 'when focus opens hover card; auto = focus on the trigger, or inside a trigger focusable when focus arrives.',
+ touchTrigger:
+ 'tap behavior with no hover; auto = tap unless trigger acts, tap = always, none = never.',
isEnabled: 'whether hover/focus triggers are enabled.',
- label: 'accessible name for popup. with label: named role="dialog"; without: role="group".',
- isOpen: 'controlled open state: true force-show, false force-hide, undefined unmanaged.',
+ label:
+ 'accessible name for popup. with label: named role="dialog"; without: role="group".',
+ isOpen:
+ 'controlled open state: true force-show, false force-hide, undefined unmanaged.',
isDefaultOpen: 'show on mount.',
onShow: 'fires when hover card becomes visible.',
onHide: 'fires when hover card hides.',
@@ -72,11 +201,24 @@ export const docsDense = {
hide: 'hide immediately.',
},
usage: {
- description: 'Headless hover-triggered floating cards. Builds on useLayer w/ hover/focus intent, delays, safe hover behavior, aria-describedby. Use for rich previews when trigger/content rendering needs full control.',
+ description:
+ 'Headless hover-triggered floating cards. Builds on useLayer w/ hover/focus intent, delays, safe hover behavior, aria-describedby. Use for rich previews when trigger/content rendering needs full control.',
bestPractices: [
- {guidance: true, description: 'Use for rich previews: profiles, entity summaries, link previews.'},
- {guidance: true, description: 'Prefer HoverCard for standard trigger-content pairs; use hook for custom trigger patterns.'},
- {guidance: false, description: 'Use for simple text hints: use Tooltip / useTooltip instead.'},
+ {
+ guidance: true,
+ description:
+ 'Use for rich previews: profiles, entity summaries, link previews.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Prefer HoverCard for standard trigger-content pairs; use hook for custom trigger patterns.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use for simple text hints: use Tooltip / useTooltip instead.',
+ },
],
},
};
diff --git a/packages/core/src/HoverCard/useHoverCard.tsx b/packages/core/src/HoverCard/useHoverCard.tsx
index bce45cf4d2..4dbe602f57 100644
--- a/packages/core/src/HoverCard/useHoverCard.tsx
+++ b/packages/core/src/HoverCard/useHoverCard.tsx
@@ -16,9 +16,11 @@ import {
useCallback,
useEffect,
useRef,
+ useState,
type ReactNode,
type RefCallback,
} from 'react';
+import {createTriggerFocusGate} from '../utils/triggerFocus';
import * as stylex from '@stylexjs/stylex';
import {
useLayer,
@@ -60,7 +62,7 @@ const styles = stylex.create({
});
/**
- * Focus trigger behavior for hover cards
+ * When focus on the trigger opens the hover card
*/
export type HoverCardFocusTrigger = 'auto' | 'always' | 'never';
@@ -96,9 +98,10 @@ export interface HoverCardOptions {
/**
* When to trigger on focus:
- * - `auto`: Only if element is naturally focusable
- * - `always`: Always attach focus listeners
- * - `never`: Never attach focus listeners (for composite widgets)
+ * - `auto`: focus on the trigger itself, or within a trigger that is
+ * focusable when focus arrives
+ * - `always`: focus on the trigger or anything inside it
+ * - `never`: never on focus (for composite widgets)
*
* @default 'auto'
*/
@@ -235,29 +238,6 @@ export interface HoverCardReturn {
hide: () => void;
}
-/**
- * Check if an element is naturally focusable
- */
-function isFocusable(element: HTMLElement): boolean {
- // Elements with explicit tabindex
- if (element.hasAttribute('tabindex')) {
- return element.tabIndex >= 0;
- }
-
- // Naturally focusable elements
- const focusableTags = ['A', 'BUTTON', 'INPUT', 'SELECT', 'TEXTAREA'];
- if (focusableTags.includes(element.tagName)) {
- return !(element as HTMLButtonElement).disabled;
- }
-
- // Elements with contenteditable
- if (element.isContentEditable) {
- return true;
- }
-
- return false;
-}
-
/**
* Hook for hover card behavior with hover/focus triggers.
*
@@ -426,27 +406,44 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
[handleTouchPointerDown],
);
- const handleFocusIn = useCallback(() => {
- if (!isEnabled) {
- return;
- }
- // A tap focuses the trigger it activates. Opening on that focus would
- // reinstate exactly the behavior the touch path just decided against —
- // and on an action trigger it covers the thing the user tapped.
- if (isTouchInteraction()) {
- return;
- }
- // Skip showing if we're in the middle of an Escape dismiss
- if (isEscapeDismissingRef.current) {
- isEscapeDismissingRef.current = false;
- return;
- }
- clearTimeouts();
- showLayer();
- }, [isEnabled, isTouchInteraction, clearTimeouts, showLayer]);
+ // Under `auto`, whether focus counts is decided when it arrives, and a
+ // focus that counted still hides on blur (utils/triggerFocus.ts).
+ const [focusGate] = useState(createTriggerFocusGate);
+
+ const handleFocusIn = useCallback(
+ (e: Event) => {
+ if (!focusGate.focusIn(e, focusTrigger) || !isEnabled) {
+ return;
+ }
+ // A tap focuses the trigger it activates. Opening on that focus would
+ // reinstate exactly the behavior the touch path just decided against —
+ // and on an action trigger it covers the thing the user tapped.
+ if (isTouchInteraction()) {
+ return;
+ }
+ // Skip showing if we're in the middle of an Escape dismiss
+ if (isEscapeDismissingRef.current) {
+ isEscapeDismissingRef.current = false;
+ return;
+ }
+ clearTimeouts();
+ showLayer();
+ },
+ [
+ focusGate,
+ focusTrigger,
+ isEnabled,
+ isTouchInteraction,
+ clearTimeouts,
+ showLayer,
+ ],
+ );
const handleFocusOut = useCallback(
(e: FocusEvent) => {
+ if (!focusGate.focusOut(e, focusTrigger)) {
+ return;
+ }
// Check if focus is moving to the hover card content
const relatedTarget = e.relatedTarget as HTMLElement | null;
const popoverElement = document.getElementById(layerId);
@@ -458,7 +455,7 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
scheduleHide();
},
- [layerId, scheduleHide],
+ [focusGate, focusTrigger, layerId, scheduleHide],
);
// Escape dismissal (WCAG 1.4.13) goes through the shared layer stack: a
@@ -558,12 +555,9 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
el.addEventListener('mouseleave', handleMouseLeave);
el.addEventListener('pointerdown', handlePointerDown);
- // Attach focus listeners based on focusTrigger option
- const shouldAttachFocus =
- focusTrigger === 'always' ||
- (focusTrigger === 'auto' && isFocusable(el));
-
- if (shouldAttachFocus) {
+ // Focus listeners unless focus never opens the card; `auto` decides
+ // per event (utils/triggerFocus.ts).
+ if (focusTrigger !== 'never') {
el.addEventListener('focusin', handleFocusIn);
el.addEventListener('focusout', handleFocusOut as EventListener);
}
diff --git a/packages/core/src/Tooltip/useTooltip.tsx b/packages/core/src/Tooltip/useTooltip.tsx
index 75879b95ef..002bf897da 100644
--- a/packages/core/src/Tooltip/useTooltip.tsx
+++ b/packages/core/src/Tooltip/useTooltip.tsx
@@ -18,9 +18,11 @@ import {
useCallback,
useEffect,
useRef,
+ useState,
type ReactNode,
type RefCallback,
} from 'react';
+import {createTriggerFocusGate} from '../utils/triggerFocus';
import * as stylex from '@stylexjs/stylex';
import {
useLayerInternal,
@@ -238,29 +240,6 @@ export interface TooltipReturn {
hide: () => void;
}
-/**
- * Check if an element is naturally focusable
- */
-function isFocusable(element: HTMLElement): boolean {
- // Elements with explicit tabindex
- if (element.hasAttribute('tabindex')) {
- return element.tabIndex >= 0;
- }
-
- // Naturally focusable elements
- const focusableTags = ['A', 'BUTTON', 'INPUT', 'SELECT', 'TEXTAREA'];
- if (focusableTags.includes(element.tagName)) {
- return !(element as HTMLButtonElement).disabled;
- }
-
- // Elements with contenteditable
- if (element.isContentEditable) {
- return true;
- }
-
- return false;
-}
-
/**
* Hook for tooltip behavior with hover/focus triggers.
*
@@ -508,32 +487,13 @@ export function useTooltipWithTriggerBehavior(
[isTouchPointerRef, layerId, scheduleHide],
);
- // Under `auto`, whether focus counts is decided when it arrives, not when
- // the listeners attach: a roving-tabindex member that was `tabindex="-1"`
- // then can be the tab stop now. A trigger that receives focus is focusable
- // by definition; focus inside it counts only while the trigger is
- // focusable too, so a plain wrapper still ignores its children's focus.
- const isFocusForTrigger = useCallback(
- (e: Event): boolean => {
- if (focusTrigger === 'always') {
- return true;
- }
- const triggerEl = e.currentTarget as HTMLElement | null;
- return (
- triggerEl != null && (e.target === triggerEl || isFocusable(triggerEl))
- );
- },
- [focusTrigger],
- );
-
- // Whether the trigger's current focus counted when it arrived, so its blur
- // hides the tooltip even if the trigger has since left the tab order.
- const focusCountedRef = useRef(false);
+ // Under `auto`, whether focus counts is decided when it arrives, and a
+ // focus that counted still hides on blur (utils/triggerFocus.ts).
+ const [focusGate] = useState(createTriggerFocusGate);
const handleFocusIn = useCallback(
(e: Event) => {
- focusCountedRef.current = isFocusForTrigger(e);
- if (!isEnabled || !focusCountedRef.current) {
+ if (!focusGate.focusIn(e, focusTrigger) || !isEnabled) {
return;
}
// A tap focuses the trigger it activates, and `:focus-visible` does not
@@ -554,8 +514,9 @@ export function useTooltipWithTriggerBehavior(
showLayer();
},
[
+ focusGate,
+ focusTrigger,
isEnabled,
- isFocusForTrigger,
isTouchInteraction,
clearTimeouts,
showLayer,
@@ -567,13 +528,12 @@ export function useTooltipWithTriggerBehavior(
// which a held tooltip skips.
const handleFocusOut = useCallback(
(e: Event) => {
- if (!focusCountedRef.current && !isFocusForTrigger(e)) {
+ if (!focusGate.focusOut(e, focusTrigger)) {
return;
}
- focusCountedRef.current = false;
scheduleHide();
},
- [isFocusForTrigger, scheduleHide],
+ [focusGate, focusTrigger, scheduleHide],
);
// Pressing the trigger hides its own tooltip: once the control is activated
@@ -640,7 +600,7 @@ export function useTooltipWithTriggerBehavior(
el.addEventListener('pointerdown', handlePointerDown);
// Focus listeners unless focus never opens the tooltip; `auto` decides
- // per event (isFocusForTrigger).
+ // per event (utils/triggerFocus.ts).
if (focusTrigger !== 'never') {
el.addEventListener('focusin', handleFocusIn);
el.addEventListener('focusout', handleFocusOut);
diff --git a/packages/core/src/utils/triggerFocus.ts b/packages/core/src/utils/triggerFocus.ts
new file mode 100644
index 0000000000..6676f45ea7
--- /dev/null
+++ b/packages/core/src/utils/triggerFocus.ts
@@ -0,0 +1,80 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file triggerFocus.ts
+ * @input A focus event on a hover-layer trigger and its focusTrigger value
+ * @output Whether that focus counts as focus on the trigger, and a gate that
+ * remembers it for the matching blur
+ * @position Shared focus-trigger judgement for Tooltip and HoverCard
+ */
+
+/** When focus on a trigger opens its layer. */
+export type TriggerFocusMode = 'auto' | 'always' | 'never';
+
+/** Whether `element` is in the tab order or naturally focusable. */
+export function isFocusableTrigger(element: HTMLElement): boolean {
+ if (element.hasAttribute('tabindex')) {
+ return element.tabIndex >= 0;
+ }
+ const focusableTags = ['A', 'BUTTON', 'INPUT', 'SELECT', 'TEXTAREA'];
+ if (focusableTags.includes(element.tagName)) {
+ return !(element as HTMLButtonElement).disabled;
+ }
+ return element.isContentEditable;
+}
+
+/**
+ * Whether a focus event on a trigger (its `currentTarget`) counts as focus on
+ * the trigger.
+ *
+ * Under `auto` it is decided when focus arrives, not when listeners attach: a
+ * roving-tabindex member that was `tabindex="-1"` then can be the tab stop
+ * now. A trigger that receives focus is focusable by definition, which covers
+ * focusable elements this check does not list, such as a `<summary>` or an SVG
+ * link. Focus inside the trigger counts only while the trigger is focusable
+ * too, so a plain wrapper ignores its children's focus.
+ */
+export function isFocusForTrigger(
+ event: Event,
+ mode: TriggerFocusMode,
+): boolean {
+ if (mode === 'always') {
+ return true;
+ }
+ if (mode === 'never') {
+ return false;
+ }
+ const trigger = event.currentTarget as HTMLElement | null;
+ return (
+ trigger != null && (event.target === trigger || isFocusableTrigger(trigger))
+ );
+}
+
+/** Remembers whether a trigger's current focus counted when it arrived. */
+export interface TriggerFocusGate {
+ /** On focusin: whether this focus opens the layer. */
+ focusIn(event: Event, mode: TriggerFocusMode): boolean;
+ /**
+ * On focusout: whether this blur closes the layer. A focus that counted
+ * closes on blur even if the trigger has since left the tab order.
+ */
+ focusOut(event: Event, mode: TriggerFocusMode): boolean;
+}
+
+/** A gate for one trigger; each hook keeps one for its lifetime. */
+export function createTriggerFocusGate(): TriggerFocusGate {
+ let isCounted = false;
+ return {
+ focusIn(event, mode) {
+ isCounted = isFocusForTrigger(event, mode);
+ return isCounted;
+ },
+ focusOut(event, mode) {
+ if (!isCounted && !isFocusForTrigger(event, mode)) {
+ return false;
+ }
+ isCounted = false;
+ return true;
+ },
+ };
+}