Skip to content

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

TypeScript

refactor(InfoTip): build on useTooltip's show() and hide(); remove the internal toggle path (#9756)

Cindy Zhang61cf773c2915
diff --git a/.changeset/infotip-on-use-tooltip.md b/.changeset/infotip-on-use-tooltip.md
new file mode 100644
index 0000000000..a1f20380c1
--- /dev/null
+++ b/.changeset/infotip-on-use-tooltip.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] InfoTip renders only its button and its help: the `display: contents` wrapper around the button is gone, and the button is the tooltip's trigger directly, built on `useTooltip`'s `show()` and `hide()`. Hover and keyboard focus still preview the help, and a click, tap, Enter, or Space still pins it until Escape, a second press, a press outside, or focus leaving. A mouse press on a previewed help keeps it in view as it pins, and a press that ends off the button does not pin it. A right-click on a previewed help now closes it at once, as it does on any tooltip trigger. Styles that reached the button through a wrapper selector now select the button itself.
+
+@cixzhang
diff --git a/apps/storybook/stories/TooltipToggleBehaviorA11y.stories.tsx b/apps/storybook/stories/TooltipToggleBehaviorA11y.stories.tsx
index 0d6331e354..9f578971a6 100644
--- a/apps/storybook/stories/TooltipToggleBehaviorA11y.stories.tsx
+++ b/apps/storybook/stories/TooltipToggleBehaviorA11y.stories.tsx
@@ -8,8 +8,8 @@
* an InfoTip.
* @position The reproduction path for the press-to-pin cases in
* `packages/core/src/Layer/__tests__/TouchTrigger.a11y.chromium.spec.ts`
- * (`component:Tooltip` FR9, FR10; InfoTip is Tooltip's press-to-pin
- * trigger). Per `docs/specs/AST-009/spec.md` FR30, a browser claim is
+ * (`component:InfoTip` FR2; InfoTip pins through `useTooltip`'s `show()`
+ * and `hide()`). 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
diff --git a/docs/families/overlay-dismissal.md b/docs/families/overlay-dismissal.md
index e801060562..18fa062823 100644
--- a/docs/families/overlay-dismissal.md
+++ b/docs/families/overlay-dismissal.md
@@ -262,14 +262,14 @@ this record's current membership snapshot must be updated with it.
## Adoption and exceptions
-| Components or surface | Adoption | Current deviation or limitation |
-| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Dialog, AlertDialog, Popover, MobileNav, Drawer, CommandPalette | shared owner; CommandPalette composes Dialog | none |
-| Tooltip, HoverCard | shared owner with DOM presence reporting | Neither provides nesting depth to descendant layers. Implementation gap: a Tooltip consumes Escape when it is the topmost layer, so the layer beneath it stays open for that press, and a Tooltip in another document is never closed by Escape (`component:Tooltip` FR6); FR8 gives that press to the layer beneath and closes a lone Tooltip in its own document. A Tooltip pinned open by a press takes Escape first (`spec:AST-003` FR4, DEC-6; `component:Tooltip` FR9); a HoverCard has no press pin. HoverCard reads its presence from the page's document, so in another document it takes no request (FR8) and returns no focus there (FR9) |
-| Focus traps with `onEscape` | shared owner through `useFocusTrap` | They provide DOM containment, not descendant depth |
-| BreadcrumbItem, ChatComposerInput, ComplexSelector, DateInput, DateRangeInput, DateTimeInput, Selector, MultiSelector, PowerSearch, BaseTypeahead, Typeahead, Tokenizer, SideNavHeading, SideNavItem, TabMenu, TopNavHeading, TopNavMenu, TopNavMegaMenu, Table, Lab TourStep, Lab ChatEmojiPicker | shared owner through `usePopover` or a composed Popover owner | Table filtering owns controlled Popover state and discards its draft on close; TourStep routes Popover close to the Tour; ChatEmojiPicker owns controlled Popover state |
-| DropdownMenu root, MoreMenu, ContextMenu, Selector, MultiSelector, TopNavHeading, TopNavMenu, TopNavMegaMenu, SideNavHeading, SideNavItem, BottomSheet, BottomSheetSwitcher, Lightbox | shared owner | Implementation gap: in another document (for BottomSheet, BottomSheetSwitcher and Lightbox, a Picture-in-Picture window), each decides focus return from the page's document and last input, so focus returns to the frame element or the page, or without the ring the last input in its document calls for (FR9) |
-| DropdownMenuSubMenu, PowerSearchEditPopover | local only | Must migrate from component-specific listeners or registries to the shared owner |
+| Components or surface | Adoption | Current deviation or limitation |
+| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Dialog, AlertDialog, Popover, MobileNav, Drawer, CommandPalette | shared owner; CommandPalette composes Dialog | none |
+| Tooltip, HoverCard | shared owner with DOM presence reporting | Neither provides nesting depth to descendant layers. Implementation gap: a Tooltip consumes Escape when it is the topmost layer, so the layer beneath it stays open for that press, and a Tooltip in another document is never closed by Escape (`component:Tooltip` FR6); FR8 gives that press to the layer beneath and closes a lone Tooltip in its own document. A Tooltip that a press pinned open through `useTooltip`'s `show()`, as a press on InfoTip does, takes Escape first (`spec:AST-003` FR4, DEC-6; `component:Tooltip` FR9, FR12); a HoverCard has no press pin. HoverCard reads its presence from the page's document, so in another document it takes no request (FR8) and returns no focus there (FR9) |
+| Focus traps with `onEscape` | shared owner through `useFocusTrap` | They provide DOM containment, not descendant depth |
+| BreadcrumbItem, ChatComposerInput, ComplexSelector, DateInput, DateRangeInput, DateTimeInput, Selector, MultiSelector, PowerSearch, BaseTypeahead, Typeahead, Tokenizer, SideNavHeading, SideNavItem, TabMenu, TopNavHeading, TopNavMenu, TopNavMegaMenu, Table, Lab TourStep, Lab ChatEmojiPicker | shared owner through `usePopover` or a composed Popover owner | Table filtering owns controlled Popover state and discards its draft on close; TourStep routes Popover close to the Tour; ChatEmojiPicker owns controlled Popover state |
+| DropdownMenu root, MoreMenu, ContextMenu, Selector, MultiSelector, TopNavHeading, TopNavMenu, TopNavMegaMenu, SideNavHeading, SideNavItem, BottomSheet, BottomSheetSwitcher, Lightbox | shared owner | Implementation gap: in another document (for BottomSheet, BottomSheetSwitcher and Lightbox, a Picture-in-Picture window), each decides focus return from the page's document and last input, so focus returns to the frame element or the page, or without the ring the last input in its document calls for (FR9) |
+| DropdownMenuSubMenu, PowerSearchEditPopover | local only | Must migrate from component-specific listeners or registries to the shared owner |
The rows marked partial or local are current adoption gaps against FR1, and the
rows naming an implementation gap are gaps against FR8 or FR9. They are not
diff --git a/docs/specs/AST-003/spec.md b/docs/specs/AST-003/spec.md
index 53b9ef8074..5e9a4d7767 100644
--- a/docs/specs/AST-003/spec.md
+++ b/docs/specs/AST-003/spec.md
@@ -72,7 +72,8 @@ browsers receive a usable reduced fallback, not equivalent behavior.
- **FR4 — Passive dependents never shield owners.** An unpinned Tooltip is
passive. It does not win or block dismissal and disappears as a consequence
when its associated owner or trigger interaction closes. A Tooltip that a
- press pinned open (`component:Tooltip` FR9) is an active owner: it takes
+ press pinned open through `useTooltip`'s `show()` (`component:Tooltip` FR9,
+ FR12), as a press on `component:InfoTip` does, is an active owner: it takes
Escape first and closes, and the owner beneath it stays open for that press
(DEC-6).
- **FR5 — Associations are explicit.** Every active or blocking owner records an
@@ -339,8 +340,8 @@ implement the missing browser systems.
**Reference:** `spec:AST-003/DEC-6`
**Decider:** `cixzhang`, `2026-10-31`
-A Tooltip that a press pinned open is something the person asked
-to keep, so it is an active owner and Escape closes it before the owner beneath
+A Tooltip that the person's press pinned open through `useTooltip`'s
+`show()`, as a press on InfoTip does, is something the person asked to keep, so it is an active owner and Escape closes it before the owner beneath
it. A Tooltip that only previews on hover or focus stays passive.
Rejected: keeping every Tooltip passive, which lets Escape close a Dialog behind
diff --git a/docs/specs/components/InfoTip/InfoTip.spec.md b/docs/specs/components/InfoTip/InfoTip.spec.md
index 723a388294..0d8c6f4fcf 100644
--- a/docs/specs/components/InfoTip/InfoTip.spec.md
+++ b/docs/specs/components/InfoTip/InfoTip.spec.md
@@ -13,6 +13,7 @@ review_triggers: [public-api, behavior, accessibility]
verified_by:
[
packages/core/src/InfoTip/InfoTip.test.tsx,
+ packages/core/src/InfoTip/InfoTip.pin.test.tsx,
packages/core/src/InfoTip/__tests__/InfoTipTouch.a11y.chromium.spec.ts,
packages/lab/src/InfoTip/InfoTip.test.tsx,
packages/core/src/Tooltip/Tooltip.test.tsx,
@@ -42,23 +43,24 @@ system_specs: [spec:AST-017, spec:AST-094]
## Contract at a glance
-| Area | Contract |
-| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| Public contract | `InfoTip` from `@astryxdesign/core` with `content`, `label` (a localized "More information"), `size` (`sm`), a `ref` forwarded to the button, and BaseProps' `xstyle`, `className`, and `style`. The `@astryxdesign/lab` export is a deprecated re-export for one release. |
-| Behavior | A named info-icon button wrapped in `component:Tooltip`, which pins the help through its internal press-to-pin path (not a public prop): hover and focus preview the help, and a click, tap, Enter, or Space pins it open until Escape, a second press, a press outside, or focus leaving. |
-| End-user impact | People on a mouse, touch, keyboard, or screen reader can open, keep open, and close the help behind an "i", and hear it once when it pins. |
-| Builder impact | Use InfoTip for help next to a label, value, or metric instead of composing an icon inside Tooltip. Lab callers change the import. |
-| Compatibility/readiness | New in Core; the `@astryxdesign/lab` export is a deprecated re-export of it for one release (FR4). |
-| Review checks | Reject a layer, listener, timer, or dismissal rule of InfoTip's own, a trigger that is not a named button, an untranslated default name, or a prop beyond those FR3 lists. |
-| Governing rules | `component:Tooltip` FR9, FR10, AR6; `architecture:public-component-api` INV21; `spec:AST-094` FR42; `spec:AST-017` (lifecycle). |
+| Area | Contract |
+| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | `InfoTip` from `@astryxdesign/core` with `content`, `label` (a localized "More information"), `size` (`sm`), a `ref` forwarded to the button, and BaseProps' `xstyle`, `className`, and `style`. The `@astryxdesign/lab` export is a deprecated re-export for one release. |
+| Behavior | A named native info-icon button that pins its help through `useTooltip`'s `show()` and `hide()`: hover and focus preview the help, a click, tap, Enter, or Space pins it open until Escape, a second press, a press outside, or focus leaving, and a mouse or pen press on a tip shown by hover holds it in place, without hiding and showing again. |
+| End-user impact | People on a mouse, touch, keyboard, or screen reader can open, keep open, and close the help behind an "i", and hear it once when it pins. |
+| Builder impact | Use InfoTip for help next to a label, value, or metric instead of composing an icon inside Tooltip. Lab callers change the import. |
+| Compatibility/readiness | New in Core; the `@astryxdesign/lab` export is a deprecated re-export of it for one release (FR4). |
+| Review checks | Reject a layer, document listener, timer, or dismissal rule of InfoTip's own, a wrapper element around the button, a trigger that is not a named native button, a pinning press that reaches a row, card, or label around it, a preview that blinks on a mouse or pen press, an untranslated default name, or a prop beyond those FR3 lists. |
+| Governing rules | `component:Tooltip` FR9, FR10, FR12, AR6; `architecture:public-component-api` INV21; `spec:AST-094` FR42; `spec:AST-017` (lifecycle). |
This table is a review projection; the body below is authoritative.
## Intent
-InfoTip is the info-icon preset over Tooltip's internal press-to-pin path. It owns the
-trigger button, its icon, its name, and its default, so every "i" in a product
-reads and behaves the same; Tooltip owns when the help opens and closes.
+InfoTip is the info-icon preset over `useTooltip`'s `show()` and `hide()`. It
+owns the trigger button, its icon, its name, its default, and the press that
+pins and closes the help, so every "i" in a product reads and behaves the
+same; Tooltip owns the preview, the pinned hold, and the announcement.
Consumer usage lives in `InfoTip.doc.mjs`.
## Compatibility and migration
@@ -66,7 +68,7 @@ Consumer usage lives in `InfoTip.doc.mjs`.
- Released default preserved: not yet released in Core; the Lab component's
props keep their meaning
- Compatibility class: additive Core export; the Lab component moves to Core
- with the same props and pins through Tooltip's internal press-to-pin path
+ with the same props and pins through `useTooltip`'s `show()` and `hide()`
instead of opening through `touchTrigger="tap"`
- Controlled/uncontrolled behavior: uncontrolled only; open state is Tooltip's
- Migration decision: DEC-1; the `@astryxdesign/lab` `InfoTip` export stays one
@@ -84,13 +86,15 @@ None.
- The trigger button, its info icon, its accessible name and default, and its
touch hit area (FR1, AR1).
-- What InfoTip passes to Tooltip (FR2).
+- The press that pins and closes the help through `useTooltip`'s `show()` and
+ `hide()`, and the button's `aria-describedby`, `aria-expanded`, and
+ `aria-controls` (FR2).
**Does not own / non-goals**
-- When the help previews, pins, closes, and is announced, its surface, and its
- Escape order — owned by `component:Tooltip` FR3–FR10 and
- `family:overlay-dismissal`.
+- When the help previews, how a pinned help closes, its announcement, its
+ surface, and its Escape order — owned by `component:Tooltip` FR3–FR10 and
+ FR12, and `family:overlay-dismissal`.
- Info artwork resolution — owned by the icon registry
(`architecture:icon-resolution-and-component-slots`).
- Rich or interactive help — `component:HoverCard`.
@@ -103,12 +107,12 @@ None.
## Behavioral and layout contract
-| ID | Invariant | Basis |
-| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------- |
-| FR1 | InfoTip renders one `<button type="button">` named by `label`, else the translated `@astryx.infoTip.label` ("More information"), containing the registry's `info` icon at `size`. | DEC-1; WCAG 2.2 SC 4.1.2; `architecture:icon-resolution-and-component-slots` |
-| FR2 | InfoTip wraps its button in `component:Tooltip` with `content` and pins its help on a press through Tooltip's internal press-to-pin path (not a public prop). It adds no layer, listener, timer, announcement, or dismissal rule of its own: previewing, pinning, closing, the trigger's `aria-expanded` and `aria-controls`, and the announcement are Tooltip's FR3–FR10. Whether InfoTip moves onto `useTooltip`'s `show()` and `hide()` (`component:Tooltip` DEC-1) is OQ1. | DEC-1; `architecture:public-component-api` INV21 |
-| FR3 | The public props are `content` (required; short, noninteractive help), `label`, `size`, a `ref` forwarded to the button, and BaseProps' `xstyle`, `className`, and `style`; InfoTip takes no open-state, placement, or trigger props. | DEC-1 |
-| FR4 | The `@astryxdesign/lab` `InfoTip` export re-exports the Core component, marked deprecated with static metadata, for one release, and is then removed. | `spec:AST-017` FR29, FR29a |
+| ID | Invariant | Basis |
+| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
+| FR1 | InfoTip renders one `<button type="button">` named by `label`, else the translated `@astryx.infoTip.label` ("More information"), containing the registry's `info` icon at `size`. | DEC-1; WCAG 2.2 SC 4.1.2; `architecture:icon-resolution-and-component-slots` |
+| FR2 | InfoTip renders its button and the layer from one `useTooltip` call with `content`, with no wrapper element; Tooltip's ref and the hit-area ref merge on the button. The button carries `aria-describedby` naming the help, `aria-expanded` (`true` only while pinned), and `aria-controls` naming the surface while the help shows. A click, tap, Enter, or Space pins the help through `show()`, and the same press on pinned help closes it through `hide()`; the press stops in the React tree, so a row, card, or label around the button does not act. A mouse or pen press on a tip shown by hover holds it in place through `show()` at pointer-down, so Tooltip's press-to-close (`component:Tooltip` FR6) leaves it open: it does not hide and show again, and the click then pins it. Touch and keyboard pin only through the click. InfoTip adds no layer, document listener, timer, announcement, or dismissal rule of its own: previewing, how pinned help closes, and the announcement are Tooltip's FR3–FR10 and FR12. | DEC-1; `component:Tooltip` FR9, FR10, FR12; `architecture:public-component-api` INV21 |
+| FR3 | The public props are `content` (required; short, noninteractive help), `label`, `size`, a `ref` forwarded to the button, and BaseProps' `xstyle`, `className`, and `style`; InfoTip takes no open-state, placement, or trigger props. | DEC-1 |
+| FR4 | The `@astryxdesign/lab` `InfoTip` export re-exports the Core component, marked deprecated with static metadata, for one release, and is then removed. | `spec:AST-017` FR29, FR29a |
### Allowed variation
@@ -129,9 +133,10 @@ None.
### Performance and resources
-- **PR1 — No resource of its own.** InfoTip adds no listener, observer, timer,
- or layer beyond the shared hit-area watch AR1 requires; Tooltip's are the
- only others it brings.
+- **PR1 — No resource of its own.** InfoTip adds no document listener,
+ observer, timer, or layer beyond its button's click and pointer-down
+ handlers and the shared hit-area watch AR1 requires; Tooltip's are the only
+ others it brings.
## Accessibility contract
@@ -154,35 +159,36 @@ None.
## Family and system relationships
-- `component:Tooltip` owns the press-to-pin path, preview, announcement, and
- surface; InfoTip is built entirely on it (DEC-1).
+- `component:Tooltip` owns the preview, the `show()` hold, the announcement,
+ and the surface; InfoTip is built entirely on `useTooltip` (DEC-1).
- `family:overlay-dismissal` owns Escape order through Tooltip.
- `architecture:icon-resolution-and-component-slots` owns the `info` artwork.
- InfoTip and Tooltip are one API, for the reason DEC-1 gives: InfoTip is built
- entirely on Tooltip's press-to-pin path and adds no layer, listener, or dismissal rule of
- its own, as `component:MoreMenu` is built on DropdownMenu.
+ entirely on `useTooltip`'s public `show()` and `hide()` and adds no layer,
+ timer, or dismissal rule of its own, as `component:MoreMenu` is built on DropdownMenu.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
-| FR1, AR1 | `InfoTip.test.tsx` button, name, catalog-default and hit-area cases; `InfoTipTouch.a11y.chromium.spec.ts` coarse-pointer reach, neighbour and fine-pointer cases | Default and custom name; each size | A trigger that is not a named button, an untranslated default, or a coarse-pointer hit area that stays under 44 px where its neighbors leave room or reaches a neighbor's target fails. | `audit:InfoTip/accessibility` |
-| FR2, AR2 | `InfoTip.test.tsx` press cases over `component:Tooltip`'s press-to-pin suite | Hover and focus preview; click, tap, Enter, Space pin; Escape | A press that does not pin, or a listener or layer InfoTip owns, fails. | `audit:InfoTip/behavior` |
-| FR3 | `InfoTip.test.tsx` props cases: the type checker rejects other props, and `ref`, `xstyle`, `className`, and `style` reach the button | `content`, `label`, `size`, `ref`, `xstyle`, `className`, `style` | A prop beyond those, or a `ref` that does not reach the button, fails. | `audit:InfoTip/api` |
-| FR4 | Lab `InfoTip.test.tsx` identity and deprecation cases | Lab import | A Lab export that is not the Core component, or lacks the deprecation metadata, fails. | `audit:InfoTip/api` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------- |
+| FR1, AR1 | `InfoTip.test.tsx` button, name, catalog-default and hit-area cases; `InfoTipTouch.a11y.chromium.spec.ts` coarse-pointer reach, neighbour and fine-pointer cases | Default and custom name; each size | A trigger that is not a named button, an untranslated default, or a coarse-pointer hit area that stays under 44 px where its neighbors leave room or reaches a neighbor's target fails. | `audit:InfoTip/accessibility` |
+| FR2, AR2 | `InfoTip.pin.test.tsx`; `InfoTip.test.tsx` press cases | Hover and focus preview; click, tap, Enter, Space pin; second press, press outside, focus leaving, and Escape close; a mouse or pen press on a hover preview; a button inside a ClickableCard, an Item row, and a `<label>` | A press that does not pin or close, a preview that closes and reopens on a mouse or pen press, a missing or stale `aria-expanded` or `aria-controls`, a press that also activates the card, row, or labelled control, or a wrapper, layer, or document listener InfoTip owns, fails. | `audit:InfoTip/behavior` |
+| FR3 | `InfoTip.test.tsx` props cases: the type checker rejects other props, and `ref`, `xstyle`, `className`, and `style` reach the button | `content`, `label`, `size`, `ref`, `xstyle`, `className`, `style` | A prop beyond those, or a `ref` that does not reach the button, fails. | `audit:InfoTip/api` |
+| FR4 | Lab `InfoTip.test.tsx` identity and deprecation cases | Lab import | A Lab export that is not the Core component, or lacks the deprecation metadata, fails. | `audit:InfoTip/api` |
## Decision log
-### DEC-1 — InfoTip is a preset over Tooltip's press-to-pin path
+### DEC-1 — InfoTip is a preset over `useTooltip`'s show and hide
**Reference:** `component:InfoTip/DEC-1`
-**Decider:** `cixzhang`, `2026-10-31`
+**Decider:** `cixzhang`, `2026-10-31`; amended `2026-11-03`
Help behind an "i" is the same job as a tooltip that pins on a press, so
-InfoTip supplies only the named button, its icon, and its default, and is
-built entirely on `component:Tooltip` and its internal press-to-pin path,
-which has no public prop. A component
-built entirely on another public API is one API with it
+InfoTip supplies only the named button, its icon, its default, and the press
+that pins, and is built entirely on `useTooltip`'s public `show()` and `hide()`
+(`component:Tooltip` FR12). Tooltip has no toggle option of its own: InfoTip
+pins the way any app's toggle-style button does. A component built entirely
+on another public API is one API with it
(`architecture:public-component-api` INV21, the reasoning `spec:AST-107` DEC-2
and DEC-3 apply to a component over a public factory), as `component:MoreMenu`
is over DropdownMenu, so InfoTip adds no second way to do Tooltip's job.
@@ -192,9 +198,7 @@ HoverCard's previews.
## Open questions
-- **OQ1 — Does InfoTip move onto `useTooltip`'s `show()` and `hide()`?**
- (`human-api`) Until then it pins through Tooltip's internal press-to-pin
- path (FR2).
+None.
## Content boundary
diff --git a/docs/specs/components/StatusDot/StatusDot.spec.md b/docs/specs/components/StatusDot/StatusDot.spec.md
index 14cb4f8278..a6d6b0f42e 100644
--- a/docs/specs/components/StatusDot/StatusDot.spec.md
+++ b/docs/specs/components/StatusDot/StatusDot.spec.md
@@ -123,14 +123,14 @@ Consumer migration instructions belong in consumer docs and release notes.
## Behavioral and layout contract
-| ID | Invariant | Basis |
-| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- |
-| FR1 | StatusDot always renders one inline-flex `span` dot, 8 by 8 CSS pixels, fully rounded, that does not shrink in a flex row, carrying the `status-dot` target and only that target. | Current source and tests |
-| FR2 | `success`, `warning`, and `error` are strong status fills: under `architecture:theme-tokens` INV11 each paints `--color-<status>` with `--color-on-<status>` ink and keeps a visible `CanvasText` border in forced-colors mode. `accent` paints `--color-accent` with `--color-on-accent` ink, and `neutral` paints `--color-icon-secondary` with the surface color as ink; these two are not INV11 status roles, and no current record sets their forced-colors treatment (OQ1). The target reflects `variant` for every value, and an extensible tone has a safe theme-independent baseline (`architecture:component-theming-surface` INV14). Implementation gap: a theme-added value the active theme does not paint receives no component plate or ink, leaving a transparent 8px box (Current-state impact). | Current source and tests |
-| FR3 | `isPulsing` animates the dot's opacity from 1 to 0.5 and back over 2 seconds, ease-in-out, indefinitely; under `prefers-reduced-motion: reduce` the animation is removed and the dot rests. | Current source and tests |
-| FR4 | A renderable `icon` renders in a wrapper centered inside the dot and filling its 8px field; it paints from `currentColor`, the variant's ink. A non-renderable value leaves the dot childless. | Current source and tests |
-| FR5 | A non-empty `tooltip` renders by placement; without one, no tooltip renders. A standalone dot is wrapped in Tooltip with that text and is a button trigger whose press pins it, named by `label`, so hover and keyboard focus preview the tooltip and a tap, click, Enter, or Space pins it (`component:Tooltip` DEC-1), and keyboard users reach it (WCAG 2.2 2.1.1). StatusDot adopts the pin once `useTooltip`'s `show()` and `hide()` (`component:Tooltip` DEC-1) ship, so a standalone dot's tooltip stays reachable on touch. A dot inside an interactive element (a button, link, menu item, or option) is a non-interactive image wrapped in Tooltip without the pin, because a control cannot nest another control: its tooltip previews on hover only, and its tooltip text joins the host's accessible name, so the host carries the status for screen readers (`architecture:interaction-modality` INV4). A host named by `aria-label` takes no name from its content, so its caller includes the status in that label. Implementation gap: the dot has no tab stop and uses Tooltip's default touch trigger, so the tooltip opens on hover and touch only (Current-state impact). | Current source and tests; `component:Tooltip` DEC-1 |
-| FR6 | `ref` reaches the dot. Supported DOM, ARIA, data, and event props reach the dot after its role and name; `xstyle`, `className`, and `style` merge in that order after component styles. | Current source and tests |
+| ID | Invariant | Basis |
+| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
+| FR1 | StatusDot always renders one inline-flex `span` dot, 8 by 8 CSS pixels, fully rounded, that does not shrink in a flex row, carrying the `status-dot` target and only that target. | Current source and tests |
+| FR2 | `success`, `warning`, and `error` are strong status fills: under `architecture:theme-tokens` INV11 each paints `--color-<status>` with `--color-on-<status>` ink and keeps a visible `CanvasText` border in forced-colors mode. `accent` paints `--color-accent` with `--color-on-accent` ink, and `neutral` paints `--color-icon-secondary` with the surface color as ink; these two are not INV11 status roles, and no current record sets their forced-colors treatment (OQ1). The target reflects `variant` for every value, and an extensible tone has a safe theme-independent baseline (`architecture:component-theming-surface` INV14). Implementation gap: a theme-added value the active theme does not paint receives no component plate or ink, leaving a transparent 8px box (Current-state impact). | Current source and tests |
+| FR3 | `isPulsing` animates the dot's opacity from 1 to 0.5 and back over 2 seconds, ease-in-out, indefinitely; under `prefers-reduced-motion: reduce` the animation is removed and the dot rests. | Current source and tests |
+| FR4 | A renderable `icon` renders in a wrapper centered inside the dot and filling its 8px field; it paints from `currentColor`, the variant's ink. A non-renderable value leaves the dot childless. | Current source and tests |
+| FR5 | A non-empty `tooltip` renders by placement; without one, no tooltip renders. A standalone dot is wrapped in Tooltip with that text and is a button trigger whose press pins it, named by `label`, so hover and keyboard focus preview the tooltip and a tap, click, Enter, or Space pins it (`component:Tooltip` FR9), and keyboard users reach it (WCAG 2.2 2.1.1). StatusDot adopts the pin through `useTooltip`'s `show()` and `hide()` (`component:Tooltip` FR12), as `component:InfoTip` does, so a standalone dot's tooltip stays reachable on touch. A dot inside an interactive element (a button, link, menu item, or option) is a non-interactive image wrapped in Tooltip without the pin, because a control cannot nest another control: its tooltip previews on hover only, and its tooltip text joins the host's accessible name, so the host carries the status for screen readers (`architecture:interaction-modality` INV4). A host named by `aria-label` takes no name from its content, so its caller includes the status in that label. Implementation gap: the dot has no tab stop and uses Tooltip's default touch trigger, so the tooltip opens on hover and touch only (Current-state impact). | Current source and tests; `component:Tooltip` DEC-1, FR9, FR12 |
+| FR6 | `ref` reaches the dot. Supported DOM, ARIA, data, and event props reach the dot after its role and name; `xstyle`, `className`, and `style` merge in that order after component styles. | Current source and tests |
### Allowed variation
diff --git a/docs/specs/components/Tooltip/Tooltip.spec.md b/docs/specs/components/Tooltip/Tooltip.spec.md
index a1c859cc6b..04d2747bb8 100644
--- a/docs/specs/components/Tooltip/Tooltip.spec.md
+++ b/docs/specs/components/Tooltip/Tooltip.spec.md
@@ -12,7 +12,7 @@ owners: [cixzhang]
review_triggers: [public-api, behavior, theming, accessibility]
verified_by:
[
- packages/core/src/Layer/usePressPin.test.tsx,
+ packages/core/src/InfoTip/InfoTip.pin.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,
@@ -40,25 +40,17 @@ 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 |
-| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Public contract | `Tooltip` with `content`, `children` or `anchorRef`, `placement` (`above`), `alignment` (`center`), `delay` (200), `hideDelay` (0), `focusTrigger` (`auto`), `touchTrigger` (`auto`), `isEnabled`, `isOpen`, `isDefaultOpen`, `onOpenChange`, and `hasHoverIndication`; target `tooltip`. `useTooltip` takes the same `touchTrigger`, and its return includes imperative `show` and `hide` (FR12). The press-to-pin path (FR9, FR10) is internal to Core and has no public prop; `component:InfoTip` is its only caller. |
-| Behavior | A `role="tooltip"` layer that describes its trigger. It opens on hover after `delay`, on keyboard focus, and on a tap that `touchTrigger` allows; 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 `touchTrigger="none"`, no touch or pen tap opens it. On the internal press-to-pin path, 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. `useTooltip`'s `show()` holds it open the same way until `hide()`, Escape, a press outside, or focus leaving (FR12). |
-| 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. Under the default `touchTrigger="auto"`, a tap on a trigger that performs an action performs only that action. On the press-to-pin path, people on touch, keyboard, or a screen reader can keep help open to read it, and hear it once when it pins. |
-| Builder impact | `touchTrigger` answers one question: is it safe to consume a tap to show this tooltip (DEC-1)? Keep the default `auto` on a trigger that performs an action, pass `tap` where a tap only reveals the tooltip, and pass `none` where a tap must never show it. Help behind an info icon uses `component:InfoTip`; an app's own toggle-style trigger is a button that calls `useTooltip`'s `show()` and `hide()` (DEC-1). |
-| Compatibility/readiness | `useTooltip` adds `show` and `hide` (FR12), an additive change. `touchTrigger` keeps its released values and its default `auto`, and the press-to-pin path adds no public prop. Nine 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 tap under `touchTrigger="auto"` that both performs the trigger's action and shows the tooltip, a pinned tooltip that closes on pointer leave or lets Escape pass to the layer beneath, a pinning trigger without `aria-expanded`, or a non-button pinning trigger without the development warning. |
-| Governing rules | WCAG 1.4.13, 2.1.1; `family:overlay-dismissal`; `spec:AST-003` FR4; `spec:AST-017` (lifecycle); `architecture:public-component-api` INV9, INV21; `architecture:layer-runtime`; `architecture:interaction-modality`; `architecture:component-theming-surface`. |
+| Area | Contract |
+| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | `Tooltip` with `content`, `children` or `anchorRef`, `placement` (`above`), `alignment` (`center`), `delay` (200), `hideDelay` (0), `focusTrigger` (`auto`), `touchTrigger` (`auto`), `isEnabled`, `isOpen`, `isDefaultOpen`, `onOpenChange`, and `hasHoverIndication`; target `tooltip`. `useTooltip` takes the same `touchTrigger`, and its return includes imperative `show` and `hide` (FR12). A tooltip pins through `show()` and `hide()` (FR9, FR10); Tooltip has no toggle prop or option, and `component:InfoTip` pins this way. |
+| Behavior | A `role="tooltip"` layer that describes its trigger. It opens on hover after `delay`, on keyboard focus, and on a tap that `touchTrigger` allows; 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 `touchTrigger="none"`, no touch or pen tap opens it. `useTooltip`'s `show()` pins it open until `hide()`, Escape, a press outside, or focus leaving, while hover and focus still preview an unpinned tooltip (FR9, FR12). `component:InfoTip`'s button pins and closes it on a click, tap, Enter, or Space. |
+| 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. Under the default `touchTrigger="auto"`, a tap on a trigger that performs an action performs only that action. When a button pins it through `show()`, as `component:InfoTip`'s does, people on touch, keyboard, or a screen reader can keep help open to read it, and hear it once when it pins. |
+| Builder impact | `touchTrigger` answers one question: is it safe to consume a tap to show this tooltip (DEC-1)? Keep the default `auto` on a trigger that performs an action, pass `tap` where a tap only reveals the tooltip, and pass `none` where a tap must never show it. Help behind an info icon uses `component:InfoTip`; an app's own toggle-style trigger is a button that calls `useTooltip`'s `show()` and `hide()` (DEC-1). |
+| Compatibility/readiness | `useTooltip` adds `show` and `hide` (FR12), an additive change. `touchTrigger` keeps its released values and its default `auto`, and pinning adds no public prop. Nine 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 tap under `touchTrigger="auto"` that both performs the trigger's action and shows the tooltip, a pinned tooltip that closes on pointer leave or lets Escape pass to the layer beneath, a pinning trigger that is not a native button or lacks `aria-expanded`, or a toggle prop or option on Tooltip. |
+| Governing rules | WCAG 1.4.13, 2.1.1; `family:overlay-dismissal`; `spec:AST-003` FR4; `spec:AST-017` (lifecycle); `architecture:public-component-api` INV9, INV21; `architecture:layer-runtime`; `architecture:interaction-modality`; `architecture:component-theming-surface`. |
This table is a review projection; the body below is authoritative.
@@ -75,13 +67,14 @@ in `Tooltip.doc.mjs`.
and its default `auto`. A disabled control is not an action, so its reason
opens on a tap (FR5); that restoration ships on its own as a patch `[fix]`
- Compatibility class: additive: `useTooltip`'s return gains `show` and `hide`
- (FR12); no public prop, default, DOM, styling, or target change; the
- press-to-pin path (FR9, FR10) is internal and adds no public surface
+ (FR12); no public prop, default, DOM, styling, or target change; pinning
+ (FR9, FR10) runs through `show()` and `hide()` and adds no other public
+ surface
- Controlled/uncontrolled behavior: uncontrolled by default; `isOpen` forces the
state, and a controlled tooltip reports close requests through
- `onOpenChange(false)` without closing itself (FR7); on the press-to-pin path
- a press on a controlled tooltip reports the toggled value through
- `onOpenChange` and does not change the state itself (FR9)
+ `onOpenChange(false)` without closing itself (FR7); `show()` and `hide()` on
+ a controlled tooltip report the request through `onShow` and `onHide` and do
+ not change the state itself (FR12)
- Migration decision: none
### CLN-0028 — Remove the surface registry behind `hasInteractiveAncestor`
@@ -149,14 +142,16 @@ Consumer migration instructions belong in consumer docs and release notes.
- The rendered tooltip surface and content inside that surface (FR1).
- Trigger wiring and when the tooltip opens and closes for each input
- (FR2–FR8), including the internal press-to-pin path and the trigger state it sets
- (FR9, FR10).
+ (FR2–FR8), including a `show()` hold and the announcement when a tooltip pins
+ (FR9, FR10, FR12).
**Does not own / non-goals**
- The trigger element — supplied by the caller or referenced externally and
outside Tooltip's owned anatomy.
- An arrow element — the current implementation renders none.
+- A pinning button's `aria-expanded` and `aria-controls` — set by the caller's
+ button (FR10, FR12).
- Layer hosting and anchor positioning — owned by `architecture:layer-runtime`;
shared Escape ordering — owned by `family:overlay-dismissal`.
- The rest of the `useTooltip` hook's public contract — an uncontracted
@@ -165,27 +160,27 @@ Consumer migration instructions belong in consumer docs and release notes.
## Public concepts
-| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
-| ------------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | ------- | ------------------- | --------- | -------------------------------- |
-| Focus trigger | `auto`, `always`, `never` | Whether keyboard focus opens the tooltip: on focusable triggers, judged when focus arrives (FR4), always, or never. | Every trigger mode. | `auto` | `component:Tooltip` | Stable | TypeScript rejects other values. |
-| Touch trigger | `auto`, `tap`, `none` | Whether it is safe to consume a tap to show the tooltip (DEC-1): `auto` shows it on a tap unless the trigger itself performs an action, a disabled control excepted (FR5); `tap` shows it on every tap; `none` on no tap. | Touch and pen without hover; the press-to-pin path decides taps itself (FR9). | `auto` | `component:Tooltip` | Stable | TypeScript rejects other values. |
+| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
+| ------------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | ------- | ------------------- | --------- | -------------------------------- |
+| Focus trigger | `auto`, `always`, `never` | Whether keyboard focus opens the tooltip: on focusable triggers, judged when focus arrives (FR4), always, or never. | Every trigger mode. | `auto` | `component:Tooltip` | Stable | TypeScript rejects other values. |
+| Touch trigger | `auto`, `tap`, `none` | Whether it is safe to consume a tap to show the tooltip (DEC-1): `auto` shows it on a tap unless the trigger itself performs an action, a disabled control excepted (FR5); `tap` shows it on every tap; `none` on no tap. | Touch and pen without hover; on a button that pins through `show()`, its click decides taps (FR9). | `auto` | `component:Tooltip` | Stable | TypeScript rejects other values. |
## Behavioral and layout contract
-| ID | Invariant | Basis |
-| ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| FR1 | The rendered tooltip contains one owned surface, `role="tooltip"`, carrying the `tooltip` target, at most 300 px wide, with the supplied `content` inside; content has no separate target and there is no arrow. | Current source, docs, and tests |
-| FR2 | Trigger wiring: a single string or number child is wrapped in a focusable inline span; element `children` attach to their first element; `anchorRef` attaches to that element. The trigger's `aria-describedby` gains the tooltip id, merged with and later restored to any existing value. Implementation gap: the wiring runs only when the trigger's listeners attach, so a trigger element replaced after mount, or a trigger whose own `aria-describedby` changes, loses it until a re-render re-attaches them (Current-state impact). | Current source and tests |
-| FR3 | On a hover-capable pointer, entering the trigger opens after `delay` ms; leaving closes after `hideDelay` ms. With `hideDelay` 0 a short bridge lets the pointer move onto the surface without closing it, and the surface stays open while hovered. | WCAG 1.4.13; tests |
-| FR4 | Focus that matches `:focus-visible` opens the tooltip per `focusTrigger`: keyboard focus, programmatic focus that follows keyboard input (AR4), pointer focus on a text-entry trigger, which browsers mark focus-visible, and programmatic focus on a text-entry trigger unless a finger or pen pressed that trigger and the last input was a pointer press, and on any other trigger unless the last input was a pointer (after keyboard input, as in AR4, or before any input). Implementation gap: script focus after a pointer press that focused nothing opens it, because the hook reads `:focus-visible` alone (Current-state impact). Focus a tap leaves behind, and other pointer focus, does not. Focus leaving the trigger schedules the hide as a pointer leave does. Under `focusTrigger="auto"`, focus opens the tooltip on any focusable trigger, judged when focus arrives. | Current source and tests |
-| FR5 | On touch and pen, a completed tap opens the tooltip per `touchTrigger` when the finger lifts; a touch that becomes a scroll, or a press the browser does not count as a tap, does not open it. Under `auto`, a tap opens it unless the trigger itself performs an action; an `aria-disabled` control, or a label for a disabled control, is not an action, so a disabled control's reason opens on a tap, even inside a clickable row or card (DEC-1). Under `tap`, every tap opens it; under `none`, no tap does. A second tap on the trigger, a tap outside, or a scroll starting outside closes it. On the press-to-pin path, FR9 decides what a tap does. Whether `auto` also leaves the tooltip shut when the tap acts on a control around the trigger is open (OQ1). | Current source and tests |
-| FR6 | Escape closes a visible tooltip; Escape during text composition is ignored. Escape routing follows `family:overlay-dismissal`: a visible topmost tooltip in the page handles that Escape, so a layer underneath stays open for that press. Implementation gap: a tooltip rendered into another document, such as an iframe or a Picture-in-Picture window, with no layer beneath it is never closed by Escape (Current-state impact). `spec:AST-003` FR4, accepted and not yet implemented, makes an unpinned tooltip passive and gives a pinned one Escape first (Current-state impact). Outside the press-to-pin path and a `show()` hold (FR12), pressing an uncontrolled tooltip's trigger closes it; a press that focuses a text-entry trigger reopens it through FR4. | WCAG 1.4.13; tests |
-| FR7 | `isOpen` forces the tooltip shown or hidden, and `isOpen={true}` suppresses hover and focus hiding; a controlled tooltip answers Escape by calling `onOpenChange(false)` without hiding, and is not closed by pressing the trigger. `isDefaultOpen` opens it on mount, still dismissible. Implementation gap: with `isOpen={false}`, any focus FR4 opens on, keyboard focus or a click into a text-field trigger, still opens the tooltip and reports `onOpenChange(true)`, and Escape then only reports `onOpenChange(false)`, so it stays until focus or the pointer leaves the trigger or the tooltip, or the caller re-renders with a new `onOpenChange` (Current-state impact). `isEnabled={false}` disables triggers and drops a pending open. | Current source and tests |
-| FR8 | `onOpenChange` reports each show and hide. `hasHoverIndication` (`auto`: a single string or number child) adds a hover cue to the inline trigger. | Current source and tests |
-| FR9 | On the press-to-pin path, an internal Tooltip option with no public prop that `component:InfoTip` uses, a click, a completed tap, Enter, or Space on a trigger whose role is `button` (a `<button>` or `role="button"`) 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. | DEC-1; WCAG 1.4.13, 2.1.1 |
-| FR10 | While the press-to-pin path 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 |
-| FR12 | `useTooltip`'s return includes imperative `show(): void` and `hide(): void`. `show()` opens the tooltip and keeps it open until `hide()`, Escape, a press outside, or focus leaving its trigger, as a pinned tooltip does (FR6, FR9); `hide()` closes it. Both report through the hook's `onShow` and `onHide`, which the Tooltip component maps to `onOpenChange` (FR8). While `isEnabled` is false, `show()` does nothing. Under a controlled `isOpen`, they report the request through `onShow`/`onHide` and do not override `isOpen` (FR7). They are how an app builds a toggle-style trigger: the app's own button calls them, carries `aria-expanded` (true while shown) and `aria-controls` naming the surface, and keeps its own accessible name. | Owner decision, 2026-11-02: app control through `useTooltip`'s imperative show and hide, not a prop. |
+| ID | Invariant | Basis |
+| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
+| FR1 | The rendered tooltip contains one owned surface, `role="tooltip"`, carrying the `tooltip` target, at most 300 px wide, with the supplied `content` inside; content has no separate target and there is no arrow. | Current source, docs, and tests |
+| FR2 | Trigger wiring: a single string or number child is wrapped in a focusable inline span; element `children` attach to their first element; `anchorRef` attaches to that element. The trigger's `aria-describedby` gains the tooltip id, merged with and later restored to any existing value. Implementation gap: the wiring runs only when the trigger's listeners attach, so a trigger element replaced after mount, or a trigger whose own `aria-describedby` changes, loses it until a re-render re-attaches them (Current-state impact). | Current source and tests |
+| FR3 | On a hover-capable pointer, entering the trigger opens after `delay` ms; leaving closes after `hideDelay` ms. With `hideDelay` 0 a short bridge lets the pointer move onto the surface without closing it, and the surface stays open while hovered. | WCAG 1.4.13; tests |
+| FR4 | Focus that matches `:focus-visible` opens the tooltip per `focusTrigger`: keyboard focus, programmatic focus that follows keyboard input (AR4), pointer focus on a text-entry trigger, which browsers mark focus-visible, and programmatic focus on a text-entry trigger unless a finger or pen pressed that trigger and the last input was a pointer press, and on any other trigger unless the last input was a pointer (after keyboard input, as in AR4, or before any input). Implementation gap: script focus after a pointer press that focused nothing opens it, because the hook reads `:focus-visible` alone (Current-state impact). Focus a tap leaves behind, and other pointer focus, does not. Focus leaving the trigger schedules the hide as a pointer leave does. Under `focusTrigger="auto"`, focus opens the tooltip on any focusable trigger, judged when focus arrives. | Current source and tests |
+| FR5 | On touch and pen, a completed tap opens the tooltip per `touchTrigger` when the finger lifts; a touch that becomes a scroll, or a press the browser does not count as a tap, does not open it. Under `auto`, a tap opens it unless the trigger itself performs an action; an `aria-disabled` control, or a label for a disabled control, is not an action, so a disabled control's reason opens on a tap, even inside a clickable row or card (DEC-1). Under `tap`, every tap opens it; under `none`, no tap does. A second tap on the trigger, a tap outside, or a scroll starting outside closes it. On a button that pins through `show()`, the button's click decides what a tap does (FR9). Whether `auto` also leaves the tooltip shut when the tap acts on a control around the trigger is open (OQ1). | Current source and tests |
+| FR6 | Escape closes a visible tooltip; Escape during text composition is ignored. Escape routing follows `family:overlay-dismissal`: a visible topmost tooltip in the page handles that Escape, so a layer underneath stays open for that press. Implementation gap: a tooltip rendered into another document, such as an iframe or a Picture-in-Picture window, with no layer beneath it is never closed by Escape (Current-state impact). `spec:AST-003` FR4, accepted and not yet implemented, makes an unpinned tooltip passive and gives a pinned one Escape first (Current-state impact). Outside a `show()` hold (FR12), pressing an uncontrolled tooltip's trigger closes it; a press that focuses a text-entry trigger reopens it through FR4. | WCAG 1.4.13; tests |
+| FR7 | `isOpen` forces the tooltip shown or hidden, and `isOpen={true}` suppresses hover and focus hiding; a controlled tooltip answers Escape by calling `onOpenChange(false)` without hiding, and is not closed by pressing the trigger. `isDefaultOpen` opens it on mount, still dismissible. Implementation gap: with `isOpen={false}`, any focus FR4 opens on, keyboard focus or a click into a text-field trigger, still opens the tooltip and reports `onOpenChange(true)`, and Escape then only reports `onOpenChange(false)`, so it stays until focus or the pointer leaves the trigger or the tooltip, or the caller re-renders with a new `onOpenChange` (Current-state impact). `isEnabled={false}` disables triggers and drops a pending open. | Current source and tests |
+| FR8 | `onOpenChange` reports each show and hide. `hasHoverIndication` (`auto`: a single string or number child) adds a hover cue to the inline trigger. | Current source and tests |
+| FR9 | A tooltip held open by `useTooltip`'s `show()` (FR12) is pinned. Tooltip has no toggle prop or option: a caller pins the tooltip by having its own native button call `show()` and `hide()`, as `component:InfoTip` does, so a click, a completed tap, Enter, or Space on that button pins the tooltip and the same press on a pinned tooltip closes it. Hover and keyboard focus still preview an unpinned tooltip per FR3 and FR4. A pinned tooltip stays open when the pointer leaves the trigger and the surface, and Tooltip's own press-to-close on the trigger leaves it open (FR6); Escape (FR6), `hide()`, such as the button's second press, a press outside the trigger and the surface, or focus moving outside them closes it. One internal owner per `useTooltip` call runs the `show()` hold and the touch trigger (FR5). | DEC-1; WCAG 1.4.13, 2.1.1 |
+| FR10 | A button that pins the tooltip through `show()` and `hide()` carries, as its own attributes, FR2's `aria-describedby`, `aria-expanded` (`true` only while pinned), and `aria-controls` naming the surface while it shows (FR12); Tooltip writes no `aria-expanded` or `aria-controls` itself. When the tooltip pins, its text is announced once through a polite live region; a preview announces nothing beyond the description. | DEC-1; WAI-ARIA 1.2 `aria-expanded` |
+| FR11 | A press inside an open Tooltip surface acts only within that surface: it never activates the trigger, a clickable container around it, or the control a label names. A tooltip that renders inside a FileInput dropzone, a ClickableCard, an Item row, or a `<label>` keeps a click on its text from opening the file picker, activating the container, or toggling or focusing the labelled control. The press still reaches page-level listeners, so a menu or Typeahead inside the surface keeps working. `architecture:layer-runtime` INV17 states this stop for every layer root. | `component:InfoTip` FR2 (a pinning press stops at its button); `component:Tooltip` DEC-1 (one tap does one thing); `architecture:layer-runtime` INV17 |
+| FR12 | `useTooltip`'s return includes imperative `show(): void` and `hide(): void`. `show()` opens the tooltip and keeps it open until `hide()`, Escape, a press outside, or focus leaving its trigger, as a pinned tooltip does (FR6, FR9). A `show()` hold that begins during a press on the trigger ends when that press ends off the trigger without a click; the hover rules then decide whether the tooltip stays. `hide()` closes it. Both report through the hook's `onShow` and `onHide`, which the Tooltip component maps to `onOpenChange` (FR8). While `isEnabled` is false, `show()` does nothing. Under a controlled `isOpen`, they report the request through `onShow`/`onHide` and do not override `isOpen` (FR7). They are how an app builds a toggle-style trigger: the app's own button calls them, carries `aria-expanded` (true while shown) and `aria-controls` naming the surface, and keeps its own accessible name. | Owner decision, 2026-11-02: app control through `useTooltip`'s imperative show and hide, not a prop. |
### Allowed variation
@@ -224,11 +219,12 @@ Consumer migration instructions belong in consumer docs and release notes.
held-closed Escape gap as the exceptions to Escape dismissal. Hiding when focus leaves, showing on hover,
and hiding on leave go beyond the required parts `spec:AST-020` FR15 adopts
and are this record's named exception, kept because they ship.
-- **AR6 — A pinned tooltip is a toggletip.** On the press-to-pin path the
- trigger is a named button that reports `aria-expanded` and `aria-controls`
- (FR10); 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).
+- **AR6 — A pinned tooltip is a toggletip.** When a button pins the tooltip
+ through `show()` and `hide()`, the trigger is a named native button that
+ reports `aria-expanded` and `aria-controls` (FR10); 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).
## Design relationships
@@ -261,17 +257,17 @@ has no arrow element.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
-| FR1 | `Tooltip.test.tsx` role/content suite | Rendered surface and supplied content | Removing the surface or content fails existing tooltip role and text assertions. | `audit:Tooltip/anatomy` |
-| FR2–FR8 | `Tooltip.test.tsx`; `useTooltip.test.tsx` | Hover, focus, tap, Escape, controlled, default open; `auto` judged when focus arrives (roving member, `<summary>`, non-focusable wrapper) | Wrong open or close for an input fails. | `audit:Tooltip/behavior` |
-| AR1–AR4 | `Tooltip.a11y.test.tsx`; `Tooltip.a11y.chromium.spec.ts`; `TooltipHoverBridge.a11y.chromium.spec.ts`; `TooltipFocusReturn.a11y.chromium.spec.ts` | Real-browser hover bridge and focus return | A tooltip that vanishes on the way to it or strands focus fails. | `audit:Tooltip/accessibility` |
-| AR5 | `Tooltip.a11y.test.tsx`; `Tooltip.a11y.chromium.spec.ts` | Wrapped, text, anchor, and hook triggers | A lost role, description, keyboard-focus show, or Escape dismissal fails; focus-leave hide, hover show, and leave hide run as advisory rows (Current-state impact). | `audit:Tooltip/accessibility` |
-| FR5 | `Tooltip.test.tsx` touch suite; `TouchTrigger.a11y.chromium.spec.ts` finger and pen cases; `useTouchTrigger.test.ts` and `touchTriggerTargets.test.tsx` disabled-control cases | Tap open, scroll, second tap, tap outside; `touchTrigger` `auto`, `tap`, and `none`; an action trigger and a trigger that performs no action; a trigger in running text; a disabled control inside a clickable row | A tap that fails to open or close as stated, opens the tooltip on a trigger that performs an action under `auto` or on any tap under `none`, or leaves a disabled control's reason shut fails. | `audit:Tooltip/behavior` |
-| FR9, FR10, AR6 | `usePressPin.test.tsx` Tooltip suites; `TouchTrigger.a11y.chromium.spec.ts` press-to-pin and mouse cases; `layerDismissalFamilies.test.tsx` pinned Tooltip over a Dialog | 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 pinning 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, or a pinning press that also activates the card, row, or labelled control around a child trigger, 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. | — |
-| FR12 | `useTooltip.showHide.test.tsx`; `Tooltip.stories.tsx` `CustomToggleTrigger` | An app button calls `show()` and `hide()`; Escape, a press outside, and focus leaving close a shown tooltip; a controlled `isOpen`; `show()` while `isEnabled` is false | A tooltip that `show()` does not open or hold, `hide()` does not close, a close path that leaves it open, a missing `onShow` or `onHide`, a `show()` that overrides a controlled `isOpen`, or a disabled tooltip that `show()` opens fails | — |
-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target | Missing, extra, prefixed, or stale mappings fail repository validation. | `audit:Tooltip/theming` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
+| FR1 | `Tooltip.test.tsx` role/content suite | Rendered surface and supplied content | Removing the surface or content fails existing tooltip role and text assertions. | `audit:Tooltip/anatomy` |
+| FR2–FR8 | `Tooltip.test.tsx`; `useTooltip.test.tsx` | Hover, focus, tap, Escape, controlled, default open; `auto` judged when focus arrives (roving member, `<summary>`, non-focusable wrapper) | Wrong open or close for an input fails. | `audit:Tooltip/behavior` |
+| AR1–AR4 | `Tooltip.a11y.test.tsx`; `Tooltip.a11y.chromium.spec.ts`; `TooltipHoverBridge.a11y.chromium.spec.ts`; `TooltipFocusReturn.a11y.chromium.spec.ts` | Real-browser hover bridge and focus return | A tooltip that vanishes on the way to it or strands focus fails. | `audit:Tooltip/accessibility` |
+| AR5 | `Tooltip.a11y.test.tsx`; `Tooltip.a11y.chromium.spec.ts` | Wrapped, text, anchor, and hook triggers | A lost role, description, keyboard-focus show, or Escape dismissal fails; focus-leave hide, hover show, and leave hide run as advisory rows (Current-state impact). | `audit:Tooltip/accessibility` |
+| FR5 | `Tooltip.test.tsx` touch suite; `TouchTrigger.a11y.chromium.spec.ts` finger and pen cases; `useTouchTrigger.test.ts` and `touchTriggerTargets.test.tsx` disabled-control cases | Tap open, scroll, second tap, tap outside; `touchTrigger` `auto`, `tap`, and `none`; an action trigger and a trigger that performs no action; a trigger in running text; a disabled control inside a clickable row | A tap that fails to open or close as stated, opens the tooltip on a trigger that performs an action under `auto` or on any tap under `none`, or leaves a disabled control's reason shut fails. | `audit:Tooltip/behavior` |
+| FR9, FR10, AR6 | `InfoTip.pin.test.tsx`; `TouchTrigger.a11y.chromium.spec.ts` InfoTip pin and mouse cases; `layerDismissalFamilies.test.tsx` pinned Tooltip over a Dialog | Click, Enter, Space, and tap pin; second press, press outside, focus leaving, and Escape close; pointer leave keeps the pin; a mouse or pen press on a hover preview; a pinning button 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 hover preview that closes and reopens on a mouse or pen press, a missing or stale `aria-expanded` or `aria-controls`, a second announcement, or a pinning press that also activates the card, row, or labelled control around the button, 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. | — |
+| FR12 | `useTooltip.showHide.test.tsx`; `InfoTip.pin.test.tsx` press-on-a-preview cases; `Tooltip.stories.tsx` `CustomToggleTrigger` | An app button calls `show()` and `hide()`; Escape, a press outside, and focus leaving close a shown tooltip; a controlled `isOpen`; `show()` while `isEnabled` is false; a `show()` hold begun during a trigger press that ends on the help or away from both | A tooltip that `show()` does not open or hold, `hide()` does not close, a close path that leaves it open, a missing `onShow` or `onHide`, a `show()` that overrides a controlled `isOpen`, a disabled tooltip that `show()` opens, or a hold begun during a trigger press that outlives a press ending off the trigger fails | — |
+| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target | Missing, extra, prefixed, or stale mappings fail repository validation. | `audit:Tooltip/theming` |
Read from source, with no focused test yet:
@@ -294,7 +290,7 @@ Read from source, with no focused test yet:
### DEC-1 — `touchTrigger` decides whether a tap may show the tooltip
**Reference:** `component:Tooltip/DEC-1`
-**Decider:** `cixzhang`, `2026-10-31`; amended `2026-11-01` and `2026-11-02`
+**Decider:** `cixzhang`, `2026-10-31`; amended `2026-11-01`, `2026-11-02`, and `2026-11-03`
`touchTrigger` answers one question: is it safe to consume a tap to show this
content? A tap that shows a tooltip must not come before the tap that performs
@@ -305,13 +301,14 @@ the tooltip on a tap only when the trigger performs no action of its own;
so its reason opens on a tap. An element that acts only through a role-less
`onClick` is a caller fix: it needs a role.
-A press-to-pin toggle answers a different question, so it does not replace
+A toggle answers a different question, so it does not replace
`touchTrigger`. A toggle needs a button under the trigger that the caller did
not add, it adds interactions that are not clearly connected to the trigger,
and it does not solve the touch case. Tooltip has no public toggle prop. An
app builds a toggle-style trigger by having its own button call `useTooltip`'s
-imperative `show()` and `hide()` (FR12). `component:InfoTip` keeps its current behavior for now: it pins
-through Tooltip's internal press-to-pin path (FR9, FR10).
+imperative `show()` and `hide()` (FR12). `component:InfoTip` is such a
+button: it keeps its behavior and pins through `show()` and `hide()` (FR9,
+FR10).
`component:HoverCard` DEC-1 applies the same rules.
Rejected: a separate toggletip component, which would repeat Tooltip's and
diff --git a/packages/core/src/Layer/usePressPin.test.tsx b/packages/core/src/InfoTip/InfoTip.pin.test.tsx
similarity index 58%
rename from packages/core/src/Layer/usePressPin.test.tsx
rename to packages/core/src/InfoTip/InfoTip.pin.test.tsx
index a0c471b767..ff15b298c1 100644
--- a/packages/core/src/Layer/usePressPin.test.tsx
+++ b/packages/core/src/InfoTip/InfoTip.pin.test.tsx
@@ -1,15 +1,17 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file usePressPin.test.tsx
- * @input Uses vitest, @testing-library/react, Tooltip, usePressPin
- * @output Tests of Tooltip's press-to-pin path: 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
+ * @file InfoTip.pin.test.tsx
+ * @input Uses vitest, @testing-library/react, InfoTip, Tooltip, HoverCard
+ * @output Tests of InfoTip's press-to-pin on useTooltip's show() and hide():
+ * a press pins and closes the help, and a pin stays when the pointer
+ * leaves. Escape, a second press, a press outside, or focus leaving closes
+ * it. The button carries the toggle state, a press on a hover preview keeps
+ * it shown, and the press stops at the button. Plus the touch trigger's
+ * outside close for a trigger in another document.
+ * @position Unit tests beside InfoTip.tsx and useTooltip.tsx
*
- * SYNC: When usePressPin.ts or useTooltip.tsx change, update these cases.
+ * SYNC: When InfoTip.tsx or useTooltip.tsx change, update these cases.
*/
import {
@@ -23,20 +25,13 @@ import {
afterEach,
} from 'vitest';
import {render, screen, fireEvent, act} from '@testing-library/react';
-import {
- useRef,
- useState,
- type KeyboardEvent as ReactKeyboardEvent,
- type ReactElement,
- type ReactNode,
-} from 'react';
-import {Tooltip, TooltipWithTriggerBehavior} from '../Tooltip/Tooltip';
+import type {ReactElement} from 'react';
+import {InfoTip} from './InfoTip';
+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';
-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';
@@ -128,31 +123,42 @@ function click(element: HTMLElement) {
fireEvent.click(element, {detail: 1});
}
-function InfoTooltip({
- children,
- ...props
-}: {
- children?: ReactNode;
- isOpen?: boolean;
- onOpenChange?: (isOpen: boolean) => void;
-}): ReactElement {
- return (
- <TooltipWithTriggerBehavior
- content="Billed on the first of each month"
- triggerBehavior="toggle"
- {...props}>
- {children ?? (
- <button type="button" aria-label="About billing">
- i
- </button>
- )}
- </TooltipWithTriggerBehavior>
- );
+const TIP = 'Billed on the first of each month';
+
+function InfoTooltip(): ReactElement {
+ return <InfoTip content={TIP} label="About billing" />;
}
-const TIP = 'Billed on the first of each month';
+describe('InfoTip press-to-pin (component:InfoTip FR2)', () => {
+ it('renders its button with no wrapper; the rest is the layer’s own nodes', () => {
+ const {container} = render(<InfoTooltip />);
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ const [first, ...rest] = Array.from(container.children);
+ expect(first).toBe(trigger);
+ // The layer renders its surface and a placeholder template, and nothing
+ // wraps the button.
+ expect(
+ rest.map(node =>
+ node.hasAttribute('popover') ? 'layer' : node.tagName.toLowerCase(),
+ ),
+ ).toEqual(['template', 'layer']);
+ });
+
+ it('a pen tap pins it, and the next pen tap closes it', () => {
+ render(<InfoTooltip />);
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ const penTap = () => {
+ fireEvent.pointerDown(trigger, {pointerType: 'pen'});
+ fireEvent.pointerUp(trigger, {pointerType: 'pen'});
+ fireEvent.click(trigger, {detail: 1});
+ };
+ penTap();
+ expect(shows(TIP)).toBe(true);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ penTap();
+ expect(shows(TIP)).toBe(false);
+ });
-describe('Tooltip press-to-pin (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'});
@@ -183,71 +189,131 @@ describe('Tooltip press-to-pin (component:Tooltip FR9)', () => {
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>,
- );
+ it('a keyboard press (Enter or Space: a click with no pointer) pins and closes it', () => {
+ render(<InfoTooltip />);
const trigger = screen.getByRole('button', {name: 'About billing'});
- fireEvent.keyDown(trigger, {key: 'Enter'});
+ fireEvent.click(trigger, {detail: 0});
expect(shows(TIP)).toBe(true);
- fireEvent.keyDown(trigger, {key: ' '});
- fireEvent.keyUp(trigger, {key: ' '});
+ fireEvent.click(trigger, {detail: 0});
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>,
- );
+ it('a mouse press on a hover preview pins it without hiding it first', () => {
+ vi.useFakeTimers();
+ render(<InfoTooltip />);
const trigger = screen.getByRole('button', {name: 'About billing'});
- // The keydown scrolls nothing and pins nothing yet.
- expect(fireEvent.keyDown(trigger, {key: ' '})).toBe(false);
+ fireEvent.pointerEnter(trigger, {pointerType: 'mouse'});
+ fireEvent.mouseEnter(trigger);
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ expect(shows(TIP)).toBe(true);
+ vi.mocked(HTMLElement.prototype.hidePopover).mockClear();
+ fireEvent.pointerDown(trigger, {pointerType: 'mouse'});
+ expect(shows(TIP)).toBe(true);
+ // The press keeps it in view; only its click pins it.
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ fireEvent.pointerUp(trigger, {pointerType: 'mouse'});
+ fireEvent.click(trigger, {detail: 1});
+ expect(shows(TIP)).toBe(true);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ expect(HTMLElement.prototype.hidePopover).not.toHaveBeenCalled();
+ click(trigger);
expect(shows(TIP)).toBe(false);
- fireEvent.keyUp(trigger, {key: ' '});
+ });
+
+ it('after a press on a preview that ends off the button, Enter and Space still pin and close it', () => {
+ vi.useFakeTimers();
+ render(<InfoTooltip />);
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ fireEvent.pointerEnter(trigger, {pointerType: 'mouse'});
+ fireEvent.mouseEnter(trigger);
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ // The press lifts outside the button, so no click follows.
+ fireEvent.pointerDown(trigger, {pointerType: 'mouse', button: 0});
+ fireEvent.pointerUp(document.body, {pointerType: 'mouse', button: 0});
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ fireEvent.click(trigger, {detail: 0});
expect(shows(TIP)).toBe(true);
- // A keyup with no keydown on the trigger presses nothing.
- fireEvent.keyUp(trigger, {key: ' '});
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ fireEvent.click(trigger, {detail: 0});
+ expect(shows(TIP)).toBe(false);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('a press on a preview released on the help ends its hold; hover then decides, and the next press pins it', () => {
+ vi.useFakeTimers();
+ render(<InfoTooltip />);
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ fireEvent.pointerEnter(trigger, {pointerType: 'mouse'});
+ fireEvent.mouseEnter(trigger);
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ const help = layerOf(TIP) as HTMLElement;
+ fireEvent.pointerDown(trigger, {pointerType: 'mouse', button: 0});
+ fireEvent.mouseLeave(trigger);
+ fireEvent.mouseEnter(help);
+ fireEvent.pointerUp(help, {pointerType: 'mouse', button: 0});
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ // The pointer rests on the help: it stays, unpinned.
+ expect(shows(TIP)).toBe(true);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ fireEvent.mouseLeave(help);
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ expect(shows(TIP)).toBe(false);
+ click(trigger);
expect(shows(TIP)).toBe(true);
+ expect(trigger).toHaveAttribute('aria-expanded', '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));
+ it('a press on a preview released away from the button and the help ends its hold and closes it', () => {
+ vi.useFakeTimers();
+ render(<InfoTooltip />);
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ fireEvent.pointerEnter(trigger, {pointerType: 'mouse'});
+ fireEvent.mouseEnter(trigger);
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ fireEvent.pointerDown(trigger, {pointerType: 'mouse', button: 0});
+ fireEvent.mouseLeave(trigger);
+ fireEvent.pointerUp(document.body, {pointerType: 'mouse', button: 0});
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ expect(shows(TIP)).toBe(false);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('a right or middle press on a preview does not hold it', () => {
+ vi.useFakeTimers();
+ render(<InfoTooltip />);
+ const trigger = screen.getByRole('button', {name: 'About billing'});
+ for (const button of [2, 1]) {
+ fireEvent.pointerEnter(trigger, {pointerType: 'mouse'});
+ fireEvent.mouseEnter(trigger);
+ act(() => {
+ vi.advanceTimersByTime(500);
});
- fireEvent.keyUp(trigger, {key: ' '});
expect(shows(TIP)).toBe(true);
- expect(trigger).toHaveAttribute('aria-expanded', 'true');
- },
- );
+ fireEvent.pointerDown(trigger, {pointerType: 'mouse', button});
+ fireEvent.pointerUp(trigger, {pointerType: 'mouse', button});
+ fireEvent.pointerLeave(trigger, {pointerType: 'mouse'});
+ fireEvent.mouseLeave(trigger);
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ expect(shows(TIP)).toBe(false);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ }
+ });
it('Escape closes a pinned tooltip', () => {
render(<InfoTooltip />);
@@ -327,157 +393,9 @@ describe('Tooltip press-to-pin (component:Tooltip FR9)', () => {
expect(shows(TIP)).toBe(true);
expect(trigger).toHaveAttribute('aria-expanded', 'true');
});
-
- it('a trigger behavior that turns to toggle after mount wires the trigger', () => {
- const {rerender} = render(
- <TooltipWithTriggerBehavior content={TIP}>
- <button type="button" aria-label="About billing">
- i
- </button>
- </TooltipWithTriggerBehavior>,
- );
- const trigger = screen.getByRole('button', {name: 'About billing'});
- expect(trigger).not.toHaveAttribute('aria-expanded');
- rerender(
- <TooltipWithTriggerBehavior content={TIP} triggerBehavior="toggle">
- <button type="button" aria-label="About billing">
- i
- </button>
- </TooltipWithTriggerBehavior>,
- );
- 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(
- <>
- <TooltipWithTriggerBehavior
- content={TIP}
- triggerBehavior="toggle"
- focusTrigger="never">
- <button type="button" aria-label="About billing">
- i
- </button>
- </TooltipWithTriggerBehavior>
- <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 trigger behavior turns to adaptive closes on leave again', () => {
- vi.useFakeTimers();
- const tip = (triggerBehavior?: 'toggle') => (
- <TooltipWithTriggerBehavior
- content={TIP}
- triggerBehavior={triggerBehavior}>
- <button type="button" aria-label="About billing">
- i
- </button>
- </TooltipWithTriggerBehavior>
- );
- 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('A press-to-pin tooltip'),
- );
- 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) => (
- <TooltipWithTriggerBehavior
- content={TIP}
- triggerBehavior="toggle"
- delay={delay}>
- <span tabIndex={0}>Billing</span>
- </TooltipWithTriggerBehavior>
- );
- const {rerender} = render(tip(200));
- rerender(tip(300));
- rerender(tip(400));
- const calls = warn.mock.calls.filter(([message]) =>
- String(message).includes('A press-to-pin tooltip'),
- );
- expect(calls).toHaveLength(1);
- } finally {
- warn.mockRestore();
- }
- });
});
-describe('Tooltip without press-to-pin (component:Tooltip FR5)', () => {
- it('a tap on an info-only trigger opens it, and no press pins it', () => {
- render(
- <Tooltip content={TIP}>
- <span tabIndex={0}>Billing</span>
- </Tooltip>,
- );
- const trigger = screen.getByText('Billing');
- tap(trigger);
- expect(shows(TIP)).toBe(true);
- expect(trigger).not.toHaveAttribute('aria-expanded');
- });
-});
-
-describe('Tooltip press-to-pin trigger state (component:Tooltip FR10)', () => {
+describe('InfoTip trigger state (component:InfoTip FR2)', () => {
it('carries aria-expanded, true only while pinned, and aria-controls while it shows', () => {
render(<InfoTooltip />);
const trigger = screen.getByRole('button', {name: 'About billing'});
@@ -511,22 +429,6 @@ describe('Tooltip press-to-pin trigger state (component:Tooltip FR10)', () => {
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 />);
@@ -543,26 +445,20 @@ describe('Tooltip press-to-pin trigger state (component:Tooltip FR10)', () => {
});
});
-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', () => {
+describe('an InfoTip press stops at its button', () => {
+ it('a clickable row around the button does not activate', () => {
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>
+ <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);
@@ -599,133 +495,6 @@ describe('a toggle press stops at its trigger', () => {
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>
- <TooltipWithTriggerBehavior
- 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(
@@ -739,7 +508,7 @@ describe('a toggle press stops at its trigger', () => {
expect(onRow).not.toHaveBeenCalled();
});
- it('without the toggle, a tap still reaches the row (released behavior)', () => {
+ it('a plain Tooltip trigger still passes a tap to the row (released behavior)', () => {
const onRow = vi.fn();
render(
<div onClick={onRow}>
diff --git a/packages/core/src/InfoTip/InfoTip.test.tsx b/packages/core/src/InfoTip/InfoTip.test.tsx
index 708b057e40..1acd04767f 100644
--- a/packages/core/src/InfoTip/InfoTip.test.tsx
+++ b/packages/core/src/InfoTip/InfoTip.test.tsx
@@ -257,7 +257,7 @@ describe('InfoTip', () => {
expect(trigger.style.marginBlockStart).toBe('4px');
});
- describe('a press pins the help (FR2, Tooltip FR9 and FR10)', () => {
+ describe('a press pins the help (FR2)', () => {
it('reports the pin on the button: aria-expanded and aria-controls', async () => {
render(<InfoTip content="Helpful context" />);
const trigger = screen.getByRole('button', {name: 'More information'});
@@ -330,9 +330,8 @@ describe('InfoTip', () => {
const trigger = screen.getByRole('button');
const layer = screen.getByRole('tooltip', {hidden: true});
- // Revealing the help is the button's whole purpose, so a tap pins it
- // (Tooltip's press-to-pin path). Without that its content is unreachable on
- // a phone.
+ // Revealing the help is the button's whole purpose, so a tap pins it.
+ // Without that its content is unreachable on a phone.
tap(trigger);
await waitFor(() => {
diff --git a/packages/core/src/InfoTip/InfoTip.tsx b/packages/core/src/InfoTip/InfoTip.tsx
index 8b7343da11..c352280339 100644
--- a/packages/core/src/InfoTip/InfoTip.tsx
+++ b/packages/core/src/InfoTip/InfoTip.tsx
@@ -4,8 +4,8 @@
/**
* @file InfoTip.tsx
- * @input Uses React, StyleX, Tooltip, Icon, useComponentTranslator, the shared
- * touch hit area, color/spacing/radius/duration/ease tokens
+ * @input Uses React, StyleX, useTooltip, Icon, useComponentTranslator, the
+ * shared touch hit area, color/spacing/radius/duration/ease tokens
* @output Exports InfoTip component, InfoTipProps, InfoTipSize types
* @position Core implementation; consumed by index.ts, tested by
* InfoTip.test.tsx; `@astryxdesign/lab` re-exports it, deprecated
@@ -17,13 +17,21 @@
* - /packages/core/src/InfoTip/index.ts (exports if types change)
*/
-import {useCallback, type ReactNode, type Ref} from 'react';
+import {
+ useCallback,
+ useState,
+ type MouseEvent,
+ type PointerEvent,
+ type ReactNode,
+ type Ref,
+} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {BaseProps} from '../BaseProps';
import {useMergedRefs} from '../hooks/useMergedRefs';
import {Icon, type IconSize} from '../Icon/Icon';
-import {TooltipWithTriggerBehavior} from '../Tooltip/Tooltip';
+import {stopInReactTree} from '../Layer/layerClickBoundary';
+import {useTooltip} from '../Tooltip/useTooltip';
import {
registerEnglishFallback,
useComponentTranslator,
@@ -122,9 +130,9 @@ const styles = stylex.create({
* labels, values, and metrics for permission notes, metric definitions, and
* field help.
*
- * InfoTip is a press-to-pin Tooltip on a named button: Tooltip opens, pins,
- * announces, and closes the help. The info icon resolves from
- * the icon registry, so themes can replace it.
+ * InfoTip is a named button that toggles `useTooltip`'s `show()` and `hide()`:
+ * the hook previews, holds, announces, and closes the help. The info icon
+ * resolves from the icon registry, so themes can replace it.
*
* @example
* ```
@@ -151,22 +159,69 @@ export function InfoTip({
}
return watchHitArea(button, insets => writeHitInsets(button, insets));
}, []);
- const mergedRef = useMergedRefs(ref, watchButtonHitArea);
+ // Whether a press pinned the help. A hover or focus preview is not pinned.
+ const [isPinned, setIsPinned] = useState(false);
+ // Whether the help shows, pinned or previewed: the button names it in
+ // `aria-controls` only then.
+ const [isShown, setIsShown] = useState(false);
+ const handleShow = useCallback(() => setIsShown(true), []);
+ // Every close ends the pin: a second press, Escape, a press outside, or
+ // focus leaving.
+ const handleHide = useCallback(() => {
+ setIsShown(false);
+ setIsPinned(false);
+ }, []);
+ const tooltip = useTooltip({onShow: handleShow, onHide: handleHide});
+ const mergedRef = useMergedRefs(ref, watchButtonHitArea, tooltip.ref);
+
+ // A primary mouse or pen press on a preview calls show() first. The hook's
+ // press-to-close then leaves it open. The click pins it.
+ const handlePointerDownCapture = useCallback(
+ (event: PointerEvent<HTMLButtonElement>) => {
+ if (
+ event.button !== 0 ||
+ event.pointerType === 'touch' ||
+ isPinned ||
+ !isShown
+ ) {
+ return;
+ }
+ tooltip.show();
+ },
+ [isPinned, isShown, tooltip],
+ );
+
+ // A click, tap, Enter, or Space pins the help, and the next one closes it.
+ // The press stops at the button: a clickable row, card, or label around it
+ // does nothing, and document listeners still see it.
+ const handleClick = useCallback(
+ (event: MouseEvent<HTMLButtonElement>) => {
+ stopInReactTree(event);
+ event.preventDefault();
+ if (isPinned) {
+ tooltip.hide();
+ return;
+ }
+ tooltip.show();
+ setIsPinned(true);
+ },
+ [isPinned, tooltip],
+ );
- // No Escape handler of its own. Tooltip's entry in the shared dismissal
+ // No Escape handler of its own. The tooltip's entry in the shared dismissal
// stack takes Escape, so one press never closes both the help and an
// enclosing Dialog.
return (
- <TooltipWithTriggerBehavior
- content={content}
- // The tooltip is the button's only purpose. A click, a tap, Enter, or
- // Space pins it open, and the press stops at the button. So an InfoTip's
- // content is reachable on a phone and from the keyboard alike.
- triggerBehavior="toggle">
+ <>
<button
ref={mergedRef}
type="button"
aria-label={label ?? t('@astryx.infoTip.label')}
+ aria-describedby={tooltip.describedBy}
+ aria-expanded={isPinned}
+ aria-controls={isShown ? tooltip.describedBy : undefined}
+ onPointerDownCapture={handlePointerDownCapture}
+ onClick={handleClick}
{...mergeProps(
stylex.props(
focusOutlineStyles.focusVisible,
@@ -179,7 +234,8 @@ export function InfoTip({
)}>
<Icon icon="info" size={size} />
</button>
- </TooltipWithTriggerBehavior>
+ {tooltip.renderTooltip(content)}
+ </>
);
}
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 8ba6a72bf8..55ca3be93f 100644
--- a/packages/core/src/Layer/__tests__/TouchTrigger.a11y.chromium.spec.ts
+++ b/packages/core/src/Layer/__tests__/TouchTrigger.a11y.chromium.spec.ts
@@ -201,7 +201,7 @@ for (const {name, story, trigger, action, layer} of cases) {
});
}
-test.describe('Tooltip press-to-pin through InfoTip (component:Tooltip FR9, FR10)', () => {
+test.describe('InfoTip press-to-pin (component:InfoTip FR2)', () => {
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';
@@ -323,7 +323,7 @@ test.describe('Tooltip and InfoTip under a finger and a pen (component:Tooltip F
}
});
-test.describe('a pinned layer under a mouse (component:Tooltip FR9)', () => {
+test.describe('a pinned InfoTip under a mouse (component:InfoTip FR2)', () => {
test.use({
hasTouch: false,
isMobile: false,
diff --git a/packages/core/src/Layer/layerDismissalFamilies.test.tsx b/packages/core/src/Layer/layerDismissalFamilies.test.tsx
index 18bde17cbf..7f99ff274f 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 (also pinned through its press-to-pin path)
+ * MobileNav, HoverCard, Tooltip (also pinned through InfoTip's show() hold)
* @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
@@ -37,7 +37,8 @@ import {Dialog} from '../Dialog/Dialog';
import {HoverCard} from '../HoverCard/HoverCard';
import {Lightbox} from '../Lightbox/Lightbox';
import {MobileNav} from '../MobileNav/MobileNav';
-import {Tooltip, TooltipWithTriggerBehavior} from '../Tooltip/Tooltip';
+import {InfoTip} from '../InfoTip/InfoTip';
+import {Tooltip} from '../Tooltip/Tooltip';
import {resetLayerStackForTests} from './layerStack';
const originalMatches = HTMLElement.prototype.matches;
@@ -438,11 +439,7 @@ describe('overlay families on the shared dismissal stack', () => {
render(
<Dialog isOpen={true} onOpenChange={onDialogChange} aria-label="Host">
- <TooltipWithTriggerBehavior
- content="Pinned tip"
- triggerBehavior="toggle">
- <button type="button">Info</button>
- </TooltipWithTriggerBehavior>
+ <InfoTip content="Pinned tip" label="Info" />
</Dialog>,
);
fireEvent.click(screen.getByRole('button', {name: 'Info'}));
diff --git a/packages/core/src/Layer/usePressPin.calls.test.tsx b/packages/core/src/Layer/usePressPin.calls.test.tsx
deleted file mode 100644
index b32859a898..0000000000
--- a/packages/core/src/Layer/usePressPin.calls.test.tsx
+++ /dev/null
@@ -1,110 +0,0 @@
-// 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 {TooltipWithTriggerBehavior} = 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(
- <TooltipWithTriggerBehavior
- content="Billed on the first of each month"
- triggerBehavior="toggle">
- <button type="button">About billing</button>
- </TooltipWithTriggerBehavior>,
- );
- fireEvent.click(screen.getByRole('button', {name: 'About billing'}));
- expectOneCallPerRender();
- });
-});
diff --git a/packages/core/src/Layer/usePressPin.ts b/packages/core/src/Layer/usePressPin.ts
deleted file mode 100644
index 28e539d018..0000000000
--- a/packages/core/src/Layer/usePressPin.ts
+++ /dev/null
@@ -1,576 +0,0 @@
-// 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, and
- * the app hold behind useTooltip's show() and hide(); 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 `touchTrigger` decides taps. `toggle` pins it on every
- * press of a button trigger. Internal: InfoTip's press-to-pin uses `toggle`.
- */
-export type LayerTriggerBehavior = 'adaptive' | '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 and the app hold: Escape, or a hide from elsewhere. */
- unpin: () => void;
- /**
- * The app's `show()`: shows the layer and holds it open, as a pin does,
- * until `release`, Escape, a press outside, or focus leaving the trigger
- * and the layer. A controlled layer reports the request instead.
- */
- hold: () => void;
- /** The app's `hide()`: drops the hold and hides the layer. */
- release: () => void;
- /** Whether the app's `show()` holds the layer open now. */
- isAppHeld: () => boolean;
- /**
- * 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, or held by the app's
- * `show()`. 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);
- }, []);
-
- // The app's show() holds the layer on any trigger, in any mode.
- const isAppHeldRef = useRef(false);
- const [isAppHeldState, setIsAppHeldState] = useState(false);
- const setAppHeld = useCallback((next: boolean) => {
- isAppHeldRef.current = next;
- setIsAppHeldState(next);
- }, []);
-
- // The last offered element lets a `triggerBehavior` change rewire it.
- const triggerRef = useRef<HTMLElement | null>(null);
- // Every offered trigger, in any mode, so focus leaving ends a pin or an
- // app hold.
- const focusTargetRef = 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 (isAppHeldRef.current) {
- setAppHeld(false);
- if (current.isOpen !== undefined) {
- current.report(false);
- return;
- }
- }
- if (current.triggerBehavior === 'toggle' && triggerRef.current != null) {
- if (current.isOpen !== undefined) {
- current.report(false);
- return;
- }
- if (isPinnedRef.current) {
- setPinned(false);
- }
- }
- current.hide();
- }, [setPinned, setAppHeld]);
-
- const {
- isTouchPointerRef,
- isTouchInteraction,
- handlePointerEnter,
- handlePointerDown,
- clearTapOpen,
- armOutsideDismiss,
- } = useTouchTriggerInternal({
- touchTrigger: isToggleMode ? 'tap' : 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();
- setAppHeld(false);
- if (current.isOpen !== undefined) {
- current.report(false);
- return;
- }
- setPinned(false);
- current.hide();
- }, [setPinned, setAppHeld, 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]);
-
- // 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;
- 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 (
- 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.isComposing ||
- (event.key !== 'Enter' && event.key !== ' ')
- ) {
- return;
- }
- // The press replaces the key's own action, such as a page scroll on Space.
- event.preventDefault();
- if (event.repeat) {
- return;
- }
- if (event.key === ' ') {
- spaceHeldRef.current = true;
- return;
- }
- pressFromKey();
- },
- [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(() => {
- const current = optionsRef.current;
- if (isAppHeldRef.current && current.isLayerOpen) {
- return current.isOpen !== false;
- }
- 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) => {
- // A Space that comes up after focus left presses nothing.
- spaceHeldRef.current = false;
- if (!isHeldOpen()) {
- return false;
- }
- const next = event.relatedTarget;
- const trigger = focusTargetRef.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(() => {
- focusTargetRef.current?.removeEventListener('focusout', handleFocusLeave);
- focusTargetRef.current = null;
- const previous = triggerRef.current;
- if (previous == null) {
- return;
- }
- previous.removeEventListener('click', handlePress);
- previous.removeEventListener('keydown', handleKeyDown);
- previous.removeEventListener('keyup', handleKeyUp);
- 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, handleKeyUp, 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) {
- return;
- }
- // Its own focus-leave listener, in any mode: `focusTrigger="never"`
- // attaches none, and an app hold needs it on any trigger.
- element.addEventListener('focusout', handleFocusLeave);
- focusTargetRef.current = element;
- if (current.triggerBehavior !== 'toggle' || !isPressPinTrigger(element)) {
- return;
- }
- element.addEventListener('click', handlePress);
- if (element.tagName !== 'BUTTON') {
- element.addEventListener('keydown', handleKeyDown);
- element.addEventListener('keyup', handleKeyUp);
- }
- ownStateRef.current = {
- expanded: element.getAttribute('aria-expanded'),
- controls: element.getAttribute('aria-controls'),
- };
- triggerRef.current = element;
- },
- [unwire, handlePress, handleKeyDown, handleKeyUp, 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,
- 'A press-to-pin tooltip 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);
- }
- if (isAppHeldRef.current) {
- setAppHeld(false);
- }
- }, [setPinned, setAppHeld]);
-
- const hold = useCallback(() => {
- const current = optionsRef.current;
- if (!current.isEnabled) {
- return;
- }
- setAppHeld(true);
- armOutsideDismiss();
- announceName();
- if (current.isOpen !== undefined) {
- current.report(true);
- return;
- }
- current.show();
- }, [setAppHeld, armOutsideDismiss, announceName]);
-
- const release = useCallback(() => {
- close();
- }, [close]);
-
- const isAppHeld = useCallback(() => isAppHeldRef.current, []);
-
- // 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) ||
- (isAppHeldState && isLayerOpen && isOpen !== false);
-
- return {
- isToggleTrigger,
- isHeldOpen,
- attach,
- unpin,
- hold,
- release,
- isAppHeld,
- 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 85bade346b..14b6fb7089 100644
--- a/packages/core/src/Layer/useTouchTrigger.ts
+++ b/packages/core/src/Layer/useTouchTrigger.ts
@@ -8,7 +8,7 @@
* @output Exports useTouchTrigger hook, isActionTrigger, LayerTouchTrigger type,
* tapLandsOnDisabledControl, TOUCH_POINTER_TYPES and useTapStop (internal:
* not re-exported from index). Also useTouchTriggerInternal, with the
- * outside dismissal's arm for the press pin (Core-internal).
+ * outside dismissal's arm for useTooltip's hold (Core-internal).
* @position Layer hook; shared touch behavior for useTooltip and useHoverCard
*
* SYNC: When modified, update:
@@ -283,8 +283,8 @@ export interface UseTouchTriggerReturn {
}
/**
- * useTouchTrigger's return plus the outside dismissal's arm, for Core's own
- * press pin (usePressPin). Not exported from the Layer entry point.
+ * useTouchTrigger's return plus the outside dismissal's arm, for useTooltip's
+ * hold behind show() and hide(). Not exported from the Layer entry point.
*
* @internal
*/
@@ -292,7 +292,7 @@ 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.
+ * hold arms it too.
*/
armOutsideDismiss: () => void;
}
@@ -328,13 +328,19 @@ export function useTouchTrigger(
}
/**
- * useTouchTrigger, plus the outside dismissal's arm that a press pin uses to
- * close on a press or scroll outside.
+ * useTouchTrigger, plus the outside dismissal's arm that useTooltip's hold
+ * uses to close on a press or scroll outside.
*
* @internal
*/
export function useTouchTriggerInternal(
options: UseTouchTriggerOptions,
+ /**
+ * Called when a press that the outside dismissal watches ends with its
+ * pointer lifted inside the layer: the layer stays open, and useTooltip
+ * ends a hold that the press started.
+ */
+ onReleaseInLayer?: () => void,
): UseTouchTriggerInternalReturn {
const {
touchTrigger,
@@ -359,6 +365,8 @@ export function useTouchTriggerInternal(
hideRef.current = hide;
const layerIdRef = useRef(layerId);
layerIdRef.current = layerId;
+ const onReleaseInLayerRef = useRef(onReleaseInLayer);
+ onReleaseInLayerRef.current = onReleaseInLayer;
// Whether a tap is what opened the layer. Only a tap-open owes the user an
// outside-tap dismissal: a hover-opened layer already closes on
@@ -421,6 +429,9 @@ export function useTouchTriggerInternal(
doc.getElementById(layerIdRef.current)?.contains(target) === true,
)
) {
+ if (event.type === 'pointerup') {
+ onReleaseInLayerRef.current?.();
+ }
return;
}
}
diff --git a/packages/core/src/Tooltip/Tooltip.test.tsx b/packages/core/src/Tooltip/Tooltip.test.tsx
index f48c2b1109..7dc56dd6e1 100644
--- a/packages/core/src/Tooltip/Tooltip.test.tsx
+++ b/packages/core/src/Tooltip/Tooltip.test.tsx
@@ -25,8 +25,8 @@ import {
fireEvent,
waitFor,
} from '@testing-library/react';
-import {useRef, type ComponentProps} from 'react';
-import {Tooltip, TooltipWithTriggerBehavior} from './Tooltip';
+import {useRef} from 'react';
+import {Tooltip} from './Tooltip';
import {ClickableCard} from '../ClickableCard/ClickableCard';
import {Item} from '../Item/Item';
import {Token} from '../Token/Token';
@@ -979,33 +979,29 @@ describe('Tooltip surface press', () => {
});
});
-describe('Tooltip, and its press-to-pin path, on every input (component:Tooltip FR5, FR9)', () => {
+describe('Tooltip on every input (component:Tooltip FR5)', () => {
beforeEach(() => {
__resetInteractionModalityForTest();
});
- type Behavior = 'adaptive' | 'toggle';
-
- /** An info-only trigger: a span, or under the toggle the button it pins. */
+ /** An info-only trigger: a span, or a button. */
function setup(
- triggerBehavior?: Behavior,
touchTrigger?: 'auto' | 'tap' | 'none',
- trigger = triggerBehavior === 'toggle' ? 'button' : 'span',
+ trigger: 'span' | 'button' = 'span',
) {
const onOpenChange = vi.fn<(open: boolean) => void>();
render(
- <TooltipWithTriggerBehavior
+ <Tooltip
content="Billed monthly"
delay={0}
onOpenChange={onOpenChange}
- triggerBehavior={triggerBehavior}
touchTrigger={touchTrigger}>
{trigger === 'button' ? (
<button type="button">Billing</button>
) : (
<span tabIndex={0}>Billing</span>
)}
- </TooltipWithTriggerBehavior>,
+ </Tooltip>,
);
const opened = () => onOpenChange.mock.calls.some(([open]) => open);
return {trigger: screen.getByText('Billing'), opened};
@@ -1026,20 +1022,16 @@ describe('Tooltip, and its press-to-pin path, on every input (component:Tooltip
setTimeout(resolve, 50);
});
- describe.each([
- ['adaptive by default', undefined, true],
- ['adaptive', 'adaptive', true],
- ['toggle', 'toggle', true],
- ] as const)('%s', (_, behavior, tapOpens) => {
+ describe('on an info-only trigger', () => {
it('a mouse hover previews it', async () => {
- const {trigger, opened} = setup(behavior);
+ const {trigger, opened} = setup();
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 {trigger, opened} = setup();
const realMatches = trigger.matches.bind(trigger);
vi.spyOn(trigger, 'matches').mockImplementation((selector: string) =>
selector === ':focus-visible' ? true : realMatches(selector),
@@ -1050,19 +1042,19 @@ describe('Tooltip, and its press-to-pin path, on every input (component:Tooltip
});
it.each(['touch', 'pen'] as const)(
- `a %s tap ${tapOpens ? 'opens' : 'never opens'} it`,
+ 'a %s tap opens it',
async pointerType => {
- const {trigger, opened} = setup(behavior);
+ const {trigger, opened} = setup();
tap(trigger, pointerType);
await settle();
- expect(opened()).toBe(tapOpens);
+ expect(opened()).toBe(true);
},
);
it.each(['mouse click', 'touch tap'] as const)(
- `a %s on a button trigger ${behavior === 'toggle' ? 'pins it' : 'pins nothing'}`,
+ 'a %s on a button trigger pins nothing',
async press => {
- const {trigger} = setup(behavior, undefined, 'button');
+ const {trigger} = setup(undefined, 'button');
if (press === 'mouse click') {
fireEvent.pointerDown(trigger, {pointerType: 'mouse'});
fireEvent.pointerUp(trigger, {pointerType: 'mouse'});
@@ -1071,46 +1063,21 @@ describe('Tooltip, and its press-to-pin path, on every input (component:Tooltip
tap(trigger, 'touch');
}
await settle();
- expect(trigger.getAttribute('aria-expanded')).toBe(
- behavior === 'toggle' ? 'true' : null,
- );
+ expect(trigger).not.toHaveAttribute('aria-expanded');
},
);
});
it.each([
- ['adaptive', 'none', 'span', 'decides: no tap opens it', false],
- ['adaptive', 'tap', 'button', 'decides: every tap opens it', true],
- ['toggle', 'none', 'button', 'is ignored: a tap pins it', true],
+ ['none', 'span', 'no tap opens it', false],
+ ['tap', 'button', 'every tap opens it', true],
] as const)(
- 'beside triggerBehavior="%s", touchTrigger="%s" on a %s %s',
- async (behavior, touchTrigger, trigger, _, tapOpens) => {
- const tip = setup(behavior, touchTrigger, trigger);
+ 'touchTrigger="%s" on a %s decides: %s',
+ async (touchTrigger, trigger, _, tapOpens) => {
+ const tip = setup(touchTrigger, trigger);
tap(tip.trigger, 'touch');
await settle();
expect(tip.opened()).toBe(tapOpens);
- if (behavior === 'toggle') {
- expect(tip.trigger.getAttribute('aria-expanded')).toBe('true');
- }
},
);
});
-
-describe('Tooltip keeps press-to-pin internal', () => {
- it('a spread props object that carries triggerBehavior at runtime pins nothing', () => {
- const props = {
- content: 'Billed monthly',
- triggerBehavior: 'toggle',
- } as unknown as ComponentProps<typeof Tooltip>;
- render(
- <Tooltip {...props}>
- <button type="button">Billing</button>
- </Tooltip>,
- );
- const trigger = screen.getByRole('button', {name: 'Billing'});
- fireEvent.pointerDown(trigger, {pointerType: 'mouse'});
- fireEvent.pointerUp(trigger, {pointerType: 'mouse'});
- fireEvent.click(trigger, {detail: 1});
- expect(trigger).not.toHaveAttribute('aria-expanded');
- });
-});
diff --git a/packages/core/src/Tooltip/Tooltip.tsx b/packages/core/src/Tooltip/Tooltip.tsx
index ea59fc16a7..373286dc0a 100644
--- a/packages/core/src/Tooltip/Tooltip.tsx
+++ b/packages/core/src/Tooltip/Tooltip.tsx
@@ -5,8 +5,7 @@
/**
* @file Tooltip.tsx
* @input Uses React, useTooltip hook
- * @output Exports Tooltip component for hover/focus triggered tooltips, and the
- * module-only TooltipWithTriggerBehavior that InfoTip's press-to-pin uses
+ * @output Exports Tooltip component for hover/focus triggered tooltips
* @position Layer component; uses display:contents wrapper to avoid cloneElement
*
* SYNC: When modified, update these files to stay in sync:
@@ -24,14 +23,10 @@ import React, {
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import * as stylex from '@stylexjs/stylex';
import {
- useTooltipWithTriggerBehavior,
+ useTooltip,
type TooltipFocusTrigger,
type TooltipTouchTrigger,
} from './useTooltip';
-import {
- stopPressPinClick,
- type LayerTriggerBehavior,
-} from '../Layer/usePressPin';
import type {LayerAlignment, LayerPlacement} from '../Layer/useLayer';
import {colorVars} from '../theme/tokens.stylex';
@@ -194,32 +189,7 @@ function mergeIds(...ids: (string | undefined | null)[]): string | undefined {
* </Tooltip>
* ```
*/
-export function Tooltip(props: TooltipProps): ReactElement {
- // The option is fixed to `adaptive`, so a spread object that carries it at
- // runtime cannot reach the press-to-pin path.
- return <TooltipWithTriggerBehavior {...props} triggerBehavior="adaptive" />;
-}
-
-/**
- * Module-only props for `TooltipWithTriggerBehavior`. Not exported from the
- * package.
- */
-export interface TooltipWithTriggerBehaviorProps extends TooltipProps {
- /**
- * How the trigger opens the tooltip. `toggle` pins it on a click, a tap,
- * Enter, or Space on a button trigger, and stops that press at the trigger
- * (see `useTooltipWithTriggerBehavior`). InfoTip uses it.
- *
- * @default 'adaptive'
- */
- triggerBehavior?: LayerTriggerBehavior;
-}
-
-/**
- * `Tooltip` with a trigger behavior. Module-only: InfoTip's press-to-pin goes
- * through it, and the package does not export it.
- */
-export function TooltipWithTriggerBehavior({
+export function Tooltip({
children,
anchorRef,
content,
@@ -229,13 +199,12 @@ export function TooltipWithTriggerBehavior({
hideDelay = 0,
focusTrigger = 'auto',
touchTrigger = 'auto',
- triggerBehavior = 'adaptive',
isEnabled = true,
onOpenChange,
hasHoverIndication = 'auto',
isOpen,
isDefaultOpen,
-}: TooltipWithTriggerBehaviorProps): ReactElement {
+}: TooltipProps): ReactElement {
const wrapperRef = useRef<HTMLDivElement>(null);
const textOnly = children != null ? isTextOnly(children) : false;
@@ -252,14 +221,13 @@ export function TooltipWithTriggerBehavior({
}, [onOpenChange]);
// Use the hook for all tooltip behavior
- const tooltip = useTooltipWithTriggerBehavior({
+ const tooltip = useTooltip({
placement,
alignment,
delay,
hideDelay,
focusTrigger,
touchTrigger,
- triggerBehavior,
isEnabled,
isOpen,
isDefaultOpen,
@@ -373,7 +341,6 @@ export function TooltipWithTriggerBehavior({
ref={tooltip.ref}
tabIndex={0}
aria-describedby={tooltip.describedBy}
- onClick={stopPressPinClick}
{...stylex.props(
styles.wrapperInline,
showHoverIndication && styles.hoverIndication,
@@ -388,10 +355,7 @@ export function TooltipWithTriggerBehavior({
// For element children: use display:contents, ref on first child
return (
<>
- <div
- ref={wrapperRef}
- onClick={stopPressPinClick}
- {...stylex.props(styles.wrapperContents)}>
+ <div ref={wrapperRef} {...stylex.props(styles.wrapperContents)}>
{children}
</div>
{tooltip.renderTooltip(content)}
diff --git a/packages/core/src/Tooltip/useTooltip.showHide.test.tsx b/packages/core/src/Tooltip/useTooltip.showHide.test.tsx
index 0d8ffe73a0..3442212c85 100644
--- a/packages/core/src/Tooltip/useTooltip.showHide.test.tsx
+++ b/packages/core/src/Tooltip/useTooltip.showHide.test.tsx
@@ -7,10 +7,9 @@
* button opens and closes the tooltip, Escape, a press outside, and focus
* leaving still close it, it is announced once, and a controlled isOpen is
* not overridden
- * @position Testing; validates the app toggle path in useTooltip.tsx and
- * usePressPin.ts
+ * @position Testing; validates the app toggle path in useTooltip.tsx
*
- * SYNC: When useTooltip.tsx or usePressPin.ts changes, update these tests.
+ * SYNC: When useTooltip.tsx changes, update these tests.
*/
import {
@@ -126,6 +125,22 @@ function ToggleTip(
const trigger = () => screen.getByRole('button', {name: 'About billing'});
+/** A button that calls show() from an ordinary onPointerDown handler. */
+function PressShowTip(): ReactElement {
+ const tooltip = useTooltip({});
+ return (
+ <>
+ <button
+ type="button"
+ ref={tooltip.ref}
+ onPointerDown={() => tooltip.show()}>
+ About billing
+ </button>
+ {tooltip.renderTooltip(TIP)}
+ </>
+ );
+}
+
describe('useTooltip show() and hide() (component:Tooltip FR12)', () => {
it("an app's own button opens the tooltip with show() and closes it with hide()", () => {
const onShow = vi.fn();
@@ -226,6 +241,51 @@ describe('useTooltip show() and hide() (component:Tooltip FR12)', () => {
expect(shows()).toBe(false);
});
+ it('a show() during a press on the trigger ends with a press released on the tooltip; hover then decides', () => {
+ vi.useFakeTimers();
+ try {
+ render(<PressShowTip />);
+ fireEvent.pointerDown(trigger(), {pointerType: 'mouse', button: 0});
+ expect(shows()).toBe(true);
+ const layer = screen.getByRole('tooltip', {hidden: true});
+ fireEvent.mouseLeave(trigger());
+ fireEvent.mouseEnter(layer);
+ fireEvent.pointerUp(layer, {pointerType: 'mouse', button: 0});
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ expect(shows()).toBe(true);
+ fireEvent.mouseLeave(layer);
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ expect(shows()).toBe(false);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('a show() during a press that ends on the trigger keeps its hold through a later press released on the tooltip', () => {
+ vi.useFakeTimers();
+ try {
+ render(<PressShowTip />);
+ fireEvent.pointerDown(trigger(), {pointerType: 'mouse', button: 0});
+ fireEvent.pointerUp(trigger(), {pointerType: 'mouse', button: 0});
+ fireEvent.click(trigger(), {detail: 1});
+ const layer = screen.getByRole('tooltip', {hidden: true});
+ fireEvent.pointerDown(layer, {pointerType: 'mouse', button: 0});
+ fireEvent.pointerUp(layer, {pointerType: 'mouse', button: 0});
+ fireEvent.mouseLeave(trigger());
+ fireEvent.mouseLeave(layer);
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ expect(shows()).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('show() does nothing while isEnabled is false', () => {
const onShow = vi.fn();
render(<ToggleTip isEnabled={false} onShow={onShow} />);
diff --git a/packages/core/src/Tooltip/useTooltip.test.tsx b/packages/core/src/Tooltip/useTooltip.test.tsx
index 228afbc901..16d97f3384 100644
--- a/packages/core/src/Tooltip/useTooltip.test.tsx
+++ b/packages/core/src/Tooltip/useTooltip.test.tsx
@@ -3,8 +3,7 @@
/**
* @file useTooltip.test.tsx
* @input Uses vitest, @testing-library/react, useTooltip hook
- * @output Unit tests for the tooltip show/hide timers and controlled state,
- * and for a press on a caller's trigger through the press-to-pin path
+ * @output Unit tests for the tooltip show/hide timers and controlled state
* @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.
@@ -23,14 +22,8 @@ import {
afterEach,
} from 'vitest';
import {render, screen, fireEvent, act} from '@testing-library/react';
-import {
- useTooltip,
- useTooltipWithTriggerBehavior,
- type TooltipOptions,
-} from './useTooltip';
+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.
@@ -602,87 +595,3 @@ describe('useTooltip — focusTrigger="auto" decides when focus arrives', () =>
expect(onHide).not.toHaveBeenCalled();
});
});
-
-describe('useTooltip’s press-to-pin path with a caller’s trigger (component:Tooltip FR9)', () => {
- function Tip({
- onTriggerClick,
- }: {
- onTriggerClick?: (event: ReactMouseEvent) => void;
- }) {
- const tooltip = useTooltipWithTriggerBehavior({
- 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();
- });
-});
-
-describe('useTooltip keeps press-to-pin internal', () => {
- it('an options object that carries triggerBehavior at runtime pins nothing', () => {
- const options = {
- triggerBehavior: 'toggle',
- delay: 0,
- } as unknown as TooltipOptions;
- function Tip() {
- const tooltip = useTooltip(options);
- return (
- <>
- <button type="button" ref={tooltip.ref}>
- What is this?
- </button>
- {tooltip.renderTooltip('Billed monthly')}
- </>
- );
- }
- render(<Tip />);
- const trigger = screen.getByRole('button', {name: 'What is this?'});
- fireEvent.click(trigger, {detail: 1});
- expect(trigger).not.toHaveAttribute('aria-expanded');
- });
-});
diff --git a/packages/core/src/Tooltip/useTooltip.tsx b/packages/core/src/Tooltip/useTooltip.tsx
index 002bf897da..1443dda361 100644
--- a/packages/core/src/Tooltip/useTooltip.tsx
+++ b/packages/core/src/Tooltip/useTooltip.tsx
@@ -4,10 +4,9 @@
/**
* @file useTooltip.tsx
- * @input Uses useLayer, usePressPin, React hooks
+ * @input Uses useLayer, useTouchTriggerInternal, React hooks
* @output Exports useTooltip hook with stable trigger refs for hover/focus/tap tooltips
- * and imperative show() and hide() for an app-built toggle trigger,
- * and the module-only useTooltipWithTriggerBehavior that InfoTip's press-to-pin uses
+ * and imperative show() and hide() for an app-built toggle trigger
* @position Layer hook; builds on useLayer for tooltip behavior
*
* SYNC: When modified, update:
@@ -30,12 +29,14 @@ import {
type LayerAlignment,
type LayerPlacement,
} from '../Layer/useLayer';
-import type {LayerTouchTrigger} from '../Layer/useTouchTrigger';
+import {
+ useTouchTriggerInternal,
+ 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, type LayerTriggerBehavior} from '../Layer/usePressPin';
import {useLayerDismissal} from '../Layer/useLayerDismissal';
import {themeProps} from '../utils/themeProps';
import {
@@ -222,8 +223,10 @@ export interface TooltipReturn {
/**
* Opens the tooltip now and keeps it open until `hide()`, Escape, a press
- * outside, or focus leaving its trigger, as a pinned tooltip does. Its text
- * is announced once. Reports through `onShow`. Under a controlled `isOpen`,
+ * outside, or focus leaving its trigger. If a press on the trigger is down
+ * when you call it, and the press ends off the trigger with no click, the
+ * hold ends. The hover rules then decide.
+ * Its text is announced once. Reports through `onShow`. Under a controlled `isOpen`,
* it calls `onShow` and does not change `isOpen`. Does nothing while
* `isEnabled` is false.
*
@@ -266,42 +269,6 @@ export interface TooltipReturn {
*/
export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
- // The option is fixed to `adaptive`, so an options object that carries it at
- // runtime cannot reach the press-to-pin path.
- return useTooltipWithTriggerBehavior({
- ...options,
- triggerBehavior: 'adaptive',
- });
-}
-
-/**
- * Module-only options for `useTooltipWithTriggerBehavior`. Not exported from
- * the package.
- */
-export interface TooltipWithTriggerBehaviorOptions extends TooltipOptions {
- /**
- * How the trigger opens the tooltip:
- * - `adaptive` (the default): hover and focus preview it. `touchTrigger`
- * decides taps.
- * - `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 trigger reports `aria-expanded`
- * and `aria-controls`, and the tooltip's text is announced once when it
- * pins. `touchTrigger` is ignored. InfoTip uses it.
- *
- * @default 'adaptive'
- */
- triggerBehavior?: LayerTriggerBehavior;
-}
-
-/**
- * `useTooltip` with a trigger behavior. Module-only: InfoTip's press-to-pin
- * goes through it, and the package does not export it.
- */
-export function useTooltipWithTriggerBehavior(
- options: TooltipWithTriggerBehaviorOptions = {},
-): TooltipReturn {
const {
placement = 'above',
alignment = 'center',
@@ -309,7 +276,6 @@ export function useTooltipWithTriggerBehavior(
hideDelay = 0,
focusTrigger = 'auto',
touchTrigger = 'auto',
- triggerBehavior = 'adaptive',
isEnabled = true,
isOpen,
isDefaultOpen = false,
@@ -367,42 +333,122 @@ export function useTooltipWithTriggerBehavior(
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.
+ // DOM listeners read the latest controlled state through a ref.
+ const latestRef = useRef({isOpen, isLayerOpen, onShow, onHide});
+ latestRef.current = {isOpen, isLayerOpen, onShow, onHide};
+
+ // The app's show() holds the tooltip open until hide(), Escape, a press or
+ // scroll outside, or focus leaving the trigger and the tooltip.
+ const isHeldRef = useRef(false);
+ const [isHeldState, setIsHeldState] = useState(false);
+ const setHeld = useCallback((next: boolean) => {
+ isHeldRef.current = next;
+ setIsHeldState(next);
+ }, []);
+
+ // Whether the current hold began during a press on the trigger. Such a
+ // hold ends with the press when the press ends off the trigger, as no click
+ // pins it. The hover rules then decide. isHoldInThisTaskRef covers a show()
+ // that runs before the hook's own pointerdown listener.
+ const isHoldFromPressRef = useRef(false);
+ const isHoldInThisTaskRef = useRef(false);
+ const handleReleaseInLayer = useCallback(() => {
+ if (isHoldFromPressRef.current && isHeldRef.current) {
+ isHoldFromPressRef.current = false;
+ setHeld(false);
+ }
+ }, [setHeld]);
+
+ // The touch trigger's outside dismissal (a press or scroll outside) ends a
+ // hold with the tooltip.
+ const hideFromTouch = useCallback(() => {
+ if (isHeldRef.current) {
+ setHeld(false);
+ const latest = latestRef.current;
+ if (latest.isOpen !== undefined) {
+ latest.onHide?.();
+ return;
+ }
+ }
+ hideNow();
+ }, [setHeld, hideNow]);
+
const {
- isToggleTrigger,
- isHeldOpen: isPressHeldOpen,
- attach: attachPressPin,
- unpin: unpinPress,
- hold: holdPress,
- release: releasePress,
- isAppHeld,
- isPinShown,
- touch: {
- isTouchPointerRef,
- isTouchInteraction,
- handlePointerEnter,
- handlePointerDown: handleTouchPointerDown,
- clearTapOpen,
+ isTouchPointerRef,
+ isTouchInteraction,
+ handlePointerEnter,
+ handlePointerDown: handleTouchPointerDown,
+ clearTapOpen,
+ armOutsideDismiss,
+ } = useTouchTriggerInternal(
+ {
+ touchTrigger,
+ isEnabled,
+ isControlled: isOpen !== undefined,
+ isOpen: isLayerOpen,
+ layerId,
+ triggerRef,
+ show: showNow,
+ hide: hideFromTouch,
},
- } = usePressPin({
- triggerBehavior,
- touchTrigger,
- isEnabled,
- isOpen,
- isLayerOpen,
- layerId,
- triggerRef,
- component: 'Tooltip',
- show: showNow,
- hide: hideNow,
- report: next => (next ? onShow?.() : onHide?.()),
- });
+ handleReleaseInLayer,
+ );
+
+ const isHeldOpen = useCallback(() => {
+ const latest = latestRef.current;
+ return isHeldRef.current && latest.isLayerOpen && latest.isOpen !== false;
+ }, []);
+
+ const releaseHold = useCallback(() => {
+ clearTapOpen();
+ setHeld(false);
+ const latest = latestRef.current;
+ if (latest.isOpen !== undefined) {
+ latest.onHide?.();
+ return;
+ }
+ hideNow();
+ }, [clearTapOpen, setHeld, hideNow]);
+
+ const dropHold = useCallback(() => {
+ if (isHeldRef.current) {
+ setHeld(false);
+ }
+ }, [setHeld]);
+
+ // Focus leaving the trigger and the tooltip ends a hold, whatever
+ // `focusTrigger` is. 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 handleHeldFocusOut = useCallback(
+ (event: FocusEvent) => {
+ if (!isHeldOpen()) {
+ return;
+ }
+ const next = event.relatedTarget;
+ const trigger = triggerRef.current;
+ const view = trigger?.ownerDocument.defaultView;
+ if (view == null || !(next instanceof view.Node)) {
+ return;
+ }
+ const surface = trigger?.ownerDocument.getElementById(layerId) ?? null;
+ if (
+ trigger?.contains(next) === true ||
+ surface?.contains(next) === true
+ ) {
+ return;
+ }
+ releaseHold();
+ },
+ [isHeldOpen, layerId, releaseHold],
+ );
- // Only a pin announces the text: a preview is already the trigger's
+ const isHoldShown = isHeldState && isLayerOpen && isOpen !== false;
+
+ // Only a hold announces the text: a preview is already the trigger's
// description.
const contentRef = useRef<HTMLDivElement | null>(null);
- useAnnounceRenderedText(contentRef, isPinShown, 'pinned');
+ useAnnounceRenderedText(contentRef, isHoldShown, 'pinned');
const contentRefs = useMergedRefs<HTMLDivElement>(
contentRef,
registerLayerSurface,
@@ -435,7 +481,7 @@ export function useTooltipWithTriggerBehavior(
// 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 || isPressHeldOpen()) {
+ if (isOpen === true || isHeldOpen()) {
return;
}
clearTimeouts();
@@ -443,7 +489,7 @@ export function useTooltipWithTriggerBehavior(
hideTimeoutRef.current = setTimeout(() => {
hideLayer();
}, effectiveHideDelay);
- }, [isOpen, isPressHeldOpen, clearTimeouts, hideLayer, hideDelay]);
+ }, [isOpen, isHeldOpen, clearTimeouts, hideLayer, hideDelay]);
// Cancel a pending hide (e.g. the pointer entered the tooltip surface).
const cancelHide = useCallback(() => {
@@ -523,9 +569,9 @@ export function useTooltipWithTriggerBehavior(
],
);
- // 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.
+ // A held tooltip's focus-leave close is the hold's own: it listens on the
+ // trigger whatever `focusTrigger` is. This schedules the unheld hide, which
+ // a held tooltip skips.
const handleFocusOut = useCallback(
(e: Event) => {
if (!focusGate.focusOut(e, focusTrigger)) {
@@ -543,12 +589,47 @@ export function useTooltipWithTriggerBehavior(
// is owned by the consumer. `hideLayer()` self-guards when already closed.
// A touch press is a different gesture (it may be the only way to open the
// tooltip at all), so the touch path answers it first.
+ // Whether a press on the trigger is down, from the hook's pointerdown to
+ // the press's end.
+ const isTriggerPressedRef = useRef(false);
+ const stopPressTrackingRef = useRef<(() => void) | null>(null);
+ const trackTriggerPress = useCallback(() => {
+ stopPressTrackingRef.current?.();
+ const view = triggerRef.current?.ownerDocument.defaultView;
+ if (view == null) {
+ return;
+ }
+ isTriggerPressedRef.current = true;
+ const trigger = triggerRef.current;
+ const stop = (event?: Event) => {
+ // A press that ends on the trigger keeps its hold, as a click does.
+ if (
+ event?.type === 'pointerup' &&
+ event.target instanceof view.Node &&
+ trigger?.contains(event.target) === true
+ ) {
+ isHoldFromPressRef.current = false;
+ }
+ view.removeEventListener('pointerup', stop, true);
+ view.removeEventListener('pointercancel', stop, true);
+ isTriggerPressedRef.current = false;
+ stopPressTrackingRef.current = null;
+ };
+ view.addEventListener('pointerup', stop, true);
+ view.addEventListener('pointercancel', stop, true);
+ stopPressTrackingRef.current = stop;
+ }, []);
+
const handlePointerDown = useCallback(
(event: PointerEvent) => {
- // A toggle trigger's press pins or closes through its click. The app's
- // hide() closes a held tooltip. Neither path hides here or waits for a
- // tap verdict.
- if (isToggleTrigger(triggerRef.current) || isAppHeld()) {
+ trackTriggerPress();
+ // The app's hide() closes a held tooltip. A press neither hides it here
+ // nor waits for a tap verdict. A show() in a capture handler of this
+ // press runs before this listener. Tie that hold to the press.
+ if (isHeldRef.current) {
+ if (isHoldInThisTaskRef.current) {
+ isHoldFromPressRef.current = true;
+ }
return;
}
if (handleTouchPointerDown(event)) {
@@ -561,9 +642,8 @@ export function useTooltipWithTriggerBehavior(
hideLayer();
},
[
- isToggleTrigger,
- isAppHeld,
handleTouchPointerDown,
+ trackTriggerPress,
isOpen,
clearTimeouts,
hideLayer,
@@ -579,6 +659,8 @@ export function useTooltipWithTriggerBehavior(
triggerRef.current.removeEventListener('mouseleave', handleMouseLeave);
triggerRef.current.removeEventListener('focusin', handleFocusIn);
triggerRef.current.removeEventListener('focusout', handleFocusOut);
+ triggerRef.current.removeEventListener('focusout', handleHeldFocusOut);
+ stopPressTrackingRef.current?.();
triggerRef.current.removeEventListener(
'pointerenter',
handlePointerEnter,
@@ -607,11 +689,12 @@ export function useTooltipWithTriggerBehavior(
}
}
+ // Its own focus-leave listener: `focusTrigger="never"` attaches none.
+ el?.addEventListener('focusout', handleHeldFocusOut);
triggerRef.current = el;
- attachPressPin(el);
},
[
- attachPressPin,
+ handleHeldFocusOut,
focusTrigger,
handleMouseEnter,
handleMouseLeave,
@@ -656,11 +739,11 @@ export function useTooltipWithTriggerBehavior(
showLayer();
} else {
clearTimeouts();
- // A pin or app hold ends when the consumer closes the tooltip.
- unpinPress();
+ // A hold ends when the consumer closes the tooltip.
+ dropHold();
hideLayer();
}
- }, [isOpen, clearTimeouts, showLayer, hideLayer, unpinPress]);
+ }, [isOpen, clearTimeouts, showLayer, hideLayer, dropHold]);
// Dismiss on Escape (WCAG 1.4.13 — dismissible) through the shared layer
// stack. A visible tip is the top-most layer, so it takes the press and
@@ -701,7 +784,7 @@ export function useTooltipWithTriggerBehavior(
onDismiss: () => {
clearTimeouts();
clearTapOpen();
- unpinPress();
+ dropHold();
if (isOpen !== undefined) {
onHide?.();
return;
@@ -738,7 +821,7 @@ export function useTooltipWithTriggerBehavior(
// 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.
- // The pin's announcement reads this element's text.
+ // The hold's announcement reads this element's text.
<div ref={contentRefs} {...stylex.props(styles.content)}>
{children}
</div>,
@@ -758,13 +841,28 @@ export function useTooltipWithTriggerBehavior(
const show = useCallback(() => {
clearTimeouts();
- holdPress();
- }, [clearTimeouts, holdPress]);
+ if (!isEnabled) {
+ return;
+ }
+ setHeld(true);
+ armOutsideDismiss();
+ isHoldFromPressRef.current = isTriggerPressedRef.current;
+ isHoldInThisTaskRef.current = true;
+ triggerRef.current?.ownerDocument.defaultView?.setTimeout(() => {
+ isHoldInThisTaskRef.current = false;
+ }, 0);
+ const latest = latestRef.current;
+ if (latest.isOpen !== undefined) {
+ latest.onShow?.();
+ return;
+ }
+ showLayer();
+ }, [clearTimeouts, isEnabled, setHeld, armOutsideDismiss, showLayer]);
const hide = useCallback(() => {
clearTimeouts();
- releasePress();
- }, [clearTimeouts, releasePress]);
+ releaseHold();
+ }, [clearTimeouts, releaseHold]);
return {
ref,
diff --git a/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx b/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx
index 780cd0a8fd..3216e7a016 100644
--- a/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx
+++ b/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx
@@ -3,7 +3,7 @@
/**
* @file useAnnounceRenderedText.adopters.test.tsx
* @input Every core component that announces its own rendered content,
- * Tooltip's pin included, with the shared own-content module replaced by a
+ * Tooltip's show() hold 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
@@ -68,7 +68,7 @@ const {BaseTypeahead} = await import('../Typeahead/BaseTypeahead');
const {Tokenizer} = await import('../Tokenizer/Tokenizer');
const {PowerSearch} = await import('../PowerSearch/PowerSearch');
const {createStaticSource} = await import('../Typeahead/createStaticSource');
-const {TooltipWithTriggerBehavior} = await import('../Tooltip/Tooltip');
+const {InfoTip} = await import('../InfoTip/InfoTip');
const source = createStaticSource([{id: 'apple', label: 'Apple'}]);
@@ -167,13 +167,12 @@ const ADOPTERS: Record<string, () => Promise<void>> = {
await expectDelegated('No results found');
},
'Tooltip/useTooltip.tsx': async () => {
- // A tooltip a press pinned says its own text (component:Tooltip FR10).
+ // A tooltip that show() holds says its own text (component:Tooltip FR12).
render(
- <TooltipWithTriggerBehavior
+ <InfoTip
content="Billed on the first of each month"
- triggerBehavior="toggle">
- <button type="button">About billing</button>
- </TooltipWithTriggerBehavior>,
+ label="About billing"
+ />,
);
fireEvent.click(screen.getByRole('button', {name: 'About billing'}));
await expectDelegated('Billed on the first of each month');