Skip to content

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

TypeScript

fix(Tooltip): Space on keyup and a press outside in another document, with triggerBehavior evidence (#9406)

Christopher Chedeau9ae589b92ba2
diff --git a/.changeset/tooltip-toggle-space-keyup.md b/.changeset/tooltip-toggle-space-keyup.md
new file mode 100644
index 0000000000..dd5fb86c8a
--- /dev/null
+++ b/.changeset/tooltip-toggle-space-keyup.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Tooltip, HoverCard: a tap-opened tooltip or hover card whose trigger renders in another document, such as an iframe, now closes on a scroll that starts outside in that document, and on a tap outside there when the trigger takes no focus.
+
+@vjeux
diff --git a/apps/storybook/stories/TooltipToggleBehaviorA11y.stories.tsx b/apps/storybook/stories/TooltipToggleBehaviorA11y.stories.tsx
index 6d53a3f082..aec56cd094 100644
--- a/apps/storybook/stories/TooltipToggleBehaviorA11y.stories.tsx
+++ b/apps/storybook/stories/TooltipToggleBehaviorA11y.stories.tsx
@@ -6,7 +6,8 @@
* @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.
+ * One is a trigger whose tooltip opens on no focus. One story has a trigger
+ * per `triggerBehavior` value.
* @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
@@ -149,3 +150,33 @@ export const FocusTriggerNever: Story = {
</div>
),
};
+
+/** One info-only trigger per `triggerBehavior` value: a tap opens, never opens, or pins. */
+export const TriggerBehaviors: Story = {
+ render: () => (
+ <div style={{padding: 100}}>
+ <VStack gap={4}>
+ <Tooltip
+ content="Adaptive: a tap opens it"
+ triggerBehavior="adaptive"
+ delay={0}>
+ <span tabIndex={0}>Adaptive term</span>
+ </Tooltip>
+ <Tooltip
+ content="Hover: touch never opens it"
+ triggerBehavior="hover"
+ delay={0}>
+ <span tabIndex={0}>Hover term</span>
+ </Tooltip>
+ <Tooltip
+ content="Toggle: a press pins it"
+ triggerBehavior="toggle"
+ delay={0}>
+ <Button label="Toggle term" variant="secondary">
+ ?
+ </Button>
+ </Tooltip>
+ </VStack>
+ </div>
+ ),
+};
diff --git a/docs/specs/components/Tooltip/Tooltip.spec.md b/docs/specs/components/Tooltip/Tooltip.spec.md
index c63841ee5e..fd6dabe1d6 100644
--- a/docs/specs/components/Tooltip/Tooltip.spec.md
+++ b/docs/specs/components/Tooltip/Tooltip.spec.md
@@ -56,7 +56,7 @@ system_specs: [spec:AST-003, spec:AST-017, spec:AST-086/FR12, spec:AST-086/FR14]
| 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). DEP-0016's deprecation metadata and codemod are not yet built; thirteen 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; twelve 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`. |
@@ -166,9 +166,6 @@ Consumer migration instructions belong in consumer docs and release notes.
- **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).
@@ -230,19 +227,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. 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 |
+| 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. 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
@@ -327,7 +324,7 @@ has no arrow element.
| 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 | `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` |
+| FR5, FR9 (`triggerBehavior`) | `Tooltip.test.tsx` trigger-behavior suite; `TouchTrigger.a11y.chromium.spec.ts` finger and pen cases; `useTooltip.test.tsx` caller-trigger cases; `usePressPin.test.tsx` keyboard and close cases | `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/src/Layer/__tests__/TouchTrigger.a11y.chromium.spec.ts b/packages/core/src/Layer/__tests__/TouchTrigger.a11y.chromium.spec.ts
index f1a3f32999..7a3cbde0f2 100644
--- a/packages/core/src/Layer/__tests__/TouchTrigger.a11y.chromium.spec.ts
+++ b/packages/core/src/Layer/__tests__/TouchTrigger.a11y.chromium.spec.ts
@@ -11,6 +11,8 @@
* the trigger, never opens for a touch that turns into a scroll, and a
* tap-opened layer closes when a tap outside lifts or a scroll starts
* outside.
+ * Each `triggerBehavior` value answers a finger or pen tap as it says, and
+ * a toggle trigger pins on a press, also under a mouse.
* @position Run with `pnpm test:a11y-contract`. Only a real engine decides
* whether a touch is a tap, a scroll or a long press, so these outcomes
* cannot be shown in jsdom; the unit suites (Tooltip.test.tsx,
@@ -273,6 +275,57 @@ test.describe('Tooltip triggerBehavior="toggle" (component:Tooltip FR9, FR10)',
});
});
+test.describe('Tooltip triggerBehavior under a finger and a pen (component:Tooltip FR5, FR9)', () => {
+ const STORY = 'a11y-tooltip-toggle-behavior--trigger-behaviors';
+ const LAYER = '.astryx-tooltip:popover-open';
+ const term = (page: Page, name: string) =>
+ page.getByText(name, {exact: true});
+
+ /** A tap: a finger through touch events, or a landed pen through pen-typed presses. */
+ async function tapWith(
+ page: Page,
+ finger: Finger,
+ target: Locator,
+ pointer: 'finger' | 'pen',
+ ) {
+ const [x, y] = await centerOf(target);
+ if (pointer === 'finger') {
+ await finger.down(x, y);
+ await finger.up();
+ return;
+ }
+ const cdp = await page.context().newCDPSession(page);
+ for (const type of ['mousePressed', 'mouseReleased'] as const) {
+ await cdp.send('Input.dispatchMouseEvent', {
+ type,
+ x,
+ y,
+ button: 'left',
+ clickCount: 1,
+ pointerType: 'pen',
+ });
+ }
+ await cdp.detach();
+ }
+
+ for (const pointer of ['finger', 'pen'] as const) {
+ test(`a ${pointer} tap never opens hover, opens adaptive, and pins toggle`, async ({
+ page,
+ }) => {
+ const finger = await openStory(page, STORY);
+ await tapWith(page, finger, term(page, 'Hover term'), pointer);
+ await page.waitForTimeout(300);
+ await expect(page.locator(LAYER)).toHaveCount(0);
+ await tapWith(page, finger, term(page, 'Adaptive term'), pointer);
+ await expect(page.locator(LAYER)).toHaveText('Adaptive: a tap opens it');
+ const toggle = page.getByRole('button', {name: 'Toggle term'});
+ await tapWith(page, finger, toggle, pointer);
+ await expect(page.locator(LAYER)).toHaveText('Toggle: a press pins it');
+ await expect(toggle).toHaveAttribute('aria-expanded', 'true');
+ });
+ }
+});
+
test.describe('a pinned layer under a mouse (component:Tooltip FR9)', () => {
test.use({
hasTouch: false,
diff --git a/packages/core/src/Layer/usePressPin.test.tsx b/packages/core/src/Layer/usePressPin.test.tsx
index 030601f04e..5f6b1e9ac5 100644
--- a/packages/core/src/Layer/usePressPin.test.tsx
+++ b/packages/core/src/Layer/usePressPin.test.tsx
@@ -23,8 +23,15 @@ import {
afterEach,
} from 'vitest';
import {render, screen, fireEvent, act} from '@testing-library/react';
-import {useRef, useState, type ReactElement, type ReactNode} from 'react';
+import {
+ useRef,
+ useState,
+ type KeyboardEvent as ReactKeyboardEvent,
+ type ReactElement,
+ type ReactNode,
+} from 'react';
import {Tooltip} from '../Tooltip/Tooltip';
+import {HoverCard} from '../HoverCard/HoverCard';
import {ClickableCard} from '../ClickableCard/ClickableCard';
import {Dialog} from '../Dialog/Dialog';
import {Item} from '../Item/Item';
@@ -188,9 +195,60 @@ describe('Tooltip triggerBehavior="toggle" (component:Tooltip FR9)', () => {
fireEvent.keyDown(trigger, {key: 'Enter'});
expect(shows(TIP)).toBe(true);
fireEvent.keyDown(trigger, {key: ' '});
+ fireEvent.keyUp(trigger, {key: ' '});
expect(shows(TIP)).toBe(false);
});
+ it('Space on a role="button" trigger presses it on keyup, as on a native button', () => {
+ render(
+ <InfoTooltip>
+ <span role="button" tabIndex={0}>
+ About billing
+ </span>
+ </InfoTooltip>,
+ );
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ // The keydown scrolls nothing and pins nothing yet.
+ expect(fireEvent.keyDown(trigger, {key: ' '})).toBe(false);
+ expect(shows(TIP)).toBe(false);
+ fireEvent.keyUp(trigger, {key: ' '});
+ expect(shows(TIP)).toBe(true);
+ // A keyup with no keydown on the trigger presses nothing.
+ fireEvent.keyUp(trigger, {key: ' '});
+ expect(shows(TIP)).toBe(true);
+ });
+
+ it.each(['keydown', 'keyup'] as const)(
+ 'a role="button" trigger that clicks itself on Space %s pins once',
+ async timing => {
+ const clickOnSpace = (event: ReactKeyboardEvent<HTMLElement>) => {
+ if (event.key === ' ') {
+ event.currentTarget.click();
+ }
+ };
+ render(
+ <InfoTooltip>
+ <span
+ role="button"
+ tabIndex={0}
+ onKeyDown={timing === 'keydown' ? clickOnSpace : undefined}
+ onKeyUp={timing === 'keyup' ? clickOnSpace : undefined}>
+ About billing
+ </span>
+ </InfoTooltip>,
+ );
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ fireEvent.keyDown(trigger, {key: ' '});
+ // A browser dispatches the keyup in a later task.
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 0));
+ });
+ fireEvent.keyUp(trigger, {key: ' '});
+ expect(shows(TIP)).toBe(true);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ },
+ );
+
it('Escape closes a pinned tooltip', () => {
render(<InfoTooltip />);
const trigger = screen.getByRole('button', {name: 'About billing'});
@@ -718,11 +776,11 @@ describe('a pin inside a modal Dialog (spec:AST-086 FR14)', () => {
});
});
-describe('a toggle trigger in another document', () => {
- it('closes the pin when focus moves to another control in that document', () => {
+describe('a hover layer whose trigger is in another document', () => {
+ /** Renders `ui` into an iframe whose HTMLElement gets this file's popover stubs. */
+ function renderInFrame(ui: ReactElement) {
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;
@@ -736,12 +794,20 @@ describe('a toggle trigger in another document', () => {
const container = frame.document.body.appendChild(
frame.document.createElement('div'),
);
- const view = render(
+ const view = render(ui, {container, baseElement: frame.document.body});
+ const done = () => {
+ view.unmount();
+ iframe.remove();
+ };
+ return {view, frame, done};
+ }
+
+ it('closes a pin when focus moves to another control in that document', () => {
+ const {view, done} = renderInFrame(
<>
<InfoTooltip />
<button type="button">Next</button>
</>,
- {container, baseElement: frame.document.body},
);
try {
const trigger = view.getByRole('button', {name: 'About billing'});
@@ -751,8 +817,91 @@ describe('a toggle trigger in another document', () => {
fireEvent.focusOut(trigger, {relatedTarget: next});
expect(trigger).toHaveAttribute('aria-expanded', 'false');
} finally {
- view.unmount();
- iframe.remove();
+ done();
+ }
+ });
+
+ it('closes a pin on a press outside in that document', () => {
+ const {view, done} = renderInFrame(
+ <>
+ <InfoTooltip />
+ <p>Elsewhere</p>
+ </>,
+ );
+ try {
+ const trigger = view.getByRole('button', {name: 'About billing'});
+ click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ // A press on content that takes no focus reaches only the listener.
+ const elsewhere = view.getByText('Elsewhere');
+ fireEvent.pointerDown(elsewhere);
+ fireEvent.pointerUp(elsewhere);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ } finally {
+ done();
+ }
+ });
+
+ // A trigger that takes focus also closes through focus leaving in a real
+ // engine, so these triggers take none.
+ it('closes a tap-opened tooltip on a tap outside in that document', () => {
+ const {view, frame, done} = renderInFrame(
+ <>
+ <Tooltip content={TIP}>
+ <span>Billing date</span>
+ </Tooltip>
+ <p>Elsewhere</p>
+ </>,
+ );
+ const open = () =>
+ [document, frame.document].some(
+ doc =>
+ doc
+ .querySelector<HTMLElement>('[popover]')
+ ?.matches(':popover-open') === true,
+ );
+ try {
+ tap(view.getByText('Billing date'));
+ expect(open()).toBe(true);
+ const elsewhere = view.getByText('Elsewhere');
+ fireEvent.pointerDown(elsewhere, {pointerType: 'touch'});
+ fireEvent.pointerUp(elsewhere, {pointerType: 'touch'});
+ expect(open()).toBe(false);
+ // A scroll that starts outside closes it too.
+ tap(view.getByText('Billing date'));
+ expect(open()).toBe(true);
+ fireEvent.pointerCancel(elsewhere, {pointerType: 'touch'});
+ expect(open()).toBe(false);
+ } finally {
+ done();
+ }
+ });
+
+ it('closes a tap-opened HoverCard on a tap outside in that document', () => {
+ const {view, frame, done} = renderInFrame(
+ <>
+ <HoverCard content={<p>Ada Lovelace, analyst</p>}>
+ <span>Ada</span>
+ </HoverCard>
+ <p>Elsewhere</p>
+ </>,
+ );
+ const open = () =>
+ [document, frame.document].some(
+ doc =>
+ doc
+ .querySelector<HTMLElement>('[popover]')
+ ?.matches(':popover-open') === true,
+ );
+ try {
+ tap(view.getByText('Ada'));
+ expect(open()).toBe(true);
+ const elsewhere = view.getByText('Elsewhere');
+ fireEvent.pointerDown(elsewhere, {pointerType: 'touch'});
+ fireEvent.pointerUp(elsewhere, {pointerType: 'touch'});
+ expect(open()).toBe(false);
+ } finally {
+ done();
}
});
});
diff --git a/packages/core/src/Layer/usePressPin.ts b/packages/core/src/Layer/usePressPin.ts
index 520ff79230..1d68c69213 100644
--- a/packages/core/src/Layer/usePressPin.ts
+++ b/packages/core/src/Layer/usePressPin.ts
@@ -177,7 +177,7 @@ export function usePressPin(options: UsePressPinOptions): UsePressPinReturn {
setIsPinnedState(next);
}, []);
- // Refs hold the wired trigger and last offered element for a later rewire.
+ // The last offered element lets a `triggerBehavior` change rewire it.
const triggerRef = useRef<HTMLElement | null>(null);
const offeredRef = useRef<HTMLElement | null>(null);
// A primitive: re-attaching the same trigger renders nothing.
@@ -280,9 +280,12 @@ export function usePressPin(options: UsePressPinOptions): UsePressPinReturn {
}
}, [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.
+ // A non-native button gets no click from the browser for a key. So Enter
+ // presses it on keydown, and Space on keyup, as on a native button. A click
+ // with no pointer (`detail` 0) while Space is down, or in a key press's
+ // task, is that same press.
const keyPressedRef = useRef(false);
+ const spaceHeldRef = useRef(false);
const handlePress = useCallback(
(event: MouseEvent) => {
const current = optionsRef.current;
@@ -292,33 +295,61 @@ export function usePressPin(options: UsePressPinOptions): UsePressPinReturn {
// The press stops at its trigger: no label control, link, or submit.
event.preventDefault();
pressPinClicks.add(event);
- if (keyPressedRef.current && event.detail === 0) {
+ if (
+ event.detail === 0 &&
+ (keyPressedRef.current || spaceHeldRef.current)
+ ) {
return;
}
toggle();
},
[toggle],
);
+ const pressFromKey = useCallback(() => {
+ keyPressedRef.current = true;
+ setTimeout(() => {
+ keyPressedRef.current = false;
+ }, 0);
+ 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;
}
+ // The press replaces the key's own action, such as a page scroll on Space.
event.preventDefault();
- keyPressedRef.current = true;
- setTimeout(() => {
- keyPressedRef.current = false;
- }, 0);
- toggle();
+ if (event.repeat) {
+ return;
+ }
+ if (event.key === ' ') {
+ spaceHeldRef.current = true;
+ return;
+ }
+ pressFromKey();
},
- [toggle],
+ [pressFromKey],
+ );
+ // Only a Space that went down on the trigger presses it when it comes up.
+ const handleKeyUp = useCallback(
+ (event: KeyboardEvent) => {
+ if (event.key !== ' ' || !spaceHeldRef.current) {
+ return;
+ }
+ spaceHeldRef.current = false;
+ const current = optionsRef.current;
+ if (!current.isEnabled || current.triggerBehavior !== 'toggle') {
+ return;
+ }
+ pressFromKey();
+ },
+ [pressFromKey],
);
const isHeldOpen = useCallback(() => {
@@ -333,6 +364,8 @@ export function usePressPin(options: UsePressPinOptions): UsePressPinReturn {
const handleFocusLeave = useCallback(
(event: FocusEvent) => {
+ // A Space that comes up after focus left presses nothing.
+ spaceHeldRef.current = false;
if (!isHeldOpen()) {
return false;
}
@@ -366,6 +399,7 @@ export function usePressPin(options: UsePressPinOptions): UsePressPinReturn {
}
previous.removeEventListener('click', handlePress);
previous.removeEventListener('keydown', handleKeyDown);
+ previous.removeEventListener('keyup', handleKeyUp);
previous.removeEventListener('focusout', handleFocusLeave);
const own = ownStateRef.current;
if (own != null) {
@@ -374,7 +408,7 @@ export function usePressPin(options: UsePressPinOptions): UsePressPinReturn {
}
ownStateRef.current = null;
triggerRef.current = null;
- }, [handlePress, handleKeyDown, handleFocusLeave]);
+ }, [handlePress, handleKeyDown, handleKeyUp, handleFocusLeave]);
// The element and mode last settled; the same pair again does nothing.
const settledRef = useRef<{
@@ -404,6 +438,7 @@ export function usePressPin(options: UsePressPinOptions): UsePressPinReturn {
element.addEventListener('click', handlePress);
if (element.tagName !== 'BUTTON') {
element.addEventListener('keydown', handleKeyDown);
+ element.addEventListener('keyup', handleKeyUp);
}
// Its own focus-leave listener: `focusTrigger="never"` attaches none.
element.addEventListener('focusout', handleFocusLeave);
@@ -413,7 +448,7 @@ export function usePressPin(options: UsePressPinOptions): UsePressPinReturn {
};
triggerRef.current = element;
},
- [unwire, handlePress, handleKeyDown, handleFocusLeave],
+ [unwire, handlePress, handleKeyDown, handleKeyUp, handleFocusLeave],
);
const attach = useCallback(
diff --git a/packages/core/src/Layer/useTouchTrigger.ts b/packages/core/src/Layer/useTouchTrigger.ts
index 65f2148279..2136464f79 100644
--- a/packages/core/src/Layer/useTouchTrigger.ts
+++ b/packages/core/src/Layer/useTouchTrigger.ts
@@ -367,6 +367,9 @@ export function useTouchTriggerInternal(
const outsideListenerRef = useRef<((event: PointerEvent) => void) | null>(
null,
);
+ // The documents the outside dismissal listens on: the page's, and the
+ // trigger's own when it renders in another document, such as an iframe.
+ const outsideDocumentsRef = useRef<Document[]>([]);
// A touch press on the trigger still waiting for its tap: calling it stops
// waiting. The next press, a cancel, the tap itself or unmounting calls it.
const forgetPendingTapRef = useRef<(() => void) | null>(null);
@@ -380,8 +383,11 @@ export function useTouchTriggerInternal(
return;
}
outsideListenerRef.current = null;
- document.removeEventListener('pointerup', listener, true);
- document.removeEventListener('pointercancel', listener, true);
+ for (const doc of outsideDocumentsRef.current) {
+ doc.removeEventListener('pointerup', listener, true);
+ doc.removeEventListener('pointercancel', listener, true);
+ }
+ outsideDocumentsRef.current = [];
}, []);
// Capture phase, so a trigger that stops propagation cannot strand an open
@@ -395,6 +401,8 @@ export function useTouchTriggerInternal(
return;
}
+ const own = triggerRef.current?.ownerDocument ?? document;
+ const docs = own === document ? [document] : [document, own];
const handleOutsidePointerEnd = (event: PointerEvent) => {
const target = event.target as Node | null;
if (target != null) {
@@ -408,7 +416,10 @@ export function useTouchTriggerInternal(
}
// Hover card content is interactive; a tap inside it is not a dismiss.
if (
- document.getElementById(layerIdRef.current)?.contains(target) === true
+ docs.some(
+ doc =>
+ doc.getElementById(layerIdRef.current)?.contains(target) === true,
+ )
) {
return;
}
@@ -418,8 +429,11 @@ export function useTouchTriggerInternal(
};
outsideListenerRef.current = handleOutsidePointerEnd;
- document.addEventListener('pointerup', handleOutsidePointerEnd, true);
- document.addEventListener('pointercancel', handleOutsidePointerEnd, true);
+ outsideDocumentsRef.current = docs;
+ for (const doc of docs) {
+ doc.addEventListener('pointerup', handleOutsidePointerEnd, true);
+ doc.addEventListener('pointercancel', handleOutsidePointerEnd, true);
+ }
}, [triggerRef, disarmOutsideDismiss]);
useEffect(() => disarmOutsideDismiss, [disarmOutsideDismiss]);
diff --git a/packages/core/src/Tooltip/Tooltip.test.tsx b/packages/core/src/Tooltip/Tooltip.test.tsx
index 0efcb6bb7f..45be9bfeb6 100644
--- a/packages/core/src/Tooltip/Tooltip.test.tsx
+++ b/packages/core/src/Tooltip/Tooltip.test.tsx
@@ -978,3 +978,122 @@ describe('Tooltip surface press', () => {
expect(screen.getByRole('checkbox')).toBeChecked();
});
});
+
+describe('Tooltip triggerBehavior on every input (component:Tooltip FR5, FR9)', () => {
+ beforeEach(() => {
+ __resetInteractionModalityForTest();
+ });
+
+ type Behavior = 'adaptive' | 'hover' | 'toggle';
+
+ /** An info-only trigger: a span, or under the toggle the button it pins. */
+ function setup(
+ triggerBehavior?: Behavior,
+ touchTrigger?: 'auto' | 'tap' | 'none',
+ trigger = triggerBehavior === 'toggle' ? 'button' : 'span',
+ ) {
+ const onOpenChange = vi.fn<(open: boolean) => void>();
+ render(
+ <Tooltip
+ content="Billed monthly"
+ delay={0}
+ onOpenChange={onOpenChange}
+ triggerBehavior={triggerBehavior}
+ touchTrigger={touchTrigger}>
+ {trigger === 'button' ? (
+ <button type="button">Billing</button>
+ ) : (
+ <span tabIndex={0}>Billing</span>
+ )}
+ </Tooltip>,
+ );
+ const opened = () => onOpenChange.mock.calls.some(([open]) => open);
+ return {trigger: screen.getByText('Billing'), opened};
+ }
+
+ /** A finger or a landed pen: down, up, then the click (a pen hovers, so no arrival). */
+ function tap(element: HTMLElement, pointerType: 'touch' | 'pen') {
+ if (pointerType === 'touch') {
+ fireEvent.pointerEnter(element, {pointerType});
+ }
+ fireEvent.pointerDown(element, {pointerType});
+ fireEvent.pointerUp(element, {pointerType});
+ fireEvent.click(element);
+ }
+
+ const settle = async () =>
+ new Promise(resolve => {
+ setTimeout(resolve, 50);
+ });
+
+ describe.each([
+ ['adaptive by default', undefined, true],
+ ['adaptive', 'adaptive', true],
+ ['hover', 'hover', false],
+ ['toggle', 'toggle', true],
+ ] as const)('%s', (_, behavior, tapOpens) => {
+ it('a mouse hover previews it', async () => {
+ const {trigger, opened} = setup(behavior);
+ fireEvent.pointerEnter(trigger, {pointerType: 'mouse'});
+ fireEvent.mouseEnter(trigger);
+ await waitFor(() => expect(opened()).toBe(true));
+ });
+
+ it('keyboard focus previews it', async () => {
+ const {trigger, opened} = setup(behavior);
+ const realMatches = trigger.matches.bind(trigger);
+ vi.spyOn(trigger, 'matches').mockImplementation((selector: string) =>
+ selector === ':focus-visible' ? true : realMatches(selector),
+ );
+ fireEvent.keyDown(document, {key: 'Tab'});
+ fireEvent.focusIn(trigger);
+ await waitFor(() => expect(opened()).toBe(true));
+ });
+
+ it.each(['touch', 'pen'] as const)(
+ `a %s tap ${tapOpens ? 'opens' : 'never opens'} it`,
+ async pointerType => {
+ const {trigger, opened} = setup(behavior);
+ tap(trigger, pointerType);
+ await settle();
+ expect(opened()).toBe(tapOpens);
+ },
+ );
+
+ it.each(['mouse click', 'touch tap'] as const)(
+ `a %s on a button trigger ${behavior === 'toggle' ? 'pins it' : 'pins nothing'}`,
+ async press => {
+ const {trigger} = setup(behavior, undefined, 'button');
+ if (press === 'mouse click') {
+ fireEvent.pointerDown(trigger, {pointerType: 'mouse'});
+ fireEvent.pointerUp(trigger, {pointerType: 'mouse'});
+ fireEvent.click(trigger);
+ } else {
+ tap(trigger, 'touch');
+ }
+ await settle();
+ expect(trigger.getAttribute('aria-expanded')).toBe(
+ behavior === 'toggle' ? 'true' : null,
+ );
+ },
+ );
+ });
+
+ it.each([
+ ['adaptive', 'none', 'span', 'decides: no tap opens it', false],
+ ['adaptive', 'tap', 'button', 'decides: every tap opens it', true],
+ ['hover', 'tap', 'button', 'is ignored: no tap opens it', false],
+ ['toggle', 'none', 'button', 'is ignored: a tap pins it', true],
+ ] as const)(
+ 'beside triggerBehavior="%s", touchTrigger="%s" on a %s %s',
+ async (behavior, touchTrigger, trigger, _, tapOpens) => {
+ const tip = setup(behavior, touchTrigger, trigger);
+ tap(tip.trigger, 'touch');
+ await settle();
+ expect(tip.opened()).toBe(tapOpens);
+ if (behavior === 'toggle') {
+ expect(tip.trigger.getAttribute('aria-expanded')).toBe('true');
+ }
+ },
+ );
+});
diff --git a/packages/core/src/Tooltip/useTooltip.test.tsx b/packages/core/src/Tooltip/useTooltip.test.tsx
index 16d97f3384..506f8adf68 100644
--- a/packages/core/src/Tooltip/useTooltip.test.tsx
+++ b/packages/core/src/Tooltip/useTooltip.test.tsx
@@ -3,7 +3,8 @@
/**
* @file useTooltip.test.tsx
* @input Uses vitest, @testing-library/react, useTooltip hook
- * @output Unit tests for the tooltip show/hide timers and controlled state
+ * @output Unit tests for the tooltip show/hide timers and controlled state,
+ * and for a press on a caller's trigger under `triggerBehavior="toggle"`
* @position Testing; validates useTooltip.tsx timing contract. Component-level
* behavior lives in Tooltip.test.tsx — this file pins the delays, the
* hover-bridge constant, and timer teardown, which are invisible from there.
@@ -24,6 +25,8 @@ import {
import {render, screen, fireEvent, act} from '@testing-library/react';
import {useTooltip, type TooltipOptions} from './useTooltip';
import {useLayer} from '../Layer/useLayer';
+import {ClickableCard} from '../ClickableCard/ClickableCard';
+import type {MouseEvent as ReactMouseEvent} from 'react';
// jsdom implements neither the Popover API nor `:popover-open`; mirror
// Tooltip.test.tsx's shims so the layer can open.
@@ -595,3 +598,60 @@ describe('useTooltip — focusTrigger="auto" decides when focus arrives', () =>
expect(onHide).not.toHaveBeenCalled();
});
});
+
+describe('useTooltip with a caller’s trigger under triggerBehavior="toggle" (component:Tooltip FR9)', () => {
+ function Tip({
+ onTriggerClick,
+ }: {
+ onTriggerClick?: (event: ReactMouseEvent) => void;
+ }) {
+ const tooltip = useTooltip({triggerBehavior: 'toggle', delay: 0});
+ return (
+ <>
+ <button type="button" ref={tooltip.ref} onClick={onTriggerClick}>
+ What is this?
+ </button>
+ {tooltip.renderTooltip('Billed monthly')}
+ </>
+ );
+ }
+ const trigger = () => screen.getByRole('button', {name: 'What is this?'});
+
+ it('the trigger’s own onClick runs, and an Astryx ClickableCard around it does not activate', () => {
+ const onCard = vi.fn();
+ const onTrigger = vi.fn();
+ render(
+ <ClickableCard label="Card" onClick={onCard}>
+ <Tip onTriggerClick={onTrigger} />
+ </ClickableCard>,
+ );
+
+ fireEvent.click(trigger());
+
+ expect(onTrigger).toHaveBeenCalledTimes(1);
+ expect(onCard).not.toHaveBeenCalled();
+ expect(trigger()).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('a plain onClick element around it receives the press, unless the trigger’s onClick stops it', () => {
+ const onRow = vi.fn();
+ const {unmount} = render(
+ <div onClick={onRow}>
+ <Tip />
+ </div>,
+ );
+ fireEvent.click(trigger());
+ expect(onRow).toHaveBeenCalledTimes(1);
+ expect(trigger()).toHaveAttribute('aria-expanded', 'true');
+ unmount();
+
+ onRow.mockClear();
+ render(
+ <div onClick={onRow}>
+ <Tip onTriggerClick={event => event.stopPropagation()} />
+ </div>,
+ );
+ fireEvent.click(trigger());
+ expect(onRow).not.toHaveBeenCalled();
+ });
+});