An open source design system that's fully customizable and agent ready
TypeScript
fix(Tooltip): under focusTrigger="auto", decide when focus arrives whether it opens the tooltip (#9366)
Cindy Zhangcdab2e6ebbf4
diff --git a/.changeset/tooltip-auto-focus-when-focused.md b/.changeset/tooltip-auto-focus-when-focused.mdnew file mode 100644index 0000000000..057dee7d10--- /dev/null+++ b/.changeset/tooltip-auto-focus-when-focused.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Tooltip: under the default `focusTrigger="auto"`, keyboard focus opens the tooltip of a trigger that was out of the tab order when the tooltip attached. A Button or IconButton in a Toolbar or ButtonGroup whose `tooltip` was set after mount, or any roving-tabindex member rendered with `tabindex="-1"`, now shows its tooltip when the arrow keys reach it. Whether focus counts is decided when it arrives, so a focusable trigger the old check missed, such as a `<summary>`, opens too. Focus inside a trigger that is not focusable still does not open it.++@cixzhangdiff --git a/docs/specs/components/Tooltip/Tooltip.spec.md b/docs/specs/components/Tooltip/Tooltip.spec.mdindex cb705452a8..c5aadb3d32 100644--- a/docs/specs/components/Tooltip/Tooltip.spec.md+++ b/docs/specs/components/Tooltip/Tooltip.spec.md@@ -46,7 +46,7 @@ system_specs: [spec:AST-003, spec:AST-017]| Behavior | A `role="tooltip"` layer that describes its trigger. It opens on hover after `delay`, on keyboard focus, and on a qualifying tap; it stays open while the pointer moves onto it, and closes on leave, Escape, or pressing the trigger (a press that focuses a text field reopens it). With `triggerBehavior="hover"`, no touch or pen tap opens it. With `triggerBehavior="toggle"`, hover and focus preview it, and a click, tap, Enter, or Space on a button trigger pins it open until Escape, a second press, a press outside, or focus leaving. || End-user impact | Mouse, keyboard, and touch users can each reveal the hint, move onto it, and dismiss it; screen-reader users hear it as the trigger's description. With the toggle, people on touch, keyboard, or a screen reader can keep it open to read it, and hear it once when it pins. || Builder impact | A trigger whose information lives only in the tooltip passes `triggerBehavior="toggle"` and a button trigger (DEC-1). `touchTrigger="tap"` callers migrate by trigger kind: the deprecating release's codemod rewrites icon and span triggers and reports the rest (DEP-0016), and CLN-0024 names each remaining kind's replacement at the next minor. |-| Compatibility/readiness | Additive `triggerBehavior`, default `adaptive`, the released behavior; `touchTrigger="tap"` deprecated (DEP-0016); `touchTrigger` is removed at the next minor, `triggerBehavior="adaptive"` keeping its `auto` behavior and `triggerBehavior="hover"` its `none` behavior (CLN-0024). FR9, FR10, and AR6 are not yet built; ten further implementation gaps (see Current-state impact). |+| Compatibility/readiness | Additive `triggerBehavior`, default `adaptive`, the released behavior; `touchTrigger="tap"` deprecated (DEP-0016); `touchTrigger` is removed at the next minor, `triggerBehavior="adaptive"` keeping its `auto` behavior and `triggerBehavior="hover"` its `none` behavior (CLN-0024). FR9, FR10, and AR6 are not yet built; nine further implementation gaps (see Current-state impact). || Review checks | Reject a tooltip that cannot be hovered or dismissed (WCAG 1.4.13), one that opens on a tap's focus or on pointer focus of a trigger that is not a text field, a lost `aria-describedby` link, a pinned tooltip that closes on pointer leave or lets Escape pass to the layer beneath, a toggle without `aria-expanded`, or a non-button toggle trigger without the development warning. || Governing rules | WCAG 1.4.13, 2.1.1; `family:overlay-dismissal`; `spec:AST-003` FR4; `spec:AST-017` (deprecation); `architecture:public-component-api` INV9, INV21; `architecture:layer-runtime`; `architecture:interaction-modality`; `architecture:component-theming-surface`. |@@ -147,15 +147,6 @@ Consumer migration instructions belong in consumer docs and release notes.its own show and hide timers, without the recognizer's intent group thatshows the next trigger at once. `architecture:interaction-modality` INV11 has`useTooltip` take its hover timing from the shared hover recognizer.-- **A roving trigger may not open on focus.** Under `focusTrigger="auto"` the- tooltip reads the tab order only when it attaches the trigger's listeners, so- a roving toolbar button or menu item rendered with `tabindex="-1"` shows its- tooltip only on mouse hover after it takes keyboard focus, until a change to- `focusTrigger`, `isEnabled`, `isOpen`, `delay`, `hideDelay`, or- `onOpenChange` 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.- **A changed trigger loses its wiring.** The tooltip wires its trigger onlywhen the trigger's listeners attach, which repeats only when `focusTrigger`,`isEnabled`, `isOpen`, `delay`, `hideDelay`, or `onOpenChange` changes. Until@@ -200,7 +191,7 @@ 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 || ---------------- | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------- | ------------------- | ------------------------------------------------------------------------- | -------------------------------- |-| Focus trigger | `auto`, `always`, `never` | Whether keyboard focus opens the tooltip: on focusable triggers (FR4's gap), always, or never. | Every trigger mode. | `auto` | `component:Tooltip` | Stable | TypeScript rejects other values. |+| Focus trigger | `auto`, `always`, `never` | Whether keyboard focus opens the tooltip: on focusable triggers, judged when focus arrives (FR4), always, or never. | Every trigger mode. | `auto` | `component:Tooltip` | Stable | TypeScript rejects other values. || Trigger behavior | `adaptive`, `hover`, `toggle` | How the trigger opens the tooltip; under every value, hover on a fine pointer and keyboard focus preview it (FR3, FR4). Under `adaptive`, a tap opens it unless the tap already acts (FR5, DEC-1), and no press pins it; under `hover`, no touch or pen tap opens it, and no press pins it; under `toggle`, a click, a completed tap, Enter, or Space pins it, and the same press on a pinned tooltip closes it (FR9). | Every trigger; `toggle` pins only on a button or own-text trigger, and any other trigger keeps tap-only opening (FR9). | `adaptive` | `component:Tooltip` | Stable | TypeScript rejects other values. || Touch trigger | `auto`, `tap`, `none` | Whether a tap opens it under `triggerBehavior="adaptive"`: unless the tap already acts, as the innermost control around the tapped element decides (DEC-1); always; or never. Ignored under `triggerBehavior="hover"` and `"toggle"`. | Touch and pen without hover. | `auto` | `component:Tooltip` | Stable; `tap` deprecated (DEP-0016); removed at the next minor (CLN-0024) | TypeScript rejects other values. |@@ -211,7 +202,7 @@ Consumer migration instructions belong in consumer docs and release notes.| FR1 | The rendered tooltip contains one owned surface, `role="tooltip"`, carrying the `tooltip` target, at most 300 px wide, with the supplied `content` inside; content has no separate target and there is no arrow. | Current source, docs, 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; `anchorRef` attaches to that element. The trigger's `aria-describedby` gains the tooltip id, merged with and later restored to any existing value. Implementation gap: the wiring runs only when the trigger's listeners attach, so a trigger element replaced after mount, or a trigger whose own `aria-describedby` changes, loses it until a re-render re-attaches them (Current-state impact). | Current source and tests || FR3 | On a hover-capable pointer, entering the trigger opens after `delay` ms; leaving closes after `hideDelay` ms. With `hideDelay` 0 a short bridge lets the pointer move onto the surface without closing it, and the surface stays open while hovered. | WCAG 1.4.13; tests |-| FR4 | Focus that matches `:focus-visible` opens the tooltip per `focusTrigger`: keyboard focus, programmatic focus that follows keyboard input (AR4), pointer focus on a text-entry trigger, which browsers mark focus-visible, and programmatic focus on a text-entry trigger unless a finger or pen pressed that trigger and the last input was a pointer press, and on any other trigger unless the last input was a pointer (after keyboard input, as in AR4, or before any input). Implementation gap: script focus after a pointer press that focused nothing opens it, because the hook reads `:focus-visible` alone (Current-state impact). Focus a tap leaves behind, and other pointer focus, does not. Focus leaving the trigger schedules the hide as a pointer leave does. Under `focusTrigger="auto"`, focus opens the tooltip on any focusable trigger. Implementation gap: `auto` recognizes only an explicit non-negative `tabindex`, HTML links, buttons, form fields, and editable elements, so a `<summary>` or an SVG link never opens on keyboard focus; and it reads the tab order only when it attaches the trigger's listeners, on mount and again when `focusTrigger`, `isEnabled`, `isOpen`, `delay`, `hideDelay`, or `onOpenChange` changes, 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). | Current source and tests |+| FR4 | Focus that matches `:focus-visible` opens the tooltip per `focusTrigger`: keyboard focus, programmatic focus that follows keyboard input (AR4), pointer focus on a text-entry trigger, which browsers mark focus-visible, and programmatic focus on a text-entry trigger unless a finger or pen pressed that trigger and the last input was a pointer press, and on any other trigger unless the last input was a pointer (after keyboard input, as in AR4, or before any input). Implementation gap: script focus after a pointer press that focused nothing opens it, because the hook reads `:focus-visible` alone (Current-state impact). Focus a tap leaves behind, and other pointer focus, does not. Focus leaving the trigger schedules the hide as a pointer leave does. Under `focusTrigger="auto"`, focus opens the tooltip on any focusable trigger, judged when focus arrives. | Current source and tests || FR5 | On touch and pen, a completed tap opens per `triggerBehavior` when the finger lifts; a touch that becomes a scroll, or a press the browser does not count as a tap, does not open it. Under `adaptive`, a tap that already acts leaves it shut: walking out from the tapped element, the trigger included, the innermost button, link, label, form control, option, menu item, or row or card made clickable with `useClickableContainer` decides, and 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 even inside a clickable row or card (DEC-1). Until CLN-0024 removes `touchTrigger`, an explicit `touchTrigger` decides instead under `adaptive`: `tap` opens on every tap and `none` on no tap. Implementation gap: the walk ships with CLN-0024 in the next minor; until then `adaptive`, like the shipped `touchTrigger="auto"`, asks only whether the trigger itself performs an action, apart from a disabled control (Compatibility and migration). A second tap on the trigger, a tap outside, or a scroll starting outside closes it. Under `hover`, no tap opens it. Under `toggle`, FR9 decides what a tap does. `hover` and `toggle` ignore `touchTrigger`. | Current source and tests || FR6 | Escape closes a visible tooltip; Escape during text composition is ignored. Escape routing follows `family:overlay-dismissal`: a visible topmost tooltip in the page handles that Escape, so a layer underneath stays open for that press. Implementation gap: a tooltip 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). `spec:AST-003` FR4, accepted and not yet implemented, makes an unpinned tooltip passive and gives a pinned one Escape first (Current-state impact). Outside `triggerBehavior="toggle"`, pressing an uncontrolled tooltip's trigger closes it; a press that focuses a text-entry trigger reopens it through FR4. | WCAG 1.4.13; tests || FR7 | `isOpen` forces the tooltip shown or hidden, and `isOpen={true}` suppresses hover and focus hiding; a controlled tooltip answers Escape by calling `onOpenChange(false)` without hiding, and is not closed by pressing the trigger. `isDefaultOpen` opens it on mount, still dismissible. Implementation gap: with `isOpen={false}`, any focus FR4 opens on, keyboard focus or a click into a text-field trigger, still opens the tooltip and reports `onOpenChange(true)`, and Escape then only reports `onOpenChange(false)`, so it stays until focus or the pointer leaves the trigger or the tooltip, or the caller re-renders with a new `onOpenChange` (Current-state impact). `isEnabled={false}` disables triggers and drops a pending open. | Current source and tests |@@ -298,7 +289,7 @@ has no arrow element.| Contract | Verification | Representative states | Mutation or failure expectation | Audit section || ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- || FR1 | `Tooltip.test.tsx` role/content suite | Rendered surface and supplied content | Removing the surface or content fails existing tooltip role and text assertions. | `audit:Tooltip/anatomy` |-| FR2–FR8 | `Tooltip.test.tsx`; `useTooltip.test.tsx` | Hover, focus, tap, Escape, controlled, default open | Wrong open or close for an input fails. | `audit:Tooltip/behavior` |+| FR2–FR8 | `Tooltip.test.tsx`; `useTooltip.test.tsx` | Hover, focus, tap, Escape, controlled, default open; `auto` judged when focus arrives (roving member, `<summary>`, non-focusable wrapper) | Wrong open or close for an input fails. | `audit:Tooltip/behavior` || AR1–AR4 | `Tooltip.a11y.test.tsx`; `Tooltip.a11y.chromium.spec.ts`; `TooltipHoverBridge.a11y.chromium.spec.ts`; `TooltipFocusReturn.a11y.chromium.spec.ts` | Real-browser hover bridge and focus return | A tooltip that vanishes on the way to it or strands focus fails. | `audit:Tooltip/accessibility` || AR5 | `Tooltip.a11y.test.tsx`; `Tooltip.a11y.chromium.spec.ts` | Wrapped, text, anchor, and hook triggers | A lost role, description, keyboard-focus show, or Escape dismissal fails; focus-leave hide, hover show, and leave hide run as advisory rows (Current-state impact). | `audit:Tooltip/accessibility` || FR5 | `Tooltip.test.tsx` touch suite; `TouchTrigger.a11y.chromium.spec.ts`; `useTouchTrigger.test.ts` and `touchTriggerTargets.test.tsx` disabled-control cases, with tap-destination cases an evidence gap until built | Tap open, scroll, second tap, tap outside; a trigger inside a link, a clickable row, or a clickable card; a trigger in running text; a disabled control inside a clickable row | A tap that fails to open or close as stated, opens the tooltip on a tap that already acts, or leaves a disabled control's reason shut fails. | `audit:Tooltip/behavior` |@@ -317,7 +308,7 @@ Read from source, with no focused test yet:- FR7: `isOpen={true}` suppressing focus hiding.- FR1: the 300 px maximum width, the `tooltip` target, and the absence of anarrow.-- FR4: `focusTrigger="always"`, `"never"`, and when `"auto"` reads the tab order,+- FR4: `focusTrigger="always"` and `"never"`,programmatic focus on a text-entry trigger after pointer input opening it,and not after a finger or pen pressed it when the last input was a pointer press, pointer focus on a text fieldopening the tooltip, programmatic focus before any input, or after a pointer press onto a trigger that is not a text field, other pointer focus not opening it, and focus leaving the triggerdiff --git a/packages/core/src/Tooltip/Tooltip.test.tsx b/packages/core/src/Tooltip/Tooltip.test.tsxindex b5e3e3cb11..0efcb6bb7f 100644--- a/packages/core/src/Tooltip/Tooltip.test.tsx+++ b/packages/core/src/Tooltip/Tooltip.test.tsx@@ -32,6 +32,10 @@ import {Item} from '../Item/Item';import {Token} from '../Token/Token';import {useTooltip} from './useTooltip';import {__resetInteractionModalityForTest} from '../utils/interactionModality';+import userEvent from '@testing-library/user-event';+import {IconButton} from '../IconButton/IconButton';+import {Toolbar} from '../Toolbar/Toolbar';+import {TestIcon} from '../__tests__/TestIcon';// Store original matches to restore laterconst originalMatches = HTMLElement.prototype.matches;@@ -821,6 +825,55 @@ describe('Tooltip sibling mode (anchorRef)', () => {});});+describe('Tooltip in a roving Toolbar (focusTrigger="auto")', () => {+ it('opens on arrow-key focus for a member whose tooltip was added after mount', async () => {+ const user = userEvent.setup();+ function FormatToolbar({hasHints}: {hasHints: boolean}) {+ return (+ <Toolbar+ label="Format"+ startContent={+ <>+ <IconButton+ label="Copy"+ icon={<TestIcon />}+ tooltip="Copy"+ onClick={() => {}}+ />+ <IconButton+ label="Filter"+ icon={<TestIcon />}+ tooltip={hasHints ? 'Filter (F)' : undefined}+ onClick={() => {}}+ />+ </>+ }+ />+ );+ }+ const {rerender} = render(<FormatToolbar hasHints={false} />);+ rerender(<FormatToolbar hasHints />);+ const filter = screen.getByRole('button', {name: 'Filter'});+ const realMatches = filter.matches.bind(filter);+ vi.spyOn(filter, 'matches').mockImplementation((selector: string) =>+ selector === ':focus-visible' ? true : realMatches(selector),+ );++ screen.getByRole('button', {name: 'Copy'}).focus();+ await user.keyboard('{ArrowRight}');+ expect(filter).toHaveFocus();+ const describedBy = filter.getAttribute('aria-describedby') ?? '';+ await waitFor(() => {+ const layer = describedBy+ .split(' ')+ .map(id => document.getElementById(id))+ .find(element => element?.textContent === 'Filter (F)');+ expect(layer).toBeDefined();+ expect(layer?.matches(':popover-open')).toBe(true);+ });+ });+});+// FR11: a press inside an open tooltip acts only within the tooltip.describe('Tooltip surface press', () => {it('keeps a click on the tooltip text from activating a clickable card', () => {diff --git a/packages/core/src/Tooltip/Tooltip.tsx b/packages/core/src/Tooltip/Tooltip.tsxindex 867772d02a..c63cac264d 100644--- a/packages/core/src/Tooltip/Tooltip.tsx+++ b/packages/core/src/Tooltip/Tooltip.tsx@@ -95,9 +95,10 @@ export interface TooltipProps {/*** 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/Tooltip/useTooltip.doc.mjs b/packages/core/src/Tooltip/useTooltip.doc.mjsindex 355149437a..d1686ef659 100644--- a/packages/core/src/Tooltip/useTooltip.doc.mjs+++ b/packages/core/src/Tooltip/useTooltip.doc.mjs@@ -11,7 +11,7 @@ export const docs = {{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 on hover, in milliseconds.', default: '200'},{name: 'hideDelay', type: 'number', description: 'Delay before hiding after mouse or focus leaves, in milliseconds.', default: '0'},- {name: 'focusTrigger', type: "'auto' | 'always' | 'never'", description: 'When focus should open the tooltip. auto only attaches focus listeners to naturally focusable elements.', default: "'auto'"},+ {name: 'focusTrigger', type: "'auto' | 'always' | 'never'", description: 'When focus should open the tooltip. 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 (an info icon rendered as a button); none never opens on touch.', default: "'auto'"},{name: 'isEnabled', type: 'boolean', description: 'Whether hover and focus triggers are enabled.', default: 'true'},{name: 'isOpen', type: 'boolean', description: 'Controlled open state. true force-shows, false force-hides, undefined lets hover/focus manage visibility.'},@@ -49,7 +49,7 @@ export const docsDense = {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 tooltip; auto = naturally focusable elements only.',+ focusTrigger: 'when focus opens tooltip; 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.',isOpen: 'controlled open state: true force-show, false force-hide, undefined unmanaged.',diff --git a/packages/core/src/Tooltip/useTooltip.test.tsx b/packages/core/src/Tooltip/useTooltip.test.tsxindex 292f64424d..16d97f3384 100644--- a/packages/core/src/Tooltip/useTooltip.test.tsx+++ b/packages/core/src/Tooltip/useTooltip.test.tsx@@ -481,3 +481,117 @@ describe('useTooltip — focus returning from a popover the keyboard closed', ()expect(tooltipElement().matches(':popover-open')).toBe(true);});});++describe('useTooltip — focusTrigger="auto" decides when focus arrives', () => {+ /** jsdom does not match `:focus-visible`; stand it up for keyboard focus. */+ function asKeyboardFocus(element: HTMLElement) {+ const realMatches = element.matches.bind(element);+ vi.spyOn(element, 'matches').mockImplementation((selector: string) =>+ selector === ':focus-visible' ? true : realMatches(selector),+ );+ }++ function RovingMember({onShow}: {onShow: () => void}) {+ const tooltip = useTooltip({onShow, delay: 0});+ return (+ <div>+ {/* A roving-tabindex member that is not the tab stop when the+ tooltip attaches. */}+ <button type="button" tabIndex={-1} ref={tooltip.ref}>+ Filter+ </button>+ {tooltip.renderTooltip('Filter (F)')}+ </div>+ );+ }++ it('opens on keyboard focus of a trigger that was tabindex="-1" when it attached', () => {+ const onShow = vi.fn();+ render(<RovingMember onShow={onShow} />);+ const member = screen.getByRole('button', {name: 'Filter'});+ asKeyboardFocus(member);+ // The roving hook moves the tab stop, then focus, as an arrow key does.+ member.setAttribute('tabindex', '0');+ fireEvent.focusIn(member);+ tick(0);+ expect(onShow).toHaveBeenCalledTimes(1);+ });++ it('opens on keyboard focus of a focusable trigger it does not list, such as a summary', () => {+ const onShow = vi.fn();+ function SummaryTrigger() {+ const tooltip = useTooltip({onShow, delay: 0});+ return (+ <details>+ <summary ref={tooltip.ref}>More</summary>+ {tooltip.renderTooltip('Show details')}+ </details>+ );+ }+ render(<SummaryTrigger />);+ const summary = screen.getByText('More');+ asKeyboardFocus(summary);+ fireEvent.focusIn(summary);+ tick(0);+ expect(onShow).toHaveBeenCalledTimes(1);+ });++ function WrapperTrigger(options: TooltipOptions) {+ const tooltip = useTooltip({delay: 0, ...options});+ return (+ <div>+ <div ref={tooltip.ref} data-testid="wrapper">+ <input aria-label="Amount" />+ </div>+ {tooltip.renderTooltip('About amounts')}+ </div>+ );+ }++ it('still ignores focus inside a trigger that is not focusable', () => {+ const onShow = vi.fn();+ render(<WrapperTrigger onShow={onShow} />);+ const input = screen.getByLabelText('Amount');+ asKeyboardFocus(input);+ fireEvent.focusIn(input);+ tick(0);+ expect(onShow).not.toHaveBeenCalled();+ });++ it('hides when focus that counted leaves, even after the trigger left the tab order', () => {+ const onShow = vi.fn();+ const onHide = vi.fn();+ function FocusableContainer() {+ const tooltip = useTooltip({onShow, onHide, delay: 0});+ return (+ <div>+ <div ref={tooltip.ref} tabIndex={0} data-testid="container">+ <button type="button">Inside</button>+ </div>+ {tooltip.renderTooltip('About the group')}+ </div>+ );+ }+ render(<FocusableContainer />);+ const inside = screen.getByRole('button', {name: 'Inside'});+ asKeyboardFocus(inside);+ fireEvent.focusIn(inside);+ tick(0);+ expect(onShow).toHaveBeenCalledTimes(1);+ // A roving hook resets the container's tab stop before moving focus on.+ screen.getByTestId('container').setAttribute('tabindex', '-1');+ fireEvent.focusOut(inside);+ tick(100);+ expect(onHide).toHaveBeenCalledTimes(1);+ });++ it('does not hide a hover-opened tooltip when focus leaves a child of a non-focusable trigger', () => {+ const onHide = vi.fn();+ render(<WrapperTrigger onHide={onHide} />);+ fireEvent.mouseEnter(screen.getByTestId('wrapper'));+ tick(0);+ fireEvent.focusOut(screen.getByLabelText('Amount'));+ tick(100);+ expect(onHide).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/src/Tooltip/useTooltip.tsx b/packages/core/src/Tooltip/useTooltip.tsxindex 9c272eade4..b9c8da0964 100644--- a/packages/core/src/Tooltip/useTooltip.tsx+++ b/packages/core/src/Tooltip/useTooltip.tsx@@ -110,9 +110,10 @@ export interface TooltipOptions {/*** 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'*/@@ -427,9 +428,32 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {[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);+const handleFocusIn = useCallback((e: Event) => {- if (!isEnabled) {+ focusCountedRef.current = isFocusForTrigger(e);+ if (!isEnabled || !focusCountedRef.current) {return;}// A tap focuses the trigger it activates, and `:focus-visible` does not@@ -449,12 +473,25 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {clearTimeouts();showLayer();},- [isEnabled, isTouchInteraction, clearTimeouts, showLayer],+ [+ isEnabled,+ isFocusForTrigger,+ isTouchInteraction,+ clearTimeouts,+ showLayer,+ ],);- const handleFocusOut = useCallback(() => {- scheduleHide();- }, [scheduleHide]);+ const handleFocusOut = useCallback(+ (e: Event) => {+ if (!focusCountedRef.current && !isFocusForTrigger(e)) {+ return;+ }+ focusCountedRef.current = false;+ scheduleHide();+ },+ [isFocusForTrigger, scheduleHide],+ );// Pressing the trigger hides its own tooltip: once the control is activated// the hint has served its purpose, and a tooltip lingering over a@@ -506,12 +543,9 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {// Press-to-dismiss on a mouse; tap-to-open on a touch pointer.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 tooltip; `auto` decides+ // per event (isFocusForTrigger).+ if (focusTrigger !== 'never') {el.addEventListener('focusin', handleFocusIn);el.addEventListener('focusout', handleFocusOut);}