An open source design system that's fully customizable and agent ready
TypeScript
fix(DropdownMenu): prevent stale trigger tooltips after selection (#9280)
zakelstorm5083ead486b6
diff --git a/.changeset/dropdownmenu-trigger-tooltips-stay-closed-after--sfj6.md b/.changeset/dropdownmenu-trigger-tooltips-stay-closed-after--sfj6.mdnew file mode 100644index 0000000000..d90a098731--- /dev/null+++ b/.changeset/dropdownmenu-trigger-tooltips-stay-closed-after--sfj6.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] DropdownMenu trigger tooltips stay closed after pointer selection and still reappear for returning keyboard focus.+@korkt-kimdiff --git a/apps/storybook/stories/DropdownMenu.stories.tsx b/apps/storybook/stories/DropdownMenu.stories.tsxindex 93639a6f58..eea4e271ac 100644--- a/apps/storybook/stories/DropdownMenu.stories.tsx+++ b/apps/storybook/stories/DropdownMenu.stories.tsx@@ -14,6 +14,7 @@ import {DropdownMenuRadioGroup,DropdownMenuRadioItem,DropdownMenuSubMenu,+ type DropdownMenuProps,} from '@astryxdesign/core/DropdownMenu';import {Button} from '@astryxdesign/core/Button';import {RadioList, RadioListItem} from '@astryxdesign/core/RadioList';@@ -81,6 +82,8 @@ const meta: Meta<typeof DropdownMenu> = {export default meta;type Story = StoryObj<typeof DropdownMenu>;+// Story args the tooltip regression spec drives through the URL.+type StoryArgs = Omit<DropdownMenuProps, 'items' | 'children'>;const readinessStyles = stylex.create({viewportStoryCanvas: {@@ -159,9 +162,10 @@ const PROJECT_DESTINATIONS = [// Basic usageexport const Default: Story = {- render: () => (+ render: (args: StoryArgs) => (<DropdownMenubutton={{label: 'Actions'}}+ {...args}items={[{label: 'Edit', onClick: () => console.log('Edit clicked')},{label: 'Duplicate', onClick: () => console.log('Duplicate clicked')},@@ -561,8 +565,8 @@ export const NoChevron: Story = {// Compound-component mode — JSX children with interactive itemsexport const CompoundBasic: Story = {- render: () => (- <DropdownMenu button={{label: 'Actions'}}>+ render: ({presentation: _, ...args}: StoryArgs) => (+ <DropdownMenu button={{label: 'Actions'}} {...args}><DropdownMenuItemicon={PencilIcon}label="Edit"diff --git a/docs/specs/components/DropdownMenu/DropdownMenu.spec.md b/docs/specs/components/DropdownMenu/DropdownMenu.spec.mdindex af6e74684e..ab7937b298 100644--- a/docs/specs/components/DropdownMenu/DropdownMenu.spec.md+++ b/docs/specs/components/DropdownMenu/DropdownMenu.spec.md@@ -126,7 +126,7 @@ component-local concepts; each keeps its released default.| FR3 | Button owns the Trigger button, BottomSheet owns the Touch sheet frame, List owns the Touch action list and Touch action rows, Indicator owns checkbox chrome, and Icon owns ordinary rendered icons. The Trigger button carries `component:Button`'s gaps: its press scale applies under reduced motion (`design:reduced-motion` DR1) and its height is fixed (`spec:AST-102` FR4). | Current source and owner docs; `design:reduced-motion` DR1; `spec:AST-102` FR4 || FR4 | The same `dropdown-menu` target reaches the alternative Pointer menu surface and Touch menu surface. Pointer action rows carry `dropdown-menu-item`; touch action rows instead use List's `list-item` target. | Current source and tests || FR5 | Both menu surfaces carry `data-astryx-menu-press` and follow `module:DropdownMenu/useMenuPress` FR1–FR7, FR10, and FR11: the row under the release acts, the highlight follows a held pointer, a mouse released outside closes and a finger leaves the menu open, the browser's stray click never acts, and the Pointer menu surface declares `touch-action` by overflow. The grow, collapse, and pan dismissal under a finger are FR21. | `module:DropdownMenu/useMenuPress`; `spec:AST-094` FR26–FR28 |-| FR6 | When the pointer menu closes, focus returns to the Trigger button with a visible ring only when the menu was driven by keyboard; a press outside that landed on a focusable control keeps focus there. | `architecture:interaction-modality` INV1; DEC-1 |+| FR6 | When the pointer menu closes, focus returns to the Trigger button with a visible ring only when the menu was driven by keyboard, and after a pointer pick the returned focus opens no trigger tooltip (`component:Tooltip` FR4); a press outside that landed on a focusable control keeps focus there. | `architecture:interaction-modality` INV1; DEC-1 || FR7 | `menuMaxHeight` replaces the 300px term of the menu's and its popover viewport's block-size cap while the viewport gutters still bound both; the touch sheet ignores it. | DEC-2 || FR8 | The Trigger button opens the pointer menu on a mouse press-down, with a settle rule on the opening release, and pressing the trigger of an open menu closes it without reopening in the same gesture; a mouse click and the keyboard open as before. The mouse press-open is shipped behavior, not a requirement until `module:DropdownMenu/useMenuPress` DEC-4 is ruled. Under a finger the trigger MUST open the menu as `spec:AST-094` FR29 states: as the finger presses in a fixed bar, after the 150 ms content-touch delay or at a tap's lift inside a scroll view; `presentation="popover"` keeps the tap open. Implementation gap: a held finger opens it after a 500 ms hold, and a tap opens it at its click. | `module:DropdownMenu/useMenuPress` FR8, FR9; `spec:AST-094` FR29 || FR9 | With `renderTrigger`, the rendered control carries `aria-haspopup`, `aria-expanded`, `aria-controls` and the `id` the menu's `aria-labelledby` points at, and receives the same press-model, keyboard-open and toggle-click handlers as the Button path; the menu is named by that control. A disabled custom trigger never opens the menu or the sheet. `button` and `renderTrigger` are mutually exclusive: both given, `renderTrigger` wins and a dev warning fires, in both presentations. A drilled-in Back row (FR11) returns to the menu by that same name: the caller's `aria-label` when given, else the control's accessible name, read as the menu opens. | DEC-3 |diff --git a/docs/specs/components/Tooltip/Tooltip.spec.md b/docs/specs/components/Tooltip/Tooltip.spec.mdindex 04d2747bb8..9f4a6be717 100644--- a/docs/specs/components/Tooltip/Tooltip.spec.md+++ b/docs/specs/components/Tooltip/Tooltip.spec.md@@ -115,13 +115,11 @@ 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 changed trigger loses its wiring.** The tooltip wires its trigger only- when the trigger's listeners attach, which repeats only when `focusTrigger`,- `isEnabled`, `isOpen`, `delay`, `hideDelay`, or `onOpenChange` changes. Until- then, a replaced element child or `anchorRef` target gets no- `aria-describedby` and no hover or focus opening, and a trigger that- re-renders with its own new `aria-describedby` loses the tooltip id (FR2,- AR1).+- **A changed trigger loses its wiring.** The Tooltip wires its element+ child or `anchorRef` target when it mounts. A replaced element child or+ `anchorRef` target gets no `aria-describedby` and no hover or focus opening+ until the Tooltip mounts again, and a trigger that re-renders with its own+ new `aria-describedby` loses the tooltip id (FR2, AR1).- **Script focus after an empty click opens the tooltip.** After a pointerpress that focuses nothing, such as a click on page text, script focus on atrigger matches `:focus-visible` and opens the tooltip, though@@ -167,20 +165,20 @@ Consumer migration instructions belong in consumer docs and release notes.## Behavioral and layout contract-| ID | Invariant | Basis |-| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |-| 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, judged when focus arrives. | Current source and tests |-| FR5 | On touch and pen, a completed tap opens the tooltip per `touchTrigger` 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 `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, even inside a clickable row or card (DEC-1). Under `tap`, every tap opens it; under `none`, no tap does. A second tap on the trigger, a tap outside, or a scroll starting outside closes it. On a button that pins through `show()`, the button's click decides what a tap does (FR9). Whether `auto` also leaves the tooltip shut when the tap acts on a control around the trigger is open (OQ1). | 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 a `show()` hold (FR12), 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 |-| FR8 | `onOpenChange` reports each show and hide. `hasHoverIndication` (`auto`: a single string or number child) adds a hover cue to the inline trigger. | Current source and tests |-| FR9 | A tooltip held open by `useTooltip`'s `show()` (FR12) is pinned. Tooltip has no toggle prop or option: a caller pins the tooltip by having its own native button call `show()` and `hide()`, as `component:InfoTip` does, so a click, a completed tap, Enter, or Space on that button pins the tooltip and the same press on a pinned tooltip closes it. Hover and keyboard focus still preview an unpinned tooltip per FR3 and FR4. A pinned tooltip stays open when the pointer leaves the trigger and the surface, and Tooltip's own press-to-close on the trigger leaves it open (FR6); Escape (FR6), `hide()`, such as the button's second press, a press outside the trigger and the surface, or focus moving outside them closes it. One internal owner per `useTooltip` call runs the `show()` hold and the touch trigger (FR5). | DEC-1; WCAG 1.4.13, 2.1.1 |-| FR10 | A button that pins the tooltip through `show()` and `hide()` carries, as its own attributes, FR2's `aria-describedby`, `aria-expanded` (`true` only while pinned), and `aria-controls` naming the surface while it shows (FR12); Tooltip writes no `aria-expanded` or `aria-controls` itself. When the tooltip pins, its text is announced once through a polite live region; a preview announces nothing beyond the description. | DEC-1; WAI-ARIA 1.2 `aria-expanded` |-| FR11 | A press inside an open Tooltip surface acts only within that surface: it never activates the trigger, a clickable container around it, or the control a label names. A tooltip that renders inside a FileInput dropzone, a ClickableCard, an Item row, or a `<label>` keeps a click on its text from opening the file picker, activating the container, or toggling or focusing the labelled control. 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:InfoTip` FR2 (a pinning press stops at its button); `component:Tooltip` DEC-1 (one tap does one thing); `architecture:layer-runtime` INV17 |-| FR12 | `useTooltip`'s return includes imperative `show(): void` and `hide(): void`. `show()` opens the tooltip and keeps it open until `hide()`, Escape, a press outside, or focus leaving its trigger, as a pinned tooltip does (FR6, FR9). A `show()` hold that begins during a press on the trigger ends when that press ends off the trigger without a click; the hover rules then decide whether the tooltip stays. `hide()` closes it. Both report through the hook's `onShow` and `onHide`, which the Tooltip component maps to `onOpenChange` (FR8). While `isEnabled` is false, `show()` does nothing. Under a controlled `isOpen`, they report the request through `onShow`/`onHide` and do not override `isOpen` (FR7). They are how an app builds a toggle-style trigger: the app's own button calls them, carries `aria-expanded` (true while shown) and `aria-controls` naming the surface, and keeps its own accessible name. | Owner decision, 2026-11-02: app control through `useTooltip`'s imperative show and hide, not a prop. |+| ID | Invariant | Basis |+| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |+| 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 Tooltip wires its element child or `anchorRef` target when it mounts, so a trigger element replaced after mount, or a trigger whose own `aria-describedby` changes, keeps the first wiring until the Tooltip mounts again (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 a closing menu or other layer returns to its trigger after a pointer pick is pointer focus, so it opens no tooltip on that trigger (`architecture:interaction-modality` INV1). 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 the tooltip per `touchTrigger` 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 `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, even inside a clickable row or card (DEC-1). Under `tap`, every tap opens it; under `none`, no tap does. A second tap on the trigger, a tap outside, or a scroll starting outside closes it. On a button that pins through `show()`, the button's click decides what a tap does (FR9). Whether `auto` also leaves the tooltip shut when the tap acts on a control around the trigger is open (OQ1). | 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 a `show()` hold (FR12), 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. A trigger whose caller removes it while disabling the tooltip closes its open, uncontrolled tooltip; when it attaches again enabled, the tooltip shows only for focus FR4 would open on. A trigger that detaches and attaches again while the tooltip stays enabled keeps the tooltip as it is. | Current source and tests |+| FR8 | `onOpenChange` reports each show and hide. `hasHoverIndication` (`auto`: a single string or number child) adds a hover cue to the inline trigger. | Current source and tests |+| FR9 | A tooltip held open by `useTooltip`'s `show()` (FR12) is pinned. Tooltip has no toggle prop or option: a caller pins the tooltip by having its own native button call `show()` and `hide()`, as `component:InfoTip` does, so a click, a completed tap, Enter, or Space on that button pins the tooltip and the same press on a pinned tooltip closes it. Hover and keyboard focus still preview an unpinned tooltip per FR3 and FR4. A pinned tooltip stays open when the pointer leaves the trigger and the surface, and Tooltip's own press-to-close on the trigger leaves it open (FR6); Escape (FR6), `hide()`, such as the button's second press, a press outside the trigger and the surface, or focus moving outside them closes it. One internal owner per `useTooltip` call runs the `show()` hold and the touch trigger (FR5). | DEC-1; WCAG 1.4.13, 2.1.1 |+| FR10 | A button that pins the tooltip through `show()` and `hide()` carries, as its own attributes, FR2's `aria-describedby`, `aria-expanded` (`true` only while pinned), and `aria-controls` naming the surface while it shows (FR12); Tooltip writes no `aria-expanded` or `aria-controls` itself. When the tooltip pins, its text is announced once through a polite live region; a preview announces nothing beyond the description. | DEC-1; WAI-ARIA 1.2 `aria-expanded` |+| FR11 | A press inside an open Tooltip surface acts only within that surface: it never activates the trigger, a clickable container around it, or the control a label names. A tooltip that renders inside a FileInput dropzone, a ClickableCard, an Item row, or a `<label>` keeps a click on its text from opening the file picker, activating the container, or toggling or focusing the labelled control. 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:InfoTip` FR2 (a pinning press stops at its button); `component:Tooltip` DEC-1 (one tap does one thing); `architecture:layer-runtime` INV17 |+| FR12 | `useTooltip`'s return includes imperative `show(): void` and `hide(): void`. `show()` opens the tooltip and keeps it open until `hide()`, Escape, a press outside, or focus leaving its trigger, as a pinned tooltip does (FR6, FR9). A `show()` hold that begins during a press on the trigger ends when that press ends off the trigger without a click; the hover rules then decide whether the tooltip stays. `hide()` closes it. Both report through the hook's `onShow` and `onHide`, which the Tooltip component maps to `onOpenChange` (FR8). While `isEnabled` is false, `show()` does nothing. Under a controlled `isOpen`, they report the request through `onShow`/`onHide` and do not override `isOpen` (FR7). They are how an app builds a toggle-style trigger: the app's own button calls them, carries `aria-expanded` (true while shown) and `aria-controls` naming the surface, and keeps its own accessible name. | Owner decision, 2026-11-02: app control through `useTooltip`'s imperative show and hide, not a prop. |### Allowed variation@@ -261,6 +259,7 @@ has no arrow element.| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- || 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; `auto` judged when focus arrives (roving member, `<summary>`, non-focusable wrapper) | Wrong open or close for an input fails. | `audit:Tooltip/behavior` |+| FR4, FR7 reattach | `useTooltip.test.tsx` detach-and-attach suite; `DropdownMenuTooltip.a11y.chromium.spec.ts` | A trigger that detaches while open; keyboard and pointer focus that arrive while detached; a data menu, a compound menu and a bottom sheet: a pointer pick, a keyboard pick, and Escape | A tooltip left open after its trigger detaches, a tooltip after a pointer pick, or none for returned keyboard focus, 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` finger and pen cases; `useTouchTrigger.test.ts` and `touchTriggerTargets.test.tsx` disabled-control cases | Tap open, scroll, second tap, tap outside; `touchTrigger` `auto`, `tap`, and `none`; an action trigger and a trigger that performs no action; 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 trigger that performs an action under `auto` or on any tap under `none`, or leaves a disabled control's reason shut fails. | `audit:Tooltip/behavior` |diff --git a/packages/core/src/DropdownMenu/__tests__/DropdownMenuTooltip.a11y.chromium.spec.ts b/packages/core/src/DropdownMenu/__tests__/DropdownMenuTooltip.a11y.chromium.spec.tsnew file mode 100644index 0000000000..ee935b3f0c--- /dev/null+++ b/packages/core/src/DropdownMenu/__tests__/DropdownMenuTooltip.a11y.chromium.spec.ts@@ -0,0 +1,153 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y scope ^packages/core/src/(DropdownMenu|Button|Tooltip|Layer)/ ^apps/storybook/stories/DropdownMenu.stories.tsx$++/**+ * @file DropdownMenuTooltip.a11y.chromium.spec.ts+ * @input The Core/DropdownMenu stories in a built Storybook and Chromium+ * @output Regression evidence for suppressed trigger tooltips and focus return+ * @position Native popover and focus-modality proof for issue #8965+ */++import {+ expect,+ test,+ type Locator,+ type Page,+} from '@astryxdesign/a11y-spec/playwright';+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => {+ await storybook?.close();+});++async function mount(page: Page, mode: string) {+ const story = mode === 'compound' ? 'compound-basic' : 'default';+ const presentation = mode === 'sheet' ? 'bottom-sheet' : 'popover';+ const params = new URLSearchParams({+ id: `core-dropdownmenu--${story}`,+ viewMode: 'story',+ args: `button.label:Actions;button.tooltip:More actions;presentation:${presentation}`,+ });+ await page.goto(`${storybook.origin}/iframe.html?${params}`);+ await holdMotionStill(page);+ const trigger = page.getByRole('button', {name: 'Actions', exact: true});+ const item = page.getByRole(mode === 'sheet' ? 'button' : 'menuitem', {+ name: 'Edit',+ exact: true,+ });+ await expect(trigger).toBeVisible();+ return {trigger, item};+}++function openTooltip(page: Page): Locator {+ return page.locator('[role="tooltip"]:popover-open');+}++async function pointerPick(page: Page, mode: string, hoverFirst = true) {+ const {trigger, item} = await mount(page, mode);+ if (hoverFirst) {+ await trigger.hover();+ await expect(openTooltip(page)).toBeVisible();+ }+ await trigger.click();+ await expect(trigger).toHaveAttribute('aria-expanded', 'true');+ await page.waitForTimeout(400);+ await expect(openTooltip(page)).toHaveCount(0);+ await item.click();+ await expect(trigger).toHaveAttribute('aria-expanded', 'false');+ await page.mouse.move(0, 0);+ await expect(trigger).toBeFocused();+ expect(+ await trigger.evaluate(el => el.matches(':hover, :focus-visible')),+ ).toBe(false);+ // Cross the show delay and hover bridge rather than passing before a timer.+ await page.waitForTimeout(400);+ await expect(openTooltip(page)).toHaveCount(0);++ await trigger.hover();+ await expect(openTooltip(page)).toBeVisible();+ await page.mouse.move(0, 0);+ await expect(openTooltip(page)).toHaveCount(0);+}++async function keyboardPick(page: Page, mode: string) {+ const {trigger, item} = await mount(page, mode);+ await page.keyboard.press('Tab');+ await expect(trigger).toBeFocused();+ await expect(openTooltip(page)).toBeVisible();+ await page.keyboard.press('Enter');+ await expect(item).toBeFocused();+ await expect(openTooltip(page)).toHaveCount(0);+ await page.keyboard.press('Enter');+ await expect(trigger).toHaveAttribute('aria-expanded', 'false');+ await expect(trigger).toBeFocused();+ await expect(openTooltip(page)).toBeVisible();+ await page.keyboard.press('Escape');+ await expect(openTooltip(page)).toHaveCount(0);+}++test('a data menu does not resurrect its tooltip after a pointer pick', async ({+ page,+}) => {+ await pointerPick(page, 'data');+});++test('a compound menu does not resurrect its tooltip after a pointer pick', async ({+ page,+}) => {+ await pointerPick(page, 'compound');+});++test('a bottom sheet does not resurrect its tooltip after a pointer pick', async ({+ page,+}) => {+ await pointerPick(page, 'sheet');+});++test('opening before the hover delay expires cancels the pending tooltip', async ({+ page,+}) => {+ await pointerPick(page, 'data', false);+});++test('keyboard selection in a data menu returns focus and shows the tooltip', async ({+ page,+}) => {+ await keyboardPick(page, 'data');+});++test('keyboard selection in a compound menu returns focus and shows the tooltip', async ({+ page,+}) => {+ await keyboardPick(page, 'compound');+});++test('keyboard selection in a bottom sheet returns focus and shows the tooltip', async ({+ page,+}) => {+ await keyboardPick(page, 'sheet');+});++test('Escape returns keyboard focus and shows the tooltip', async ({page}) => {+ const {trigger, item} = await mount(page, 'data');+ await page.keyboard.press('Tab');+ await expect(trigger).toBeFocused();+ await page.keyboard.press('Enter');+ await expect(item).toBeFocused();+ await expect(openTooltip(page)).toHaveCount(0);+ await page.keyboard.press('Escape');+ await expect(trigger).toHaveAttribute('aria-expanded', 'false');+ await expect(trigger).toBeFocused();+ await expect(openTooltip(page)).toBeVisible();+});diff --git a/packages/core/src/InfoTip/InfoTip.pin.test.tsx b/packages/core/src/InfoTip/InfoTip.pin.test.tsxindex 50d8e142ca..7628d4a775 100644--- a/packages/core/src/InfoTip/InfoTip.pin.test.tsx+++ b/packages/core/src/InfoTip/InfoTip.pin.test.tsx@@ -419,6 +419,24 @@ describe('InfoTip press-to-pin (component:InfoTip FR2)', () => {});});+describe('a pinned InfoTip and a caller ref that changes on each render', () => {+ it('stays pinned when the parent renders again with an inline ref', () => {+ const Parent = ({count}: {count: number}) => (+ <div data-count={count}>+ <InfoTip ref={() => {}} content={TIP} label="About billing" />+ </div>+ );+ const {rerender} = render(<Parent count={0} />);+ const trigger = screen.getByRole('button', {name: 'About billing'});+ click(trigger);+ expect(shows(TIP)).toBe(true);+ rerender(<Parent count={1} />);+ rerender(<Parent count={2} />);+ expect(shows(TIP)).toBe(true);+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ });+});+describe('InfoTip trigger state (component:InfoTip FR2)', () => {it('carries aria-expanded, true only while pinned, and aria-controls while it shows', () => {render(<InfoTooltip />);diff --git a/packages/core/src/Tooltip/useTooltip.test.tsx b/packages/core/src/Tooltip/useTooltip.test.tsxindex 16d97f3384..39ffa3afae 100644--- a/packages/core/src/Tooltip/useTooltip.test.tsx+++ b/packages/core/src/Tooltip/useTooltip.test.tsx@@ -24,6 +24,8 @@ import {import {render, screen, fireEvent, act} from '@testing-library/react';import {useTooltip, type TooltipOptions} from './useTooltip';import {useLayer} from '../Layer/useLayer';+import {useMergedRefs} from '../hooks/useMergedRefs';+import type {Ref} from 'react';// jsdom implements neither the Popover API nor `:popover-open`; mirror// Tooltip.test.tsx's shims so the layer can open.@@ -162,6 +164,169 @@ describe('useTooltip — show delay', () => {});});+// A caller that removes the trigger wiring while its own layer is open, as+// DropdownMenu's Button does.+function DetachableHarness({+ isAttached,+ ...options+}: TooltipOptions & {isAttached: boolean}) {+ // As Button does for DropdownMenu: removing the wiring also disables it.+ const tooltip = useTooltip({+ ...options,+ isEnabled: isAttached && (options.isEnabled ?? true),+ });+ return (+ <div>+ <button+ type="button"+ ref={isAttached ? tooltip.ref : undefined}+ aria-describedby={tooltip.describedBy}>+ Trigger+ </button>+ {tooltip.renderTooltip('Helpful text')}+ </div>+ );+}++describe('useTooltip — a trigger that detaches and attaches again', () => {+ it('closes an open tooltip when its trigger stays detached', async () => {+ const onHide = vi.fn();+ const {rerender} = render(<DetachableHarness isAttached onHide={onHide} />);+ fireEvent.mouseEnter(trigger());+ tick(200);+ expect(tooltipElement().matches(':popover-open')).toBe(true);++ rerender(<DetachableHarness isAttached={false} onHide={onHide} />);+ await act(async () => {});+ expect(tooltipElement().matches(':popover-open')).toBe(false);+ expect(onHide).toHaveBeenCalledTimes(1);+ });++ it('shows on attach for keyboard focus that arrived while detached', async () => {+ const {rerender} = render(<DetachableHarness isAttached />);+ rerender(<DetachableHarness isAttached={false} />);+ await act(async () => {});+ const matches = trigger().matches.bind(trigger());+ vi.spyOn(trigger(), 'matches').mockImplementation(+ selector => selector === ':focus-visible' || matches(selector),+ );+ act(() => trigger().focus());++ rerender(<DetachableHarness isAttached />);+ expect(tooltipElement().matches(':popover-open')).toBe(true);+ });++ it('stays closed on attach for pointer focus that arrived while detached', async () => {+ const {rerender} = render(<DetachableHarness isAttached />);+ rerender(<DetachableHarness isAttached={false} />);+ await act(async () => {});+ act(() => trigger().focus());++ rerender(<DetachableHarness isAttached />);+ expect(tooltipElement().matches(':popover-open')).toBe(false);+ });+});++/** A trigger whose caller merges its own inline ref, as Button and InfoTip do. */+function InlineRefHarness({+ label,+ isShown = true,+ ...options+}: TooltipOptions & {label: string; isShown?: boolean}) {+ const tooltip = useTooltip(options);+ return (+ <div>+ {isShown && (+ <button+ type="button"+ ref={el => {+ tooltip.ref(el);+ }}+ aria-describedby={tooltip.describedBy}>+ {label}+ </button>+ )}+ {tooltip.renderTooltip('Helpful text')}+ </div>+ );+}++/** A trigger that merges its consumer's ref, as Button does. */+function MergedRefHarness({+ consumerRef,+ ...options+}: TooltipOptions & {consumerRef: Ref<HTMLButtonElement>}) {+ const tooltip = useTooltip(options);+ const ref = useMergedRefs<HTMLButtonElement>(consumerRef, tooltip.ref);+ return (+ <div>+ <button type="button" ref={ref} aria-describedby={tooltip.describedBy}>+ Trigger+ </button>+ {tooltip.renderTooltip('Helpful text')}+ </div>+ );+}++describe('useTooltip — a caller ref that changes on each render', () => {+ it('keeps a hovered tooltip open when the parent renders again', () => {+ const onHide = vi.fn();+ const {rerender} = render(+ <MergedRefHarness consumerRef={() => {}} onHide={onHide} />,+ );+ fireEvent.mouseEnter(trigger());+ tick(200);+ expect(tooltipElement().matches(':popover-open')).toBe(true);++ rerender(<MergedRefHarness consumerRef={() => {}} onHide={onHide} />);+ rerender(<MergedRefHarness consumerRef={() => {}} onHide={onHide} />);+ expect(tooltipElement().matches(':popover-open')).toBe(true);+ expect(onHide).not.toHaveBeenCalled();+ });++ it('keeps a tooltip dismissed with Escape closed when the parent renders again', () => {+ const {rerender} = render(<MergedRefHarness consumerRef={() => {}} />);+ const matches = trigger().matches.bind(trigger());+ vi.spyOn(trigger(), 'matches').mockImplementation(+ selector => selector === ':focus-visible' || matches(selector),+ );+ act(() => trigger().focus());+ expect(tooltipElement().matches(':popover-open')).toBe(true);+ fireEvent.keyDown(trigger(), {key: 'Escape'});+ expect(tooltipElement().matches(':popover-open')).toBe(false);++ rerender(<MergedRefHarness consumerRef={() => {}} />);+ expect(tooltipElement().matches(':popover-open')).toBe(false);+ });++ it('removes its listeners when the caller reports null for a removed trigger', () => {+ const onShow = vi.fn();+ const {rerender} = render(+ <InlineRefHarness label="Trigger" onShow={onShow} />,+ );+ const removed = screen.getByRole('button', {name: 'Trigger'});+ rerender(+ <InlineRefHarness label="Trigger" onShow={onShow} isShown={false} />,+ );+ fireEvent.mouseEnter(removed);+ tick(1000);+ expect(onShow).not.toHaveBeenCalled();+ });+});++describe('useTooltip — a pending show and isEnabled', () => {+ it('drops a pending show when the tooltip is disabled, even if it is enabled again before the delay ends', () => {+ const onShow = vi.fn();+ const {rerender} = render(<Harness onShow={onShow} />);+ fireEvent.mouseEnter(trigger());+ tick(100);+ rerender(<Harness onShow={onShow} isEnabled={false} />);+ rerender(<Harness onShow={onShow} />);+ tick(200);+ expect(onShow).not.toHaveBeenCalled();+ });+});+describe('useTooltip — touch suppression', () => {it('never shows on the hover a finger synthesizes, but still on a mouse', () => {// Touch is decided per interaction from the pointer type — a finger'sdiff --git a/packages/core/src/Tooltip/useTooltip.tsx b/packages/core/src/Tooltip/useTooltip.tsxindex 653d1e4dab..510381753e 100644--- a/packages/core/src/Tooltip/useTooltip.tsx+++ b/packages/core/src/Tooltip/useTooltip.tsx@@ -21,7 +21,7 @@ import {type ReactNode,type RefCallback,} from 'react';-import {createTriggerFocusGate} from '../utils/triggerFocus';+import {createTriggerFocusGate, isFocusOnTrigger} from '../utils/triggerFocus';import * as stylex from '@stylexjs/stylex';import {useLayerInternal,@@ -308,6 +308,17 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {const showTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);const hideTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);const triggerRef = useRef<HTMLElement | null>(null);+ // Whether the tooltip is enabled now, for a show that runs after a render+ // (a pending hover show) and for the trigger ref callback.+ const isEnabledRef = useRef(isEnabled);+ isEnabledRef.current = isEnabled;+ // Counts the renders in which the tooltip is disabled. A pending show+ // records it, so a show scheduled before a disable is dropped even when+ // the tooltip is enabled again before the timer fires.+ const disabledRendersRef = useRef(0);+ if (!isEnabled) {+ disabledRendersRef.current += 1;+ }// Clear all timeoutsconst clearTimeouts = useCallback(() => {@@ -460,22 +471,16 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {return;}clearTimeouts();+ const disabledRenders = disabledRendersRef.current;showTimeoutRef.current = setTimeout(() => {- showLayer();+ // A show runs only if the tooltip stayed enabled since it was+ // scheduled: nothing would close a tooltip that opens after a disable.+ if (disabledRendersRef.current === disabledRenders) {+ showLayer();+ }}, delay);}, [isEnabled, isOpen, clearTimeouts, showLayer, delay]);- // A show scheduled while the triggers were enabled must not outlive them:- // disabling also detaches the leave listener that would have cancelled it,- // so the timer would open a tooltip that nothing ever closes. Only the- // pending show is dropped; a pending hide still runs.- useEffect(() => {- if (!isEnabled && showTimeoutRef.current) {- clearTimeout(showTimeoutRef.current);- showTimeoutRef.current = null;- }- }, [isEnabled]);-// Schedule hide with delay (suppressed when isOpen is true).// A small hover bridge (when hideDelay is 0) lets the pointer travel from the// trigger onto the tooltip surface without the tooltip vanishing — required@@ -537,23 +542,25 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {// focus that counted still hides on blur (utils/triggerFocus.ts).const [focusGate] = useState(createTriggerFocusGate);+ // Whether focus on `target` opens the tooltip. With a `trigger`, its+ // `focusTrigger` rule applies too. Only `:focus-visible` focus opens it, and+ // a tap never does: a tapped `<input>` also matches `:focus-visible`.+ const opensOnFocus = useCallback(+ (target: HTMLElement, trigger: HTMLElement | null): boolean => {+ if (trigger != null && !isFocusOnTrigger(target, trigger, focusTrigger)) {+ return false;+ }+ return !isTouchInteraction() && target.matches(':focus-visible');+ },+ [focusTrigger, isTouchInteraction],+ );+const handleFocusIn = useCallback((e: Event) => {if (!focusGate.focusIn(e, focusTrigger) || !isEnabled) {return;}- // A tap focuses the trigger it activates, and `:focus-visible` does not- // filter that out on every element: a tapped `<input>` or contenteditable- // matches it. Those are exactly the action triggers `auto` just decided- // to keep shut, so without this the focus reopens what the tap- // suppressed, over the field the user is trying to type into.- if (isTouchInteraction()) {- return;- }- // Only show tooltip for keyboard focus (:focus-visible),- // not programmatic focus (e.g. dialog auto-focus, touch tap)- const target = e.target as HTMLElement;- if (!target.matches(':focus-visible')) {+ if (!opensOnFocus(e.target as HTMLElement, null)) {return;}clearTimeouts();@@ -563,7 +570,7 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {focusGate,focusTrigger,isEnabled,- isTouchInteraction,+ opensOnFocus,clearTimeouts,showLayer,],@@ -656,66 +663,155 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {],);- // Interaction ref that handles event listeners only- const interactionRef: RefCallback<HTMLElement> = useCallback(- (el: HTMLElement | null) => {- // Cleanup previous element- if (triggerRef.current) {- triggerRef.current.removeEventListener('mouseenter', handleMouseEnter);- triggerRef.current.removeEventListener('mouseleave', handleMouseLeave);- triggerRef.current.removeEventListener('focusin', handleFocusIn);- triggerRef.current.removeEventListener('focusout', handleFocusOut);- triggerRef.current.removeEventListener('focusout', handleHeldFocusOut);- stopPressTrackingRef.current?.();- triggerRef.current.removeEventListener(- 'pointerenter',- handlePointerEnter,- );- triggerRef.current.removeEventListener(- 'pointerdown',- handlePointerDown,- );- }+ // The trigger's listeners call the latest handlers through this ref, so the+ // trigger ref callback keeps one identity.+ const handlersRef = useRef({+ handleMouseEnter,+ handleMouseLeave,+ handleFocusIn,+ handleFocusOut,+ handleHeldFocusOut,+ handlePointerEnter,+ handlePointerDown,+ focusTrigger,+ isOpen,+ dropHold,+ hideNow,+ showNow,+ opensOnFocus,+ });+ handlersRef.current = {+ handleMouseEnter,+ handleMouseLeave,+ handleFocusIn,+ handleFocusOut,+ handleHeldFocusOut,+ handlePointerEnter,+ handlePointerDown,+ focusTrigger,+ isOpen,+ dropHold,+ hideNow,+ showNow,+ opensOnFocus,+ };- if (el) {- // Attach hover listeners. `pointerenter` runs before the synthesized- // `mouseenter` a tap produces, which is what lets the hover path know- // it is looking at a finger.- el.addEventListener('pointerenter', handlePointerEnter);- el.addEventListener('mouseenter', handleMouseEnter);- el.addEventListener('mouseleave', handleMouseLeave);- // Press-to-dismiss on a mouse; tap-to-open on a touch pointer.- el.addEventListener('pointerdown', handlePointerDown);-- // Focus listeners unless focus never opens the tooltip; `auto` decides- // per event (utils/triggerFocus.ts).- if (focusTrigger !== 'never') {- el.addEventListener('focusin', handleFocusIn);- el.addEventListener('focusout', handleFocusOut);- }+ // Removes the attached trigger's listeners (the trigger ref callback's+ // cleanup).+ const detachTriggerRef = useRef<(() => void) | null>(null);+ // Set when the trigger detached while the tooltip was disabled: the+ // caller removed the wiring (DropdownMenu's Button while its menu is+ // open), so the next enabled attach reads the focus that arrived meanwhile.+ const wasSuppressedRef = useRef(false);++ // The trigger's ref callback owns every trigger listener, and reads the+ // trigger's state when it attaches and detaches.+ const interactionRef = useCallback((el: HTMLElement | null) => {+ // A caller that reports `null` by hand detaches the trigger, as the+ // returned cleanup does.+ if (el == null) {+ detachTriggerRef.current?.();+ return;+ }+ if (el === triggerRef.current) {+ return;+ }+ detachTriggerRef.current?.();+ const latest = () => handlersRef.current;+ // `pointerenter` runs before the synthesized `mouseenter` a tap produces,+ // which is what lets the hover path know it is looking at a finger.+ const onPointerEnter = (e: PointerEvent) => latest().handlePointerEnter(e);+ const onMouseEnter = () => latest().handleMouseEnter();+ const onMouseLeave = (e: Event) => latest().handleMouseLeave(e);+ // Press-to-dismiss on a mouse; tap-to-open on a touch pointer.+ const onPointerDown = (e: PointerEvent) => latest().handlePointerDown(e);+ // Focus counts unless focus never opens the tooltip; `auto` decides per+ // event (isFocusForTrigger).+ const onFocusIn = (e: Event) => {+ if (latest().focusTrigger !== 'never') {+ latest().handleFocusIn(e);+ }+ };+ const onFocusOut = (e: Event) => {+ if (latest().focusTrigger !== 'never') {+ latest().handleFocusOut(e);}+ };+ // A held tooltip's own focus-leave close, whatever `focusTrigger` is.+ const onHeldFocusOut = (e: FocusEvent) => latest().handleHeldFocusOut(e);+ el.addEventListener('pointerenter', onPointerEnter);+ el.addEventListener('mouseenter', onMouseEnter);+ el.addEventListener('mouseleave', onMouseLeave);+ el.addEventListener('pointerdown', onPointerDown);+ el.addEventListener('focusin', onFocusIn);+ el.addEventListener('focusout', onFocusOut);+ el.addEventListener('focusout', onHeldFocusOut);+ triggerRef.current = el;++ // A trigger that attaches again after its wiring was removed+ // (DropdownMenu's Button as its menu closes) missed the focus that+ // arrived meanwhile. Show for it only if it would open the tooltip:+ // returned keyboard focus does, focus returned after a pointer pick does+ // not. Any other attach leaves the tooltip as it is, so a tooltip+ // dismissed with Escape stays closed.+ const focused = el.ownerDocument.activeElement;+ const wasSuppressed = wasSuppressedRef.current;+ if (isEnabledRef.current) {+ wasSuppressedRef.current = false;+ }+ if (+ wasSuppressed &&+ isEnabledRef.current &&+ latest().isOpen === undefined &&+ latest().focusTrigger !== 'never' &&+ focused instanceof HTMLElement &&+ el.contains(focused) &&+ latest().opensOnFocus(focused, el)+ ) {+ latest().showNow();+ }- // Its own focus-leave listener: `focusTrigger="never"` attaches none.- el?.addEventListener('focusout', handleHeldFocusOut);- triggerRef.current = el;- },- [- handleHeldFocusOut,- focusTrigger,- handleMouseEnter,- handleMouseLeave,- handleFocusIn,- handleFocusOut,- handlePointerEnter,- handlePointerDown,- ],- );+ const detach = () => {+ if (detachTriggerRef.current === detach) {+ detachTriggerRef.current = null;+ }+ el.removeEventListener('pointerenter', onPointerEnter);+ el.removeEventListener('mouseenter', onMouseEnter);+ el.removeEventListener('mouseleave', onMouseLeave);+ el.removeEventListener('pointerdown', onPointerDown);+ el.removeEventListener('focusin', onFocusIn);+ el.removeEventListener('focusout', onFocusOut);+ el.removeEventListener('focusout', onHeldFocusOut);+ stopPressTrackingRef.current?.();+ if (triggerRef.current === el) {+ triggerRef.current = null;+ }+ // A caller removes the wiring as it disables the tooltip. Close an+ // uncontrolled tooltip then, or the next attach shows a stale tooltip.+ // A detach while enabled, such as a merged ref that changes identity+ // on a re-render, keeps a hovered or held tooltip open.+ if (!isEnabledRef.current && latest().isOpen === undefined) {+ wasSuppressedRef.current = true;+ latest().dropHold();+ latest().hideNow();+ }+ };+ detachTriggerRef.current = detach;+ return detach;+ }, []);// Combined ref - shorthand for calling both positionRef and interactionRef- const ref: RefCallback<HTMLElement> = useCallback(+ const ref = useCallback((el: HTMLElement | null) => {layerRef(el);- interactionRef(el);+ const detachInteraction = interactionRef(el);+ if (el == null) {+ return;+ }+ return () => {+ detachInteraction?.();+ layerRef(null);+ };},[layerRef, interactionRef],);diff --git a/packages/core/src/utils/triggerFocus.ts b/packages/core/src/utils/triggerFocus.tsindex 6676f45ea7..3a637670be 100644--- a/packages/core/src/utils/triggerFocus.ts+++ b/packages/core/src/utils/triggerFocus.ts@@ -37,6 +37,22 @@ export function isFocusableTrigger(element: HTMLElement): boolean {export function isFocusForTrigger(event: Event,mode: TriggerFocusMode,+): boolean {+ return isFocusOnTrigger(+ event.target,+ event.currentTarget as HTMLElement | null,+ mode,+ );+}++/**+ * `isFocusForTrigger` for focus already on `target`, inside `trigger`: the+ * same rule, read when a trigger attaches with focus inside it.+ */+export function isFocusOnTrigger(+ target: EventTarget | null,+ trigger: HTMLElement | null,+ mode: TriggerFocusMode,): boolean {if (mode === 'always') {return true;@@ -44,10 +60,7 @@ export function isFocusForTrigger(if (mode === 'never') {return false;}- const trigger = event.currentTarget as HTMLElement | null;- return (- trigger != null && (event.target === trigger || isFocusableTrigger(trigger))- );+ return trigger != null && (target === trigger || isFocusableTrigger(trigger));}/** Remembers whether a trigger's current focus counted when it arrived. */