An open source design system that's fully customizable and agent ready
TypeScript
feat(Tooltip): useTooltip returns show() and hide() for an app-built toggle trigger (#9727)
Cindy Zhang97191cf7fc42
diff --git a/.changeset/use-tooltip-show-hide.md b/.changeset/use-tooltip-show-hide.mdnew file mode 100644index 0000000000..13275fb489--- /dev/null+++ b/.changeset/use-tooltip-show-hide.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] `useTooltip` returns `show()` and `hide()`. `show()` opens the tooltip and keeps it open until `hide()`, Escape, a press outside, or focus leaving its trigger, and its text is announced once. `hide()` closes it. Both fire `onShow` and `onHide`. Under a controlled `isOpen`, they only call those callbacks. Use them to build a toggle-style trigger: your own button calls them on each press, sets `aria-expanded` and `aria-controls={describedBy}`, and keeps its own accessible name.++@cixzhangdiff --git a/apps/storybook/stories/Tooltip.stories.tsx b/apps/storybook/stories/Tooltip.stories.tsxindex f578b8a95f..8567ac8e33 100644--- a/apps/storybook/stories/Tooltip.stories.tsx+++ b/apps/storybook/stories/Tooltip.stories.tsx@@ -155,6 +155,43 @@ export const WithHook: Story = {},};+/**+ * A toggle-style trigger built on `useTooltip`'s `show()` and `hide()`: the+ * app's own button pins the tooltip on a press and closes it on the next one.+ * Escape, a press outside, or focus leaving also close it. The button carries+ * `aria-expanded` while the press holds it and `aria-controls` naming the+ * tooltip. Hover and keyboard focus still preview it.+ */+export const CustomToggleTrigger: Story = {+ render: function CustomToggleTriggerExample() {+ const [isPinned, setIsPinned] = useState(false);+ const tooltip = useTooltip({onHide: () => setIsPinned(false)});++ return (+ <div style={{padding: 100}}>+ <Button+ label="About billing"+ variant="secondary"+ ref={tooltip.ref}+ aria-describedby={tooltip.describedBy}+ aria-expanded={isPinned}+ aria-controls={tooltip.describedBy}+ onClick={() => {+ if (isPinned) {+ tooltip.hide();+ } else {+ tooltip.show();+ }+ setIsPinned(!isPinned);+ }}>+ ?+ </Button>+ {tooltip.renderTooltip('Billed monthly, on the first day')}+ </div>+ );+ },+};+export const LongContent: Story = {args: {placement: 'above',diff --git a/docs/specs/components/Tooltip/Tooltip.spec.md b/docs/specs/components/Tooltip/Tooltip.spec.mdindex ea62e3c489..a1c859cc6b 100644--- a/docs/specs/components/Tooltip/Tooltip.spec.md+++ b/docs/specs/components/Tooltip/Tooltip.spec.md@@ -50,15 +50,15 @@ system_specs: [spec:AST-003, spec:AST-017, spec:AST-086/FR12, spec:AST-086/FR14]## 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`. 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. |-| 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 | No public API change: `touchTrigger` keeps its released values and its default `auto`, and the press-to-pin path adds no public prop. Ten 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). 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`. |This table is a review projection; the body below is authoritative.@@ -74,8 +74,9 @@ in `Tooltip.doc.mjs`.- Released default preserved: yes. `touchTrigger` keeps its released valuesand its default `auto`. A disabled control is not an action, so its reasonopens on a tap (FR5); that restoration ships on its own as a patch `[fix]`-- Compatibility class: no public prop, default, DOM, styling, or target change;- the press-to-pin path (FR9, FR10) is internal and adds no public surface+- 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- Controlled/uncontrolled behavior: uncontrolled by default; `isOpen` forces thestate, and a controlled tooltip reports close requests through`onOpenChange(false)` without closing itself (FR7); on the press-to-pin path@@ -97,9 +98,6 @@ Consumer migration instructions belong in consumer docs and release notes.## Current-state impact-- **`useTooltip` has no `show()` or `hide()` yet.** An app cannot yet build- its own toggle-style trigger as DEC-1 describes; `component:InfoTip` pins- through the internal press-to-pin path (FR9, FR10).- **`hasInteractiveAncestor` still asks the surface registry.** Until thenext minor, the public `hasInteractiveAncestor` answers true for a pressinside an open Tooltip or HoverCard surface, as its documentation states;@@ -161,8 +159,9 @@ Consumer migration instructions belong in consumer docs and release notes.- An arrow element — the current implementation renders none.- Layer hosting and anchor positioning — owned by `architecture:layer-runtime`;shared Escape ordering — owned by `family:overlay-dismissal`.-- The `useTooltip` hook's public contract — an uncontracted module; this record- covers Tooltip's observable behavior.+- The rest of the `useTooltip` hook's public contract — an uncontracted+ module; this record covers Tooltip's observable behavior and the hook's+ `show` and `hide` (FR12).## Public concepts@@ -180,12 +179,13 @@ Consumer migration instructions belong in consumer docs and release notes.| 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, 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 |+| 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. |### Allowed variation@@ -270,6 +270,7 @@ has no arrow element.| 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` |Read from source, with no focused test yet:@@ -309,8 +310,7 @@ A press-to-pin toggle answers a different question, so it does not replacenot 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. Anapp builds a toggle-style trigger by having its own button call `useTooltip`'s-imperative `show()` and `hide()`, which are not built yet (Current-state-impact). `component:InfoTip` keeps its current behavior for now: it pins+imperative `show()` and `hide()` (FR12). `component:InfoTip` keeps its current behavior for now: it pinsthrough Tooltip's internal press-to-pin path (FR9, FR10).`component:HoverCard` DEC-1 applies the same rules.diff --git a/packages/core/api-report.md b/packages/core/api-report.mdindex 53f6c3d530..2f4f9034a9 100644--- a/packages/core/api-report.md+++ b/packages/core/api-report.md@@ -5667,10 +5667,12 @@ interface TooltipProps (props of Tooltip)interface TooltipReturnanchorId: stringdescribedBy: string+ hide: () => voidinteractionRef: RefCallback<HTMLElement>positionRef: RefCallback<HTMLElement>ref: RefCallback<HTMLElement>renderTooltip: (children: ReactNode, props?: Omit<ContextRenderProps, 'positioning'>) => ReactNode+ show: () => voidtype TooltipTouchTrigger = LayerTouchTriggerinterface TopNavHeadingProps extends BaseProps<HTMLElement> (props of TopNavHeading)interface TopNavItemProps extends BaseProps<HTMLAnchorElement> (props of TopNavItem)diff --git a/packages/core/src/Layer/usePressPin.ts b/packages/core/src/Layer/usePressPin.tsindex fec178eb7f..28e539d018 100644--- a/packages/core/src/Layer/usePressPin.ts+++ b/packages/core/src/Layer/usePressPin.ts@@ -6,8 +6,9 @@* @file usePressPin.ts* @input A hover layer's trigger, open state, show and hide, and its* `triggerBehavior` and `touchTrigger` options- * @output usePressPin, the press toggle that pins a hover layer open;- * isPressPinTrigger; stopPressPinClick; the LayerTriggerBehavior type+ * @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.*@@ -103,8 +104,18 @@ export interface UsePressPinReturn {isHeldOpen: () => boolean;/** Wires the trigger element, or unwires it with `null`. */attach: (element: HTMLElement | null) => void;- /** Drops the pin: Escape, or a hide that came from elsewhere. */+ /** 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@@ -112,8 +123,9 @@ export interface UsePressPinReturn {*/handleFocusLeave: (event: FocusEvent) => boolean;/**- * Whether the layer shows pinned on a wired trigger. The host then announces- * its rendered text, unless the layer has a `label`.+ * 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. */@@ -175,8 +187,19 @@ export function usePressPin(options: UsePressPinOptions): UsePressPinReturn {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'>(@@ -192,6 +215,13 @@ export function usePressPin(options: UsePressPinOptions): UsePressPinReturn {// 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);@@ -202,7 +232,7 @@ export function usePressPin(options: UsePressPinOptions): UsePressPinReturn {}}current.hide();- }, [setPinned]);+ }, [setPinned, setAppHeld]);const {isTouchPointerRef,@@ -233,13 +263,14 @@ export function usePressPin(options: UsePressPinOptions): UsePressPinReturn {const close = useCallback(() => {const current = optionsRef.current;clearTapOpen();+ setAppHeld(false);if (current.isOpen !== undefined) {current.report(false);return;}setPinned(false);current.hide();- }, [setPinned, clearTapOpen]);+ }, [setPinned, setAppHeld, clearTapOpen]);const announceName = useCallback(() => {const current = optionsRef.current;@@ -348,6 +379,9 @@ export function usePressPin(options: UsePressPinOptions): UsePressPinReturn {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;}@@ -364,7 +398,7 @@ export function usePressPin(options: UsePressPinOptions): UsePressPinReturn {return false;}const next = event.relatedTarget;- const trigger = triggerRef.current;+ 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;@@ -387,6 +421,8 @@ export function usePressPin(options: UsePressPinOptions): UsePressPinReturn {);const unwire = useCallback(() => {+ focusTargetRef.current?.removeEventListener('focusout', handleFocusLeave);+ focusTargetRef.current = null;const previous = triggerRef.current;if (previous == null) {return;@@ -394,7 +430,6 @@ export function usePressPin(options: UsePressPinOptions): UsePressPinReturn {previous.removeEventListener('click', handlePress);previous.removeEventListener('keydown', handleKeyDown);previous.removeEventListener('keyup', handleKeyUp);- previous.removeEventListener('focusout', handleFocusLeave);const own = ownStateRef.current;if (own != null) {restoreAttribute(previous, 'aria-expanded', own.expanded);@@ -423,10 +458,14 @@ export function usePressPin(options: UsePressPinOptions): UsePressPinReturn {}settledRef.current = {element, mode: current.triggerBehavior};unwire();- if (element == null || current.triggerBehavior !== 'toggle') {+ if (element == null) {return;}- if (!isPressPinTrigger(element)) {+ // 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);@@ -434,8 +473,6 @@ export function usePressPin(options: UsePressPinOptions): UsePressPinReturn {element.addEventListener('keydown', handleKeyDown);element.addEventListener('keyup', handleKeyUp);}- // Its own focus-leave listener: `focusTrigger="never"` attaches none.- element.addEventListener('focusout', handleFocusLeave);ownStateRef.current = {expanded: element.getAttribute('aria-expanded'),controls: element.getAttribute('aria-controls'),@@ -473,7 +510,31 @@ export function usePressPin(options: UsePressPinOptions): UsePressPinReturn {if (isPinnedRef.current) {setPinned(false);}- }, [setPinned]);+ 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.@@ -490,13 +551,18 @@ export function usePressPin(options: UsePressPinOptions): UsePressPinReturn {writeAttribute(trigger, 'aria-controls', isLayerOpen ? layerId : null);});- const isPinShown = isToggleMode && isWired && isExpanded;+ const isPinShown =+ (isToggleMode && isWired && isExpanded) ||+ (isAppHeldState && isLayerOpen && isOpen !== false);return {isToggleTrigger,isHeldOpen,attach,unpin,+ hold,+ release,+ isAppHeld,handleFocusLeave,isPinShown,touch: {diff --git a/packages/core/src/Tooltip/useTooltip.doc.mjs b/packages/core/src/Tooltip/useTooltip.doc.mjsindex e1ece96f65..68d9e30af0 100644--- a/packages/core/src/Tooltip/useTooltip.doc.mjs+++ b/packages/core/src/Tooltip/useTooltip.doc.mjs@@ -110,6 +110,18 @@ export const docs = {description:'Render function for the anchor-positioned tooltip content. The positioning opt-out is excluded: the tooltip always derives its position from placement/alignment.',},+ {+ name: 'show',+ type: '() => void',+ description:+ 'Opens the tooltip now and keeps it open until hide(), Escape, a press outside, or focus leaving its trigger. Its text is announced once, and onShow fires. Under a controlled isOpen it only calls onShow. Does nothing while isEnabled is false.',+ },+ {+ name: 'hide',+ type: '() => void',+ description:+ 'Closes the tooltip now, and onHide fires. Under a controlled isOpen it only calls onHide.',+ },],usage: {description:@@ -125,6 +137,11 @@ export const docs = {description:'Prefer the Tooltip component for standard wrapping; use the hook when the trigger is not a simple child.',},+ {+ guidance: true,+ description:+ 'For a toggle-style trigger, have your own button call show() and hide() on each press. Give it aria-describedby and aria-controls set to describedBy, and aria-expanded (true while show() holds the tooltip, false after hide() or onHide), and keep its own accessible name. For an info icon, use InfoTip instead.',+ },{guidance: false,description:@@ -167,6 +184,8 @@ export const docsDense = {anchorId: 'CSS anchor name.',describedBy: 'ID for aria-describedby.',renderTooltip: 'renders anchor-positioned tooltip content.',+ show: 'opens + holds until hide()/Escape/outside press/focus leave; announces once; onShow. Controlled: onShow only. No-op when disabled.',+ hide: 'closes; onHide. Controlled: onHide only.',},usage: {description:@@ -182,6 +201,11 @@ export const docsDense = {description:'Prefer Tooltip for standard wrapping; use hook when trigger is not simple child.',},+ {+ guidance: true,+ description:+ 'Toggle-style trigger: own button calls show()/hide() per press, sets aria-describedby + aria-controls={describedBy}, aria-expanded (true while held), keeps its own name. Info icon: use InfoTip.',+ },{guidance: false,description:diff --git a/packages/core/src/Tooltip/useTooltip.showHide.test.tsx b/packages/core/src/Tooltip/useTooltip.showHide.test.tsxnew file mode 100644index 0000000000..0d8ffe73a0--- /dev/null+++ b/packages/core/src/Tooltip/useTooltip.showHide.test.tsx@@ -0,0 +1,236 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useTooltip.showHide.test.tsx+ * @input Uses vitest, @testing-library/react, useTooltip+ * @output Tests of useTooltip's imperative show() and hide(): an app's own+ * 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+ *+ * SYNC: When useTooltip.tsx or usePressPin.ts changes, update these tests.+ */++import {+ describe,+ it,+ expect,+ vi,+ beforeAll,+ afterAll,+ beforeEach,+ afterEach,+} from 'vitest';+import {render, screen, fireEvent, act} from '@testing-library/react';+import {useState, type ReactElement} from 'react';+import {useTooltip, type TooltipOptions} from './useTooltip';+import type * as UseAnnounceModule from '../hooks/useAnnounce';+import {__resetInteractionModalityForTest} from '../utils/interactionModality';++const {announce} = vi.hoisted(() => ({announce: vi.fn()}));+vi.mock('../hooks/useAnnounce', async importOriginal => ({+ ...(await importOriginal<typeof UseAnnounceModule>()),+ announceMessage: vi.fn(() => null),+ useAnnounce: () => announce,+}));++const originalMatches = HTMLElement.prototype.matches;+const popoverOpenState = new WeakMap<HTMLElement, boolean>();++beforeAll(() => {+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {+ popoverOpenState.set(this, true);+ });+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {+ popoverOpenState.set(this, false);+ });+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (HTMLElement.prototype as any).matches = function (+ this: HTMLElement,+ selector: string,+ ): boolean {+ if (selector === ':popover-open') {+ return popoverOpenState.get(this) ?? false;+ }+ return originalMatches.call(this, selector);+ };+});++afterAll(() => {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (HTMLElement.prototype as any).matches = originalMatches;+});++beforeEach(() => {+ __resetInteractionModalityForTest();+ announce.mockClear();+ vi.useFakeTimers();+});++afterEach(() => {+ vi.useRealTimers();+});++const TIP = 'Billed monthly';++function shows(): boolean {+ const layer = screen.queryByText(TIP)?.closest<HTMLElement>('[popover]');+ return layer != null && layer.matches(':popover-open');+}++/** A mouse click: the press, then its click. */+function click(element: HTMLElement) {+ fireEvent.pointerDown(element, {pointerType: 'mouse'});+ fireEvent.pointerUp(element, {pointerType: 'mouse'});+ fireEvent.click(element, {detail: 1});+}++/** An app's own toggle button built on show() and hide(). */+function ToggleTip(+ props: TooltipOptions & {onPinnedChange?: (pinned: boolean) => void},+): ReactElement {+ const {onPinnedChange, onHide, ...options} = props;+ const [isPinned, setIsPinned] = useState(false);+ const tooltip = useTooltip({+ ...options,+ onHide: () => {+ onHide?.();+ setIsPinned(false);+ },+ });+ return (+ <>+ <button+ type="button"+ ref={tooltip.ref}+ aria-expanded={isPinned}+ aria-controls={tooltip.describedBy}+ onClick={() => {+ if (isPinned) {+ tooltip.hide();+ } else {+ tooltip.show();+ }+ setIsPinned(!isPinned);+ onPinnedChange?.(!isPinned);+ }}>+ About billing+ </button>+ <button type="button">Next</button>+ {tooltip.renderTooltip(TIP)}+ </>+ );+}++const trigger = () => screen.getByRole('button', {name: 'About billing'});++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();+ const onHide = vi.fn();+ render(<ToggleTip onShow={onShow} onHide={onHide} />);++ click(trigger());+ expect(shows()).toBe(true);+ expect(onShow).toHaveBeenCalledTimes(1);+ expect(trigger()).toHaveAttribute('aria-expanded', 'true');++ click(trigger());+ expect(shows()).toBe(false);+ expect(onHide).toHaveBeenCalled();+ expect(trigger()).toHaveAttribute('aria-expanded', 'false');+ });++ it('a shown tooltip stays open when the pointer leaves its trigger', () => {+ render(<ToggleTip />);+ click(trigger());+ fireEvent.mouseLeave(trigger(), {relatedTarget: document.body});+ act(() => {+ vi.advanceTimersByTime(1000);+ });+ expect(shows()).toBe(true);+ });++ it('announces its text once on show()', () => {+ render(<ToggleTip />);+ click(trigger());+ act(() => {+ vi.advanceTimersByTime(100);+ });+ expect(announce).toHaveBeenCalledTimes(1);+ expect(announce).toHaveBeenCalledWith(TIP, 'polite');+ });++ it('Escape closes a shown tooltip and reports it', () => {+ const onHide = vi.fn();+ render(<ToggleTip onHide={onHide} />);+ click(trigger());+ fireEvent.keyDown(document, {key: 'Escape'});+ expect(shows()).toBe(false);+ expect(onHide).toHaveBeenCalled();+ expect(trigger()).toHaveAttribute('aria-expanded', 'false');+ });++ it('a press outside closes a shown tooltip', () => {+ render(<ToggleTip />);+ click(trigger());+ fireEvent.pointerDown(document.body, {pointerType: 'mouse'});+ fireEvent.pointerUp(document.body, {pointerType: 'mouse'});+ expect(shows()).toBe(false);+ expect(trigger()).toHaveAttribute('aria-expanded', 'false');+ });++ it('focus leaving the trigger for another control closes a shown tooltip', () => {+ render(<ToggleTip />);+ trigger().focus();+ click(trigger());+ expect(shows()).toBe(true);+ const next = screen.getByRole('button', {name: 'Next'});+ fireEvent.focusOut(trigger(), {relatedTarget: next});+ expect(shows()).toBe(false);+ });++ it('focus leaving closes it under focusTrigger="never" too', () => {+ render(<ToggleTip focusTrigger="never" />);+ click(trigger());+ const next = screen.getByRole('button', {name: 'Next'});+ fireEvent.focusOut(trigger(), {relatedTarget: next});+ expect(shows()).toBe(false);+ });++ it('under a controlled isOpen, show() and hide() report and do not override it', () => {+ const onShow = vi.fn();+ const onHide = vi.fn();+ function Controlled(): ReactElement {+ const tooltip = useTooltip({isOpen: false, onShow, onHide});+ return (+ <>+ <button type="button" ref={tooltip.ref} onClick={tooltip.show}>+ About billing+ </button>+ <button type="button" onClick={tooltip.hide}>+ Close+ </button>+ {tooltip.renderTooltip(TIP)}+ </>+ );+ }+ render(<Controlled />);+ click(trigger());+ expect(onShow).toHaveBeenCalledTimes(1);+ expect(shows()).toBe(false);+ fireEvent.click(screen.getByRole('button', {name: 'Close'}));+ expect(onHide).toHaveBeenCalledTimes(1);+ expect(shows()).toBe(false);+ });++ it('show() does nothing while isEnabled is false', () => {+ const onShow = vi.fn();+ render(<ToggleTip isEnabled={false} onShow={onShow} />);+ click(trigger());+ expect(shows()).toBe(false);+ expect(onShow).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/src/Tooltip/useTooltip.tsx b/packages/core/src/Tooltip/useTooltip.tsxindex 1805903c9b..75879b95ef 100644--- a/packages/core/src/Tooltip/useTooltip.tsx+++ b/packages/core/src/Tooltip/useTooltip.tsx@@ -5,7 +5,8 @@/*** @file useTooltip.tsx* @input Uses useLayer, usePressPin, React hooks- * @output Exports useTooltip hook with stable trigger refs for hover/focus/tap tooltips,+ * @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* @position Layer hook; builds on useLayer for tooltip behavior*@@ -216,6 +217,25 @@ export interface TooltipReturn {children: ReactNode,props?: Omit<ContextRenderProps, 'positioning'>,) => ReactNode;++ /**+ * 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`,+ * it calls `onShow` and does not change `isOpen`. Does nothing while+ * `isEnabled` is false.+ *+ * Use `show()` and `hide()` to build a toggle-style trigger: your own button+ * calls them, sets `aria-describedby` and `aria-controls` to `describedBy`+ * and `aria-expanded` (true while shown), and keeps its own accessible name.+ */+ show: () => void;++ /**+ * Closes the tooltip now. Reports through `onHide`. Under a controlled+ * `isOpen`, it calls `onHide` and does not change `isOpen`.+ */+ hide: () => void;}/**@@ -375,6 +395,9 @@ export function useTooltipWithTriggerBehavior(isHeldOpen: isPressHeldOpen,attach: attachPressPin,unpin: unpinPress,+ hold: holdPress,+ release: releasePress,+ isAppHeld,isPinShown,touch: {isTouchPointerRef,@@ -562,9 +585,10 @@ export function useTooltipWithTriggerBehavior(// tooltip at all), so the touch path answers it first.const handlePointerDown = useCallback((event: PointerEvent) => {- // A press on a toggle trigger pins or closes through its click. It- // neither hides the preview here nor waits for a tap verdict.- if (isToggleTrigger(triggerRef.current)) {+ // 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()) {return;}if (handleTouchPointerDown(event)) {@@ -576,7 +600,14 @@ export function useTooltipWithTriggerBehavior(clearTimeouts();hideLayer();},- [isToggleTrigger, handleTouchPointerDown, isOpen, clearTimeouts, hideLayer],+ [+ isToggleTrigger,+ isAppHeld,+ handleTouchPointerDown,+ isOpen,+ clearTimeouts,+ hideLayer,+ ],);// Interaction ref that handles event listeners only@@ -665,9 +696,11 @@ export function useTooltipWithTriggerBehavior(showLayer();} else {clearTimeouts();+ // A pin or app hold ends when the consumer closes the tooltip.+ unpinPress();hideLayer();}- }, [isOpen, clearTimeouts, showLayer, hideLayer]);+ }, [isOpen, clearTimeouts, showLayer, hideLayer, unpinPress]);// 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@@ -763,6 +796,16 @@ export function useTooltipWithTriggerBehavior(],);+ const show = useCallback(() => {+ clearTimeouts();+ holdPress();+ }, [clearTimeouts, holdPress]);++ const hide = useCallback(() => {+ clearTimeouts();+ releasePress();+ }, [clearTimeouts, releasePress]);+return {ref,positionRef: layerRef,@@ -770,5 +813,7 @@ export function useTooltipWithTriggerBehavior(anchorId: layerAnchorId,describedBy: layerId,renderTooltip,+ show,+ hide,};}