Skip to content

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

TypeScript

feat(Tooltip): triggerBehavior="toggle" pins the tooltip on a press (#9232)

Christopher Chedeau1d04d40fd3d5
diff --git a/.changeset/trigger-behavior-toggle.md b/.changeset/trigger-behavior-toggle.md
new file mode 100644
index 0000000000..6eef27cfbf
--- /dev/null
+++ b/.changeset/trigger-behavior-toggle.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Tooltip and `useTooltip` take `triggerBehavior` (type `TooltipTriggerBehavior`). `adaptive`, the default, keeps the released behavior. `hover` previews the tooltip on hover and focus, and no touch or pen tap opens it. `toggle` pins the tooltip on a click, tap, Enter, or Space on a button trigger, and the same press closes it. Escape, a press outside, or focus leaving also closes it. The press stops at the trigger: its default action is prevented, the trigger's own handlers still run, and a clickable row, card, or label around it does nothing. With `anchorRef` or a caller's own trigger, a plain `onClick` element around the trigger still receives the press, and so does an Item row when that trigger is not a native button. The trigger reports `aria-expanded` and `aria-controls`, and the tooltip's text is announced once when it pins. A trigger that is not a button gets a development warning. `touchTrigger` now decides taps only under `adaptive`.
+
+@vjeux
diff --git a/apps/storybook/stories/TooltipToggleBehaviorA11y.stories.tsx b/apps/storybook/stories/TooltipToggleBehaviorA11y.stories.tsx
new file mode 100644
index 0000000000..6d53a3f082
--- /dev/null
+++ b/apps/storybook/stories/TooltipToggleBehaviorA11y.stories.tsx
@@ -0,0 +1,151 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file TooltipToggleBehaviorA11y.stories.tsx
+ * @input Uses Tooltip, Button, ClickableCard and Layout from core
+ * @output Fixtures for the toggle-behavior browser tests. One is a button
+ * whose only job is its tooltip, alone and inside a clickable card. One is
+ * an anchored trigger with its own click handler, inside a clickable card.
+ * One is a trigger whose tooltip opens on no focus.
+ * @position The reproduction path for the `triggerBehavior="toggle"` cases in
+ * `packages/core/src/Layer/__tests__/TouchTrigger.a11y.chromium.spec.ts`
+ * (`component:Tooltip` FR9, FR10). Per `docs/specs/AST-009/spec.md` FR30, a
+ * browser claim is checked against a checked-in story.
+ *
+ * SYNC: The spec navigates to these story ids by name. Nothing at compile
+ * time catches a renamed export — the Chromium spec does, when it finds no
+ * story.
+ */
+
+import {useRef, useState} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import {Button} from '@astryxdesign/core/Button';
+import {ClickableCard} from '@astryxdesign/core/ClickableCard';
+import {VStack} from '@astryxdesign/core/Layout';
+import {Tooltip} from '@astryxdesign/core/Tooltip';
+
+const meta: Meta = {
+ title: 'a11y/Tooltip toggle behavior',
+ // Driven by the toggle-behavior spec, not photographed: the states under test
+ // are pins and closes across presses, which no single frame shows.
+ tags: ['no-visual'],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'A button whose only job is its tooltip takes `triggerBehavior="toggle"`: a click, a tap, Enter, or Space pins the tooltip, and the same press closes it. Inside a clickable card, the press stops at the trigger.',
+ },
+ },
+ },
+};
+
+export default meta;
+
+type Story = StoryObj;
+
+/** A press pins the tooltip open; the same press, Escape, or a press outside closes it. */
+export const ButtonToggle: Story = {
+ render: () => (
+ <div style={{padding: 100}}>
+ <Tooltip
+ content="Rows are ranked by how many places import the icon"
+ placement="above"
+ triggerBehavior="toggle">
+ <Button label="What is this?" variant="secondary">
+ ?
+ </Button>
+ </Tooltip>
+ </div>
+ ),
+};
+
+function InAClickableCardRender() {
+ const [opened, setOpened] = useState(0);
+ return (
+ <div style={{padding: 100, maxWidth: 360}}>
+ <VStack gap={2}>
+ <ClickableCard label="Icon usage" onClick={() => setOpened(n => n + 1)}>
+ <VStack gap={2}>
+ Icon usage
+ <Tooltip
+ content="Rows are ranked by how many places import the icon"
+ placement="above"
+ triggerBehavior="toggle">
+ <Button label="What is this?" variant="secondary">
+ ?
+ </Button>
+ </Tooltip>
+ </VStack>
+ </ClickableCard>
+ <span>Card opened {opened} times</span>
+ </VStack>
+ </div>
+ );
+}
+
+/** A press on the trigger pins its tooltip and stops there: the card does not open. */
+export const InAClickableCard: Story = {
+ render: () => <InAClickableCardRender />,
+};
+
+function AnchoredActionInACardRender() {
+ const [opened, setOpened] = useState(0);
+ const [pressed, setPressed] = useState(0);
+ const anchorRef = useRef<HTMLButtonElement>(null);
+ return (
+ <div style={{padding: 100, maxWidth: 360}}>
+ <VStack gap={2}>
+ <ClickableCard label="Icon usage" onClick={() => setOpened(n => n + 1)}>
+ <VStack gap={2}>
+ Icon usage
+ <Button
+ ref={anchorRef}
+ label="What is this?"
+ variant="secondary"
+ onClick={() => setPressed(n => n + 1)}>
+ ?
+ </Button>
+ <Tooltip
+ anchorRef={anchorRef}
+ content="Rows are ranked by how many places import the icon"
+ placement="above"
+ triggerBehavior="toggle"
+ />
+ </VStack>
+ </ClickableCard>
+ <span>Card opened {opened} times</span>
+ <span>Button pressed {pressed} times</span>
+ </VStack>
+ </div>
+ );
+}
+
+/**
+ * An anchored trigger with its own click handler, in a clickable card: the
+ * pinning press runs the trigger's own handler, and the card ignores it.
+ */
+export const AnchoredActionInACard: Story = {
+ render: () => <AnchoredActionInACardRender />,
+};
+
+/** A tooltip that opens on no focus: focus moving to another control still closes a pin. */
+export const FocusTriggerNever: Story = {
+ render: () => (
+ <div style={{padding: 100}}>
+ <VStack gap={2}>
+ <Tooltip
+ content="Rows are ranked by how many places import the icon"
+ placement="above"
+ triggerBehavior="toggle"
+ focusTrigger="never">
+ <Button label="What is this?" variant="secondary">
+ ?
+ </Button>
+ </Tooltip>
+ <Button label="Next" variant="secondary">
+ Next
+ </Button>
+ </VStack>
+ </div>
+ ),
+};
diff --git a/docs/specs/components/Tooltip/Tooltip.spec.md b/docs/specs/components/Tooltip/Tooltip.spec.md
index 52500cb079..c63841ee5e 100644
--- a/docs/specs/components/Tooltip/Tooltip.spec.md
+++ b/docs/specs/components/Tooltip/Tooltip.spec.md
@@ -12,6 +12,8 @@ owners: [cixzhang]
review_triggers: [public-api, behavior, theming, accessibility]
verified_by:
[
+ packages/core/src/Layer/usePressPin.test.tsx,
+ packages/core/src/Layer/layerDismissalFamilies.test.tsx,
packages/core/src/Tooltip/Tooltip.test.tsx,
packages/core/src/Layer/__tests__/TouchTrigger.a11y.chromium.spec.ts,
packages/core/src/Tooltip/useTooltip.test.tsx,
@@ -33,11 +35,19 @@ architecture:
architecture:public-component-api,
]
contributing: []
-system_specs: [spec:AST-003, spec:AST-017]
+system_specs: [spec:AST-003, spec:AST-017, spec:AST-086/FR12, spec:AST-086/FR14]
---
# Tooltip component contract
+<!-- path-applicability:v1 -->
+
+```json
+{
+ "paths": ["packages/core/src/Layer/usePressPin.ts"]
+}
+```
+
## Contract at a glance
| Area | Contract |
@@ -46,7 +56,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, an opt-in early migration when run explicitly, rewrites icon and span triggers and reports the rest (DEP-0016), and CLN-0024 names each remaining kind's replacement in 0.8.0, whose upgrade runs the codemod again. |
-| 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). |
+| 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). DEP-0016's deprecation metadata and codemod are not yet built; thirteen 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`. |
@@ -150,12 +160,18 @@ Consumer migration instructions belong in consumer docs and release notes.
`touchTrigger="auto"` asks only whether the trigger itself performs an action,
so a truncated label inside a link opens its tooltip on the tap that follows
the link. The walk ships with CLN-0024 (FR5, DEC-1).
-- **Toggle pinning is not built.** `triggerBehavior` and its three values, the
- toggle (FR9), the trigger wiring and announcement (FR10), and a pinned
- tooltip's Escape priority (`spec:AST-003` FR4) are specified and not
- implemented, and the codemod DEP-0016 names does not exist yet.
- `touchTrigger="tap"` is the shipped way to open on every tap, and
- `touchTrigger="none"` the shipped way to open on no tap.
+- **DEP-0016 is not built.** `touchTrigger="tap"` carries no `@deprecated`
+ metadata yet, and the `astryx upgrade` codemod DEP-0016 names does not exist
+ yet; `triggerBehavior` is built (FR9, FR10, and FR5's rules for its values).
+- **FR9's own-text pin is not built.** A trigger whose tooltip repeats its own
+ visible text, such as a truncated Text, gets FR9's development warning under
+ `triggerBehavior="toggle"` and keeps tap-only opening.
+- **A press outside misses a pin in another document.** The outside dismissal
+ listens only in the page's document. So a pin whose trigger renders in an
+ iframe or a Picture-in-Picture window stays after a press outside there (FR9).
+- **An Item row runs on a press of an anchored button-role trigger.** Item's
+ row click skips only native controls. So an anchored or caller's trigger that
+ is not a native button pins the tooltip and also runs the row (FR9).
- **The tooltip consumes Escape until AST-003 ships.** A visible, topmost
tooltip handles Escape, as `family:overlay-dismissal` records, so the layer
underneath it, such as a Dialog, stays open for that press. `spec:AST-003`
@@ -214,19 +230,19 @@ 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 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 |
-| 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 | With `triggerBehavior="toggle"` and a trigger whose role is `button` (a `<button>` or `role="button"`), a click, a completed tap, Enter, or Space on the trigger pins the tooltip open, and the same press on a pinned tooltip closes it. Hover and keyboard focus still preview it per FR3 and FR4; on touch no preview opens and a tap pins it, while a touch that becomes a scroll pins nothing. A pinned tooltip stays open when the pointer leaves the trigger and the surface; Escape (FR6), a second press, a press outside the trigger and the surface, or focus moving outside them closes it. In a controlled tooltip a press reports the toggled value through `onOpenChange` and does not change the state itself (FR7). A press that pins or closes the layer stops at its trigger: it does not reach a clickable row, card, or container around it, or the control a label names. A trigger whose role is not `button` gets a development warning and keeps tap-only opening: every completed tap opens the tooltip, and no press pins it. A trigger whose tooltip repeats its own visible text, such as a truncated Text that is its own tab stop, may take `triggerBehavior="toggle"` without being a button: a press pins it as on a button trigger, and it gets no development warning, no `aria-expanded` or `aria-controls`, and no announcement, since its text is already its content. Implementation gap: not yet built (Current-state impact). | DEC-1; WCAG 1.4.13, 2.1.1 |
-| FR10 | While `triggerBehavior="toggle"` wires a button trigger, the trigger carries `aria-expanded`, `true` only while pinned, and `aria-controls` naming the surface while it shows, each replacing the trigger's own value while wired and restored on cleanup; FR2's `aria-describedby` is kept. When the tooltip pins, its text is announced once through a polite live region; a preview announces nothing beyond the description. Implementation gap: not yet built (Current-state impact). | 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:Tooltip` FR9 (a pinning press stops at its trigger); `component:Tooltip` DEC-1 (one tap does one thing); `architecture:layer-runtime` INV17 |
+| 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 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 |
+| 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 | With `triggerBehavior="toggle"` and a trigger whose role is `button` (a `<button>` or `role="button"`), a click, a completed tap, Enter, or Space on the trigger pins the tooltip open, and the same press on a pinned tooltip closes it. Hover and keyboard focus still preview it per FR3 and FR4; on touch no preview opens and a tap pins it, while a touch that becomes a scroll pins nothing. A pinned tooltip stays open when the pointer leaves the trigger and the surface; Escape (FR6), a second press, a press outside the trigger and the surface, or focus moving outside them closes it. In a controlled tooltip a press reports the toggled value through `onOpenChange` and does not change the state itself (FR7). A press that pins or closes the layer stops at its trigger: it does not reach a clickable row, card, or container around it, or the control a label names. With `anchorRef`, or `useTooltip` with a caller's trigger, the caller's own handlers still receive the press: the anchor's `onClick` runs, and a plain `onClick` element around the anchor receives it unless the anchor's `onClick` stops it; Astryx clickable rows, cards, and containers ignore it. A trigger whose role is not `button` gets a development warning and keeps tap-only opening: every completed tap opens the tooltip, and no press pins it. A trigger whose tooltip repeats its own visible text, such as a truncated Text that is its own tab stop, may take `triggerBehavior="toggle"` without being a button: a press pins it as on a button trigger, and it gets no development warning, no `aria-expanded` or `aria-controls`, and no announcement, since its text is already its content. Implementation gaps (Current-state impact): the own-text clause is not built in Core yet. A pin whose trigger renders in another document, such as an iframe or a Picture-in-Picture window, does not yet close on a press outside there. An Item row still runs on a press of an anchored or caller's trigger that is not a native button. | DEC-1; WCAG 1.4.13, 2.1.1 |
+| FR10 | While `triggerBehavior="toggle"` wires a button trigger, the trigger carries `aria-expanded`, `true` only while pinned, and `aria-controls` naming the surface while it shows, each replacing the trigger's own value while wired and restored on cleanup; FR2's `aria-describedby` is kept. 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:Tooltip` FR9 (a pinning press stops at its trigger); `component:Tooltip` DEC-1 (one tap does one thing); `architecture:layer-runtime` INV17 |
### Allowed variation
@@ -270,7 +286,6 @@ Consumer migration instructions belong in consumer docs and release notes.
(FR10), apart from FR9's trigger whose tooltip repeats its own text; keyboard and touch users pin and close the tooltip without hover
(FR9); it is announced once when it pins (FR10); and it persists until
Escape, a second press, a press outside, or focus leaving (FR9, WCAG 1.4.13).
- Implementation gap: not yet built.
## Design relationships
@@ -310,8 +325,9 @@ has no arrow element.
| 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` |
-| FR9, FR10, AR6 | Evidence gap until built: a press-toggle suite in `Tooltip.test.tsx` and `useTooltip.test.tsx`, and a real-touch and keyboard case in `TouchTrigger.a11y.chromium.spec.ts` | Click, Enter, Space, and tap pin; second press, press outside, focus leaving, and Escape close; pointer leave keeps the pin; controlled; non-button trigger; a truncated Text trigger whose tooltip repeats its text; a toggle trigger inside a ClickableCard, an Item row, and a `<label>` | A press that does not pin or close as stated, a pin lost on pointer leave, a missing or stale `aria-expanded` or `aria-controls`, a second announcement, a non-button trigger without the warning or its tap fallback, an own-text trigger that warns, gets `aria-expanded`, or is announced, or a pinning press that also activates the card, row, or labelled control around the trigger, fails. | `audit:Tooltip/behavior` |
-| FR5, FR9 (`triggerBehavior`) | Evidence gap until built: a trigger-behavior suite in `Tooltip.test.tsx` and `useTooltip.test.tsx`, and a real-touch and pen case in `TouchTrigger.a11y.chromium.spec.ts` | `adaptive` by default and explicitly, `hover`, and `toggle`, each with mouse hover, keyboard focus, touch, and pen; `touchTrigger` beside each value | Under any value, a lost hover or keyboard-focus preview; under `adaptive`, an info-only tap that leaves the tooltip shut or a press that pins it; under `hover`, a touch or pen tap that opens it or a press that pins it; under `toggle`, a click, tap, Enter, or Space that does not pin or close it as FR9 states; or a `touchTrigger` that changes `hover` or `toggle`, fails. | `audit:Tooltip/behavior` |
+| FR9, FR10, AR6 | `usePressPin.test.tsx` Tooltip suites; `TouchTrigger.a11y.chromium.spec.ts` toggle-behavior and mouse cases; `layerDismissalFamilies.test.tsx` pinned Tooltip over a Dialog; own text: evidence gap until built | Click, Enter, Space, and tap pin; second press, press outside, focus leaving, and Escape close; pointer leave keeps the pin; controlled; non-button trigger; a truncated Text trigger whose tooltip repeats its text; a toggle trigger inside a ClickableCard, an Item row, and a `<label>` | A press that does not pin or close as stated, a pin lost on pointer leave, a missing or stale `aria-expanded` or `aria-controls`, a second announcement, a non-button trigger without the warning or its tap fallback, an own-text trigger that warns, gets `aria-expanded`, or is announced, or a pinning press that also activates the card, row, or labelled control around a child trigger, fails. | `audit:Tooltip/behavior` |
+| FR9 (`anchorRef`) | `usePressPin.test.tsx` `anchorRef` suite; `TouchTrigger.a11y.chromium.spec.ts` anchored case | An anchor with its own `onClick`, inside a ClickableCard, an Item row, a Table row that expands on click, and a plain `onClick` row | An anchor's own `onClick` that does not run, or an Astryx card, row, or Table row around the anchor that activates, fails. | `audit:Tooltip/behavior` |
+| FR5, FR9 (`triggerBehavior`) | Evidence gap: a trigger-behavior suite in `Tooltip.test.tsx`, a touch and pen case in `TouchTrigger.a11y.chromium.spec.ts`, and FR9's `useTooltip` clause in `useTooltip.test.tsx` | `adaptive` by default and explicitly, `hover`, and `toggle`, each with mouse hover, keyboard focus, touch, and pen; `touchTrigger` beside each value; a `useTooltip` trigger inside an Astryx clickable card and inside a plain `onClick` element | Under any value, a lost hover or keyboard-focus preview; under `adaptive`, an info-only tap that leaves the tooltip shut or a press that pins it; under `hover`, a touch or pen tap that opens it or a press that pins it; under `toggle`, a click, tap, Enter, or Space that does not pin or close it as FR9 states; or a `touchTrigger` that changes `hover` or `toggle`, fails. | `audit:Tooltip/behavior` |
| FR11 | `Tooltip.test.tsx` surface-press suite; `FileInputTooltipPress.a11y.chromium.spec.ts` | A tooltip inside a clickable container and inside a `<label>`; FileInput compact and dropzone status tooltips, with a click on the empty dropzone as the positive control | A click on tooltip text that runs the container's click handler, checks or focuses a labelled control, or opens the file picker fails. | — |
| DEP-0016, CLN-0024 | Evidence gap until built: the codemod's tests and fixtures beside its transform, and the codemod verify workflow | `touchTrigger="tap"` on an icon and a span, and on an own-text trigger, an info-only button, a button with its own action, a link, and an unknown element, under each codemod; `"auto"` and `"none"`; `triggerBehavior` beside `touchTrigger`; spreads and dynamic values | A rewrite that changes behavior; under DEP-0016's codemod, a rewritten own-text, button, link, or unknown-element site; under CLN-0024's codemod, a rewritten button, link, or unknown-element site, or an identifiable own-text site left unrewritten; a reported site without its manual-migration note (all three options for a button or link); a missed static use; or a silently skipped dynamic one fails. | `audit:Tooltip/api` |
| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target | Missing, extra, prefixed, or stale mappings fail repository validation. | `audit:Tooltip/theming` |
diff --git a/packages/core/api-report.md b/packages/core/api-report.md
index aa30a74bee..ceeeb3ba91 100644
--- a/packages/core/api-report.md
+++ b/packages/core/api-report.md
@@ -2674,6 +2674,7 @@ component Tooltip(props: TooltipProps)
prop onOpenChange?: (isOpen: boolean) => void
prop placement?: LayerPlacement = 'above'
prop touchTrigger?: TooltipTouchTrigger = 'auto'
+ prop triggerBehavior?: TooltipTriggerBehavior = 'adaptive'
component TopNav(props: TopNavProps)
prop centerContent?: ReactNode
prop children?: ReactNode
@@ -5654,6 +5655,7 @@ interface TooltipOptions
onShow?: () => void
placement?: LayerPlacement = 'above'
touchTrigger?: TooltipTouchTrigger = 'auto'
+ triggerBehavior?: TooltipTriggerBehavior = 'adaptive'
interface TooltipProps (props of Tooltip)
interface TooltipReturn
anchorId: string
@@ -5663,6 +5665,7 @@ interface TooltipReturn
ref: RefCallback<HTMLElement>
renderTooltip: (children: ReactNode, props?: Omit<ContextRenderProps, 'positioning'>) => ReactNode
type TooltipTouchTrigger = LayerTouchTrigger
+type TooltipTriggerBehavior = 'adaptive' | 'hover' | 'toggle'
interface TopNavHeadingProps extends BaseProps<HTMLElement> (props of TopNavHeading)
interface TopNavItemProps extends BaseProps<HTMLAnchorElement> (props of TopNavItem)
interface TopNavMegaMenuFeaturedCardProps extends BaseProps<HTMLDivElement> (props of TopNavMegaMenuFeaturedCard)
@@ -8902,6 +8905,7 @@ TooltipOptions (.)
TooltipProps (.)
TooltipReturn (.)
TooltipTouchTrigger (.)
+TooltipTriggerBehavior (.)
useTooltip (.)
```
diff --git a/packages/core/src/Layer/__tests__/TouchTrigger.a11y.chromium.spec.ts b/packages/core/src/Layer/__tests__/TouchTrigger.a11y.chromium.spec.ts
index bc1f163433..f1a3f32999 100644
--- a/packages/core/src/Layer/__tests__/TouchTrigger.a11y.chromium.spec.ts
+++ b/packages/core/src/Layer/__tests__/TouchTrigger.a11y.chromium.spec.ts
@@ -198,3 +198,147 @@ for (const {name, story, trigger, action, layer} of cases) {
});
});
}
+
+test.describe('Tooltip triggerBehavior="toggle" (component:Tooltip FR9, FR10)', () => {
+ const STORY = 'a11y-tooltip-toggle-behavior--button-toggle';
+ const CARD_STORY = 'a11y-tooltip-toggle-behavior--in-a-clickable-card';
+ const LAYER = '.astryx-tooltip:popover-open';
+ const pinButton = (page: Page) =>
+ page.getByRole('button', {name: 'What is this?'});
+
+ test('a real tap pins the tooltip, and the next tap on the trigger closes it', async ({
+ page,
+ }) => {
+ const finger = await openStory(page, STORY);
+ const button = pinButton(page);
+ await expect(button).toBeVisible();
+ await expect(button).toHaveAttribute('aria-expanded', 'false');
+ const [x, y] = await centerOf(button);
+ await finger.down(x, y);
+ await finger.up();
+ await expect(page.locator(LAYER)).toHaveCount(1);
+ await expect(page.locator(LAYER)).toBeVisible();
+ await expect(button).toHaveAttribute('aria-expanded', 'true');
+ await finger.down(x, y);
+ await finger.up();
+ await expect(page.locator(LAYER)).toHaveCount(0);
+ await expect(button).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ test('a tap outside closes a pinned tooltip', async ({page}) => {
+ const finger = await openStory(page, STORY);
+ const button = pinButton(page);
+ await expect(button).toBeVisible();
+ const [x, y] = await centerOf(button);
+ await finger.down(x, y);
+ await finger.up();
+ await expect(page.locator(LAYER)).toHaveCount(1);
+ await finger.down(...OUTSIDE);
+ await finger.up();
+ await expect(page.locator(LAYER)).toHaveCount(0);
+ await expect(button).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ test('Enter pins it and Space closes it from the keyboard', async ({
+ page,
+ }) => {
+ await openStory(page, STORY);
+ const button = pinButton(page);
+ await expect(button).toBeVisible();
+ await button.focus();
+ await page.keyboard.press('Enter');
+ await expect(button).toHaveAttribute('aria-expanded', 'true');
+ await expect(page.locator(LAYER)).toHaveCount(1);
+ await page.keyboard.press(' ');
+ await expect(button).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ test('a tap on the trigger inside a clickable card pins its tooltip and stops there', async ({
+ page,
+ }) => {
+ const finger = await openStory(page, CARD_STORY);
+ const button = pinButton(page);
+ const count = page.getByText(/^Card opened \d+ times$/);
+ await expect(button).toBeVisible();
+ await expect(count).toHaveText('Card opened 0 times');
+ const [x, y] = await centerOf(button);
+ await finger.down(x, y);
+ await finger.up();
+ await expect(page.locator(LAYER)).toHaveCount(1);
+ await expect(button).toHaveAttribute('aria-expanded', 'true');
+ await expect(count).toHaveText('Card opened 0 times');
+ await page.mouse.click(x, y);
+ await expect(page.locator(LAYER)).toHaveCount(0);
+ await expect(count).toHaveText('Card opened 0 times');
+ });
+});
+
+test.describe('a pinned layer under a mouse (component:Tooltip FR9)', () => {
+ test.use({
+ hasTouch: false,
+ isMobile: false,
+ viewport: {width: 1024, height: 768},
+ });
+
+ async function open(page: Page, id: string) {
+ await page.goto(`${storybook.origin}/iframe.html?id=${id}&viewMode=story`);
+ }
+
+ /** Whether focus sits on no element: a press on text that takes none. */
+ async function focusIsOnBody(page: Page): Promise<boolean> {
+ return page.evaluate(() => document.activeElement === document.body);
+ }
+
+ test('a click on a pinned tooltip’s own text keeps it pinned', async ({
+ page,
+ }) => {
+ await open(page, 'a11y-tooltip-toggle-behavior--button-toggle');
+ const button = page.getByRole('button', {name: 'What is this?'});
+ const layer = page.locator('.astryx-tooltip:popover-open');
+ await button.click();
+ await expect(layer).toHaveCount(1);
+ await expect(button).toHaveAttribute('aria-expanded', 'true');
+ await layer
+ .getByText('Rows are ranked by how many places import the icon')
+ .click();
+ expect(await focusIsOnBody(page)).toBe(true);
+ await expect(layer).toHaveCount(1);
+ await expect(button).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ test('a click on an anchored trigger runs its own click handler and pins it, and the card around it ignores the press', async ({
+ page,
+ }) => {
+ await open(page, 'a11y-tooltip-toggle-behavior--anchored-action-in-a-card');
+ const button = page.getByRole('button', {name: 'What is this?'});
+ const layer = page.locator('.astryx-tooltip:popover-open');
+ const opened = page.getByText(/^Card opened \d+ times$/);
+ const pressed = page.getByText(/^Button pressed \d+ times$/);
+ await expect(opened).toHaveText('Card opened 0 times');
+ await expect(pressed).toHaveText('Button pressed 0 times');
+ await button.click();
+ await expect(layer).toHaveCount(1);
+ await expect(button).toHaveAttribute('aria-expanded', 'true');
+ await expect(pressed).toHaveText('Button pressed 1 times');
+ await expect(opened).toHaveText('Card opened 0 times');
+ await button.click();
+ await expect(layer).toHaveCount(0);
+ await expect(pressed).toHaveText('Button pressed 2 times');
+ await expect(opened).toHaveText('Card opened 0 times');
+ });
+
+ test('with focusTrigger="never", Tab to another control closes a pinned tooltip', async ({
+ page,
+ }) => {
+ await open(page, 'a11y-tooltip-toggle-behavior--focus-trigger-never');
+ const button = page.getByRole('button', {name: 'What is this?'});
+ const layer = page.locator('.astryx-tooltip:popover-open');
+ await button.click();
+ await expect(layer).toHaveCount(1);
+ await expect(button).toBeFocused();
+ await page.keyboard.press('Tab');
+ await expect(page.getByRole('button', {name: 'Next'})).toBeFocused();
+ await expect(layer).toHaveCount(0);
+ await expect(button).toHaveAttribute('aria-expanded', 'false');
+ });
+});
diff --git a/packages/core/src/Layer/layerClickBoundary.ts b/packages/core/src/Layer/layerClickBoundary.ts
index ed32d2eacc..221243a7ef 100644
--- a/packages/core/src/Layer/layerClickBoundary.ts
+++ b/packages/core/src/Layer/layerClickBoundary.ts
@@ -6,7 +6,7 @@
* @file layerClickBoundary.ts
* @input React pointer, mouse, touch and click events on a layer root
* @output Exports layerClickBoundary, the props every layer content root
- * spreads, including the layer-root mark
+ * spreads, including the layer-root mark; also stopInReactTree
* @position Internal to Layer; used by useLayer's renderers and the Dialog,
* Drawer, Lightbox, MobileNav, BottomSheetPanel and ToastViewport roots.
* Not exported from the package.
@@ -61,7 +61,7 @@ const returnTrue = () => true;
* React's dispatch asks `isPropagationStopped()` before each further
* listener; the native event is left alone.
*/
-function stopInReactTree(event: SyntheticEvent): void {
+export function stopInReactTree(event: SyntheticEvent): void {
event.isPropagationStopped = returnTrue;
}
diff --git a/packages/core/src/Layer/layerDismissalFamilies.test.tsx b/packages/core/src/Layer/layerDismissalFamilies.test.tsx
index 60826849f5..c59471ac3c 100644
--- a/packages/core/src/Layer/layerDismissalFamilies.test.tsx
+++ b/packages/core/src/Layer/layerDismissalFamilies.test.tsx
@@ -3,7 +3,7 @@
/**
* @file layerDismissalFamilies.test.tsx
* @input Uses vitest, @testing-library/react, BottomSheet, Dialog, Lightbox,
- * MobileNav, HoverCard, Tooltip
+ * MobileNav, HoverCard, Tooltip (also pinned by `triggerBehavior="toggle"`)
* @output Tests that every overlay family shares the one dismissal stack
* @position Colocated with layerStack; the families' own behavior is tested in
* their own files, this one only asks who takes the press
@@ -433,6 +433,38 @@ describe('overlay families on the shared dismissal stack', () => {
expect(event.defaultPrevented).toBe(true);
});
+ it('a Tooltip a press pinned takes the Escape first, and the Dialog stays open (spec:AST-003 FR4)', () => {
+ const onDialogChange = vi.fn();
+
+ render(
+ <Dialog isOpen={true} onOpenChange={onDialogChange} aria-label="Host">
+ <Tooltip content="Pinned tip" triggerBehavior="toggle">
+ <button type="button">Info</button>
+ </Tooltip>
+ </Dialog>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Info'}));
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();
+ expect(screen.getByRole('button', {name: 'Info'})).toHaveAttribute(
+ 'aria-expanded',
+ 'true',
+ );
+ vi.mocked(HTMLElement.prototype.hidePopover).mockClear();
+
+ let event = new KeyboardEvent('keydown');
+ act(() => {
+ event = pressEscape();
+ });
+
+ expect(HTMLElement.prototype.hidePopover).toHaveBeenCalled();
+ expect(screen.getByRole('button', {name: 'Info'})).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ );
+ expect(onDialogChange).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(true);
+ });
+
it('a controlled Tooltip takes the press and reports instead of hiding', () => {
const onTipChange = vi.fn();
const onDialogChange = vi.fn();
diff --git a/packages/core/src/Layer/usePressPin.calls.test.tsx b/packages/core/src/Layer/usePressPin.calls.test.tsx
new file mode 100644
index 0000000000..211489e1a6
--- /dev/null
+++ b/packages/core/src/Layer/usePressPin.calls.test.tsx
@@ -0,0 +1,110 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file usePressPin.calls.test.tsx
+ * @input Tooltip, with usePressPin, the touch trigger hooks and
+ * useLayerDismissal wrapped in call counters
+ * @output Unit tests: the layer's hook makes one usePressPin call per render,
+ * and that call is the only path to the touch trigger
+ * (`architecture:react-component-runtime` INV16)
+ * @position Beside usePressPin.test.tsx, which covers what the pin does
+ *
+ * useLayerDismissal runs once per render, so one usePressPin call per render
+ * shows as equal counts. Touch trigger calls come only from usePressPin.
+ */
+
+import {fireEvent, render, screen} from '@testing-library/react';
+import {beforeEach, describe, expect, it, vi} from 'vitest';
+import type * as PressPinModule from './usePressPin';
+import type * as TouchTriggerModule from './useTouchTrigger';
+import type * as LayerDismissalModule from './useLayerDismissal';
+
+const calls = vi.hoisted(() => ({
+ pin: 0,
+ touch: 0,
+ publicTouch: 0,
+ touchOutsidePin: 0,
+ render: 0,
+ isInPin: false,
+}));
+
+vi.mock('./usePressPin', async importOriginal => {
+ const actual = await importOriginal<typeof PressPinModule>();
+ return {
+ ...actual,
+ usePressPin: (options: PressPinModule.UsePressPinOptions) => {
+ calls.pin += 1;
+ calls.isInPin = true;
+ try {
+ return actual.usePressPin(options);
+ } finally {
+ calls.isInPin = false;
+ }
+ },
+ };
+});
+
+vi.mock('./useTouchTrigger', async importOriginal => {
+ const actual = await importOriginal<typeof TouchTriggerModule>();
+ return {
+ ...actual,
+ useTouchTrigger: (options: TouchTriggerModule.UseTouchTriggerOptions) => {
+ calls.publicTouch += 1;
+ return actual.useTouchTrigger(options);
+ },
+ useTouchTriggerInternal: (
+ options: TouchTriggerModule.UseTouchTriggerOptions,
+ ) => {
+ calls.touch += 1;
+ if (!calls.isInPin) {
+ calls.touchOutsidePin += 1;
+ }
+ return actual.useTouchTriggerInternal(options);
+ },
+ };
+});
+
+vi.mock('./useLayerDismissal', async importOriginal => {
+ const actual = await importOriginal<typeof LayerDismissalModule>();
+ return {
+ ...actual,
+ useLayerDismissal: (
+ options: LayerDismissalModule.UseLayerDismissalOptions,
+ ) => {
+ calls.render += 1;
+ return actual.useLayerDismissal(options);
+ },
+ };
+});
+
+const {Tooltip} = await import('../Tooltip/Tooltip');
+
+beforeEach(() => {
+ calls.pin = 0;
+ calls.touch = 0;
+ calls.publicTouch = 0;
+ calls.touchOutsidePin = 0;
+ calls.render = 0;
+});
+
+function expectOneCallPerRender() {
+ expect(calls.render).toBeGreaterThan(0);
+ expect(calls.pin).toBe(calls.render);
+ expect(calls.touch).toBe(calls.pin);
+ expect(calls.touchOutsidePin).toBe(0);
+ expect(calls.publicTouch).toBe(0);
+}
+
+describe('usePressPin is each layer’s one call (react-component-runtime INV16)', () => {
+ it('Tooltip: one usePressPin call per render, the only path to the touch trigger', () => {
+ render(
+ <Tooltip
+ content="Billed on the first of each month"
+ triggerBehavior="toggle">
+ <button type="button">About billing</button>
+ </Tooltip>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'About billing'}));
+ expectOneCallPerRender();
+ });
+});
diff --git a/packages/core/src/Layer/usePressPin.test.tsx b/packages/core/src/Layer/usePressPin.test.tsx
new file mode 100644
index 0000000000..030601f04e
--- /dev/null
+++ b/packages/core/src/Layer/usePressPin.test.tsx
@@ -0,0 +1,758 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file usePressPin.test.tsx
+ * @input Uses vitest, @testing-library/react, Tooltip, usePressPin
+ * @output Tests of `triggerBehavior="toggle"`: a press pins and closes the
+ * layer, and a pin stays when the pointer leaves. Escape, a second press, a
+ * press outside, or focus leaving closes it. The trigger carries the toggle
+ * state, the press stops at the trigger, and a non-button trigger warns.
+ * @position Unit tests beside usePressPin
+ *
+ * SYNC: When usePressPin.ts or useTooltip.tsx change, update these cases.
+ */
+
+import {
+ describe,
+ it,
+ expect,
+ vi,
+ beforeAll,
+ beforeEach,
+ afterAll,
+ afterEach,
+} from 'vitest';
+import {render, screen, fireEvent, act} from '@testing-library/react';
+import {useRef, useState, type ReactElement, type ReactNode} from 'react';
+import {Tooltip} from '../Tooltip/Tooltip';
+import {ClickableCard} from '../ClickableCard/ClickableCard';
+import {Dialog} from '../Dialog/Dialog';
+import {Item} from '../Item/Item';
+import {Table} from '../Table/Table';
+import {useTableRowExpansion} from '../Table/plugins/rowExpansion/useTableRowExpansion';
+import {announceMessage} from '../hooks/useAnnounce';
+import type * as UseAnnounceModule from '../hooks/useAnnounce';
+import {__resetInteractionModalityForTest} from '../utils/interactionModality';
+import {__resetDevWarnings} from '../utils/devWarning';
+
+// useAnnounce routes the pin's message into an open modal's own region.
+const {announce} = vi.hoisted(() => ({announce: vi.fn()}));
+vi.mock('../hooks/useAnnounce', async importOriginal => ({
+ ...(await importOriginal<typeof UseAnnounceModule>()),
+ announceMessage: vi.fn(() => null),
+ useAnnounce: () => announce,
+}));
+
+const originalMatches = HTMLElement.prototype.matches;
+const popoverOpenState = new WeakMap<HTMLElement, boolean>();
+
+beforeAll(() => {
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ popoverOpenState.set(this, true);
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ popoverOpenState.set(this, false);
+ });
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (HTMLElement.prototype as any).matches = function (
+ this: HTMLElement,
+ selector: string,
+ ): boolean {
+ if (selector === ':popover-open') {
+ return popoverOpenState.get(this) ?? false;
+ }
+ return originalMatches.call(this, selector);
+ };
+});
+
+afterAll(() => {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (HTMLElement.prototype as any).matches = originalMatches;
+});
+
+beforeEach(() => {
+ __resetInteractionModalityForTest();
+ __resetDevWarnings();
+ vi.mocked(announceMessage).mockClear();
+ announce.mockClear();
+ // jsdom does not implement showModal/close.
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ this.removeAttribute('open');
+ });
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+/** The layer holding `text`, when it is rendered. */
+function layerOf(text: string): HTMLElement | null {
+ return (
+ screen
+ .queryByText(text, {exact: false})
+ ?.closest<HTMLElement>('[popover]') ?? null
+ );
+}
+
+/** Whether the layer holding `text` shows. */
+function shows(text: string): boolean {
+ const layer = layerOf(text);
+ return layer != null && layer.matches(':popover-open');
+}
+
+/** A finger's tap, in the order a browser dispatches it. */
+function tap(element: HTMLElement) {
+ fireEvent.pointerEnter(element, {pointerType: 'touch'});
+ fireEvent.pointerDown(element, {pointerType: 'touch'});
+ fireEvent.pointerUp(element, {pointerType: 'touch'});
+ fireEvent.mouseEnter(element);
+ fireEvent.click(element);
+}
+
+/** A mouse click: the press, then its click. */
+function click(element: HTMLElement) {
+ fireEvent.pointerDown(element, {pointerType: 'mouse'});
+ fireEvent.pointerUp(element, {pointerType: 'mouse'});
+ fireEvent.click(element, {detail: 1});
+}
+
+function InfoTooltip({
+ children,
+ ...props
+}: {
+ children?: ReactNode;
+ isOpen?: boolean;
+ onOpenChange?: (isOpen: boolean) => void;
+}): ReactElement {
+ return (
+ <Tooltip
+ content="Billed on the first of each month"
+ triggerBehavior="toggle"
+ {...props}>
+ {children ?? (
+ <button type="button" aria-label="About billing">
+ i
+ </button>
+ )}
+ </Tooltip>
+ );
+}
+
+const TIP = 'Billed on the first of each month';
+
+describe('Tooltip triggerBehavior="toggle" (component:Tooltip FR9)', () => {
+ it('a click pins the tooltip open, and the same click closes it', () => {
+ render(<InfoTooltip />);
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ click(trigger);
+ expect(shows(TIP)).toBe(true);
+ click(trigger);
+ expect(shows(TIP)).toBe(false);
+ });
+
+ it('a pinned tooltip stays when the pointer leaves the trigger', () => {
+ vi.useFakeTimers();
+ render(<InfoTooltip />);
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ click(trigger);
+ fireEvent.mouseLeave(trigger);
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+ expect(shows(TIP)).toBe(true);
+ });
+
+ it('a tap pins it, and the next tap on the trigger closes it', () => {
+ render(<InfoTooltip />);
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ tap(trigger);
+ expect(shows(TIP)).toBe(true);
+ tap(trigger);
+ expect(shows(TIP)).toBe(false);
+ });
+
+ it('Enter and Space on a role="button" trigger pin and close it', () => {
+ render(
+ <InfoTooltip>
+ <span role="button" tabIndex={0}>
+ About billing
+ </span>
+ </InfoTooltip>,
+ );
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ fireEvent.keyDown(trigger, {key: 'Enter'});
+ expect(shows(TIP)).toBe(true);
+ fireEvent.keyDown(trigger, {key: ' '});
+ expect(shows(TIP)).toBe(false);
+ });
+
+ it('Escape closes a pinned tooltip', () => {
+ render(<InfoTooltip />);
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ click(trigger);
+ fireEvent.keyDown(trigger, {key: 'Escape'});
+ expect(shows(TIP)).toBe(false);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('a press outside closes it, and a press on the tooltip keeps it', () => {
+ render(
+ <>
+ <InfoTooltip />
+ <p>Elsewhere</p>
+ </>,
+ );
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ click(trigger);
+ const layer = layerOf(TIP) as HTMLElement;
+ fireEvent.pointerDown(layer);
+ fireEvent.pointerUp(layer);
+ expect(shows(TIP)).toBe(true);
+ // The outside dismissal (useTouchTrigger) closes it when the press lifts.
+ const elsewhere = screen.getByText('Elsewhere');
+ fireEvent.pointerDown(elsewhere);
+ fireEvent.pointerUp(elsewhere);
+ expect(shows(TIP)).toBe(false);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('a scroll that starts outside closes it', () => {
+ render(
+ <>
+ <InfoTooltip />
+ <p>Elsewhere</p>
+ </>,
+ );
+ click(screen.getByRole('button', {name: 'About billing'}));
+ fireEvent.pointerCancel(screen.getByText('Elsewhere'));
+ expect(shows(TIP)).toBe(false);
+ });
+
+ it('focus moving outside closes it', () => {
+ render(
+ <>
+ <InfoTooltip />
+ <button type="button">Next field</button>
+ </>,
+ );
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ act(() => {
+ trigger.focus();
+ });
+ click(trigger);
+ expect(shows(TIP)).toBe(true);
+ act(() => {
+ screen.getByRole('button', {name: 'Next field'}).focus();
+ });
+ expect(shows(TIP)).toBe(false);
+ });
+
+ it('a press on the pinned tooltip’s own text keeps it, though focus moves to no element', () => {
+ render(<InfoTooltip />);
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ act(() => {
+ trigger.focus();
+ });
+ click(trigger);
+ // In Chromium a press on text that takes no focus moves focus from the
+ // trigger to the body: the focusout names no element.
+ const text = screen.getByText(TIP);
+ fireEvent.pointerDown(text);
+ fireEvent.focusOut(trigger, {relatedTarget: null});
+ fireEvent.pointerUp(text);
+ fireEvent.click(text);
+ expect(shows(TIP)).toBe(true);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('a triggerBehavior that turns to toggle after mount wires the trigger', () => {
+ const {rerender} = render(
+ <Tooltip content={TIP}>
+ <button type="button" aria-label="About billing">
+ i
+ </button>
+ </Tooltip>,
+ );
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ expect(trigger).not.toHaveAttribute('aria-expanded');
+ rerender(
+ <Tooltip content={TIP} triggerBehavior="toggle">
+ <button type="button" aria-label="About billing">
+ i
+ </button>
+ </Tooltip>,
+ );
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ click(trigger);
+ expect(shows(TIP)).toBe(true);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ rerender(
+ <Tooltip content={TIP}>
+ <button type="button" aria-label="About billing">
+ i
+ </button>
+ </Tooltip>,
+ );
+ expect(trigger).not.toHaveAttribute('aria-expanded');
+ });
+
+ it('with focusTrigger="never", focus moving to another control closes a pinned tooltip', () => {
+ render(
+ <>
+ <Tooltip content={TIP} triggerBehavior="toggle" focusTrigger="never">
+ <button type="button" aria-label="About billing">
+ i
+ </button>
+ </Tooltip>
+ <button type="button">Next field</button>
+ </>,
+ );
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ act(() => {
+ trigger.focus();
+ });
+ click(trigger);
+ expect(shows(TIP)).toBe(true);
+ act(() => {
+ screen.getByRole('button', {name: 'Next field'}).focus();
+ });
+ expect(shows(TIP)).toBe(false);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('a pinned tooltip whose triggerBehavior turns to adaptive closes on leave again', () => {
+ vi.useFakeTimers();
+ const tip = (triggerBehavior?: 'toggle') => (
+ <Tooltip content={TIP} triggerBehavior={triggerBehavior}>
+ <button type="button" aria-label="About billing">
+ i
+ </button>
+ </Tooltip>
+ );
+ const {rerender} = render(tip('toggle'));
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ click(trigger);
+ expect(shows(TIP)).toBe(true);
+ rerender(tip());
+ fireEvent.mouseLeave(trigger);
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+ expect(shows(TIP)).toBe(false);
+ });
+
+ it('a controlled tooltip reports the toggled value and does not change itself (FR7)', () => {
+ const onOpenChange = vi.fn();
+ render(<InfoTooltip isOpen={false} onOpenChange={onOpenChange} />);
+ click(screen.getByRole('button', {name: 'About billing'}));
+ expect(onOpenChange).toHaveBeenCalledWith(true);
+ expect(shows(TIP)).toBe(false);
+ });
+
+ it('a trigger that is not a button warns and keeps tap-only opening', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ render(
+ <InfoTooltip>
+ <span tabIndex={0}>Billing</span>
+ </InfoTooltip>,
+ );
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('triggerBehavior="toggle"'),
+ );
+ const trigger = screen.getByText('Billing');
+ click(trigger);
+ expect(shows(TIP)).toBe(false);
+ expect(trigger).not.toHaveAttribute('aria-expanded');
+ tap(trigger);
+ expect(shows(TIP)).toBe(true);
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ it('warns once per trigger: at mount, and not again on re-render or re-attach', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ const tip = (delay: number) => (
+ <Tooltip content={TIP} triggerBehavior="toggle" delay={delay}>
+ <span tabIndex={0}>Billing</span>
+ </Tooltip>
+ );
+ const {rerender} = render(tip(200));
+ rerender(tip(300));
+ rerender(tip(400));
+ const calls = warn.mock.calls.filter(([message]) =>
+ String(message).includes('triggerBehavior="toggle"'),
+ );
+ expect(calls).toHaveLength(1);
+ } finally {
+ warn.mockRestore();
+ }
+ });
+});
+
+describe('Tooltip triggerBehavior="adaptive" and "hover" (component:Tooltip FR5)', () => {
+ /** An info-only trigger: a tap on it performs no action of its own. */
+ function Hint(props: {triggerBehavior?: 'adaptive' | 'hover'}): ReactElement {
+ return (
+ <Tooltip content={TIP} {...props}>
+ <span tabIndex={0}>Billing</span>
+ </Tooltip>
+ );
+ }
+
+ it('adaptive, the default: a tap on an info-only trigger opens it', () => {
+ render(<Hint />);
+ tap(screen.getByText('Billing'));
+ expect(shows(TIP)).toBe(true);
+ });
+
+ it('hover: a tap never opens it, a mouse hover still previews it, and no press pins it', () => {
+ vi.useFakeTimers();
+ render(<Hint triggerBehavior="hover" />);
+ const trigger = screen.getByText('Billing');
+ tap(trigger);
+ expect(shows(TIP)).toBe(false);
+ fireEvent.pointerEnter(trigger, {pointerType: 'mouse'});
+ fireEvent.mouseEnter(trigger);
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ expect(shows(TIP)).toBe(true);
+ click(trigger);
+ expect(trigger).not.toHaveAttribute('aria-expanded');
+ });
+});
+
+describe('Tooltip triggerBehavior="toggle" trigger state (component:Tooltip FR10)', () => {
+ it('carries aria-expanded, true only while pinned, and aria-controls while it shows', () => {
+ render(<InfoTooltip />);
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(trigger).not.toHaveAttribute('aria-controls');
+ click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ expect(trigger).toHaveAttribute(
+ 'aria-controls',
+ (layerOf(TIP) as HTMLElement).id,
+ );
+ // The description link is kept (FR2).
+ expect(trigger.getAttribute('aria-describedby')).toContain(
+ (layerOf(TIP) as HTMLElement).id,
+ );
+ click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(trigger).not.toHaveAttribute('aria-controls');
+ });
+
+ it('a hover preview leaves aria-expanded false', () => {
+ vi.useFakeTimers();
+ render(<InfoTooltip />);
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ fireEvent.pointerEnter(trigger, {pointerType: 'mouse'});
+ fireEvent.mouseEnter(trigger);
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ expect(shows(TIP)).toBe(true);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it("restores the trigger's own aria-expanded and aria-controls on cleanup", () => {
+ const {unmount} = render(
+ <InfoTooltip>
+ <button type="button" aria-expanded="false" aria-controls="menu-1">
+ Menu
+ </button>
+ </InfoTooltip>,
+ );
+ const trigger = screen.getByRole('button', {name: 'Menu'});
+ click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ unmount();
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(trigger).toHaveAttribute('aria-controls', 'menu-1');
+ });
+
+ it('announces its text once when it pins, and nothing for a preview', () => {
+ vi.useFakeTimers();
+ render(<InfoTooltip />);
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ fireEvent.pointerEnter(trigger, {pointerType: 'mouse'});
+ fireEvent.mouseEnter(trigger);
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ expect(announce).not.toHaveBeenCalled();
+ click(trigger);
+ expect(announce).toHaveBeenCalledTimes(1);
+ expect(announce).toHaveBeenCalledWith(TIP, 'polite');
+ });
+});
+
+describe('a toggle press stops at its trigger', () => {
+ it('a clickable row around the trigger does not activate, and the trigger’s own onClick runs', () => {
+ const onRow = vi.fn();
+ const onOwn = vi.fn();
+ // The stop is React-only: page-level listeners still see each press.
+ const onPage = vi.fn();
+ document.addEventListener('click', onPage);
+ render(
+ <div onClick={onRow}>
+ <InfoTooltip>
+ <button type="button" aria-label="About billing" onClick={onOwn}>
+ i
+ </button>
+ </InfoTooltip>
+ </div>,
+ );
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ tap(trigger);
+ expect(shows(TIP)).toBe(true);
+ expect(onOwn).toHaveBeenCalledTimes(1);
+ expect(onRow).not.toHaveBeenCalled();
+ click(trigger);
+ expect(shows(TIP)).toBe(false);
+ expect(onRow).not.toHaveBeenCalled();
+ expect(onPage).toHaveBeenCalledTimes(2);
+ document.removeEventListener('click', onPage);
+ });
+
+ it('a press inside a label does not operate the labelled control', () => {
+ render(
+ <label>
+ <input type="checkbox" /> Email me
+ <InfoTooltip />
+ </label>,
+ );
+ click(screen.getByRole('button', {name: 'About billing'}));
+ expect(shows(TIP)).toBe(true);
+ expect(screen.getByRole('checkbox')).not.toBeChecked();
+ });
+
+ it('inside a ClickableCard, the card does not open', () => {
+ const onCard = vi.fn();
+ render(
+ <ClickableCard label="Billing" onClick={onCard}>
+ Billing
+ <InfoTooltip />
+ </ClickableCard>,
+ );
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ tap(trigger);
+ expect(shows(TIP)).toBe(true);
+ click(trigger);
+ expect(shows(TIP)).toBe(false);
+ expect(onCard).not.toHaveBeenCalled();
+ });
+
+ describe('with anchorRef (component:Tooltip FR9: the caller’s own handlers still receive the press)', () => {
+ function Anchored({
+ onOwn,
+ stopsOwnClick = false,
+ }: {
+ onOwn?: () => void;
+ stopsOwnClick?: boolean;
+ }) {
+ const ref = useRef<HTMLButtonElement>(null);
+ return (
+ <>
+ <button
+ ref={ref}
+ type="button"
+ aria-label="About billing"
+ onClick={event => {
+ onOwn?.();
+ if (stopsOwnClick) {
+ event.stopPropagation();
+ }
+ }}>
+ i
+ </button>
+ <Tooltip content={TIP} anchorRef={ref} triggerBehavior="toggle" />
+ </>
+ );
+ }
+
+ it('an action anchor’s own onClick fires on a pinning press', () => {
+ const onOwn = vi.fn();
+ render(<Anchored onOwn={onOwn} />);
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ click(trigger);
+ expect(shows(TIP)).toBe(true);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ expect(onOwn).toHaveBeenCalledTimes(1);
+ click(trigger);
+ expect(shows(TIP)).toBe(false);
+ expect(onOwn).toHaveBeenCalledTimes(2);
+ });
+
+ it('an Astryx ClickableCard around the anchor does not open', () => {
+ const onCard = vi.fn();
+ render(
+ <ClickableCard label="Billing" onClick={onCard}>
+ Billing
+ <Anchored />
+ </ClickableCard>,
+ );
+ click(screen.getByRole('button', {name: 'About billing'}));
+ expect(shows(TIP)).toBe(true);
+ expect(onCard).not.toHaveBeenCalled();
+ });
+
+ it('an Astryx Item row around the anchor does not activate', () => {
+ const onRow = vi.fn();
+ render(
+ <Item label="Billing" onClick={onRow} endContent={<Anchored />} />,
+ );
+ click(screen.getByRole('button', {name: 'About billing'}));
+ expect(shows(TIP)).toBe(true);
+ expect(onRow).not.toHaveBeenCalled();
+ });
+
+ it('an Astryx Table row that expands on click does not expand', () => {
+ function Rows() {
+ const [expanded, setExpanded] = useState(new Set<string>());
+ const expansion = useTableRowExpansion<{id: string; name: string}>({
+ expandedKeys: expanded,
+ onToggle: key =>
+ setExpanded(previous => {
+ const next = new Set(previous);
+ if (next.has(key)) {
+ next.delete(key);
+ } else {
+ next.add(key);
+ }
+ return next;
+ }),
+ getRowKey: item => item.id,
+ renderExpanded: item => <div data-testid="panel">{item.name}</div>,
+ hasRowClickExpansion: true,
+ });
+ return (
+ <Table
+ data={[{id: 'a', name: 'Ada'}]}
+ columns={[
+ {key: 'name', header: 'Name', renderCell: () => <Anchored />},
+ ]}
+ idKey="id"
+ plugins={{expansion}}
+ />
+ );
+ }
+ render(<Rows />);
+ click(screen.getByRole('button', {name: 'About billing'}));
+ expect(shows(TIP)).toBe(true);
+ expect(screen.queryByTestId('panel')).not.toBeInTheDocument();
+ });
+
+ it('a plain onClick row receives the press, unless the anchor’s own onClick stops it', () => {
+ const onRow = vi.fn();
+ const {unmount} = render(
+ <div onClick={onRow}>
+ <Anchored />
+ </div>,
+ );
+ click(screen.getByRole('button', {name: 'About billing'}));
+ expect(shows(TIP)).toBe(true);
+ expect(onRow).toHaveBeenCalledTimes(1);
+ unmount();
+ onRow.mockClear();
+ render(
+ <div onClick={onRow}>
+ <Anchored stopsOwnClick />
+ </div>,
+ );
+ click(screen.getByRole('button', {name: 'About billing'}));
+ expect(shows(TIP)).toBe(true);
+ expect(onRow).not.toHaveBeenCalled();
+ });
+ });
+
+ it('inside an Item row, the row does not activate', () => {
+ const onRow = vi.fn();
+ render(
+ <Item label="Billing" onClick={onRow} endContent={<InfoTooltip />} />,
+ );
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ click(trigger);
+ expect(shows(TIP)).toBe(true);
+ tap(trigger);
+ expect(shows(TIP)).toBe(false);
+ expect(onRow).not.toHaveBeenCalled();
+ });
+
+ it('without the toggle, a tap still reaches the row (released behavior)', () => {
+ const onRow = vi.fn();
+ render(
+ <div onClick={onRow}>
+ <Tooltip content={TIP}>
+ <button type="button" aria-label="About billing">
+ i
+ </button>
+ </Tooltip>
+ </div>,
+ );
+ tap(screen.getByRole('button', {name: 'About billing'}));
+ expect(onRow).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('a pin inside a modal Dialog (spec:AST-086 FR14)', () => {
+ it('is announced through the modal, not the page body behind it', async () => {
+ render(
+ <Dialog isOpen={true} onOpenChange={() => {}} aria-label="Billing">
+ <InfoTooltip />
+ </Dialog>,
+ );
+ click(screen.getByRole('button', {name: 'About billing'}));
+ expect(shows(TIP)).toBe(true);
+ expect(announce).toHaveBeenCalledWith(TIP, 'polite');
+ expect(announceMessage).not.toHaveBeenCalled();
+ });
+});
+
+describe('a toggle trigger in another document', () => {
+ it('closes the pin when focus moves to another control in that document', () => {
+ const iframe = document.body.appendChild(document.createElement('iframe'));
+ const frame = iframe.contentWindow as Window & typeof globalThis;
+ // The frame has its own HTMLElement, without this file's popover stubs.
+ const proto = frame.HTMLElement.prototype;
+ const frameMatches = proto.matches;
+ proto.showPopover = HTMLElement.prototype.showPopover;
+ proto.hidePopover = HTMLElement.prototype.hidePopover;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (proto as any).matches = function (this: HTMLElement, selector: string) {
+ return selector === ':popover-open'
+ ? (popoverOpenState.get(this) ?? false)
+ : frameMatches.call(this, selector);
+ };
+ const container = frame.document.body.appendChild(
+ frame.document.createElement('div'),
+ );
+ const view = render(
+ <>
+ <InfoTooltip />
+ <button type="button">Next</button>
+ </>,
+ {container, baseElement: frame.document.body},
+ );
+ try {
+ const trigger = view.getByRole('button', {name: 'About billing'});
+ click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ const next = view.getByRole('button', {name: 'Next'});
+ fireEvent.focusOut(trigger, {relatedTarget: next});
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ } finally {
+ view.unmount();
+ iframe.remove();
+ }
+ });
+});
diff --git a/packages/core/src/Layer/usePressPin.ts b/packages/core/src/Layer/usePressPin.ts
new file mode 100644
index 0000000000..520ff79230
--- /dev/null
+++ b/packages/core/src/Layer/usePressPin.ts
@@ -0,0 +1,481 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file usePressPin.ts
+ * @input A hover layer's trigger, open state, show and hide, and its
+ * `triggerBehavior` and `touchTrigger` options
+ * @output usePressPin, the press toggle that pins a hover layer open;
+ * isPressPinTrigger; stopPressPinClick; the LayerTriggerBehavior type
+ * @position Core-internal: one call per hover layer, useTooltip's. It owns
+ * the layer's touch trigger, so the host makes no second touch-trigger call.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/Tooltip/useTooltip.tsx
+ * - /packages/core/src/Layer/usePressPin.test.tsx
+ */
+
+import {
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+ type MouseEvent as ReactMouseEvent,
+ type RefObject,
+} from 'react';
+import {useAnnounce} from '../hooks/useAnnounce';
+import {useDevWarning} from '../hooks/useDevWarning';
+import {stopInReactTree} from './layerClickBoundary';
+import {
+ useTouchTriggerInternal,
+ type LayerTouchTrigger,
+ type UseTouchTriggerReturn,
+} from './useTouchTrigger';
+
+/**
+ * How the trigger opens the layer. `adaptive`, the default, previews it on
+ * hover and focus, and a tap opens it unless the trigger acts. While
+ * `touchTrigger` remains, it decides those taps. `hover` previews it on hover
+ * and focus, and no touch or pen tap opens it. `toggle` pins it on every
+ * press of a button trigger.
+ */
+export type LayerTriggerBehavior = 'adaptive' | 'hover' | 'toggle';
+
+/** The clicks a press pin answered, so the wrapper can stop them (`stopPressPinClick`). */
+const pressPinClicks = new WeakSet<Event>();
+
+/**
+ * The layer component's wrapper handler. It stops a press that pinned or
+ * closed the layer in the React tree only, after the trigger's own handlers.
+ * No clickable row, card, or container around the trigger then receives it,
+ * and document and window listeners still do. An anchored trigger has no
+ * wrapper, so a plain `onClick` element around it still receives the press.
+ */
+export function stopPressPinClick(event: ReactMouseEvent): void {
+ if (pressPinClicks.has(event.nativeEvent)) {
+ stopInReactTree(event);
+ }
+}
+
+/** Whether presses on this element can pin a layer: a button, by role. */
+export function isPressPinTrigger(element: Element): boolean {
+ const role = element.getAttribute('role');
+ if (role != null && role !== '') {
+ return role === 'button';
+ }
+ return element.tagName === 'BUTTON';
+}
+
+export interface UsePressPinOptions {
+ /** The layer's `triggerBehavior`. */
+ triggerBehavior: LayerTriggerBehavior;
+ /** Whether the layer's triggers are live at all. */
+ isEnabled: boolean;
+ /** The controlled open value, or `undefined` when uncontrolled. */
+ isOpen: boolean | undefined;
+ /** Whether the layer shows now. */
+ isLayerOpen: boolean;
+ /** The layer surface's element id. */
+ layerId: string;
+ /** The component its development warning names. */
+ component: string;
+ /** Shows the layer now, with no delay. */
+ show: () => void;
+ /** Hides the layer now. */
+ hide: () => void;
+ /** Reports a controlled layer's toggled value without changing it. */
+ report: (isOpen: boolean) => void;
+ /** The layer's `label`: a press that pins the layer says it once, in place of its text. */
+ label?: string;
+ /** The layer's `touchTrigger`, which decides taps only under `adaptive`. */
+ touchTrigger: LayerTouchTrigger;
+ /** The host's trigger element, which the touch trigger reads. */
+ triggerRef: RefObject<HTMLElement | null>;
+}
+
+export interface UsePressPinReturn {
+ /** Whether presses on this trigger pin the layer: toggle mode and a button. */
+ isToggleTrigger: (element: HTMLElement | null) => boolean;
+ /**
+ * Whether a press holds the layer open now: a pin on a wired trigger while
+ * the layer shows, or a controlled layer's open value. The host's hover and
+ * focus hides ask it.
+ */
+ isHeldOpen: () => boolean;
+ /** Wires the trigger element, or unwires it with `null`. */
+ attach: (element: HTMLElement | null) => void;
+ /** Drops the pin: Escape, or a hide that came from elsewhere. */
+ unpin: () => void;
+ /**
+ * While pinned, focus moving onto an element outside the trigger and the
+ * layer closes it. Returns whether the pin decided. The pin calls it for its
+ * trigger, and a host calls it for the layer's own content.
+ */
+ handleFocusLeave: (event: FocusEvent) => boolean;
+ /**
+ * Whether the layer shows pinned on a wired trigger. The host then announces
+ * its rendered text, unless the layer has a `label`.
+ */
+ isPinShown: boolean;
+ /** The layer's touch trigger (useTouchTriggerInternal), wired to the pin. */
+ touch: Pick<
+ UseTouchTriggerReturn,
+ | 'isTouchPointerRef'
+ | 'isTouchInteraction'
+ | 'handlePointerEnter'
+ | 'handlePointerDown'
+ | 'clearTapOpen'
+ >;
+}
+
+function restoreAttribute(
+ element: HTMLElement,
+ name: string,
+ value: string | null,
+): void {
+ if (value == null) {
+ element.removeAttribute(name);
+ } else {
+ element.setAttribute(name, value);
+ }
+}
+
+function writeAttribute(
+ element: HTMLElement,
+ name: string,
+ value: string | null,
+): void {
+ if (element.getAttribute(name) !== value) {
+ restoreAttribute(element, name, value);
+ }
+}
+
+/**
+ * Pins a hover layer open on a press of a button trigger, under
+ * `triggerBehavior="toggle"`. The same press closes it, and so do Escape, a
+ * press or scroll outside, and focus that leaves the trigger and the layer.
+ * The press stops at the trigger. A trigger that is not a button gets a
+ * development warning and keeps tap-only opening.
+ */
+export function usePressPin(options: UsePressPinOptions): UsePressPinReturn {
+ const {triggerBehavior, isOpen, isLayerOpen, layerId} = options;
+ const isToggleMode = triggerBehavior === 'toggle';
+
+ // DOM listeners read the latest options and announcer through refs. The
+ // announcer is the layer's own: inside a modal, the modal's region.
+ const optionsRef = useRef(options);
+ optionsRef.current = options;
+ const announce = useAnnounce();
+ const announceRef = useRef(announce);
+ announceRef.current = announce;
+
+ const isPinnedRef = useRef(false);
+ const [isPinned, setIsPinnedState] = useState(false);
+ const setPinned = useCallback((next: boolean) => {
+ isPinnedRef.current = next;
+ setIsPinnedState(next);
+ }, []);
+
+ // Refs hold the wired trigger and last offered element for a later rewire.
+ const triggerRef = useRef<HTMLElement | null>(null);
+ const offeredRef = useRef<HTMLElement | null>(null);
+ // A primitive: re-attaching the same trigger renders nothing.
+ const [offeredKind, setOfferedKind] = useState<'none' | 'other' | 'button'>(
+ 'none',
+ );
+ // The trigger's own aria-expanded and aria-controls, restored on unwiring.
+ const ownStateRef = useRef<{
+ expanded: string | null;
+ controls: string | null;
+ } | null>(null);
+
+ // The touch trigger's outside dismissal (a press or scroll outside) closes
+ // a pinned layer through the pin, so the pin drops with it.
+ const hideFromTouch = useCallback(() => {
+ const current = optionsRef.current;
+ if (current.triggerBehavior === 'toggle' && triggerRef.current != null) {
+ if (current.isOpen !== undefined) {
+ current.report(false);
+ return;
+ }
+ if (isPinnedRef.current) {
+ setPinned(false);
+ }
+ }
+ current.hide();
+ }, [setPinned]);
+
+ const {
+ isTouchPointerRef,
+ isTouchInteraction,
+ handlePointerEnter,
+ handlePointerDown,
+ clearTapOpen,
+ armOutsideDismiss,
+ } = useTouchTriggerInternal({
+ touchTrigger: isToggleMode
+ ? 'tap'
+ : triggerBehavior === 'hover'
+ ? 'none'
+ : options.touchTrigger,
+ isEnabled: options.isEnabled,
+ isControlled: isOpen !== undefined,
+ isOpen: isLayerOpen,
+ layerId,
+ triggerRef: options.triggerRef,
+ show: options.show,
+ hide: hideFromTouch,
+ });
+
+ const isToggleTrigger = useCallback(
+ (element: HTMLElement | null) =>
+ optionsRef.current.triggerBehavior === 'toggle' &&
+ element != null &&
+ isPressPinTrigger(element),
+ [],
+ );
+
+ const close = useCallback(() => {
+ const current = optionsRef.current;
+ clearTapOpen();
+ if (current.isOpen !== undefined) {
+ current.report(false);
+ return;
+ }
+ setPinned(false);
+ current.hide();
+ }, [setPinned, clearTapOpen]);
+
+ const announceName = useCallback(() => {
+ const current = optionsRef.current;
+ const name = current.label?.trim() ?? '';
+ if (name !== '') {
+ announceRef.current(name, 'polite');
+ }
+ }, []);
+
+ const toggle = useCallback(() => {
+ const current = optionsRef.current;
+ if (current.isOpen !== undefined) {
+ if (!current.isOpen) {
+ armOutsideDismiss();
+ announceName();
+ } else {
+ clearTapOpen();
+ }
+ current.report(!current.isOpen);
+ return;
+ }
+ // A pin counts only while its layer shows; a closed layer pins again.
+ if (isPinnedRef.current && current.isLayerOpen) {
+ setPinned(false);
+ clearTapOpen();
+ current.hide();
+ } else {
+ setPinned(true);
+ current.show();
+ armOutsideDismiss();
+ announceName();
+ }
+ }, [setPinned, announceName, armOutsideDismiss, clearTapOpen]);
+
+ // Enter or Space presses a non-native button, which gets no click from the
+ // browser. A same-task click from its own key handler is that press.
+ const keyPressedRef = useRef(false);
+ const handlePress = useCallback(
+ (event: MouseEvent) => {
+ const current = optionsRef.current;
+ if (!current.isEnabled || current.triggerBehavior !== 'toggle') {
+ return;
+ }
+ // The press stops at its trigger: no label control, link, or submit.
+ event.preventDefault();
+ pressPinClicks.add(event);
+ if (keyPressedRef.current && event.detail === 0) {
+ return;
+ }
+ toggle();
+ },
+ [toggle],
+ );
+ const handleKeyDown = useCallback(
+ (event: KeyboardEvent) => {
+ const current = optionsRef.current;
+ if (
+ !current.isEnabled ||
+ current.triggerBehavior !== 'toggle' ||
+ event.repeat ||
+ event.isComposing ||
+ (event.key !== 'Enter' && event.key !== ' ')
+ ) {
+ return;
+ }
+ event.preventDefault();
+ keyPressedRef.current = true;
+ setTimeout(() => {
+ keyPressedRef.current = false;
+ }, 0);
+ toggle();
+ },
+ [toggle],
+ );
+
+ const isHeldOpen = useCallback(() => {
+ const current = optionsRef.current;
+ if (current.triggerBehavior !== 'toggle' || triggerRef.current == null) {
+ return false;
+ }
+ return current.isOpen !== undefined
+ ? current.isOpen && current.isLayerOpen
+ : isPinnedRef.current && current.isLayerOpen;
+ }, []);
+
+ const handleFocusLeave = useCallback(
+ (event: FocusEvent) => {
+ if (!isHeldOpen()) {
+ return false;
+ }
+ const next = event.relatedTarget;
+ const trigger = triggerRef.current;
+ // Focus that leaves for no element is a press's to decide. The trigger
+ // can sit in another document, so the check uses its own window.
+ const view = trigger?.ownerDocument.defaultView;
+ if (view == null || !(next instanceof view.Node)) {
+ return true;
+ }
+ const surface =
+ trigger?.ownerDocument.getElementById(optionsRef.current.layerId) ??
+ null;
+ if (
+ trigger?.contains(next) === true ||
+ surface?.contains(next) === true
+ ) {
+ return true;
+ }
+ close();
+ return true;
+ },
+ [isHeldOpen, close],
+ );
+
+ const unwire = useCallback(() => {
+ const previous = triggerRef.current;
+ if (previous == null) {
+ return;
+ }
+ previous.removeEventListener('click', handlePress);
+ previous.removeEventListener('keydown', handleKeyDown);
+ previous.removeEventListener('focusout', handleFocusLeave);
+ const own = ownStateRef.current;
+ if (own != null) {
+ restoreAttribute(previous, 'aria-expanded', own.expanded);
+ restoreAttribute(previous, 'aria-controls', own.controls);
+ }
+ ownStateRef.current = null;
+ triggerRef.current = null;
+ }, [handlePress, handleKeyDown, handleFocusLeave]);
+
+ // The element and mode last settled; the same pair again does nothing.
+ const settledRef = useRef<{
+ element: HTMLElement | null;
+ mode: LayerTriggerBehavior;
+ } | null>(null);
+
+ const wire = useCallback(
+ (element: HTMLElement | null) => {
+ const current = optionsRef.current;
+ const settled = settledRef.current;
+ if (
+ settled != null &&
+ settled.element === element &&
+ settled.mode === current.triggerBehavior
+ ) {
+ return;
+ }
+ settledRef.current = {element, mode: current.triggerBehavior};
+ unwire();
+ if (element == null || current.triggerBehavior !== 'toggle') {
+ return;
+ }
+ if (!isPressPinTrigger(element)) {
+ return;
+ }
+ element.addEventListener('click', handlePress);
+ if (element.tagName !== 'BUTTON') {
+ element.addEventListener('keydown', handleKeyDown);
+ }
+ // Its own focus-leave listener: `focusTrigger="never"` attaches none.
+ element.addEventListener('focusout', handleFocusLeave);
+ ownStateRef.current = {
+ expanded: element.getAttribute('aria-expanded'),
+ controls: element.getAttribute('aria-controls'),
+ };
+ triggerRef.current = element;
+ },
+ [unwire, handlePress, handleKeyDown, handleFocusLeave],
+ );
+
+ const attach = useCallback(
+ (element: HTMLElement | null) => {
+ offeredRef.current = element;
+ // Hosts detach and re-attach within one commit, so a detach is not kept.
+ if (element != null) {
+ setOfferedKind(isPressPinTrigger(element) ? 'button' : 'other');
+ }
+ wire(element);
+ },
+ [wire],
+ );
+
+ const isWired = isToggleMode && offeredKind === 'button';
+ useDevWarning(
+ options.component,
+ '`triggerBehavior="toggle"` pins only a button trigger (a <button> or role="button"); this trigger keeps tap-only opening.',
+ isToggleMode && offeredKind === 'other',
+ );
+
+ // A later `triggerBehavior` change rewires here; the ref does not rerun.
+ useEffect(() => {
+ wire(offeredRef.current);
+ }, [triggerBehavior, wire]);
+
+ const unpin = useCallback(() => {
+ if (isPinnedRef.current) {
+ setPinned(false);
+ }
+ }, [setPinned]);
+
+ // Each path that hides a pinned layer drops the pin itself, so a layer that
+ // does not show is never reported expanded.
+ const isExpanded = (isOpen !== undefined ? isOpen : isPinned) && isLayerOpen;
+
+ // The trigger's aria-expanded and aria-controls follow the pin. No deps: a
+ // host can swap the trigger on any commit; equal values are not rewritten.
+ useEffect(() => {
+ const trigger = triggerRef.current;
+ if (!isToggleMode || !isWired || trigger == null) {
+ return;
+ }
+ writeAttribute(trigger, 'aria-expanded', isExpanded ? 'true' : 'false');
+ writeAttribute(trigger, 'aria-controls', isLayerOpen ? layerId : null);
+ });
+
+ const isPinShown = isToggleMode && isWired && isExpanded;
+
+ return {
+ isToggleTrigger,
+ isHeldOpen,
+ attach,
+ unpin,
+ handleFocusLeave,
+ isPinShown,
+ touch: {
+ isTouchPointerRef,
+ isTouchInteraction,
+ handlePointerEnter,
+ handlePointerDown,
+ clearTapOpen,
+ },
+ };
+}
diff --git a/packages/core/src/Layer/useTouchTrigger.ts b/packages/core/src/Layer/useTouchTrigger.ts
index 9939eeec30..65f2148279 100644
--- a/packages/core/src/Layer/useTouchTrigger.ts
+++ b/packages/core/src/Layer/useTouchTrigger.ts
@@ -7,7 +7,8 @@
* @input Touch trigger mode, layer open state, trigger ref, show/hide callbacks
* @output Exports useTouchTrigger hook, isActionTrigger, LayerTouchTrigger type,
* tapLandsOnDisabledControl, TOUCH_POINTER_TYPES and useTapStop (internal:
- * not re-exported from index)
+ * not re-exported from index). Also useTouchTriggerInternal, with the
+ * outside dismissal's arm for the press pin (Core-internal).
* @position Layer hook; shared touch behavior for useTooltip and useHoverCard
*
* SYNC: When modified, update:
@@ -281,6 +282,21 @@ export interface UseTouchTriggerReturn {
clearTapOpen: () => void;
}
+/**
+ * useTouchTrigger's return plus the outside dismissal's arm, for Core's own
+ * press pin (usePressPin). Not exported from the Layer entry point.
+ *
+ * @internal
+ */
+export interface UseTouchTriggerInternalReturn extends UseTouchTriggerReturn {
+ /**
+ * Arms the outside dismissal a tap-open gets: a press that lifts outside
+ * the trigger and the layer, or a scroll that starts there, hides it. A
+ * press pin arms it too.
+ */
+ armOutsideDismiss: () => void;
+}
+
/**
* Touch behavior shared by the hover layers.
*
@@ -301,6 +317,25 @@ export interface UseTouchTriggerReturn {
export function useTouchTrigger(
options: UseTouchTriggerOptions,
): UseTouchTriggerReturn {
+ const touch = useTouchTriggerInternal(options);
+ return {
+ isTouchPointerRef: touch.isTouchPointerRef,
+ isTouchInteraction: touch.isTouchInteraction,
+ handlePointerEnter: touch.handlePointerEnter,
+ handlePointerDown: touch.handlePointerDown,
+ clearTapOpen: touch.clearTapOpen,
+ };
+}
+
+/**
+ * useTouchTrigger, plus the outside dismissal's arm that a press pin uses to
+ * close on a press or scroll outside.
+ *
+ * @internal
+ */
+export function useTouchTriggerInternal(
+ options: UseTouchTriggerOptions,
+): UseTouchTriggerInternalReturn {
const {
touchTrigger,
isEnabled,
@@ -503,5 +538,6 @@ export function useTouchTrigger(
handlePointerEnter,
handlePointerDown,
clearTapOpen: disarmOutsideDismiss,
+ armOutsideDismiss,
};
}
diff --git a/packages/core/src/Tooltip/Tooltip.doc.mjs b/packages/core/src/Tooltip/Tooltip.doc.mjs
index 0045533756..d13ce2b91f 100644
--- a/packages/core/src/Tooltip/Tooltip.doc.mjs
+++ b/packages/core/src/Tooltip/Tooltip.doc.mjs
@@ -84,9 +84,16 @@ export const docs = {
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 (a button, link, or form control), whose tap belongs to the control; an aria-disabled control performs none, so a tap on it opens its reason. tap always opens; use it for an info icon rendered as a button, whose only job is to reveal the tooltip. none never opens on touch.',
+ 'What a tap does where there is no hover. auto opens on tap unless the trigger performs an action of its own (a button, link, or form control), whose tap belongs to the control; an aria-disabled control performs none, so a tap on it opens its reason. tap always opens. none never opens on touch. It decides only under triggerBehavior="adaptive", the default.',
default: "'auto'",
},
+ {
+ name: 'triggerBehavior',
+ type: "'adaptive' | 'hover' | 'toggle'",
+ description:
+ 'How the trigger opens the tooltip. adaptive (the default): hover and focus preview it, and a tap opens it unless the trigger performs an action of its own, as touchTrigger decides while it remains. hover: hover and focus preview it, and no touch or pen tap opens it. toggle, on a button trigger: a click, a tap, Enter, or Space pins the tooltip and the same press closes it, while hover and keyboard focus still preview it. A pinned tooltip stays until Escape, a second press, a press outside, or focus leaving, and the press stops at the trigger, so a clickable row or card around it does not activate (with anchorRef, the anchored trigger still runs its own onClick, Astryx clickable rows and cards ignore the press except an Item row when the anchor is not a native button, and a plain onClick element around the anchor receives it unless that onClick stops it). The trigger reports aria-expanded and aria-controls, and the text is announced once when it pins. Use it for an info icon or any button whose only job is revealing the tooltip.',
+ default: "'adaptive'",
+ },
{
name: 'isEnabled',
type: 'boolean',
@@ -130,7 +137,7 @@ export const docs = {
bestPractices: [
{guidance: true, description: 'Keep tooltip content concise: aim for under 140 characters of plain text.'},
{guidance: true, description: 'Add a tooltip to icon-only buttons and controls that lack a visible label.'},
- {guidance: true, description: 'Set touchTrigger to tap when the trigger is a button whose only job is revealing the tooltip, such as an info icon: touch has no hover, and auto keeps the tap for triggers that perform an action.'},
+ {guidance: true, description: 'Set triggerBehavior to toggle when the trigger is a button whose only job is revealing the tooltip, such as an info icon: a click, a tap, Enter, or Space pins it, and the press stops at the trigger.'},
{guidance: false, description: 'Place interactive elements like links or buttons inside a tooltip; use HoverCard or Popover instead.'},
{guidance: false, description: 'Use tooltips for essential information that users must see to complete a task.'},
],
@@ -197,9 +204,16 @@ export const docsZh = {
name: 'touchTrigger',
type: "'auto' | 'tap' | 'none'",
description:
- '在没有悬停的触摸设备上,轻点的行为。auto:轻点即打开,除非触发元素本身会执行操作(按钮、链接、表单控件),此时轻点归该控件所有;设置了 aria-disabled 的控件不执行操作,因此轻点它会显示其原因。tap:始终轻点打开——适用于以按钮形式呈现、唯一作用就是显示工具提示的信息图标。none:触摸永不打开。',
+ '在没有悬停的触摸设备上,轻点的行为。auto:轻点即打开,除非触发元素本身会执行操作(按钮、链接、表单控件),此时轻点归该控件所有;设置了 aria-disabled 的控件不执行操作,因此轻点它会显示其原因。tap:始终轻点打开。none:触摸永不打开。仅在 triggerBehavior 为 adaptive(默认)时生效。',
default: "'auto'",
},
+ {
+ name: 'triggerBehavior',
+ type: "'adaptive' | 'hover' | 'toggle'",
+ description:
+ '触发元素如何打开工具提示。adaptive(默认):悬停和聚焦会预览;轻点即打开,除非触发元素本身会执行操作(在 touchTrigger 仍存在期间由它决定)。hover:悬停和聚焦会预览,触摸或触控笔轻点都不会打开。toggle(仅限按钮触发元素):单击、轻点、Enter 或空格键固定打开,再按一次关闭;悬停和键盘聚焦仍会预览。固定后,直到按 Escape、再次按下、在外部按下或焦点移出才关闭;这次按下止于触发元素,外层可点击的行或卡片不会被激活(使用 anchorRef 时,锚定元素自身的 onClick 仍会运行,Astryx 的可点击行和卡片会忽略这次按下,但锚定元素不是原生按钮时,Item 行仍会响应,锚定元素外层普通的 onClick 元素仍会收到,除非锚定元素的 onClick 阻止它)。触发元素会报告 aria-expanded 和 aria-controls,固定时朗读一次文本。适用于信息图标等唯一作用就是显示工具提示的按钮。',
+ default: "'adaptive'",
+ },
{
name: 'isEnabled',
type: 'boolean',
@@ -238,7 +252,7 @@ export const docsZh = {
bestPractices: [
{guidance: true, description: 'Keep tooltip content concise: aim for under 140 characters of plain text.'},
{guidance: true, description: 'Add a tooltip to icon-only buttons and controls that lack a visible label.'},
- {guidance: true, description: 'Set touchTrigger to tap when the trigger is a button whose only job is revealing the tooltip, such as an info icon: touch has no hover, and auto keeps the tap for triggers that perform an action.'},
+ {guidance: true, description: 'Set triggerBehavior to toggle when the trigger is a button whose only job is revealing the tooltip, such as an info icon: a click, a tap, Enter, or Space pins it, and the press stops at the trigger.'},
{guidance: false, description: 'Place interactive elements like links or buttons inside a tooltip; use HoverCard or Popover instead.'},
{guidance: false, description: 'Use tooltips for essential information that users must see to complete a task.'},
],
@@ -255,7 +269,7 @@ export const docsDense = {
bestPractices: [
{guidance: true, description: 'Keep tooltip content concise: aim for under 140 characters of plain text.'},
{guidance: true, description: 'Add a tooltip to icon-only buttons and controls that lack a visible label.'},
- {guidance: true, description: 'Set touchTrigger to tap when the trigger is a button whose only job is revealing the tooltip, such as an info icon: touch has no hover, and auto keeps the tap for triggers that perform an action.'},
+ {guidance: true, description: 'Set triggerBehavior to toggle when the trigger is a button whose only job is revealing the tooltip, such as an info icon: a click, a tap, Enter, or Space pins it, and the press stops at the trigger.'},
{guidance: false, description: 'Place interactive elements like links or buttons inside a tooltip; use HoverCard or Popover instead.'},
{guidance: false, description: 'Use tooltips for essential information that users must see to complete a task.'},
],
@@ -274,7 +288,8 @@ export const docsDense = {
delay: 'Show delay in ms.',
hideDelay: 'Hide delay in ms.',
focusTrigger: 'Controls when focus events trigger tooltip.',
- touchTrigger: 'Tap behavior where there is no hover. auto = tap opens unless the trigger acts (button/link/control; an aria-disabled control does not act); tap = always opens (info icon rendered as a button); none = never on touch.',
+ touchTrigger: 'Tap behavior where there is no hover, under triggerBehavior="adaptive" only. auto = tap opens unless the trigger acts (button/link/control; an aria-disabled control does not act); tap = always opens; none = never on touch.',
+ triggerBehavior: 'adaptive (default) = hover/focus preview, a tap opens unless the trigger acts; hover = hover/focus preview, no touch/pen tap opens; toggle = a click/tap/Enter/Space on a button trigger pins the tooltip (aria-expanded, announced once), the same press closes it, and the press stops at the trigger.',
isEnabled: 'Enables/disables tooltip triggers.',
onOpenChange: 'Callback when visibility changes; true=shown, false=hidden.',
hasHoverIndication: 'Dashed underline on trigger element.',
diff --git a/packages/core/src/Tooltip/Tooltip.tsx b/packages/core/src/Tooltip/Tooltip.tsx
index c63cac264d..4c447623d7 100644
--- a/packages/core/src/Tooltip/Tooltip.tsx
+++ b/packages/core/src/Tooltip/Tooltip.tsx
@@ -25,12 +25,18 @@ import * as stylex from '@stylexjs/stylex';
import {
useTooltip,
type TooltipFocusTrigger,
+ type TooltipTriggerBehavior,
type TooltipTouchTrigger,
} from './useTooltip';
+import {stopPressPinClick} from '../Layer/usePressPin';
import type {LayerAlignment, LayerPlacement} from '../Layer/useLayer';
import {colorVars} from '../theme/tokens.stylex';
-export type {TooltipFocusTrigger, TooltipTouchTrigger} from './useTooltip';
+export type {
+ TooltipFocusTrigger,
+ TooltipTriggerBehavior,
+ TooltipTouchTrigger,
+} from './useTooltip';
const styles = stylex.create({
wrapperContents: {
@@ -109,15 +115,40 @@ export interface TooltipProps {
* - `auto`: tap opens the tooltip, unless the trigger performs an action of
* its own (a button, a link, a form control) — that tap belongs to the
* control, and a hint about a control the user just operated is noise
- * - `tap`: tap always opens the tooltip. This is what an info icon rendered
- * as a button wants: it looks like an action to the DOM, but revealing the
- * tooltip is the only thing it does
+ * - `tap`: tap always opens the tooltip, even on a trigger that acts
* - `none`: touch never opens the tooltip
*
+ * It decides only under `triggerBehavior="adaptive"`, the default.
+ *
* @default 'auto'
*/
touchTrigger?: TooltipTouchTrigger;
+ /**
+ * How the trigger opens the tooltip:
+ * - `adaptive` (the default): hover and focus preview it. A tap opens it
+ * unless the trigger performs an action of its own. While `touchTrigger`
+ * remains, it decides those taps.
+ * - `hover`: hover and focus preview it; no touch or pen tap opens it.
+ * - `toggle`: on a button trigger, a click, a tap, Enter, or Space pins the
+ * tooltip open, and the same press closes it. Hover and keyboard focus
+ * still preview it. A pinned tooltip stays until Escape, a second press,
+ * a press outside, or focus leaving. The press stops at the trigger. Its
+ * default action is prevented, and the trigger's own handlers still run.
+ * No clickable row or card around the trigger activates. With
+ * `anchorRef`, the anchor's own `onClick` runs, and a plain `onClick`
+ * element around it receives the press unless that `onClick` stops it.
+ * Astryx clickable rows, cards, and containers ignore it, except an Item
+ * row when the anchor is not a native button. The trigger reports
+ * `aria-expanded` and `aria-controls`, and the tooltip's text is
+ * announced once when it pins. Use it for a trigger whose information
+ * lives only in the tooltip, such as an info icon. `touchTrigger` is
+ * ignored.
+ *
+ * @default 'adaptive'
+ */
+ triggerBehavior?: TooltipTriggerBehavior;
+
/**
* Whether the tooltip is enabled.
* When false, hover/focus triggers are disabled.
@@ -201,6 +232,7 @@ export function Tooltip({
hideDelay = 0,
focusTrigger = 'auto',
touchTrigger = 'auto',
+ triggerBehavior = 'adaptive',
isEnabled = true,
onOpenChange,
hasHoverIndication = 'auto',
@@ -230,6 +262,7 @@ export function Tooltip({
hideDelay,
focusTrigger,
touchTrigger,
+ triggerBehavior,
isEnabled,
isOpen,
isDefaultOpen,
@@ -343,6 +376,7 @@ export function Tooltip({
ref={tooltip.ref}
tabIndex={0}
aria-describedby={tooltip.describedBy}
+ onClick={stopPressPinClick}
{...stylex.props(
styles.wrapperInline,
showHoverIndication && styles.hoverIndication,
@@ -357,7 +391,10 @@ export function Tooltip({
// For element children: use display:contents, ref on first child
return (
<>
- <div ref={wrapperRef} {...stylex.props(styles.wrapperContents)}>
+ <div
+ ref={wrapperRef}
+ onClick={stopPressPinClick}
+ {...stylex.props(styles.wrapperContents)}>
{children}
</div>
{tooltip.renderTooltip(content)}
diff --git a/packages/core/src/Tooltip/index.ts b/packages/core/src/Tooltip/index.ts
index 99d411531f..1dcef4e7d8 100644
--- a/packages/core/src/Tooltip/index.ts
+++ b/packages/core/src/Tooltip/index.ts
@@ -15,6 +15,7 @@
export {useTooltip} from './useTooltip';
export type {
TooltipFocusTrigger,
+ TooltipTriggerBehavior,
TooltipTouchTrigger,
TooltipOptions,
TooltipReturn,
diff --git a/packages/core/src/Tooltip/useTooltip.doc.mjs b/packages/core/src/Tooltip/useTooltip.doc.mjs
index d1686ef659..f6373172bb 100644
--- a/packages/core/src/Tooltip/useTooltip.doc.mjs
+++ b/packages/core/src/Tooltip/useTooltip.doc.mjs
@@ -12,7 +12,8 @@ export const docs = {
{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 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: '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. It decides only under triggerBehavior="adaptive", the default.', default: "'auto'"},
+ {name: 'triggerBehavior', type: "'adaptive' | 'hover' | 'toggle'", description: 'How the trigger opens the tooltip. adaptive (the default) previews on hover and focus and opens on a tap unless the trigger acts (touchTrigger decides while it remains); hover previews on hover and focus, and no touch or pen tap opens it; toggle, on a button trigger, pins on a click, a tap, Enter, or Space and closes on the same press, Escape, a press outside, or focus leaving. The trigger carries aria-expanded and aria-controls, the tooltip is announced once when it pins. Astryx clickable rows and cards ignore the pinning press, except an Item row on a trigger that is not a native button; a plain onClick ancestor still receives it from the hook (the Tooltip component stops it at a child trigger).', default: "'adaptive'"},
{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.'},
{name: 'isDefaultOpen', type: 'boolean', description: 'Whether the tooltip should be shown on mount.', default: 'false'},
@@ -50,7 +51,8 @@ export const docsDense = {
delay: 'show delay in ms.',
hideDelay: 'hide delay after mouse/focus leave in ms.',
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.',
+ touchTrigger: 'tap behavior with no hover, under triggerBehavior adaptive only; auto = tap unless trigger acts, tap = always, none = never.',
+ triggerBehavior: 'adaptive (default) = hover/focus preview, tap opens unless the trigger acts; hover = no touch/pen tap opens; toggle = a press on a button trigger pins and closes; clickable rows and cards ignore it (an Item row only on a native-button trigger), and the Tooltip component also stops it at a child trigger.',
isEnabled: 'whether hover/focus triggers are enabled.',
isOpen: 'controlled open state: true force-show, false force-hide, undefined unmanaged.',
isDefaultOpen: 'show on mount.',
diff --git a/packages/core/src/Tooltip/useTooltip.tsx b/packages/core/src/Tooltip/useTooltip.tsx
index b9c8da0964..589a037d60 100644
--- a/packages/core/src/Tooltip/useTooltip.tsx
+++ b/packages/core/src/Tooltip/useTooltip.tsx
@@ -4,7 +4,7 @@
/**
* @file useTooltip.tsx
- * @input Uses useLayer, useTouchTrigger, React hooks
+ * @input Uses useLayer, usePressPin, React hooks
* @output Exports useTooltip hook with stable trigger refs for hover/focus/tap tooltips
* @position Layer hook; builds on useLayer for tooltip behavior
*
@@ -26,12 +26,12 @@ import {
type LayerAlignment,
type LayerPlacement,
} from '../Layer/useLayer';
-import {
- useTouchTrigger,
- type LayerTouchTrigger,
-} from '../Layer/useTouchTrigger';
+import type {LayerTouchTrigger} from '../Layer/useTouchTrigger';
+import {useAnnounceRenderedText} from '../hooks/useAnnounceRenderedText';
+import {useMergedRefs} from '../hooks/useMergedRefs';
import {layerAnimations} from '../Layer/layerAnimations.stylex';
import {registerLayerSurface} from '../Layer/layerSurfacePress';
+import {usePressPin} from '../Layer/usePressPin';
import {useLayerDismissal} from '../Layer/useLayerDismissal';
import {themeProps} from '../utils/themeProps';
import {
@@ -83,6 +83,14 @@ export type TooltipFocusTrigger = 'auto' | 'always' | 'never';
*/
export type TooltipTouchTrigger = LayerTouchTrigger;
+/**
+ * How the trigger opens the tooltip. `adaptive`, the default, previews it on
+ * hover and focus, and a tap opens it unless the trigger acts. `hover`
+ * previews it on hover and focus, and no touch or pen tap opens it. `toggle`
+ * pins it on a click, tap, Enter, or Space on a button trigger.
+ */
+export type TooltipTriggerBehavior = 'adaptive' | 'hover' | 'toggle';
+
export interface TooltipOptions {
/**
* Position placement relative to anchor
@@ -124,15 +132,35 @@ export interface TooltipOptions {
* - `auto`: tap opens the tooltip, unless the trigger performs an action of
* its own (a button, a link, a form control) — that tap belongs to the
* control, and a hint about a control the user just operated is noise
- * - `tap`: tap always opens the tooltip. This is what an info icon rendered
- * as a button wants: it looks like an action to the DOM, but revealing the
- * tooltip is the only thing it does
+ * - `tap`: tap always opens the tooltip, even on a trigger that acts
* - `none`: touch never opens the tooltip
*
+ * It decides only under `triggerBehavior="adaptive"`, the default.
+ *
* @default 'auto'
*/
touchTrigger?: TooltipTouchTrigger;
+ /**
+ * How the trigger opens the tooltip:
+ * - `adaptive` (the default): hover and focus preview it. A tap opens it
+ * unless the trigger performs an action of its own. While `touchTrigger`
+ * remains, it decides those taps.
+ * - `hover`: hover and focus preview it; no touch or pen tap opens it.
+ * - `toggle`: on a button trigger, a click, a tap, Enter, or Space pins the
+ * tooltip open, and the same press closes it. Hover and keyboard focus
+ * still preview it. A pinned tooltip stays until Escape, a second press,
+ * a press outside, or focus leaving. Astryx clickable rows and cards
+ * ignore the pinning press, except an Item row on a trigger that is not
+ * a native button. The `Tooltip` component also stops it at a child
+ * trigger. A hook caller stops a plain `onClick` ancestor itself. The
+ * trigger reports `aria-expanded` and `aria-controls`, and the tooltip's
+ * text is announced once when it pins. `touchTrigger` is ignored.
+ *
+ * @default 'adaptive'
+ */
+ triggerBehavior?: TooltipTriggerBehavior;
+
/**
* Whether the tooltip is enabled.
* When false, hover/focus triggers are disabled.
@@ -275,6 +303,7 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
hideDelay = 0,
focusTrigger = 'auto',
touchTrigger = 'auto',
+ triggerBehavior = 'adaptive',
isEnabled = true,
isOpen,
isDefaultOpen = false,
@@ -332,23 +361,44 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
hideLayer();
}, [clearTimeouts, hideLayer]);
+ // A press pins the tooltip under `triggerBehavior="toggle"`. The pin also
+ // owns the tooltip's touch trigger, so this one call wires both.
const {
- isTouchPointerRef,
- isTouchInteraction,
- handlePointerEnter,
- handlePointerDown: handleTouchPointerDown,
- clearTapOpen,
- } = useTouchTrigger({
+ isToggleTrigger,
+ isHeldOpen: isPressHeldOpen,
+ attach: attachPressPin,
+ unpin: unpinPress,
+ isPinShown,
+ touch: {
+ isTouchPointerRef,
+ isTouchInteraction,
+ handlePointerEnter,
+ handlePointerDown: handleTouchPointerDown,
+ clearTapOpen,
+ },
+ } = usePressPin({
+ triggerBehavior,
touchTrigger,
isEnabled,
- isControlled: isOpen !== undefined,
- isOpen: isLayerOpen,
- layerId: layerId,
+ isOpen,
+ isLayerOpen,
+ layerId,
triggerRef,
+ component: 'Tooltip',
show: showNow,
hide: hideNow,
+ report: next => (next ? onShow?.() : onHide?.()),
});
+ // Only a pin announces the text: a preview is already the trigger's
+ // description.
+ const contentRef = useRef<HTMLDivElement | null>(null);
+ useAnnounceRenderedText(contentRef, isPinShown, 'pinned');
+ const contentRefs = useMergedRefs<HTMLDivElement>(
+ contentRef,
+ registerLayerSurface,
+ );
+
// Schedule show with delay (suppressed when isOpen is false)
const scheduleShow = useCallback(() => {
if (!isEnabled || isOpen === false) {
@@ -376,7 +426,7 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
// trigger onto the tooltip surface without the tooltip vanishing — required
// for WCAG 1.4.13 (Content on Hover or Focus: hoverable).
const scheduleHide = useCallback(() => {
- if (isOpen === true) {
+ if (isOpen === true || isPressHeldOpen()) {
return;
}
clearTimeouts();
@@ -384,7 +434,7 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
hideTimeoutRef.current = setTimeout(() => {
hideLayer();
}, effectiveHideDelay);
- }, [isOpen, clearTimeouts, hideLayer, hideDelay]);
+ }, [isOpen, isPressHeldOpen, clearTimeouts, hideLayer, hideDelay]);
// Cancel a pending hide (e.g. the pointer entered the tooltip surface).
const cancelHide = useCallback(() => {
@@ -482,6 +532,9 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
],
);
+ // A pinned tooltip's focus-leave close is the pin's own: it listens on the
+ // trigger whatever `focusTrigger` is. This schedules the unpinned hide,
+ // which a held tooltip skips.
const handleFocusOut = useCallback(
(e: Event) => {
if (!focusCountedRef.current && !isFocusForTrigger(e)) {
@@ -502,6 +555,11 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
// tooltip at all), so the touch path answers it first.
const handlePointerDown = useCallback(
(event: PointerEvent) => {
+ // A press on a toggle trigger pins or closes through its click. It
+ // neither hides the preview here nor waits for a tap verdict.
+ if (isToggleTrigger(triggerRef.current)) {
+ return;
+ }
if (handleTouchPointerDown(event)) {
return;
}
@@ -511,7 +569,7 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
clearTimeouts();
hideLayer();
},
- [handleTouchPointerDown, isOpen, clearTimeouts, hideLayer],
+ [isToggleTrigger, handleTouchPointerDown, isOpen, clearTimeouts, hideLayer],
);
// Interaction ref that handles event listeners only
@@ -552,8 +610,10 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
}
triggerRef.current = el;
+ attachPressPin(el);
},
[
+ attachPressPin,
focusTrigger,
handleMouseEnter,
handleMouseLeave,
@@ -641,6 +701,7 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
onDismiss: () => {
clearTimeouts();
clearTapOpen();
+ unpinPress();
if (isOpen !== undefined) {
onHide?.();
return;
@@ -677,7 +738,8 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
// something else in the shared interactive-ancestor walk, so a
// clickable container around the trigger leaves the press alone while
// document listeners still see it.
- <div ref={registerLayerSurface} {...stylex.props(styles.content)}>
+ // The pin's announcement reads this element's text.
+ <div ref={contentRefs} {...stylex.props(styles.content)}>
{children}
</div>,
renderProps,
@@ -690,6 +752,7 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
popoverXstyle,
cancelHide,
scheduleHide,
+ contentRefs,
],
);
diff --git a/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx b/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx
index e2330e9fd4..81d7cd056d 100644
--- a/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx
+++ b/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx
@@ -2,8 +2,9 @@
/**
* @file useAnnounceRenderedText.adopters.test.tsx
- * @input Every core component that announces its own rendered content, with
- * the shared own-content module replaced by a recorder
+ * @input Every core component that announces its own rendered content,
+ * Tooltip's pin included, with the shared own-content module replaced by a
+ * recorder
* @output architecture:react-component-runtime INV10 test: each adopter hands
* its own-content announcement to the shared module and announces none of it
* itself
@@ -67,6 +68,7 @@ const {BaseTypeahead} = await import('../Typeahead/BaseTypeahead');
const {TokenizerWithPresentation} =
await import('../internal/tokenizer-presentation');
const {createStaticSource} = await import('../Typeahead/createStaticSource');
+const {Tooltip} = await import('../Tooltip');
const source = createStaticSource([{id: 'apple', label: 'Apple'}]);
@@ -164,6 +166,18 @@ const ADOPTERS: Record<string, () => Promise<void>> = {
fireEvent.change(screen.getByRole('combobox'), {target: {value: 'zzz'}});
await expectDelegated('No results found');
},
+ 'Tooltip/useTooltip.tsx': async () => {
+ // A tooltip a press pinned says its own text (component:Tooltip FR10).
+ render(
+ <Tooltip
+ content="Billed on the first of each month"
+ triggerBehavior="toggle">
+ <button type="button">About billing</button>
+ </Tooltip>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'About billing'}));
+ await expectDelegated('Billed on the first of each month');
+ },
'Tokenizer/TokenizerBottomSheet.tsx': async () => {
// The sheet's own content is a caller's `emptySearchText` element; the
// default EmptyState announces itself.