Skip to content

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

TypeScript

fix(Text, Heading): the truncation tooltip mounts on the first hover, tap or focus (#10290)

Cindy Zhang360701de73f2
diff --git a/.changeset/text-tooltip-mounts-on-interest.md b/.changeset/text-tooltip-mounts-on-interest.md
new file mode 100644
index 0000000000..5dbe9215cd
--- /dev/null
+++ b/.changeset/text-tooltip-mounts-on-interest.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A truncated Text or Heading mounts its tooltip on the first hover, tap or focus, not as soon as it renders, so a long table or list of truncated cells mounts no closed tooltip layers at load. The hover delay, the tap and the focus rules are the tooltip's own: a touch that becomes a scroll opens nothing, and a tap outside closes it. No visual change.
+
+@cixzhang
diff --git a/apps/storybook/stories/Text.stories.tsx b/apps/storybook/stories/Text.stories.tsx
index 544051c771..2e62a62d6a 100644
--- a/apps/storybook/stories/Text.stories.tsx
+++ b/apps/storybook/stories/Text.stories.tsx
@@ -244,6 +244,25 @@ export const SingleLineTruncation: Story = {
),
};
+const MANY_ROWS = Array.from(
+ {length: 500},
+ (_, index) =>
+ `Row ${index + 1}: a cell label far wider than the column it has been given`,
+);
+
+/** A long list of truncated cells, as in a table, for checking load cost. */
+export const ManyTruncatedRows: Story = {
+ render: () => (
+ <div style={{width: '240px'}}>
+ {MANY_ROWS.map(label => (
+ <Text key={label} type="body" maxLines={1}>
+ {label}
+ </Text>
+ ))}
+ </div>
+ ),
+};
+
export const MultiLineTruncation: Story = {
render: () => (
<div style={{width: '300px', border: '1px solid #ccc', padding: '12px'}}>
diff --git a/docs/specs/components/Heading/Heading.spec.md b/docs/specs/components/Heading/Heading.spec.md
index d5a3dcf9ed..ea44dad024 100644
--- a/docs/specs/components/Heading/Heading.spec.md
+++ b/docs/specs/components/Heading/Heading.spec.md
@@ -35,15 +35,15 @@ system_specs: [spec:AST-009, spec:AST-024]
## Contract at a glance
-| Area | Contract |
-| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Public contract | A semantic heading with a required `level`, an optional theme-extensible visual `type`, `weight`, `accessibilityLevel`, and the shared text controls documented in `Heading.doc.mjs`. |
-| Behavior | `level` picks `h1`–`h6` and the default visual scale; `type` and `weight` change only appearance; `accessibilityLevel` sets `aria-level` when it differs. |
-| End-user impact | Screen-reader users navigate a document outline that matches the page's sections, whatever size each heading is drawn at. |
-| Builder impact | A long unbroken token in non-truncated Heading wraps. Inside a flex row, the flex child needs `min-width: 0` for the wrap to apply, and a caller's own container that sets `overflow-wrap: anywhere` does not reach Heading's text; Core's `anywhere` containers pass their wrap to it. |
-| Compatibility/readiness | Released behavior recorded as current, with one styling output change: non-truncated Heading sets `overflow-wrap` (`break-word`, or `anywhere` inside Core's `anywhere` containers). No API change. One implementation gap is listed under Current-state impact. |
-| Review checks | Reject a visual `type` or `weight` that changes the element or level, a heading that renders without a level baseline, or a duplicate native tooltip for truncation. |
-| Governing rules | `spec:AST-024` (custom visual types, weight precedence, unchanged accessibility); `architecture:component-theming-surface/INV6,INV14`; `architecture:public-component-api/INV5,INV6,INV8`. |
+| Area | Contract |
+| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | A semantic heading with a required `level`, an optional theme-extensible visual `type`, `weight`, `accessibilityLevel`, and the shared text controls documented in `Heading.doc.mjs`. |
+| Behavior | `level` picks `h1`–`h6` and the default visual scale; `type` and `weight` change only appearance; `accessibilityLevel` sets `aria-level` when it differs. |
+| End-user impact | Screen-reader users navigate a document outline that matches the page's sections, whatever size each heading is drawn at. |
+| Builder impact | A long unbroken token in non-truncated Heading wraps. Inside a flex row, the flex child needs `min-width: 0` for the wrap to apply, and a caller's own container that sets `overflow-wrap: anywhere` does not reach Heading's text; Core's `anywhere` containers pass their wrap to it. The truncation Tooltip mounts on the first hover, completed tap or focus (AR3). |
+| Compatibility/readiness | Released behavior recorded as current, with one styling output change and one DOM change: non-truncated Heading sets `overflow-wrap` (`break-word`, or `anywhere` inside Core's `anywhere` containers). The truncation Tooltip mounts on the first hover, completed tap or focus, so until then a clamped Heading has no tooltip layer and no `aria-describedby` (AR3). No API change. One implementation gap is listed under Current-state impact. |
+| Review checks | Reject a visual `type` or `weight` that changes the element or level, a heading that renders without a level baseline, or a duplicate native tooltip for truncation. |
+| Governing rules | `spec:AST-024` (custom visual types, weight precedence, unchanged accessibility); `architecture:component-theming-surface/INV6,INV14`; `architecture:public-component-api/INV5,INV6,INV8`. |
This table is a review projection; the body below is authoritative.
@@ -58,10 +58,12 @@ Heading's own contract.
## Compatibility and migration
- Released default preserved: `yes`
-- Compatibility class: one styling output change, with no public prop,
- default, or DOM change: non-truncated Heading sets `overflow-wrap`
+- Compatibility class: one styling output change and one DOM change, with
+ no public prop or default change: non-truncated Heading sets `overflow-wrap`
(`break-word`, or `anywhere` inside Core's `anywhere` containers), so a long
- unbroken token wraps (FR3)
+ unbroken token wraps (FR3). The truncation Tooltip mounts on the first
+ hover, completed tap or focus (AR3): before that, a clamped Heading has no closed
+ tooltip layer and no tooltip description in the DOM
- Controlled/uncontrolled behavior: not applicable
- Migration decision: none
@@ -121,14 +123,14 @@ Consumer migration instructions belong in consumer docs and release notes.
### Representative states
-| State | Required invariant | Allowed variation |
-| ----------------------- | -------------------------------------------------------------- | ----------------- |
-| Level only | `h{level}` at the level's scale. | Level. |
-| Display type | Same element; display scale and weight; `data-type` reflected. | Type. |
-| Theme-added type | Same element; level baseline; `data-type` reflected. | Theme paint. |
-| Accessibility override | `aria-level` differs from the element's level. | — |
-| Truncated with tooltip | Clamped heading anchors one Tooltip with the full text. | Placement. |
-| Truncation, tooltip off | Clamped heading; no measurement; no Tooltip. | — |
+| State | Required invariant | Allowed variation |
+| ----------------------- | ----------------------------------------------------------------------------------------------------------- | ----------------- |
+| Level only | `h{level}` at the level's scale. | Level. |
+| Display type | Same element; display scale and weight; `data-type` reflected. | Type. |
+| Theme-added type | Same element; level baseline; `data-type` reflected. | Theme paint. |
+| Accessibility override | `aria-level` differs from the element's level. | — |
+| Truncated with tooltip | Clamped heading anchors one Tooltip with the full text, mounted on the first hover, completed tap or focus. | Placement. |
+| Truncation, tooltip off | Clamped heading; no measurement; no Tooltip. | — |
### Transformation and precedence order
@@ -144,7 +146,9 @@ Consumer migration instructions belong in consumer docs and release notes.
- **PR1 — Measured only when needed.** Truncation is measured only when
`maxLines` is positive and the tooltip is enabled; re-measuring follows size
and content changes without a per-heading observer; the Tooltip module loads
- only when the text is truncated.
+ only when the text is truncated, and the Tooltip itself mounts only on the
+ first hover, completed tap or focus, so until that first interaction a page of
+ clamped text mounts no closed tooltip layers.
## Accessibility contract
@@ -154,7 +158,10 @@ Consumer migration instructions belong in consumer docs and release notes.
level through `aria-level` without changing the element.
- **AR3 — Truncated text.** The full text stays in the heading's DOM; the
truncation Tooltip is the only tooltip, and any description it adds is
- Tooltip's.
+ Tooltip's. The Tooltip mounts on the first hover, completed tap or focus on the
+ clamped heading, and that interaction opens it as it would once
+ mounted, by Tooltip's own rules (Tooltip FR3–FR5); until then the heading
+ carries no tooltip description, since its full text is already in its DOM.
## Design relationships
@@ -178,21 +185,22 @@ Tooltip.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------ |
-| FR1, AR2 | `Heading.test.tsx` level and `accessibilityLevel` tests | Levels 1–6; differing and equal override | A wrong element, a missing `aria-level` for a differing override, or an `aria-level` added for an equal one fails. | `audit:Heading/a11y` |
-| FR2 | `Heading.test.tsx` target, type, theme-added type, weight, and omitted-type tests; `extensibleAxes.test.ts`; `HeadingAudit.a11y.chromium.spec.ts` on the AuditMatrix story | Display types, theme-added type, weight | A lost `heading` class or `data-level`, `data-color`, `data-type`, or `data-weight` reflection, a reflected omitted type, or a theme-added type losing its level baseline fails. Display sizes out of order, or an explicit `bold` no heavier than the display default, fails the browser spec. Gap: the level scales and the level default weights have no paint check. | `audit:Heading/theming` |
-| FR3 | Stable visual baseline `core-heading--level-1`; `Heading.stories.tsx`; `HeadingAudit.a11y.chromium.spec.ts` | Level 1 default; secondary color; `center` and `end` alignment | A changed level-1 scale, color, or display comes back changed for review; a `justify` that does not resolve to logical `center` or `end`, or heading text below its WCAG contrast threshold, fails the browser spec. Gap: `display` precedence, `textWrap`, cap-height trim, strikethrough, and the theme-added color baseline have no automated check. | `audit:Heading/behavior` |
-| FR3 (reflow) | `Heading.test.tsx` long unbroken tokens; `TextReflow.a11y.chromium.spec.ts`; `scripts/text-overflow-wrap-anywhere.test.mjs` | A long unbroken token, untruncated and single-line truncated, at 320 CSS px; Text inside CommandPaletteEmpty and Banner | A token that does not wrap in an untruncated heading, a page that scrolls sideways at 320 px, single-line truncation that no longer clips on one line, Text inside CommandPaletteEmpty or Banner that loses the container's `anywhere` wrap or crosses an inline edge, or a Core style that sets `overflow-wrap: anywhere` without passing it to Text, fails. | `audit:Heading/a11y` |
-| FR4, PR1 | `Heading.test.tsx` truncation-measurement tests; `useTruncation.test.tsx`; `HeadingAudit.a11y.chromium.spec.ts` | Tooltip on and off; content change; one and two lines | Measuring with the tooltip off, not measuring with it on, or a missed re-measure fails. A one-line heading without its ellipsis, a two-line clamp that does not hold two lines, or a clipped heading whose hover shows no full-text tooltip fails the browser spec. Gap: the `wordBreak` defaults and the tooltip placement have no automated check. | `audit:Heading/behavior` |
-| FR5 | `Heading.test.tsx` ref, `id`, passthrough, `aria-level` precedence, styling-input, and line-clamp tests | Rerender; `id`; `data-testid`; caller `aria-level`; `className`, `xstyle`, and `style` | A detached ref, a lost `id` or test id, a derived `aria-level` that overrides the caller's, a `className` or `xstyle` that is dropped or merges before the component styles, or a caller `WebkitLineClamp` that replaces the clamp fails. | `audit:Heading/behavior` |
-| AR1 | `Heading.test.tsx` display-type element tests | Levels with display and theme-added types | A visual type that changes the element fails. | `audit:Heading/a11y` |
-| AR3 | `Heading.test.tsx` truncation title test; `HeadingAudit.a11y.chromium.spec.ts` | Truncated heading | A native `title` on a truncated heading fails both. | `audit:Heading/a11y` |
-| AR1, AR2 | `HeadingAudit.a11y.chromium.spec.ts` reading Chromium's accessibility tree (`spec:AST-009` FR3) | Levels, equal and differing override, display types | A heading exposed with a role or level other than its element or `aria-level` requires fails the browser spec. | `audit:Heading/a11y` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------ |
+| FR1, AR2 | `Heading.test.tsx` level and `accessibilityLevel` tests | Levels 1–6; differing and equal override | A wrong element, a missing `aria-level` for a differing override, or an `aria-level` added for an equal one fails. | `audit:Heading/a11y` |
+| FR2 | `Heading.test.tsx` target, type, theme-added type, weight, and omitted-type tests; `extensibleAxes.test.ts`; `HeadingAudit.a11y.chromium.spec.ts` on the AuditMatrix story | Display types, theme-added type, weight | A lost `heading` class or `data-level`, `data-color`, `data-type`, or `data-weight` reflection, a reflected omitted type, or a theme-added type losing its level baseline fails. Display sizes out of order, or an explicit `bold` no heavier than the display default, fails the browser spec. Gap: the level scales and the level default weights have no paint check. | `audit:Heading/theming` |
+| FR3 | Stable visual baseline `core-heading--level-1`; `Heading.stories.tsx`; `HeadingAudit.a11y.chromium.spec.ts` | Level 1 default; secondary color; `center` and `end` alignment | A changed level-1 scale, color, or display comes back changed for review; a `justify` that does not resolve to logical `center` or `end`, or heading text below its WCAG contrast threshold, fails the browser spec. Gap: `display` precedence, `textWrap`, cap-height trim, strikethrough, and the theme-added color baseline have no automated check. | `audit:Heading/behavior` |
+| FR3 (reflow) | `Heading.test.tsx` long unbroken tokens; `TextReflow.a11y.chromium.spec.ts`; `scripts/text-overflow-wrap-anywhere.test.mjs` | A long unbroken token, untruncated and single-line truncated, at 320 CSS px; Text inside CommandPaletteEmpty and Banner | A token that does not wrap in an untruncated heading, a page that scrolls sideways at 320 px, single-line truncation that no longer clips on one line, Text inside CommandPaletteEmpty or Banner that loses the container's `anywhere` wrap or crosses an inline edge, or a Core style that sets `overflow-wrap: anywhere` without passing it to Text, fails. | `audit:Heading/a11y` |
+| FR4, PR1 | `Heading.test.tsx` truncation-measurement tests; `useTruncation.test.tsx`; `HeadingAudit.a11y.chromium.spec.ts` | Tooltip on and off; content change; one and two lines | Measuring with the tooltip off, not measuring with it on, or a missed re-measure fails. A one-line heading without its ellipsis, a two-line clamp that does not hold two lines, or a clipped heading whose hover shows no full-text tooltip fails the browser spec. Gap: the `wordBreak` defaults and the tooltip placement have no automated check. | `audit:Heading/behavior` |
+| AR3 (tooltip mount), PR1 | `Heading.test.tsx` "the truncation tooltip mounts on the first interaction" case: no tooltip layer before any interaction, one on the first hover; the shared mount behavior is covered by the `Text.test.tsx` cases, since Text and Heading share `TruncationTooltip` | Truncated before and after the first hover, tap, or focus | A tooltip layer or description before the first interaction, or a first hover, tap or focus that does not open the Tooltip by its own rules, fails. Gap: no accessibility-tree check of the description (`spec:AST-009` FR3). | `audit:Heading/a11y` |
+| FR5 | `Heading.test.tsx` ref, `id`, passthrough, `aria-level` precedence, styling-input, and line-clamp tests | Rerender; `id`; `data-testid`; caller `aria-level`; `className`, `xstyle`, and `style` | A detached ref, a lost `id` or test id, a derived `aria-level` that overrides the caller's, a `className` or `xstyle` that is dropped or merges before the component styles, or a caller `WebkitLineClamp` that replaces the clamp fails. | `audit:Heading/behavior` |
+| AR1 | `Heading.test.tsx` display-type element tests | Levels with display and theme-added types | A visual type that changes the element fails. | `audit:Heading/a11y` |
+| AR3 | `Heading.test.tsx` truncation title test; `HeadingAudit.a11y.chromium.spec.ts` | Truncated heading | A native `title` on a truncated heading fails both. | `audit:Heading/a11y` |
+| AR1, AR2 | `HeadingAudit.a11y.chromium.spec.ts` reading Chromium's accessibility tree (`spec:AST-009` FR3) | Levels, equal and differing override, display types | A heading exposed with a role or level other than its element or `aria-level` requires fails the browser spec. | `audit:Heading/a11y` |
## Decision log
-None recorded. The record describes shipped behavior.
+None recorded.
## Open questions
diff --git a/docs/specs/components/Text/Text.spec.md b/docs/specs/components/Text/Text.spec.md
index 50bf24357a..c17702a085 100644
--- a/docs/specs/components/Text/Text.spec.md
+++ b/docs/specs/components/Text/Text.spec.md
@@ -33,15 +33,15 @@ system_specs: [spec:AST-009]
## Contract at a glance
-| Area | Contract |
-| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Public contract | A polymorphic text element with a semantic `type`, optional `size`, `color`, and `weight` overrides, an `as` element choice, and the text layout controls documented in `Text.doc.mjs`. |
-| Behavior | `type` sets size, weight, and default color from the theme; theme-added types and colors fall back to the body and primary baselines; truncated text offers its full content in a Tooltip. |
-| End-user impact | Readers get consistent type across the product; clamped text keeps its full content available on hover and in the DOM. |
-| Builder impact | A long unbroken token in non-truncated Text wraps. Inside a flex row, the flex child needs `min-width: 0` for the wrap to apply, and a caller's own container that sets `overflow-wrap: anywhere` does not reach Text's text; Core's `anywhere` containers pass their wrap to it. |
-| Compatibility/readiness | Released behavior recorded as current, with one styling output change: non-truncated Text sets `overflow-wrap` (`break-word`, or `anywhere` inside Core's `anywhere` containers). No API change. One implementation gap is listed under Current-state impact. |
-| Review checks | Reject a theme-added type or color that renders unstyled, a native `title` beside the truncation Tooltip, or measurement when the tooltip is off. |
-| Governing rules | `architecture:component-theming-surface/INV6,INV14`; `architecture:public-component-api/INV5,INV6,INV8`. |
+| Area | Contract |
+| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | A polymorphic text element with a semantic `type`, optional `size`, `color`, and `weight` overrides, an `as` element choice, and the text layout controls documented in `Text.doc.mjs`. |
+| Behavior | `type` sets size, weight, and default color from the theme; theme-added types and colors fall back to the body and primary baselines; truncated text offers its full content in a Tooltip. |
+| End-user impact | Readers get consistent type across the product; clamped text keeps its full content available on hover and in the DOM. |
+| Builder impact | A long unbroken token in non-truncated Text wraps. Inside a flex row, the flex child needs `min-width: 0` for the wrap to apply, and a caller's own container that sets `overflow-wrap: anywhere` does not reach Text's text; Core's `anywhere` containers pass their wrap to it. The truncation Tooltip mounts on the first hover, completed tap or focus (AR2). |
+| Compatibility/readiness | Released behavior recorded as current, with one styling output change and one DOM change: non-truncated Text sets `overflow-wrap` (`break-word`, or `anywhere` inside Core's `anywhere` containers). The truncation Tooltip mounts on the first hover, completed tap or focus, so until then a clamped Text has no tooltip layer and no `aria-describedby` (AR2). No API change. One implementation gap is listed under Current-state impact. |
+| Review checks | Reject a theme-added type or color that renders unstyled, a native `title` beside the truncation Tooltip, or measurement when the tooltip is off. |
+| Governing rules | `architecture:component-theming-surface/INV6,INV14`; `architecture:public-component-api/INV5,INV6,INV8`. |
This table is a review projection; the body below is authoritative.
@@ -55,10 +55,12 @@ the truncation behavior of that element. Heading is documented beside Text in
## Compatibility and migration
- Released default preserved: `yes`
-- Compatibility class: one styling output change, with no public prop,
- default, or DOM change: non-truncated Text sets `overflow-wrap`
+- Compatibility class: one styling output change and one DOM change, with
+ no public prop or default change: non-truncated Text sets `overflow-wrap`
(`break-word`, or `anywhere` inside Core's `anywhere` containers), so a long
- unbroken token wraps (FR3)
+ unbroken token wraps (FR3). The truncation Tooltip mounts on the first
+ hover, completed tap or focus (AR2): before that, a clamped Text has no closed
+ tooltip layer and no tooltip description in the DOM
- Controlled/uncontrolled behavior: not applicable
- Migration decision: none
@@ -123,13 +125,13 @@ Consumer migration instructions belong in consumer docs and release notes.
### Representative states
-| State | Required invariant | Allowed variation |
-| ----------------------- | ------------------------------------------------------- | ----------------- |
-| Default | `span` with body type and primary color. | Content. |
-| Supporting | Supporting type with secondary color. | Color override. |
-| Theme-added type | Body baseline; `data-type` names the added type. | Theme paint. |
-| Truncated with tooltip | Clamped element anchors one Tooltip; no native `title`. | Placement. |
-| Truncation, tooltip off | Clamped element; no measurement; no Tooltip. | — |
+| State | Required invariant | Allowed variation |
+| ----------------------- | ----------------------------------------------------------------------------------------------------------- | ----------------- |
+| Default | `span` with body type and primary color. | Content. |
+| Supporting | Supporting type with secondary color. | Color override. |
+| Theme-added type | Body baseline; `data-type` names the added type. | Theme paint. |
+| Truncated with tooltip | Clamped element anchors one Tooltip, mounted on the first hover, completed tap or focus; no native `title`. | Placement. |
+| Truncation, tooltip off | Clamped element; no measurement; no Tooltip. | — |
### Transformation and precedence order
@@ -145,7 +147,9 @@ Consumer migration instructions belong in consumer docs and release notes.
- **PR1 — Measured only when needed.** Truncation is measured only when
`maxLines` is positive and the tooltip is enabled; re-measuring follows size
and content changes without a per-element observer; the Tooltip module loads
- only when the text is truncated.
+ only when the text is truncated, and the Tooltip itself mounts only on the
+ first hover, completed tap or focus, so until that first interaction a page of
+ clamped text mounts no closed tooltip layers.
## Accessibility contract
@@ -154,7 +158,10 @@ Consumer migration instructions belong in consumer docs and release notes.
`component:Heading`.
- **AR2 — Truncated text.** The full text stays in the element's DOM; the
truncation Tooltip is the only tooltip, and any description it adds is
- Tooltip's.
+ Tooltip's. The Tooltip mounts on the first hover, completed tap or focus on the
+ clamped element, and that interaction opens it as it would once
+ mounted, by Tooltip's own rules (Tooltip FR3–FR5); until then the element
+ carries no tooltip description, since its full text is already in its DOM.
## Design relationships
@@ -180,18 +187,19 @@ record declares no anatomy-theming block rather than assign `heading` to Text.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------- | ------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- |
-| FR1, AR1 | `Text.test.tsx` element, target, and reflection tests | Default `span`; `p`, `div`, `label` | A wrong element, a lost `text` class, or a lost `data-type`, `data-size`, or `data-color` reflection fails. Gap: no test asserts that Text adds no role, and no accessibility-tree check proves the element's role (`spec:AST-009` FR3). | `audit:Text/behavior` |
-| FR2 | `Text.test.tsx` theme-added type and color tests; stable visual baseline `core-text--body` | Theme-added type and color; built-in color; body default | A theme-added type or color losing its reflection, a theme-added color losing its primary baseline, or a lost color override, fails; a changed body scale or color comes back changed for review. Gap: no test asserts a theme-added type's body baseline (the custom-type test checks only the class and `data-type`), and the built-in type tests assert presence only, so each type's size, line height, and weight, and the `size` and `weight` overrides in paint, have no automated check. Each type's default color and a built-in color's paint also have no automated check; the color tests assert `data-color` only. | `audit:Text/theming` |
-| FR3 | `Text.stories.tsx` | Display, cap-height trim, wrap, strikethrough, tabular numbers | Gap: the prop tests assert presence only, so `display` precedence, `justify`, and every text treatment have no automated check. | `audit:Text/behavior` |
-| FR3 (reflow) | `Text.test.tsx` long unbroken tokens; `TextReflow.a11y.chromium.spec.ts`; `scripts/text-overflow-wrap-anywhere.test.mjs` | A long unbroken token, inline and block, untruncated and single-line truncated, at 320 CSS px; Text inside CommandPaletteEmpty and Banner | A token that does not wrap in untruncated text, a page that scrolls sideways at 320 px, single-line truncation that no longer clips on one line, Text inside CommandPaletteEmpty or Banner that loses the container's `anywhere` wrap or crosses an inline edge, or a Core style that sets `overflow-wrap: anywhere` without passing it to Text, fails. | `audit:Text/a11y` |
-| FR4, AR2, PR1 | `Text.test.tsx` native-title and truncation-measurement tests; `useTruncation.test.tsx` | Truncated with tooltip; tooltip off; content change | A native `title`, measuring with the tooltip off, not measuring with it on, or a missed re-measure fails. Gap: the ellipsis and line clamp, the `wordBreak` defaults, and the tooltip's appearance and placement have no automated check. | `audit:Text/a11y` |
-| FR5 | `Text.test.tsx` ref and passthrough tests | Rerender; `data-testid` | A detached ref or a lost test id fails. Gap: no test covers other DOM passthrough, the styling-input merge order, or the line clamp after `style`. | `audit:Text/behavior` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- |
+| FR1, AR1 | `Text.test.tsx` element, target, and reflection tests | Default `span`; `p`, `div`, `label` | A wrong element, a lost `text` class, or a lost `data-type`, `data-size`, or `data-color` reflection fails. Gap: no test asserts that Text adds no role, and no accessibility-tree check proves the element's role (`spec:AST-009` FR3). | `audit:Text/behavior` |
+| FR2 | `Text.test.tsx` theme-added type and color tests; stable visual baseline `core-text--body` | Theme-added type and color; built-in color; body default | A theme-added type or color losing its reflection, a theme-added color losing its primary baseline, or a lost color override, fails; a changed body scale or color comes back changed for review. Gap: no test asserts a theme-added type's body baseline (the custom-type test checks only the class and `data-type`), and the built-in type tests assert presence only, so each type's size, line height, and weight, and the `size` and `weight` overrides in paint, have no automated check. Each type's default color and a built-in color's paint also have no automated check; the color tests assert `data-color` only. | `audit:Text/theming` |
+| FR3 | `Text.stories.tsx` | Display, cap-height trim, wrap, strikethrough, tabular numbers | Gap: the prop tests assert presence only, so `display` precedence, `justify`, and every text treatment have no automated check. | `audit:Text/behavior` |
+| FR3 (reflow) | `Text.test.tsx` long unbroken tokens; `TextReflow.a11y.chromium.spec.ts`; `scripts/text-overflow-wrap-anywhere.test.mjs` | A long unbroken token, inline and block, untruncated and single-line truncated, at 320 CSS px; Text inside CommandPaletteEmpty and Banner | A token that does not wrap in untruncated text, a page that scrolls sideways at 320 px, single-line truncation that no longer clips on one line, Text inside CommandPaletteEmpty or Banner that loses the container's `anywhere` wrap or crosses an inline edge, or a Core style that sets `overflow-wrap: anywhere` without passing it to Text, fails. | `audit:Text/a11y` |
+| FR4, AR2, PR1 | `Text.test.tsx` native-title and truncation-measurement tests; `useTruncation.test.tsx` | Truncated with tooltip; tooltip off; content change | A native `title`, measuring with the tooltip off, not measuring with it on, or a missed re-measure fails. Gap: the ellipsis and line clamp, the `wordBreak` defaults, and the tooltip's appearance and placement have no automated check. | `audit:Text/a11y` |
+| AR2 (tooltip mount), PR1 | `Text.test.tsx` "the truncation tooltip mounts on the first interaction" cases: no tooltip layer or description before any interaction; the first hover mounts it and opens it after the hover delay; a pointer that leaves first opens nothing; the tap that mounts it opens it and a tap outside closes it; a touch that becomes a scroll mounts nothing; focus inside the clamped element mounts it; a caller's `preventDefault` does not stop the mount. Real-browser mount count on the `ManyTruncatedRows` story (500 rows: no tooltip layers at load) | Truncated before and after the first hover, tap, or focus | A tooltip layer or description before the first interaction, or a first hover, tap or focus that does not open the Tooltip by its own rules, fails. Gap: no accessibility-tree check of the description (`spec:AST-009` FR3). | `audit:Text/a11y` |
+| FR5 | `Text.test.tsx` ref and passthrough tests | Rerender; `data-testid` | A detached ref or a lost test id fails. Gap: no test covers other DOM passthrough, the styling-input merge order, or the line clamp after `style`. | `audit:Text/behavior` |
## Decision log
-None recorded. The record describes shipped behavior.
+None recorded.
## Open questions
diff --git a/packages/core/src/DropdownMenu/lazyMenuBottomSheet.ts b/packages/core/src/DropdownMenu/lazyMenuBottomSheet.ts
index 00971419ad..785e216bb0 100644
--- a/packages/core/src/DropdownMenu/lazyMenuBottomSheet.ts
+++ b/packages/core/src/DropdownMenu/lazyMenuBottomSheet.ts
@@ -35,6 +35,7 @@ import {
type ReactElement,
} from 'react';
import {useIsHydrating} from '../hooks/useIsHydrating';
+import {createModuleLoader} from '../utils/moduleLoader';
import type {MenuBottomSheet as EagerMenuBottomSheet} from './MenuBottomSheet';
import type {MenuBottomSheetActionList as EagerMenuBottomSheetActionList} from './MenuBottomSheetActionList';
import type * as ActionListModule from './MenuBottomSheetActionList';
@@ -49,23 +50,10 @@ const LazyMenuBottomSheet = lazy(async () =>
// closed, so its first render is the first open. Once preloaded, it renders
// directly instead of through lazy(): a suspended render on open would hold
// the rows back (React delays revealing them for up to 300ms).
-let actionListModule: typeof ActionListModule | null = null;
-let actionListLoad: Promise<typeof ActionListModule> | null = null;
-async function loadActionList(): Promise<typeof ActionListModule> {
- actionListLoad ??= import('./MenuBottomSheetActionList').then(
- module => {
- actionListModule = module;
- return module;
- },
- (error: unknown) => {
- // A failed load (a dropped connection) is not kept: the next caller
- // asks the module loader again.
- actionListLoad = null;
- throw error;
- },
- );
- return actionListLoad;
-}
+const actionList = createModuleLoader<typeof ActionListModule>(
+ async () => import('./MenuBottomSheetActionList'),
+);
+const loadActionList = actionList.load;
/** What a preload of the action list came to: loaded, or failed with the loader's error. */
export type ActionListPreload =
@@ -113,7 +101,7 @@ export function MenuBottomSheetActionList(
// Chosen once per mount, so a module that arrives later never swaps the
// rendered list (which would remount it and drop focus).
const [LoadedActionList] = useState(
- () => actionListModule?.MenuBottomSheetActionList ?? null,
+ () => actionList.loaded()?.MenuBottomSheetActionList ?? null,
);
if (useIsHydrating()) {
return null;
diff --git a/packages/core/src/Heading/Heading.test.tsx b/packages/core/src/Heading/Heading.test.tsx
index 89da9f0b0a..6f7e32bec2 100644
--- a/packages/core/src/Heading/Heading.test.tsx
+++ b/packages/core/src/Heading/Heading.test.tsx
@@ -7,9 +7,11 @@
import * as stylex from '@stylexjs/stylex';
import {typeScaleVars} from '../theme/tokens.stylex';
-import {act, render, screen} from '@testing-library/react';
+import {act, fireEvent, render, screen, waitFor} from '@testing-library/react';
import {describe, it, expect, vi} from 'vitest';
import {Heading} from './Heading';
+// Loaded up front, so the truncation tooltip's lazy import resolves at once.
+import '../Tooltip/Tooltip';
const headingStyles = stylex.create({
// Overrides a property Heading's own level styles set, so the consumer
@@ -465,3 +467,64 @@ describe('Heading outline, passthrough, and styling-input precedence', () => {
}
});
});
+
+// A truncated Heading mounts its tooltip on the first interaction, as Text does.
+describe('the truncation tooltip mounts on the first interaction', () => {
+ const TITLE = 'A heading far wider than the space it has been given';
+
+ function withOverflowAndPopover() {
+ const proto = window.HTMLElement.prototype;
+ const original = {
+ scrollWidth: Object.getOwnPropertyDescriptor(proto, 'scrollWidth'),
+ offsetWidth: Object.getOwnPropertyDescriptor(proto, 'offsetWidth'),
+ showPopover: proto.showPopover,
+ };
+ Object.defineProperty(proto, 'scrollWidth', {
+ configurable: true,
+ get: () => 400,
+ });
+ Object.defineProperty(proto, 'offsetWidth', {
+ configurable: true,
+ get: () => 100,
+ });
+ const showPopover = vi.fn();
+ proto.showPopover = showPopover;
+ return {
+ showPopover,
+ restore: () => {
+ if (original.scrollWidth) {
+ Object.defineProperty(proto, 'scrollWidth', original.scrollWidth);
+ }
+ if (original.offsetWidth) {
+ Object.defineProperty(proto, 'offsetWidth', original.offsetWidth);
+ }
+ proto.showPopover = original.showPopover;
+ },
+ };
+ }
+
+ it('mounts no tooltip layer before any interaction, and one on the first hover', async () => {
+ const {showPopover, restore} = withOverflowAndPopover();
+ try {
+ render(
+ <Heading level={2} maxLines={1}>
+ {TITLE}
+ </Heading>,
+ );
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 300));
+ });
+ expect(screen.queryByRole('tooltip', {hidden: true})).toBeNull();
+
+ fireEvent.pointerEnter(screen.getByText(TITLE), {pointerType: 'mouse'});
+ await waitFor(
+ () => {
+ expect(showPopover).toHaveBeenCalled();
+ },
+ {timeout: 3000},
+ );
+ } finally {
+ restore();
+ }
+ });
+});
diff --git a/packages/core/src/Heading/Heading.tsx b/packages/core/src/Heading/Heading.tsx
index 564490a3a8..de84c5ad97 100644
--- a/packages/core/src/Heading/Heading.tsx
+++ b/packages/core/src/Heading/Heading.tsx
@@ -19,7 +19,7 @@
* - /packages/cli/assets/templates/blocks/components/Text/ (showcase blocks)
*/
-import {lazy, Suspense, useRef, type ReactNode} from 'react';
+import {useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {
TextColor,
@@ -45,6 +45,11 @@ import {
truncationTooltipStyles,
} from '../Text/text.stylex';
import {useTruncation} from '../Text/useTruncation';
+import {
+ TruncationTooltip,
+ useTruncationTooltipInterest,
+} from '../Text/TruncationTooltip';
+import {composeEventHandlers} from '../utils/composeEventHandlers';
import {resolveStyleColor} from '../Text/Text';
import type {LayerPlacement} from '../Layer';
import {mergeProps} from '../utils/mergeProps';
@@ -53,10 +58,6 @@ import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
import type {HeadingTypeMap} from './index';
-const LazyXDSTooltip = lazy(async () =>
- import('../Tooltip/Tooltip').then(mod => ({default: mod.Tooltip})),
-);
-
/**
* Heading level (1-6). Determines both visual styling and semantic HTML element.
*/
@@ -267,6 +268,8 @@ export function Heading({
typeof hasTruncateTooltip === 'string' ? hasTruncateTooltip : 'above';
const tooltipEnabled =
maxLines > 0 && hasTruncateTooltip !== false && truncation.isTruncated;
+ // The tooltip mounts on the first hover, tap or focus, not with the text.
+ const tooltipInterest = useTruncationTooltipInterest(tooltipEnabled);
// Ref for the heading element (used as tooltip anchor)
const headingRef = useRef<HTMLHeadingElement>(null);
@@ -318,21 +321,34 @@ export function Heading({
{...style, ...inlineStyle},
)}
{...ariaProps}
- {...props}>
+ {...props}
+ onPointerEnter={composeEventHandlers(
+ tooltipInterest.onPointerEnter,
+ props.onPointerEnter,
+ )}
+ onPointerLeave={composeEventHandlers(
+ tooltipInterest.onPointerLeave,
+ props.onPointerLeave,
+ )}
+ onPointerDown={composeEventHandlers(
+ tooltipInterest.onPointerDown,
+ props.onPointerDown,
+ )}
+ onFocus={composeEventHandlers(tooltipInterest.onFocus, props.onFocus)}
+ onBlur={composeEventHandlers(tooltipInterest.onBlur, props.onBlur)}>
{children}
</Component>
- {tooltipEnabled && (
- <Suspense fallback={null}>
- <LazyXDSTooltip
- anchorRef={headingRef}
- content={
- <span {...stylex.props(truncationTooltipStyles.content)}>
- {truncation.fullText}
- </span>
- }
- placement={tooltipPlacement}
- />
- </Suspense>
+ {tooltipEnabled && tooltipInterest.isWanted && (
+ <TruncationTooltip
+ anchorRef={headingRef}
+ content={
+ <span {...stylex.props(truncationTooltipStyles.content)}>
+ {truncation.fullText}
+ </span>
+ }
+ placement={tooltipPlacement}
+ interest={tooltipInterest}
+ />
)}
</>
);
diff --git a/packages/core/src/Layer/useTouchTrigger.ts b/packages/core/src/Layer/useTouchTrigger.ts
index 3f290ceb0d..f4ff46b775 100644
--- a/packages/core/src/Layer/useTouchTrigger.ts
+++ b/packages/core/src/Layer/useTouchTrigger.ts
@@ -6,7 +6,8 @@
* @file useTouchTrigger.ts
* @input Touch trigger mode, layer open state, trigger ref, show/hide callbacks
* @output Exports useTouchTrigger hook, isActionTrigger, LayerTouchTrigger type,
- * tapLandsOnDisabledControl, TOUCH_POINTER_TYPES and useTapStop (internal:
+ * tapLandsOnDisabledControl, TOUCH_POINTER_TYPES, useTapRecognizer and
+ * useTapStop (internal:
* not re-exported from index). Also useTouchTriggerInternal, with the
* outside dismissal's arm for useTooltip's hold (Core-internal).
* @position Layer hook; shared touch behavior for useTooltip and useHoverCard
@@ -48,6 +49,7 @@ import {
useCallback,
useEffect,
useRef,
+ useState,
type MouseEvent as ReactMouseEvent,
type PointerEvent as ReactPointerEvent,
type RefObject,
@@ -80,6 +82,72 @@ export type LayerTouchTrigger = 'auto' | 'tap' | 'none';
*/
export const TOUCH_POINTER_TYPES = new Set(['touch', 'pen']);
+/** Waits for the tap that a touch or pen press may become. Internal. */
+export interface TapRecognizer {
+ /**
+ * Call on every press. A touch or pen press on `trigger` waits for its tap:
+ * the press's own `click`. A touch the browser takes for a scroll or a
+ * pinch (`pointercancel`) is no tap, and a new press replaces one still
+ * waiting. Returns whether the press is touch or pen.
+ */
+ press(
+ event: PointerEvent,
+ trigger: Element | null,
+ onTap: (tapEvent: Event) => void,
+ ): boolean;
+ /** Stops waiting for a press still waiting for its tap. */
+ forget(): void;
+}
+
+/** One tap recognizer for a trigger, released on unmount. Internal. */
+export function useTapRecognizer(): TapRecognizer {
+ const [recognizer] = useState(createTapRecognizer);
+ // Releases a pending tap on unmount.
+ useEffect(() => () => recognizer.forget(), [recognizer]);
+ return recognizer;
+}
+
+function createTapRecognizer(): TapRecognizer {
+ let stopWaiting: (() => void) | null = null;
+ const forget = () => {
+ stopWaiting?.();
+ stopWaiting = null;
+ };
+ return {
+ press(event, trigger, onTap) {
+ forget();
+ if (!TOUCH_POINTER_TYPES.has(event.pointerType)) {
+ return false;
+ }
+ if (trigger == null) {
+ return true;
+ }
+ // The tap must belong to this press. A key press or a new pointer press
+ // advances the gesture, so a keyboard activation that later fires
+ // `click` on the trigger (Enter on a button) is not mistaken for it.
+ const gesture = currentGesture();
+ const stop = () => {
+ trigger.removeEventListener('click', handleTap);
+ trigger.removeEventListener('pointercancel', stop);
+ if (stopWaiting === stop) {
+ stopWaiting = null;
+ }
+ };
+ const handleTap = (tapEvent: Event) => {
+ stop();
+ if (currentGesture() === gesture) {
+ onTap(tapEvent);
+ }
+ };
+ trigger.addEventListener('click', handleTap);
+ trigger.addEventListener('pointercancel', stop);
+ stopWaiting = stop;
+ return true;
+ },
+ forget,
+ };
+}
+
export function useTapStop(event: 'click'): {
onPointerDown: (event: ReactPointerEvent<Element>) => void;
onClick: (event: ReactMouseEvent<Element>) => void;
@@ -296,6 +364,11 @@ export interface UseTouchTriggerInternalReturn extends UseTouchTriggerReturn {
* hold arms it too.
*/
armOutsideDismiss: () => void;
+ /**
+ * Answers a tap the trigger completed before the layer mounted, by the same
+ * rules as a tap it sees, and arms the outside dismissal when it opens.
+ */
+ answerTap: (tapEvent: Event | null) => void;
}
/**
@@ -379,9 +452,7 @@ export function useTouchTriggerInternal(
// The documents the outside dismissal listens on: the page's, and the
// trigger's own when it renders in another document, such as an iframe.
const outsideDocumentsRef = useRef<Document[]>([]);
- // A touch press on the trigger still waiting for its tap: calling it stops
- // waiting. The next press, a cancel, the tap itself or unmounting calls it.
- const forgetPendingTapRef = useRef<(() => void) | null>(null);
+ const tapRecognizer = useTapRecognizer();
const readModality = useInteractionModalityTrackingFor(triggerRef);
@@ -453,9 +524,6 @@ export function useTouchTriggerInternal(
// Releases the outside-dismiss listener on unmount.
useEffect(() => disarmOutsideDismiss, [disarmOutsideDismiss]);
- // Releases a pending tap on unmount.
- useEffect(() => () => forgetPendingTapRef.current?.(), []);
-
const isTouchInteraction = useCallback(
() => isTouchPointerRef.current && readModality() === 'pointer',
[readModality],
@@ -471,12 +539,12 @@ export function useTouchTriggerInternal(
// What a tap on the trigger does. It runs from the tap's `click`, after the
// render that armed it, so it reads the latest props through this ref.
- const answerTapRef = useRef<(tapEvent: Event) => void>(() => {});
- answerTapRef.current = (tapEvent: Event) => {
+ const answerTapRef = useRef<(tapEvent: Event | null) => void>(() => {});
+ answerTapRef.current = (tapEvent: Event | null) => {
const trigger = triggerRef.current;
// A tap that landed in a disabled control is that control's: its reason
// opens. Every other tap is the trigger's to decide.
- const tapped = tapEvent.target instanceof Element ? tapEvent.target : null;
+ const tapped = tapEvent?.target instanceof Element ? tapEvent.target : null;
const mode =
touchTrigger === 'auto'
? tapped != null && tapLandsOnDisabledControl(tapped)
@@ -509,45 +577,20 @@ export function useTouchTriggerInternal(
(event: PointerEvent): boolean => {
const isTouch = TOUCH_POINTER_TYPES.has(event.pointerType);
isTouchPointerRef.current = isTouch;
- // A new press replaces one that never became a tap.
- forgetPendingTapRef.current?.();
-
if (!isTouch || isControlled) {
+ tapRecognizer.forget();
return false;
}
-
const trigger =
event.currentTarget instanceof Element
? event.currentTarget
: triggerRef.current;
- if (trigger == null) {
- return true;
- }
-
- // The tap must belong to this press. A key press or a new pointer press
- // advances the gesture, so a keyboard activation that later fires
- // `click` on the trigger (Enter on a button) is not mistaken for it.
- const gesture = currentGesture();
- const forget = () => {
- trigger.removeEventListener('click', handleTap);
- trigger.removeEventListener('pointercancel', forget);
- if (forgetPendingTapRef.current === forget) {
- forgetPendingTapRef.current = null;
- }
- };
- const handleTap = (tapEvent: Event) => {
- forget();
- if (currentGesture() === gesture) {
- answerTapRef.current(tapEvent);
- }
- };
- trigger.addEventListener('click', handleTap);
- // The browser took the touch for a scroll or a pinch: no tap is coming.
- trigger.addEventListener('pointercancel', forget);
- forgetPendingTapRef.current = forget;
+ tapRecognizer.press(event, trigger, tapEvent =>
+ answerTapRef.current(tapEvent),
+ );
return true;
},
- [isControlled, triggerRef],
+ [isControlled, triggerRef, tapRecognizer],
);
// A layer closed by any other path (Escape, a consumer, the browser) leaves
@@ -563,6 +606,11 @@ export function useTouchTriggerInternal(
wasOpenRef.current = isOpen;
}, [isOpen, disarmOutsideDismiss]);
+ const answerTap = useCallback(
+ (tapEvent: Event | null) => answerTapRef.current(tapEvent),
+ [],
+ );
+
return {
isTouchPointerRef,
isTouchInteraction,
@@ -570,5 +618,6 @@ export function useTouchTriggerInternal(
handlePointerDown,
clearTapOpen: disarmOutsideDismiss,
armOutsideDismiss,
+ answerTap,
};
}
diff --git a/packages/core/src/Text/Text.test.tsx b/packages/core/src/Text/Text.test.tsx
index ae3365aea7..6e459bf426 100644
--- a/packages/core/src/Text/Text.test.tsx
+++ b/packages/core/src/Text/Text.test.tsx
@@ -5,9 +5,12 @@
* Tests for Text component
*/
-import {render, screen} from '@testing-library/react';
+import {act, fireEvent, render, screen, waitFor} from '@testing-library/react';
import {describe, it, expect, vi} from 'vitest';
+import userEvent from '@testing-library/user-event';
import {Text} from './Text';
+// Loaded up front, so the truncation tooltip's lazy import resolves at once.
+import '../Tooltip/Tooltip';
import type {TextType} from './Text';
import type {TextColor} from '../theme/types';
@@ -470,3 +473,340 @@ describe('Text keeps its children mounted when maxLines changes', () => {
expect(screen.getByRole('textbox', {name: 'Note'})).toBe(input);
});
});
+
+// A page of truncated text mounted one closed tooltip layer per element at
+// load. The tooltip now mounts on the first hover, tap or focus, and that
+// interaction opens it as it would once mounted.
+describe('the truncation tooltip mounts on the first interaction', () => {
+ const LABEL = 'A label far wider than the space it has been given';
+
+ function withOverflowAndPopover() {
+ const proto = window.HTMLElement.prototype;
+ const original = {
+ scrollWidth: Object.getOwnPropertyDescriptor(proto, 'scrollWidth'),
+ offsetWidth: Object.getOwnPropertyDescriptor(proto, 'offsetWidth'),
+ showPopover: proto.showPopover,
+ hidePopover: proto.hidePopover,
+ };
+ Object.defineProperty(proto, 'scrollWidth', {
+ configurable: true,
+ get: () => 400,
+ });
+ Object.defineProperty(proto, 'offsetWidth', {
+ configurable: true,
+ get: () => 100,
+ });
+ const showPopover = vi.fn();
+ const hidePopover = vi.fn();
+ proto.showPopover = showPopover;
+ proto.hidePopover = hidePopover;
+ return {
+ showPopover,
+ hidePopover,
+ restore: () => {
+ if (original.scrollWidth) {
+ Object.defineProperty(proto, 'scrollWidth', original.scrollWidth);
+ }
+ if (original.offsetWidth) {
+ Object.defineProperty(proto, 'offsetWidth', original.offsetWidth);
+ }
+ proto.showPopover = original.showPopover;
+ proto.hidePopover = original.hidePopover;
+ },
+ };
+ }
+
+ it('mounts no tooltip layer and no description before any interaction', async () => {
+ const {restore} = withOverflowAndPopover();
+ try {
+ render(
+ <Text type="body" maxLines={1}>
+ {LABEL}
+ </Text>,
+ );
+ // Let a lazily loaded tooltip settle, if one were mounting.
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 300));
+ });
+ expect(screen.queryByRole('tooltip', {hidden: true})).toBeNull();
+ expect(screen.getByText(LABEL)).not.toHaveAttribute('aria-describedby');
+ } finally {
+ restore();
+ }
+ });
+
+ it('mounts the tooltip on the first hover and opens it after the hover delay', async () => {
+ const {showPopover, restore} = withOverflowAndPopover();
+ try {
+ render(
+ <Text type="body" maxLines={1}>
+ {LABEL}
+ </Text>,
+ );
+ const text = screen.getByText(LABEL);
+ fireEvent.pointerEnter(text, {pointerType: 'mouse'});
+ await waitFor(
+ () => {
+ expect(screen.queryByRole('tooltip', {hidden: true})).not.toBeNull();
+ },
+ {timeout: 3000},
+ );
+ await waitFor(
+ () => {
+ expect(showPopover).toHaveBeenCalled();
+ },
+ {timeout: 3000},
+ );
+ expect(text.getAttribute('aria-describedby')).toBe(
+ screen.getByRole('tooltip', {hidden: true}).id,
+ );
+ } finally {
+ restore();
+ }
+ });
+
+ it('opens on the first hover after the hover delay, not later', async () => {
+ const {showPopover, restore} = withOverflowAndPopover();
+ try {
+ render(
+ <Text type="body" maxLines={1}>
+ {LABEL}
+ </Text>,
+ );
+ // Truncation is measured and the Tooltip module loads.
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 50));
+ });
+ vi.useFakeTimers();
+ const text = screen.getByText(LABEL);
+ act(() => {
+ fireEvent.pointerEnter(text, {pointerType: 'mouse'});
+ fireEvent.mouseEnter(text);
+ });
+ act(() => {
+ vi.advanceTimersByTime(199);
+ });
+ expect(showPopover).not.toHaveBeenCalled();
+ act(() => {
+ vi.advanceTimersByTime(1);
+ });
+ expect(showPopover).toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ restore();
+ }
+ });
+
+ it('opens no tooltip when the pointer leaves before the hover delay ends', async () => {
+ const {showPopover, restore} = withOverflowAndPopover();
+ try {
+ render(
+ <Text type="body" maxLines={1}>
+ {LABEL}
+ </Text>,
+ );
+ const text = screen.getByText(LABEL);
+ fireEvent.pointerEnter(text, {pointerType: 'mouse'});
+ // A browser follows a mouse's pointerleave with mouseleave.
+ fireEvent.pointerLeave(text, {pointerType: 'mouse'});
+ fireEvent.mouseLeave(text);
+ await waitFor(
+ () => {
+ expect(screen.queryByRole('tooltip', {hidden: true})).not.toBeNull();
+ },
+ {timeout: 3000},
+ );
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 300));
+ });
+ expect(showPopover).not.toHaveBeenCalled();
+ } finally {
+ restore();
+ }
+ });
+
+ // A finger's arrival is not yet a tap: only the tap's click mounts the
+ // tooltip, and the touch trigger answers it, arming the outside dismissal.
+ function tap(element: Element) {
+ fireEvent.pointerDown(element, {pointerType: 'touch'});
+ fireEvent.pointerUp(element, {pointerType: 'touch'});
+ fireEvent.click(element);
+ }
+
+ it('opens on the tap that mounts it, and a tap outside closes it', async () => {
+ const {showPopover, hidePopover, restore} = withOverflowAndPopover();
+ try {
+ render(
+ <>
+ <Text type="body" maxLines={1}>
+ {LABEL}
+ </Text>
+ <button type="button">Elsewhere</button>
+ </>,
+ );
+ const text = screen.getByText(LABEL);
+ fireEvent.pointerEnter(text, {pointerType: 'touch'});
+ tap(text);
+ await waitFor(
+ () => {
+ expect(showPopover).toHaveBeenCalled();
+ },
+ {timeout: 3000},
+ );
+ tap(screen.getByRole('button', {name: 'Elsewhere'}));
+ await waitFor(
+ () => {
+ expect(hidePopover).toHaveBeenCalled();
+ },
+ {timeout: 3000},
+ );
+ } finally {
+ restore();
+ }
+ });
+
+ // Focus inside the clamped text mounts the tooltip. Whether it then opens
+ // is Tooltip's own focus rule: focus on a descendant of a trigger that is
+ // not itself focusable does not open it.
+ it('mounts on keyboard focus inside the clamped text', async () => {
+ const {restore} = withOverflowAndPopover();
+ try {
+ const user = userEvent.setup();
+ render(
+ <Text type="body" maxLines={1}>
+ <a href="#details">{LABEL}</a>
+ </Text>,
+ );
+ expect(screen.queryByRole('tooltip', {hidden: true})).toBeNull();
+ await user.tab();
+ expect(screen.getByRole('link', {name: LABEL})).toHaveFocus();
+ await waitFor(
+ () => {
+ expect(screen.queryByRole('tooltip', {hidden: true})).not.toBeNull();
+ },
+ {timeout: 3000},
+ );
+ } finally {
+ restore();
+ }
+ });
+
+ it('opens nothing for a click that follows a scroll with no press of its own', async () => {
+ const {showPopover, restore} = withOverflowAndPopover();
+ try {
+ render(
+ <Text type="body" maxLines={1}>
+ {LABEL}
+ </Text>,
+ );
+ const text = screen.getByText(LABEL);
+ fireEvent.pointerDown(text, {pointerType: 'touch'});
+ fireEvent.pointerCancel(text, {pointerType: 'touch'});
+ fireEvent.click(text);
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 300));
+ });
+ expect(showPopover).not.toHaveBeenCalled();
+ } finally {
+ restore();
+ }
+ });
+
+ it("still mounts on a tap when the caller's handlers prevent the default", async () => {
+ const {showPopover, restore} = withOverflowAndPopover();
+ try {
+ render(
+ <Text
+ type="body"
+ maxLines={1}
+ onPointerDown={event => event.preventDefault()}
+ onClick={event => event.preventDefault()}>
+ {LABEL}
+ </Text>,
+ );
+ tap(screen.getByText(LABEL));
+ await waitFor(
+ () => {
+ expect(showPopover).toHaveBeenCalled();
+ },
+ {timeout: 3000},
+ );
+ } finally {
+ restore();
+ }
+ });
+
+ it('opens for a mouse that leaves and comes back before the tooltip mounts', async () => {
+ const {showPopover, restore} = withOverflowAndPopover();
+ try {
+ render(
+ <Text type="body" maxLines={1}>
+ {LABEL}
+ </Text>,
+ );
+ const text = screen.getByText(LABEL);
+ // A browser follows each pointer event of a mouse with its mouse event.
+ fireEvent.pointerEnter(text, {pointerType: 'mouse'});
+ fireEvent.mouseEnter(text);
+ fireEvent.pointerLeave(text, {pointerType: 'mouse'});
+ fireEvent.mouseLeave(text);
+ fireEvent.pointerEnter(text, {pointerType: 'mouse'});
+ fireEvent.mouseEnter(text);
+ await waitFor(
+ () => {
+ expect(showPopover).toHaveBeenCalled();
+ },
+ {timeout: 3000},
+ );
+ } finally {
+ restore();
+ }
+ });
+
+ it('opens nothing after a mouse press made while the tooltip loads', async () => {
+ const {showPopover, restore} = withOverflowAndPopover();
+ try {
+ render(
+ <Text type="body" maxLines={1}>
+ {LABEL}
+ </Text>,
+ );
+ const text = screen.getByText(LABEL);
+ fireEvent.pointerEnter(text, {pointerType: 'mouse'});
+ fireEvent.pointerDown(text, {pointerType: 'mouse'});
+ await waitFor(
+ () => {
+ expect(screen.queryByRole('tooltip', {hidden: true})).not.toBeNull();
+ },
+ {timeout: 3000},
+ );
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 300));
+ });
+ expect(showPopover).not.toHaveBeenCalled();
+ } finally {
+ restore();
+ }
+ });
+
+ it('mounts nothing for a touch that becomes a scroll', async () => {
+ const {restore} = withOverflowAndPopover();
+ try {
+ render(
+ <Text type="body" maxLines={1}>
+ {LABEL}
+ </Text>,
+ );
+ const text = screen.getByText(LABEL);
+ fireEvent.pointerEnter(text, {pointerType: 'touch'});
+ fireEvent.pointerDown(text, {pointerType: 'touch'});
+ fireEvent.pointerCancel(text, {pointerType: 'touch'});
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 300));
+ });
+ expect(screen.queryByRole('tooltip', {hidden: true})).toBeNull();
+ } finally {
+ restore();
+ }
+ });
+});
diff --git a/packages/core/src/Text/Text.tsx b/packages/core/src/Text/Text.tsx
index 7c4b08f143..2ebc2776ec 100644
--- a/packages/core/src/Text/Text.tsx
+++ b/packages/core/src/Text/Text.tsx
@@ -16,7 +16,7 @@
* - /packages/cli/assets/templates/blocks/components/Text/ (showcase blocks)
*/
-import {lazy, Suspense, use, useRef, type ReactNode} from 'react';
+import {use, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {
TextType,
@@ -47,6 +47,11 @@ import {
truncationTooltipStyles,
} from './text.stylex';
import {useTruncation} from './useTruncation';
+import {
+ TruncationTooltip,
+ useTruncationTooltipInterest,
+} from './TruncationTooltip';
+import {composeEventHandlers} from '../utils/composeEventHandlers';
import type {LayerPlacement} from '../Layer';
import {mergeProps} from '../utils/mergeProps';
import {useMergedRefs} from '../hooks/useMergedRefs';
@@ -54,10 +59,6 @@ import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
import {TextClampContext} from './textClampContext';
-const LazyXDSTooltip = lazy(async () =>
- import('../Tooltip/Tooltip').then(mod => ({default: mod.Tooltip})),
-);
-
export type {TextType, TextSize};
export interface TextProps extends Omit<BaseProps, 'children'> {
@@ -273,6 +274,8 @@ export function Text({
typeof hasTruncateTooltip === 'string' ? hasTruncateTooltip : 'above';
const tooltipEnabled =
maxLines > 0 && hasTruncateTooltip !== false && truncation.isTruncated;
+ // The tooltip mounts on the first hover, tap or focus, not with the text.
+ const tooltipInterest = useTruncationTooltipInterest(tooltipEnabled);
// Ref for the text element (used as tooltip anchor)
const textRef = useRef<HTMLElement>(null);
@@ -321,24 +324,37 @@ export function Text({
className,
{...style, ...inlineStyle},
)}
- {...props}>
+ {...props}
+ onPointerEnter={composeEventHandlers(
+ tooltipInterest.onPointerEnter,
+ props.onPointerEnter,
+ )}
+ onPointerLeave={composeEventHandlers(
+ tooltipInterest.onPointerLeave,
+ props.onPointerLeave,
+ )}
+ onPointerDown={composeEventHandlers(
+ tooltipInterest.onPointerDown,
+ props.onPointerDown,
+ )}
+ onFocus={composeEventHandlers(tooltipInterest.onFocus, props.onFocus)}
+ onBlur={composeEventHandlers(tooltipInterest.onBlur, props.onBlur)}>
{/* Always mounted, so a change of maxLines keeps every child mounted. */}
<TextClampContext value={isClamped || isInClampedText}>
{children}
</TextClampContext>
</Component>
- {tooltipEnabled && (
- <Suspense fallback={null}>
- <LazyXDSTooltip
- anchorRef={textRef}
- content={
- <span {...stylex.props(truncationTooltipStyles.content)}>
- {truncation.fullText}
- </span>
- }
- placement={tooltipPlacement}
- />
- </Suspense>
+ {tooltipEnabled && tooltipInterest.isWanted && (
+ <TruncationTooltip
+ anchorRef={textRef}
+ content={
+ <span {...stylex.props(truncationTooltipStyles.content)}>
+ {truncation.fullText}
+ </span>
+ }
+ placement={tooltipPlacement}
+ interest={tooltipInterest}
+ />
)}
</>
);
diff --git a/packages/core/src/Text/TruncationTooltip.tsx b/packages/core/src/Text/TruncationTooltip.tsx
new file mode 100644
index 0000000000..023b3d7b0a
--- /dev/null
+++ b/packages/core/src/Text/TruncationTooltip.tsx
@@ -0,0 +1,179 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file TruncationTooltip.tsx
+ * @input A truncated element's ref, its full text and the tooltip placement
+ * @output Exports `useTruncationTooltipInterest`, which loads the Tooltip
+ * module once text is truncated and tracks the first hover, tap or focus on
+ * it, and `TruncationTooltip`, the Tooltip that mounts on that interaction
+ * @position Shared by Text and Heading. Until the first interaction a page of
+ * truncated text mounts no tooltip layers, and the tooltip that then mounts
+ * answers that interaction as it would once mounted.
+ */
+
+import {
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+ type FocusEvent,
+ type PointerEvent,
+ type ReactNode,
+ type RefObject,
+} from 'react';
+import type {LayerPlacement} from '../Layer';
+import {createModuleLoader} from '../utils/moduleLoader';
+import type {Tooltip as TooltipType} from '../Tooltip/Tooltip';
+import {useTapRecognizer} from '../Layer/useTouchTrigger';
+import {
+ TooltipPresentInterestContext,
+ type TooltipPresentInterestState,
+} from '../Tooltip/tooltipPresentInterest';
+
+type TooltipComponent = typeof TooltipType;
+
+// The Tooltip module. Once loaded, a tooltip renders from it at once: no
+// boundary suspends, so the first hover's delay starts on the hover.
+const tooltipModule = createModuleLoader(
+ async () => import('../Tooltip/Tooltip'),
+);
+
+export interface TruncationTooltipInterest {
+ /** Whether a hover, tap or focus has reached the element. It stays true. */
+ readonly isWanted: boolean;
+ /** The Tooltip component, once its module has loaded. */
+ readonly tooltip: TooltipComponent | null;
+ /** The interaction that mounted the tooltip, until the tooltip reads it. */
+ readonly interestRef: RefObject<TooltipPresentInterestState>;
+ readonly onPointerEnter: (event: PointerEvent<HTMLElement>) => void;
+ readonly onPointerLeave: (event: PointerEvent<HTMLElement>) => void;
+ readonly onPointerDown: (event: PointerEvent<HTMLElement>) => void;
+ readonly onFocus: (event: FocusEvent<HTMLElement>) => void;
+ readonly onBlur: (event: FocusEvent<HTMLElement>) => void;
+}
+
+/**
+ * Tracks the interaction that mounts a truncated element's tooltip, while
+ * `isEnabled`, until the mounted tooltip reads it. A finger's arrival does not
+ * count: only a press that the touch trigger's recognizer takes for a tap
+ * does. Once the tooltip has read the interaction, its own listeners take
+ * over.
+ */
+export function useTruncationTooltipInterest(
+ isEnabled: boolean,
+): TruncationTooltipInterest {
+ const [isWanted, setIsWanted] = useState(false);
+ const [tooltip, setTooltip] = useState<TooltipComponent | null>(
+ () => tooltipModule.loaded()?.Tooltip ?? null,
+ );
+ // Syncs with the module loader: truncated text loads the Tooltip module, so
+ // the first interaction mounts the tooltip at once.
+ useEffect(() => {
+ if (!isEnabled || tooltip != null) {
+ return;
+ }
+ let isCurrent = true;
+ tooltipModule.load().then(
+ loaded => {
+ if (isCurrent) {
+ setTooltip(() => loaded.Tooltip);
+ }
+ },
+ () => {},
+ );
+ return () => {
+ isCurrent = false;
+ };
+ }, [isEnabled, tooltip]);
+ const interestRef = useRef<TooltipPresentInterestState>({
+ interest: null,
+ tapEvent: null,
+ isRead: false,
+ });
+ const tapRecognizer = useTapRecognizer();
+ const want = useCallback(
+ (interest: 'hover' | 'tap' | 'focus', tapEvent: Event | null = null) => {
+ const state = interestRef.current;
+ if (!isEnabled || state.isRead) {
+ return;
+ }
+ state.interest = interest;
+ state.tapEvent = tapEvent;
+ setIsWanted(true);
+ },
+ [isEnabled],
+ );
+ const forget = useCallback((interest: 'hover' | 'focus') => {
+ const state = interestRef.current;
+ if (!state.isRead && state.interest === interest) {
+ state.interest = null;
+ }
+ }, []);
+ const onPointerEnter = useCallback(
+ (event: PointerEvent<HTMLElement>) => {
+ if (event.pointerType !== 'touch') {
+ want('hover');
+ }
+ },
+ [want],
+ );
+ const onPointerLeave = useCallback(() => forget('hover'), [forget]);
+ const onPointerDown = useCallback(
+ (event: PointerEvent<HTMLElement>) => {
+ if (!isEnabled || interestRef.current.isRead) {
+ tapRecognizer.forget();
+ return;
+ }
+ const isTouch = tapRecognizer.press(
+ event.nativeEvent,
+ event.currentTarget,
+ tapEvent => want('tap', tapEvent),
+ );
+ // A mouse press cancels a hover show, as a mounted tooltip does. A pen
+ // press waits for its tap.
+ if (!isTouch) {
+ forget('hover');
+ }
+ },
+ [isEnabled, tapRecognizer, want, forget],
+ );
+ const onFocus = useCallback(() => want('focus'), [want]);
+ const onBlur = useCallback(() => forget('focus'), [forget]);
+ return {
+ isWanted,
+ tooltip,
+ interestRef,
+ onPointerEnter,
+ onPointerLeave,
+ onPointerDown,
+ onFocus,
+ onBlur,
+ };
+}
+
+/** The truncated element's Tooltip, given the interaction that mounted it. */
+export function TruncationTooltip({
+ anchorRef,
+ content,
+ placement,
+ interest,
+}: {
+ anchorRef: RefObject<HTMLElement | null>;
+ content: ReactNode;
+ placement: LayerPlacement;
+ interest: TruncationTooltipInterest;
+}): ReactNode {
+ // A first interaction before the module loads mounts the tooltip once it
+ // has: the interaction is held until the tooltip reads it.
+ const Tooltip = interest.tooltip;
+ if (Tooltip == null) {
+ return null;
+ }
+ return (
+ <TooltipPresentInterestContext value={interest.interestRef}>
+ <Tooltip anchorRef={anchorRef} content={content} placement={placement} />
+ </TooltipPresentInterestContext>
+ );
+}
diff --git a/packages/core/src/Tooltip/tooltipPresentInterest.ts b/packages/core/src/Tooltip/tooltipPresentInterest.ts
new file mode 100644
index 0000000000..3afa9eb996
--- /dev/null
+++ b/packages/core/src/Tooltip/tooltipPresentInterest.ts
@@ -0,0 +1,38 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file tooltipPresentInterest.ts
+ * @input React createContext
+ * @output Exports `TooltipPresentInterestContext` and its value types: the
+ * interaction on a tooltip's anchor that mounted the tooltip
+ * @position Internal to Core, not exported from the Tooltip entry. A
+ * truncated Text or Heading mounts its tooltip on the first hover, tap or
+ * focus, and provides that interaction here, so the tooltip answers it when
+ * its trigger attaches, as its own listeners would have.
+ */
+
+import {createContext, type RefObject} from 'react';
+
+/**
+ * The interaction on the anchor that mounted the tooltip: a hover from a
+ * mouse or pen still over it, a completed tap, or focus inside it. `null`
+ * when there is none.
+ */
+export type TooltipPresentInterest = 'hover' | 'tap' | 'focus' | null;
+
+/**
+ * Holds the interaction until the tooltip's trigger attaches. The tooltip
+ * reads it once and marks it read, so a later remount opens nothing by itself.
+ */
+export interface TooltipPresentInterestState {
+ interest: TooltipPresentInterest;
+ /** The `click` that completed the tap, for the touch trigger's rules. */
+ tapEvent: Event | null;
+ isRead: boolean;
+}
+
+export const TooltipPresentInterestContext =
+ createContext<RefObject<TooltipPresentInterestState> | null>(null);
+TooltipPresentInterestContext.displayName = 'TooltipPresentInterestContext';
diff --git a/packages/core/src/Tooltip/useTooltip.tsx b/packages/core/src/Tooltip/useTooltip.tsx
index 745b6d0514..cbf9c8e212 100644
--- a/packages/core/src/Tooltip/useTooltip.tsx
+++ b/packages/core/src/Tooltip/useTooltip.tsx
@@ -14,6 +14,7 @@
*/
import {
+ use,
useCallback,
useEffect,
useRef,
@@ -21,6 +22,7 @@ import {
type ReactNode,
type RefCallback,
} from 'react';
+import {TooltipPresentInterestContext} from './tooltipPresentInterest';
import {createTriggerFocusGate, isFocusOnTrigger} from '../utils/triggerFocus';
import * as stylex from '@stylexjs/stylex';
import {
@@ -311,6 +313,8 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
const showTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const hideTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const triggerRef = useRef<HTMLElement | null>(null);
+ // Set only by a Core component that mounts the tooltip on interaction.
+ const presentInterest = use(TooltipPresentInterestContext);
// Whether the tooltip is enabled now, for a show that runs after a render
// (a pending hover show) and for the trigger ref callback.
const isEnabledRef = useRef(isEnabled);
@@ -394,6 +398,7 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
handlePointerDown: handleTouchPointerDown,
clearTapOpen,
armOutsideDismiss,
+ answerTap,
} = useTouchTriggerInternal(
{
touchTrigger,
@@ -683,6 +688,8 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
hideNow,
showNow,
opensOnFocus,
+ presentInterest,
+ answerTap,
});
handlersRef.current = {
handleMouseEnter,
@@ -698,6 +705,8 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
hideNow,
showNow,
opensOnFocus,
+ presentInterest,
+ answerTap,
};
// Removes the attached trigger's listeners (the trigger ref callback's
@@ -775,6 +784,30 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
latest().showNow();
}
+ // This tooltip mounted after the interaction that wants it. It answers
+ // that interaction once, by the same rules as its listeners.
+ const state = latest().presentInterest?.current;
+ const interest = state == null || state.isRead ? null : state.interest;
+ const tapEvent = state?.tapEvent ?? null;
+ if (state != null) {
+ state.isRead = true;
+ }
+ if (isEnabledRef.current && latest().isOpen === undefined) {
+ if (interest === 'hover') {
+ latest().handleMouseEnter();
+ } else if (interest === 'tap') {
+ latest().answerTap(tapEvent);
+ } else if (
+ interest === 'focus' &&
+ latest().focusTrigger !== 'never' &&
+ focused instanceof HTMLElement &&
+ el.contains(focused) &&
+ latest().opensOnFocus(focused, el)
+ ) {
+ latest().showNow();
+ }
+ }
+
const detach = () => {
if (detachTriggerRef.current === detach) {
detachTriggerRef.current = null;
diff --git a/packages/core/src/utils/moduleLoader.ts b/packages/core/src/utils/moduleLoader.ts
new file mode 100644
index 0000000000..b4708a1997
--- /dev/null
+++ b/packages/core/src/utils/moduleLoader.ts
@@ -0,0 +1,47 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file moduleLoader.ts
+ * @input A function that imports a module on demand
+ * @output Exports `createModuleLoader`: one shared load of that module, and
+ * the module once it has loaded
+ * @position Internal utility. A component that loads a module before it is
+ * needed renders the loaded module directly, with no suspended render, so
+ * React does not hold back what it shows.
+ */
+
+/** One module, loaded once on demand. Internal. */
+export interface ModuleLoader<T> {
+ /**
+ * Loads the module, or returns the load already running or done. A failed
+ * load is not kept: the next call asks the module loader again (a loader
+ * that retries then loads it; a browser does not fetch a native module again
+ * once its import failed).
+ */
+ load(): Promise<T>;
+ /** The module once it has loaded, else null. */
+ loaded(): T | null;
+}
+
+export function createModuleLoader<T>(
+ importModule: () => Promise<T>,
+): ModuleLoader<T> {
+ let module: T | null = null;
+ let pending: Promise<T> | null = null;
+ return {
+ async load() {
+ pending ??= importModule().then(
+ loadedModule => {
+ module = loadedModule;
+ return loadedModule;
+ },
+ (error: unknown) => {
+ pending = null;
+ throw error;
+ },
+ );
+ return pending;
+ },
+ loaded: () => module,
+ };
+}