Skip to content

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

TypeScript

feat(core): promote InfoTip from Lab as the info preset over Tooltip's press toggle (#9238)

Christopher Chedeau449486fdcedd
diff --git a/.changeset/promote-infotip-to-core-cli.md b/.changeset/promote-infotip-to-core-cli.md
new file mode 100644
index 0000000000..a1e27f6435
--- /dev/null
+++ b/.changeset/promote-infotip-to-core-cli.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[component] `astryx discover` no longer lists `InfoTip` among the components `@astryxdesign/lab` contributes: InfoTip is a Core component now, described by `astryx component InfoTip`.
+
+@vjeux
diff --git a/.changeset/promote-infotip-to-core.md b/.changeset/promote-infotip-to-core.md
new file mode 100644
index 0000000000..528e7685bf
--- /dev/null
+++ b/.changeset/promote-infotip-to-core.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[component] Promote `InfoTip` from Lab to Core, imported from `@astryxdesign/core/InfoTip` or the package root: an info-icon button whose press pins its help. Hover and keyboard focus preview the help, and a click, tap, Enter, or Space pins it open until Escape, a second press, a press outside, or focus leaving, through Tooltip's `triggerBehavior="toggle"`. Its default name is the translated "More information", and under a coarse pointer it takes taps out toward 44 px without taking a neighbour's. The `@astryxdesign/lab` `InfoTip` export is now a deprecated re-export of the Core component and is removed in the next release: import it from `@astryxdesign/core` instead.
+
+@vjeux
diff --git a/apps/storybook/stories/InfoTip.stories.tsx b/apps/storybook/stories/InfoTip.stories.tsx
index c9aad4bd65..a3c72853b3 100644
--- a/apps/storybook/stories/InfoTip.stories.tsx
+++ b/apps/storybook/stories/InfoTip.stories.tsx
@@ -1,12 +1,12 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import type {Meta, StoryObj} from '@storybook/react';
-import {InfoTip} from '@astryxdesign/lab/InfoTip';
+import {InfoTip} from '@astryxdesign/core/InfoTip';
import {HStack} from '@astryxdesign/core/Layout';
import {Text} from '@astryxdesign/core/Text';
const meta: Meta<typeof InfoTip> = {
- title: 'Lab/InfoTip',
+ title: 'Core/InfoTip',
component: InfoTip,
tags: ['autodocs'],
argTypes: {
@@ -42,11 +42,10 @@ export const NextToALabel: Story = {
};
/**
- * The trigger is a button, so `Tooltip`'s `auto` touch rule would give the tap
- * to the control and suppress the tooltip. `InfoTip` sets `touchTrigger="tap"`
- * because revealing the tooltip is the button's only purpose — tap the icon on
- * a phone (or with touch emulation on) and the tooltip opens; tap outside and
- * it dismisses.
+ * Revealing the help is the button's only purpose, so `InfoTip` sets
+ * `triggerBehavior="toggle"`: tap the icon on a phone (or with touch emulation
+ * on), click it, or press Enter or Space and the help pins open; tap outside
+ * and it dismisses.
*/
export const Touch: Story = {
render: () => (
diff --git a/apps/storybook/stories/LayerDismissal.stories.tsx b/apps/storybook/stories/LayerDismissal.stories.tsx
index 745e347c23..fdbd3c0d7d 100644
--- a/apps/storybook/stories/LayerDismissal.stories.tsx
+++ b/apps/storybook/stories/LayerDismissal.stories.tsx
@@ -2,8 +2,8 @@
/**
* @file LayerDismissal.stories.tsx
- * @input Uses Dialog, Popover, Tooltip, Lightbox, MobileNav, BottomSheet,
- * Button, Layout from @astryxdesign/core; InfoTip from @astryxdesign/lab
+ * @input Uses Dialog, Popover, Tooltip, InfoTip, Lightbox, MobileNav,
+ * BottomSheet, Button, Layout from @astryxdesign/core
* @output Storybook stories demonstrating shared layer dismissal
* @position Storybook; the visual contract for the layer dismissal stack
*
@@ -33,7 +33,7 @@ import {
VStack,
} from '@astryxdesign/core';
import {BottomSheet} from '@astryxdesign/core/BottomSheet';
-import {InfoTip} from '@astryxdesign/lab/InfoTip';
+import {InfoTip} from '@astryxdesign/core/InfoTip';
import type {Meta, StoryObj} from '@storybook/react-vite';
const sheetStyles = stylex.create({
@@ -729,7 +729,7 @@ export const PurposeFlipsWhileOpen: Story = {
};
/**
- * A lab InfoTip inside a modal, its tip showing. One Escape hides the tip and
+ * An InfoTip inside a modal, its tip showing. One Escape hides the tip and
* leaves the modal open; a second closes the modal.
*
* The InfoTip used to `stopPropagation()` the press at its trigger, so the
diff --git a/docs/specs/components/InfoTip/InfoTip.spec.md b/docs/specs/components/InfoTip/InfoTip.spec.md
index efcaff9c89..581e08b62c 100644
--- a/docs/specs/components/InfoTip/InfoTip.spec.md
+++ b/docs/specs/components/InfoTip/InfoTip.spec.md
@@ -12,6 +12,8 @@ owners: [cixzhang]
review_triggers: [public-api, behavior, accessibility]
verified_by:
[
+ packages/core/src/InfoTip/InfoTip.test.tsx,
+ packages/core/src/InfoTip/__tests__/InfoTipTouch.a11y.chromium.spec.ts,
packages/lab/src/InfoTip/InfoTip.test.tsx,
packages/core/src/Tooltip/Tooltip.test.tsx,
scripts/check-knowledge.mjs,
@@ -30,6 +32,14 @@ system_specs: [spec:AST-017, spec:AST-094]
# InfoTip component contract
+<!-- path-applicability:v1 -->
+
+```json
+{
+ "paths": ["packages/lab/src/InfoTip/index.ts"]
+}
+```
+
## Contract at a glance
| Area | Contract |
@@ -38,7 +48,7 @@ system_specs: [spec:AST-017, spec:AST-094]
| Behavior | A named info-icon button wrapped in `component:Tooltip` with `triggerBehavior="toggle"`: hover and focus preview the help, and a click, tap, Enter, or Space pins it open until Escape, a second press, a press outside, or focus leaving. |
| End-user impact | People on a mouse, touch, keyboard, or screen reader can open, keep open, and close the help behind an "i", and hear it once when it pins. |
| Builder impact | Use InfoTip for help next to a label, value, or metric instead of composing an icon inside Tooltip. Lab callers change the import. |
-| Compatibility/readiness | New in Core; Core has no implementation yet (Current-state impact). The Lab component ships with Tooltip's `touchTrigger="tap"` and an English default name. |
+| Compatibility/readiness | New in Core; the `@astryxdesign/lab` export is a deprecated re-export of it for one release (FR4). |
| Review checks | Reject a layer, listener, timer, or dismissal rule of InfoTip's own, a trigger that is not a named button, an untranslated default name, or a prop beyond those FR3 lists. |
| Governing rules | `component:Tooltip` FR9, FR10, AR6; `architecture:public-component-api` INV21; `spec:AST-094` FR42; `spec:AST-017` (lifecycle). |
@@ -66,10 +76,7 @@ Consumer migration instructions belong in consumer docs and release notes.
## Current-state impact
-- **Core has no InfoTip yet.** Only the Lab component ships. It wraps a named
- button in Tooltip with `touchTrigger="tap"`, so a tap opens the help, hover
- and focus open it, and nothing pins it (`component:Tooltip` FR9 is not
- built). Its default name is the English literal "More information" (FR1).
+None.
## Ownership boundary
@@ -97,12 +104,12 @@ Consumer migration instructions belong in consumer docs and release notes.
## Behavioral and layout contract
-| ID | Invariant | Basis |
-| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------- |
-| FR1 | InfoTip renders one `<button type="button">` named by `label`, else the translated `@astryx.infoTip.label` ("More information"), containing the registry's `info` icon at `size`. Implementation gap: the Lab component's default name is an untranslated English literal (Current-state impact). | DEC-1; WCAG 2.2 SC 4.1.2; `architecture:icon-resolution-and-component-slots` |
-| FR2 | InfoTip wraps its button in `component:Tooltip` with `content` and `triggerBehavior="toggle"`, and adds no layer, listener, timer, announcement, or dismissal rule of its own: previewing, pinning, closing, the trigger's `aria-expanded` and `aria-controls`, and the announcement are Tooltip's FR3–FR10. Implementation gap: the Lab component passes `touchTrigger="tap"` (Current-state impact). | DEC-1; `architecture:public-component-api` INV21 |
-| FR3 | The public props are `content` (required; short, noninteractive help), `label`, `size`, a `ref` forwarded to the button, and BaseProps' `xstyle`, `className`, and `style`; InfoTip takes no open-state, placement, or trigger props. | DEC-1 |
-| FR4 | The `@astryxdesign/lab` `InfoTip` export re-exports the Core component, marked deprecated with static metadata, for one release, and is then removed. | `spec:AST-017` FR29, FR29a |
+| ID | Invariant | Basis |
+| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------- |
+| FR1 | InfoTip renders one `<button type="button">` named by `label`, else the translated `@astryx.infoTip.label` ("More information"), containing the registry's `info` icon at `size`. | DEC-1; WCAG 2.2 SC 4.1.2; `architecture:icon-resolution-and-component-slots` |
+| FR2 | InfoTip wraps its button in `component:Tooltip` with `content` and `triggerBehavior="toggle"`, and adds no layer, listener, timer, announcement, or dismissal rule of its own: previewing, pinning, closing, the trigger's `aria-expanded` and `aria-controls`, and the announcement are Tooltip's FR3–FR10. | DEC-1; `architecture:public-component-api` INV21 |
+| FR3 | The public props are `content` (required; short, noninteractive help), `label`, `size`, a `ref` forwarded to the button, and BaseProps' `xstyle`, `className`, and `style`; InfoTip takes no open-state, placement, or trigger props. | DEC-1 |
+| FR4 | The `@astryxdesign/lab` `InfoTip` export re-exports the Core component, marked deprecated with static metadata, for one release, and is then removed. | `spec:AST-017` FR29, FR29a |
### Allowed variation
@@ -133,7 +140,7 @@ Consumer migration instructions belong in consumer docs and release notes.
named (FR1), and, under a coarse pointer, reaches 44 px through an invisible
hit area where its neighbors leave room: the hit area never overlaps a
neighbor's target and is clamped to half the gap between close neighbors
- (`spec:AST-094` FR42). Implementation gap: not yet built in Core.
+ (`spec:AST-094` FR42).
- **AR2 — The help is a toggletip.** `component:Tooltip` AR6: keyboard and
touch users pin and close the help without hover, the button reports
`aria-expanded`, and the help is announced once when it pins.
@@ -142,7 +149,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
| ---------------- | ----------------------------------------- | ------------------------ | -------------- | ------------------ |
-| Trigger button | A small round button that holds the icon. | Current Lab source | Supporting | FR1, AR1 |
+| Trigger button | A small round button that holds the icon. | Current source | Supporting | FR1, AR1 |
| Info icon | The registry's `info` artwork at `size`. | Icon registry | Supporting | FR1 |
| Help surface | Tooltip's surface with `content`. | `component:Tooltip` | Prominent | FR2 |
@@ -158,12 +165,12 @@ Consumer migration instructions belong in consumer docs and release notes.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| -------- | -------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
-| FR1, AR1 | `InfoTip.test.tsx` (Lab today) name and button cases; evidence gap until built: the translated default and the coarse-pointer hit area | Default and custom name; each size | A trigger that is not a named button, an untranslated default, or a coarse-pointer hit area that stays under 44 px where its neighbors leave room or reaches a neighbor's target fails. | `audit:InfoTip/accessibility` |
-| FR2, AR2 | Evidence gap until built: Core `InfoTip.test.tsx` press cases over `component:Tooltip`'s press-toggle suite | Hover and focus preview; click, tap, Enter, Space pin; Escape | A press that does not pin, or a listener or layer InfoTip owns, fails. | `audit:InfoTip/behavior` |
-| FR3 | Evidence gap until built: a type test of the public props | `content`, `label`, `size`, `ref`, `xstyle`, `className`, `style` | A prop beyond those, or a `ref` that does not reach the button, fails. | `audit:InfoTip/api` |
-| FR4 | Evidence gap until built: an export test of the Lab re-export | Lab import | A Lab export that is not the Core component, or lacks the deprecation metadata, fails. | `audit:InfoTip/api` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
+| FR1, AR1 | `InfoTip.test.tsx` button, name, catalog-default and hit-area cases; `InfoTipTouch.a11y.chromium.spec.ts` coarse-pointer reach, neighbour and fine-pointer cases | Default and custom name; each size | A trigger that is not a named button, an untranslated default, or a coarse-pointer hit area that stays under 44 px where its neighbors leave room or reaches a neighbor's target fails. | `audit:InfoTip/accessibility` |
+| FR2, AR2 | `InfoTip.test.tsx` press cases over `component:Tooltip`'s press-toggle suite | Hover and focus preview; click, tap, Enter, Space pin; Escape | A press that does not pin, or a listener or layer InfoTip owns, fails. | `audit:InfoTip/behavior` |
+| FR3 | `InfoTip.test.tsx` props cases: the type checker rejects other props, and `ref`, `xstyle`, `className`, and `style` reach the button | `content`, `label`, `size`, `ref`, `xstyle`, `className`, `style` | A prop beyond those, or a `ref` that does not reach the button, fails. | `audit:InfoTip/api` |
+| FR4 | Lab `InfoTip.test.tsx` identity and deprecation cases | Lab import | A Lab export that is not the Core component, or lacks the deprecation metadata, fails. | `audit:InfoTip/api` |
## Decision log
diff --git a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json
index 61a66cc0ea..64e101a20c 100644
--- a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json
+++ b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json
@@ -2528,7 +2528,6 @@
"spec:AST-086"
],
"packages/lab/src/DiffViewer/DiffViewer.tsx": ["FR13", "FR3", "FR3"],
- "packages/lab/src/InfoTip/InfoTip.tsx": ["#5168"],
"packages/lab/src/LogStream/LogStream.tsx": ["FR3"],
"packages/lab/src/MobilePowerSearch/MobilePowerSearch.tsx": [
"AST-086",
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index 0f6c619ccf..0612525a49 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -465,6 +465,13 @@
"path": "components/icon-button",
"aliases": []
},
+ {
+ "name": "component-info-tip",
+ "path": "components/info-tip",
+ "aliases": [
+ "components/lab/info-tip"
+ ]
+ },
{
"name": "component-input-group",
"path": "components/input-group",
@@ -600,11 +607,6 @@
"path": "components/lab/emoji-picker",
"aliases": []
},
- {
- "name": "component-lab-info-tip",
- "path": "components/lab/info-tip",
- "aliases": []
- },
{
"name": "component-lab-list-input",
"path": "components/lab/list-input",
diff --git a/packages/cli/assets/discover/official-packages.json b/packages/cli/assets/discover/official-packages.json
index 1bc625e358..15bd9a9b23 100644
--- a/packages/cli/assets/discover/official-packages.json
+++ b/packages/cli/assets/discover/official-packages.json
@@ -132,10 +132,6 @@
"kind": "component",
"name": "EmojiPicker"
},
- {
- "kind": "component",
- "name": "InfoTip"
- },
{
"kind": "component",
"name": "ListInput"
diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon-set.json b/packages/cli/test/__golden__/no-icon-set/search-icon-set.json
index 6bf726fd1b..7536f0bfee 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-icon-set.json
+++ b/packages/cli/test/__golden__/no-icon-set/search-icon-set.json
@@ -3,7 +3,7 @@
"type": "search",
"data": {
"query": "icon set",
- "matchCount": 374,
+ "matchCount": 375,
"results": [
{
"domain": "doc",
@@ -105,6 +105,17 @@
"command": "astryx component IconButton",
"mentions": []
},
+ {
+ "domain": "component",
+ "name": "InfoTip",
+ "package": "@astryxdesign/core",
+ "score": "<text>",
+ "reason": "<text>",
+ "description": "<text>",
+ "import": "@astryxdesign/core/InfoTip",
+ "command": "astryx component InfoTip",
+ "mentions": []
+ },
{
"domain": "hook",
"name": "useInputContainer",
@@ -234,18 +245,6 @@
"kind": "block",
"command": "astryx template CenterInsideACard --type block",
"mentions": []
- },
- {
- "domain": "template",
- "name": "ChatComposerDrawerShowcase",
- "package": "@astryxdesign/core",
- "score": "<text>",
- "reason": "<text>",
- "description": "<text>",
- "displayName": "<text>",
- "kind": "block",
- "command": "astryx template ChatComposerDrawerShowcase --type block",
- "mentions": []
}
]
},
diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt b/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt
index e51ca61ba7..58aa4db9ef 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt
+++ b/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt
@@ -1,4 +1,4 @@
-Results for "icon set" (20 of 374)
+Results for "icon set" (20 of 375)
name: authoring/building-blocks/templates/build-the-template/template-assets/template-icons
section: use-astryx-icon
domain: doc
@@ -42,6 +42,11 @@ domain: component
package: @astryxdesign/core
import: @astryxdesign/core/IconButton
command: pnpm exec astryx component IconButton
+name: InfoTip
+domain: component
+package: @astryxdesign/core
+import: @astryxdesign/core/InfoTip
+command: pnpm exec astryx component InfoTip
name: useInputContainer
domain: hook
package: @astryxdesign/core
@@ -87,8 +92,4 @@ command: pnpm exec astryx template CenterHorizontal --type block
name: CenterInsideACard
domain: template
package: @astryxdesign/core
-command: pnpm exec astryx template CenterInsideACard --type block
-name: ChatComposerDrawerShowcase
-domain: template
-package: @astryxdesign/core
-command: pnpm exec astryx template ChatComposerDrawerShowcase --type block
\ No newline at end of file
+command: pnpm exec astryx template CenterInsideACard --type block
\ No newline at end of file
diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon.json b/packages/cli/test/__golden__/no-icon-set/search-icon.json
index 5f30250a6b..e1cd2f591b 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-icon.json
+++ b/packages/cli/test/__golden__/no-icon-set/search-icon.json
@@ -3,7 +3,7 @@
"type": "search",
"data": {
"query": "icon",
- "matchCount": 223,
+ "matchCount": 224,
"results": [
{
"domain": "component",
@@ -39,6 +39,17 @@
"command": "astryx component IconButton",
"mentions": []
},
+ {
+ "domain": "component",
+ "name": "InfoTip",
+ "package": "@astryxdesign/core",
+ "score": "<text>",
+ "reason": "<text>",
+ "description": "<text>",
+ "import": "@astryxdesign/core/InfoTip",
+ "command": "astryx component InfoTip",
+ "mentions": []
+ },
{
"domain": "hook",
"name": "useInputContainer",
@@ -232,18 +243,6 @@
"kind": "block",
"command": "astryx template ChatComposerFooterActions --type block",
"mentions": []
- },
- {
- "domain": "template",
- "name": "ChatComposerFullFeatured",
- "package": "@astryxdesign/core",
- "score": "<text>",
- "reason": "<text>",
- "description": "<text>",
- "displayName": "<text>",
- "kind": "block",
- "command": "astryx template ChatComposerFullFeatured --type block",
- "mentions": []
}
]
},
diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon.txt b/packages/cli/test/__golden__/no-icon-set/search-icon.txt
index 62ba263a79..e262976dd8 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-icon.txt
+++ b/packages/cli/test/__golden__/no-icon-set/search-icon.txt
@@ -1,4 +1,4 @@
-Results for "icon" (20 of 223)
+Results for "icon" (20 of 224)
name: Icon
domain: component
package: @astryxdesign/core
@@ -14,6 +14,11 @@ domain: component
package: @astryxdesign/core
import: @astryxdesign/core/IconButton
command: pnpm exec astryx component IconButton
+name: InfoTip
+domain: component
+package: @astryxdesign/core
+import: @astryxdesign/core/InfoTip
+command: pnpm exec astryx component InfoTip
name: useInputContainer
domain: hook
package: @astryxdesign/core
@@ -83,8 +88,4 @@ command: pnpm exec astryx template ChatComposerDrawerWithProgress --type blo
name: ChatComposerFooterActions
domain: template
package: @astryxdesign/core
-command: pnpm exec astryx template ChatComposerFooterActions --type block
-name: ChatComposerFullFeatured
-domain: template
-package: @astryxdesign/core
-command: pnpm exec astryx template ChatComposerFullFeatured --type block
\ No newline at end of file
+command: pnpm exec astryx template ChatComposerFooterActions --type block
\ No newline at end of file
diff --git a/packages/core/api-report.md b/packages/core/api-report.md
index 36a98fa508..1c69f1db57 100644
--- a/packages/core/api-report.md
+++ b/packages/core/api-report.md
@@ -1325,6 +1325,13 @@ component IconButton(props: IconButtonProps)
prop width?: SizeValue
prop xstyle?: StyleXStyles
inherits AriaAttributes, DOMAttributes, HTMLAttributes
+component InfoTip(props: InfoTipProps)
+ prop content: ReactNode
+ prop label?: string = A translated "More information"
+ prop ref?: Ref<HTMLButtonElement>
+ prop size?: InfoTipSize = 'sm'
+ prop xstyle?: StyleXStyles
+ inherits HTMLAttributes
component InputClearButton(props: InputClearButtonProps)
prop iconClassName?: string
prop label: string
@@ -4483,6 +4490,8 @@ type IndicatorRegistrySource = DefinedTheme | string | null | undefined
type IndicatorSize = 'sm' | 'md'
type IndicatorState<F extends IndicatorFamily = IndicatorFamily> = IndicatorFamilyMap[F]
type InferData<D extends ReadonlyArray<FieldDefinition>> = { [F in D[number] as F['key']]: FieldTypeToJS[F['type']] }
+interface InfoTipProps extends Pick<BaseProps, 'xstyle' | 'className' | 'style'> (props of InfoTip)
+type InfoTipSize = IconSize
type InlineNode<Extension extends MarkdownExtensionNode = never> = { type: 'text'; content: string } | { type: 'bold'; children: InlineNode<Extension>[] } | { type: 'italic'; children: InlineNode<Extension>[] } | { type: 'strik … #7f5046d1
type InlineNodeWithMath<Extension extends MarkdownExtensionNode = never> = { type: 'text'; content: string } | { type: 'bold'; children: InlineNodeWithMath<Extension>[] } | { type: 'italic'; children: InlineNodeWithMath<Extension>[] } … #7144a813
interface InputARIA
@@ -7161,6 +7170,16 @@ useIndicator (.)
indicatorScope (.)
```
+## `./InfoTip`
+
+### Also exported from an earlier entry point
+
+```text
+InfoTip (.)
+InfoTipProps (.)
+InfoTipSize (.)
+```
+
## `./InputGroup`
### Also exported from an earlier entry point
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index 5f8b41ca8c..f6cab932d9 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -2270,5 +2270,9 @@
"@astryx.comments.postFailed": {
"defaultMessage": "Your comment couldn't be posted.",
"description": "Error shown above the new-comment composer of a lab Comments panel when posting failed; the draft is kept and a Retry action follows."
+ },
+ "@astryx.infoTip.label": {
+ "defaultMessage": "More information",
+ "description": "Default accessible name of an InfoTip, the small info-icon button whose press reveals help about the label, value, or metric beside it."
}
}
diff --git a/packages/core/package.json b/packages/core/package.json
index b8d438af31..7fbaca35f2 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -399,6 +399,11 @@
"types": "./dist/Indicator/index.d.ts",
"default": "./dist/Indicator/index.js"
},
+ "./InfoTip": {
+ "source": "./src/InfoTip/index.ts",
+ "types": "./dist/InfoTip/index.d.ts",
+ "default": "./dist/InfoTip/index.js"
+ },
"./InputGroup": {
"source": "./src/InputGroup/index.ts",
"types": "./dist/InputGroup/index.d.ts",
diff --git a/packages/core/src/InfoTip/InfoTip.doc.mjs b/packages/core/src/InfoTip/InfoTip.doc.mjs
new file mode 100644
index 0000000000..ec5db4ed35
--- /dev/null
+++ b/packages/core/src/InfoTip/InfoTip.doc.mjs
@@ -0,0 +1,192 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
+
+export const docs = {
+ name: 'InfoTip',
+ displayName: 'Info Tip',
+ // Keeps the registry route InfoTip had as a canary-only Lab component.
+ registry: {aliases: ['lab/info-tip']},
+ category: 'Feedback & Status',
+ keywords: [
+ 'info',
+ 'tooltip',
+ 'help',
+ 'hint',
+ 'affordance',
+ 'icon',
+ 'label',
+ 'field',
+ 'metric',
+ 'definition',
+ ],
+ props: [
+ {
+ name: 'content',
+ type: 'ReactNode',
+ description:
+ "Content to display in the tooltip. Typically short, non-interactive text. Mirrors Tooltip's content prop.",
+ required: true,
+ },
+ {
+ name: 'label',
+ type: 'string',
+ description:
+ 'Accessible name for the trigger button. Defaults to the translated "More information".',
+ default: "'More information'",
+ },
+ {
+ name: 'size',
+ type: "'xsm' | 'sm' | 'md' | 'lg'",
+ description:
+ 'Size of the info icon (12px, 16px, 20px, 24px). Maps 1:1 to Icon sizes.',
+ default: "'sm'",
+ },
+ {
+ name: 'xstyle',
+ type: 'StyleXStyles',
+ description:
+ 'StyleX styles for layout customization (margins, positioning, sizing). Must be a stylex.create() value, not an inline style object like style={{}}.',
+ },
+ ],
+ usage: {
+ description:
+ 'An info icon that reveals help: a small "i" button. Hover and keyboard focus preview the help, and a click, tap, Enter, or Space pins it open until Escape, a second press, a press outside, or focus leaving. Use it next to labels, values, and metrics for permission notes, metric definitions, and field help. Its value over hand-composing Icon inside Tooltip is the pre-wired accessible trigger: a real button with an aria-label, Tab-reachable, tooltip on hover AND focus AND tap, and Escape dismissal.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Keep tooltip content concise, plain, and non-interactive; use Popover or HoverCard for links and buttons.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Override label when "More information" is too generic, e.g. "About this metric".',
+ },
+ {
+ guidance: true,
+ description:
+ 'Rely on InfoTip rather than a hand-rolled info button on touch: it sets Tooltip triggerBehavior to toggle, so a tap, a click, Enter, or Space pins the tooltip even though the trigger is a button, and a tap outside dismisses it.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Hand-compose Icon inside Tooltip for info affordances; the bare Icon is aria-hidden and unfocusable, so keyboard and screen-reader users never see it.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use InfoTip for essential information users must see to complete a task; put that text inline instead.',
+ },
+ ],
+ },
+};
+
+/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
+export const docsZh = {
+ name: 'InfoTip',
+ displayName: 'Info Tip',
+ props: [
+ {
+ name: 'content',
+ type: 'ReactNode',
+ description:
+ '工具提示中显示的内容。通常为简短的非交互文本。与 Tooltip 的 content 属性一致。',
+ required: true,
+ },
+ {
+ name: 'label',
+ type: 'string',
+ description: '触发按钮的无障碍名称。默认为翻译后的“More information”。',
+ default: "'More information'",
+ },
+ {
+ name: 'size',
+ type: "'xsm' | 'sm' | 'md' | 'lg'",
+ description:
+ '信息图标的尺寸(12px、16px、20px、24px)。与 Icon 尺寸一一对应。',
+ default: "'sm'",
+ },
+ {
+ name: 'xstyle',
+ type: 'StyleXStyles',
+ description:
+ '用于布局自定义的 StyleX 样式(边距、定位、尺寸)。必须是 stylex.create() 的值,不能是内联样式对象如 style={{}}。',
+ },
+ ],
+ usage: {
+ description:
+ 'An info icon that reveals help: a small "i" button. Hover and keyboard focus preview the help, and a click, tap, Enter, or Space pins it open until Escape, a second press, a press outside, or focus leaving. Use it next to labels, values, and metrics for permission notes, metric definitions, and field help.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Keep tooltip content concise, plain, and non-interactive; use Popover or HoverCard for links and buttons.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Override label when "More information" is too generic, e.g. "About this metric".',
+ },
+ {
+ guidance: true,
+ description:
+ 'Rely on InfoTip rather than a hand-rolled info button on touch: it sets Tooltip triggerBehavior to toggle, so a tap, a click, Enter, or Space pins the tooltip even though the trigger is a button, and a tap outside dismisses it.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Hand-compose Icon inside Tooltip for info affordances; the bare Icon is aria-hidden and unfocusable, so keyboard and screen-reader users never see it.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use InfoTip for essential information users must see to complete a task; put that text inline instead.',
+ },
+ ],
+ },
+};
+
+/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */
+export const docsDense = {
+ description:
+ 'Inline info-icon help affordance: accessible "i" button trigger pre-wired into a Tooltip.',
+ usage: {
+ description:
+ 'A small "i" button: hover and keyboard focus preview the help; a click, tap, Enter, or Space pins it open. Use next to labels, values, and metrics for permission notes, metric definitions, and field help. Pre-wired accessible trigger: real button, aria-label, Tab-reachable, tooltip on hover AND focus AND tap, Escape dismissal.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Keep tooltip content concise, plain, and non-interactive; use Popover or HoverCard for links and buttons.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Override label when "More information" is too generic, e.g. "About this metric".',
+ },
+ {
+ guidance: true,
+ description:
+ 'Rely on InfoTip rather than a hand-rolled info button on touch: it sets Tooltip triggerBehavior to toggle, so a tap, a click, Enter, or Space pins the tooltip even though the trigger is a button, and a tap outside dismisses it.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Hand-compose Icon inside Tooltip for info affordances; the bare Icon is aria-hidden and unfocusable.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use InfoTip for essential information users must see to complete a task; put that text inline instead.',
+ },
+ ],
+ },
+ propDescriptions: {
+ content:
+ 'Tooltip content. Short, non-interactive text. Mirrors Tooltip content prop.',
+ label:
+ "Accessible name for the trigger button. Default: the translated 'More information'.",
+ size: 'Info icon size (12/16/20/24px). Maps 1:1 to Icon sizes.',
+ },
+};
diff --git a/packages/core/src/InfoTip/InfoTip.test.tsx b/packages/core/src/InfoTip/InfoTip.test.tsx
new file mode 100644
index 0000000000..62681c7191
--- /dev/null
+++ b/packages/core/src/InfoTip/InfoTip.test.tsx
@@ -0,0 +1,407 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file InfoTip.test.tsx
+ * @input Uses vitest, @testing-library/react, @testing-library/user-event,
+ * InfoTip, InternationalizationProvider, the shared hit area (mocked)
+ * @output Unit tests for InfoTip's named button, its press toggle over
+ * Tooltip, its props, and its touch hit area
+ * @position Testing; validates InfoTip.tsx (component:InfoTip FR1–FR3, AR1)
+ *
+ * SYNC: When InfoTip.tsx changes, update tests to match new behavior
+ */
+
+import {createRef} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {describe, it, expect, vi, beforeAll, afterAll} from 'vitest';
+import {render, screen, fireEvent, waitFor, act} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {InternationalizationProvider} from '../i18n';
+import type * as HitAreaModule from '../utils/hitArea';
+import type {HitInsets} from '../utils/hitArea';
+import {InfoTip} from './InfoTip';
+
+// On a coarse pointer, the shared hit area measures neighbours in a real
+// layout. Here it reports what it was asked to watch, and each test answers
+// for it.
+const hitAreaWatches = vi.hoisted(
+ () => [] as {element: Element; onInsets: (insets: HitInsets) => void}[],
+);
+vi.mock('../utils/hitArea', async importOriginal => ({
+ ...(await importOriginal<typeof HitAreaModule>()),
+ watchHitArea: (element: Element, onInsets: (insets: HitInsets) => void) => {
+ const watch = {element, onInsets};
+ hitAreaWatches.push(watch);
+ return () => {
+ hitAreaWatches.splice(hitAreaWatches.indexOf(watch), 1);
+ };
+ },
+}));
+
+// Store original matches to restore later
+const originalMatches = HTMLElement.prototype.matches;
+
+// Track popover open state per element
+const popoverOpenState = new WeakMap<HTMLElement, boolean>();
+
+// Mock Popover API for jsdom, and :focus-visible for keyboard-focus tests
+// (same harness as core Tooltip.test.tsx, plus :focus-visible)
+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);
+ });
+
+ // Intercept :popover-open and :focus-visible, delegate everything else
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (HTMLElement.prototype as any).matches = function (
+ selector: string,
+ ): boolean {
+ if (selector === ':popover-open') {
+ return popoverOpenState.get(this) ?? false;
+ }
+ if (selector === ':focus-visible') {
+ // Treat any focused element as keyboard-focused in tests
+ return this === document.activeElement;
+ }
+ return originalMatches.call(this, selector);
+ };
+});
+
+afterAll(() => {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (HTMLElement.prototype as any).matches = originalMatches;
+});
+
+const overrides = stylex.create({
+ spaced: {marginInlineStart: 12},
+});
+
+/** Focus the trigger the way a keyboard user would land on it. */
+function focusTrigger(trigger: HTMLElement) {
+ act(() => {
+ trigger.focus();
+ });
+ fireEvent.focusIn(trigger);
+}
+
+describe('InfoTip', () => {
+ it('renders a button trigger with the default accessible name', () => {
+ render(<InfoTip content="Helpful context" />);
+ const trigger = screen.getByRole('button', {name: 'More information'});
+ expect(trigger.tagName).toBe('BUTTON');
+ expect(trigger).toHaveAttribute('type', 'button');
+ });
+
+ it('takes its default name from the translation catalog (FR1)', () => {
+ render(
+ <InternationalizationProvider
+ locale="en"
+ overrides={{en: {'@astryx.infoTip.label': 'Learn more'}}}>
+ <InfoTip content="Helpful context" />
+ </InternationalizationProvider>,
+ );
+ expect(screen.getByRole('button', {name: 'Learn more'})).toBeVisible();
+ });
+
+ it('takes no open-state, placement, or trigger props (FR3)', () => {
+ render(
+ <InfoTip
+ content="Helpful context"
+ // @ts-expect-error InfoTip has no placement: Tooltip places the help.
+ placement="below"
+ />,
+ );
+ render(
+ <InfoTip
+ content="Helpful context"
+ // @ts-expect-error InfoTip has no open state: Tooltip owns it.
+ isOpen
+ />,
+ );
+ render(
+ <InfoTip
+ content="Helpful context"
+ // @ts-expect-error InfoTip always pins on a press.
+ triggerBehavior="hover"
+ />,
+ );
+ expect(screen.getAllByRole('button')).toHaveLength(3);
+ });
+
+ it('uses a custom label as the accessible name', () => {
+ render(
+ <InfoTip content="30-day rolling average." label="About this metric" />,
+ );
+ const trigger = screen.getByRole('button', {name: 'About this metric'});
+ expect(trigger).toHaveAttribute('aria-label', 'About this metric');
+ });
+
+ it('links the trigger to the tooltip layer via aria-describedby', () => {
+ render(<InfoTip content="Helpful context" />);
+ const layer = screen.getByRole('tooltip', {hidden: true});
+ expect(layer).toHaveTextContent('Helpful context');
+ const trigger = screen.getByRole('button', {name: 'More information'});
+ expect(trigger.getAttribute('aria-describedby')).toBe(layer.id);
+ });
+
+ it('is reachable with Tab', async () => {
+ const user = userEvent.setup();
+ render(<InfoTip content="Helpful context" />);
+ const trigger = screen.getByRole('button', {name: 'More information'});
+ await user.tab();
+ expect(trigger).toHaveFocus();
+ });
+
+ it('shows the tooltip on hover', async () => {
+ vi.mocked(HTMLElement.prototype.showPopover).mockClear();
+ render(<InfoTip content="Helpful context" />);
+ const trigger = screen.getByRole('button', {name: 'More information'});
+
+ fireEvent.mouseEnter(trigger);
+
+ await waitFor(() => {
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();
+ });
+ });
+
+ it('shows the tooltip on keyboard focus', async () => {
+ vi.mocked(HTMLElement.prototype.showPopover).mockClear();
+ render(<InfoTip content="Helpful context" />);
+ const trigger = screen.getByRole('button', {name: 'More information'});
+
+ focusTrigger(trigger);
+
+ await waitFor(() => {
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();
+ });
+ const layer = screen.getByRole('tooltip', {hidden: true});
+ expect(popoverOpenState.get(layer)).toBe(true);
+ });
+
+ it('closes the tooltip on Escape', async () => {
+ render(<InfoTip content="Helpful context" />);
+ const trigger = screen.getByRole('button', {name: 'More information'});
+ const layer = screen.getByRole('tooltip', {hidden: true});
+
+ focusTrigger(trigger);
+ await waitFor(() => {
+ expect(popoverOpenState.get(layer)).toBe(true);
+ });
+
+ fireEvent.keyDown(trigger, {key: 'Escape'});
+
+ await waitFor(() => {
+ expect(popoverOpenState.get(layer)).toBe(false);
+ });
+ });
+
+ it('re-opens after Escape once the trigger is left and re-hovered', async () => {
+ render(<InfoTip content="Helpful context" />);
+ const trigger = screen.getByRole('button', {name: 'More information'});
+ const layer = screen.getByRole('tooltip', {hidden: true});
+
+ focusTrigger(trigger);
+ await waitFor(() => {
+ expect(popoverOpenState.get(layer)).toBe(true);
+ });
+
+ fireEvent.keyDown(trigger, {key: 'Escape'});
+ await waitFor(() => {
+ expect(popoverOpenState.get(layer)).toBe(false);
+ });
+
+ // Leave (resets dismissal), then re-enter
+ act(() => {
+ trigger.blur();
+ });
+ fireEvent.focusOut(trigger);
+ fireEvent.mouseLeave(trigger);
+
+ fireEvent.mouseEnter(trigger);
+ await waitFor(() => {
+ expect(popoverOpenState.get(layer)).toBe(true);
+ });
+ });
+
+ it('renders ReactNode tooltip content', () => {
+ render(<InfoTip content={<span data-testid="rich-content">Rich</span>} />);
+ expect(screen.getByTestId('rich-content')).toBeInTheDocument();
+ });
+ it('forwards its ref to the button (FR3)', () => {
+ const ref = createRef<HTMLButtonElement>();
+ render(<InfoTip content="Helpful context" ref={ref} />);
+ expect(ref.current).toBe(
+ screen.getByRole('button', {name: 'More information'}),
+ );
+ });
+
+ it('puts xstyle, className, and style on the button (FR3)', () => {
+ render(
+ <InfoTip
+ content="Helpful context"
+ xstyle={overrides.spaced}
+ className="caller-class"
+ style={{marginBlockStart: 4}}
+ />,
+ );
+ const trigger = screen.getByRole('button', {name: 'More information'});
+ for (const token of (stylex.props(overrides.spaced).className ?? '').split(
+ ' ',
+ )) {
+ expect(trigger).toHaveClass(token);
+ }
+ expect(trigger).toHaveClass('caller-class');
+ expect(trigger.style.marginBlockStart).toBe('4px');
+ });
+
+ describe('a press pins the help (FR2, Tooltip FR9 and FR10)', () => {
+ it('reports the pin on the button: aria-expanded and aria-controls', async () => {
+ render(<InfoTip content="Helpful context" />);
+ const trigger = screen.getByRole('button', {name: 'More information'});
+ const layer = screen.getByRole('tooltip', {hidden: true});
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+
+ fireEvent.click(trigger);
+
+ await waitFor(() => {
+ expect(popoverOpenState.get(layer)).toBe(true);
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ expect(trigger).toHaveAttribute('aria-controls', layer.id);
+ });
+
+ it('stays pinned when the pointer leaves, and a second click closes it', async () => {
+ render(<InfoTip content="Helpful context" />);
+ const trigger = screen.getByRole('button', {name: 'More information'});
+ const layer = screen.getByRole('tooltip', {hidden: true});
+
+ fireEvent.mouseEnter(trigger);
+ fireEvent.click(trigger);
+ await waitFor(() => {
+ expect(popoverOpenState.get(layer)).toBe(true);
+ });
+ fireEvent.mouseLeave(trigger);
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 300));
+ });
+ expect(popoverOpenState.get(layer)).toBe(true);
+
+ fireEvent.click(trigger);
+ await waitFor(() => {
+ expect(popoverOpenState.get(layer)).toBe(false);
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it.each(['Enter', ' '])('pins on %j from the keyboard', async key => {
+ const user = userEvent.setup();
+ render(<InfoTip content="Helpful context" />);
+ const trigger = screen.getByRole('button', {name: 'More information'});
+ await user.tab();
+ expect(trigger).toHaveFocus();
+
+ await user.keyboard(key === ' ' ? '[Space]' : '[Enter]');
+
+ await waitFor(() => {
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+ });
+ });
+
+ describe('touch', () => {
+ /**
+ * A tap, in the order a browser dispatches it. First the finger's pointer
+ * events, then the hover it synthesizes, then the `click` that says the
+ * touch was a tap.
+ */
+ const tap = (element: HTMLElement) => {
+ fireEvent.pointerEnter(element, {pointerType: 'touch'});
+ fireEvent.pointerDown(element, {pointerType: 'touch'});
+ fireEvent.pointerUp(element, {pointerType: 'touch'});
+ fireEvent.mouseEnter(element);
+ fireEvent.click(element);
+ };
+
+ it('pins on a tap, though the trigger is a button', async () => {
+ render(<InfoTip content="30-day rolling average." />);
+ const trigger = screen.getByRole('button');
+ const layer = screen.getByRole('tooltip', {hidden: true});
+
+ // Revealing the help is the button's whole purpose, so a tap pins it
+ // (`triggerBehavior="toggle"`). Without that its content is unreachable on
+ // a phone.
+ tap(trigger);
+
+ await waitFor(() => {
+ expect(popoverOpenState.get(layer)).toBe(true);
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('closes on a second tap of the trigger', async () => {
+ render(<InfoTip content="30-day rolling average." />);
+ const trigger = screen.getByRole('button');
+ const layer = screen.getByRole('tooltip', {hidden: true});
+
+ tap(trigger);
+ await waitFor(() => {
+ expect(popoverOpenState.get(layer)).toBe(true);
+ });
+
+ tap(trigger);
+ await waitFor(() => {
+ expect(popoverOpenState.get(layer)).toBe(false);
+ });
+ });
+
+ it('closes on a tap outside', async () => {
+ render(
+ <>
+ <InfoTip content="30-day rolling average." />
+ <button type="button">Elsewhere</button>
+ </>,
+ );
+ const trigger = screen.getByRole('button', {name: 'More information'});
+ const layer = screen.getByRole('tooltip', {hidden: true});
+
+ tap(trigger);
+ await waitFor(() => {
+ expect(popoverOpenState.get(layer)).toBe(true);
+ });
+
+ // The tap outside counts when the finger lifts.
+ const elsewhere = screen.getByRole('button', {name: 'Elsewhere'});
+ fireEvent.pointerDown(elsewhere, {pointerType: 'touch'});
+ fireEvent.pointerUp(elsewhere, {pointerType: 'touch'});
+
+ await waitFor(() => {
+ expect(popoverOpenState.get(layer)).toBe(false);
+ });
+ });
+ });
+
+ describe('touch hit area (AR1)', () => {
+ it('grows the button toward 44 px as far as the shared hit area allows', () => {
+ const {unmount} = render(<InfoTip content="Helpful context" />);
+ const trigger = screen.getByRole('button', {name: 'More information'});
+ const watch = hitAreaWatches.find(entry => entry.element === trigger);
+ expect(watch).toBeDefined();
+
+ act(() => watch?.onInsets({top: 12, right: 6, bottom: 12, left: 4}));
+ expect(trigger.style.getPropertyValue('--astryx-hit-inset-top')).toBe(
+ '12px',
+ );
+ expect(trigger.style.getPropertyValue('--astryx-hit-inset-left')).toBe(
+ '4px',
+ );
+
+ unmount();
+ expect(hitAreaWatches.some(entry => entry.element === trigger)).toBe(
+ false,
+ );
+ });
+ });
+});
diff --git a/packages/core/src/InfoTip/InfoTip.tsx b/packages/core/src/InfoTip/InfoTip.tsx
new file mode 100644
index 0000000000..fed5e1e56d
--- /dev/null
+++ b/packages/core/src/InfoTip/InfoTip.tsx
@@ -0,0 +1,186 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file InfoTip.tsx
+ * @input Uses React, StyleX, Tooltip, Icon, useComponentTranslator, the shared
+ * touch hit area, color/spacing/radius/duration/ease tokens
+ * @output Exports InfoTip component, InfoTipProps, InfoTipSize types
+ * @position Core implementation; consumed by index.ts, tested by
+ * InfoTip.test.tsx; `@astryxdesign/lab` re-exports it, deprecated
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/InfoTip/InfoTip.doc.mjs (props table, features)
+ * - /docs/specs/components/InfoTip/InfoTip.spec.md (contract)
+ * - /packages/core/src/InfoTip/InfoTip.test.tsx (tests for new/changed behavior)
+ * - /packages/core/src/InfoTip/index.ts (exports if types change)
+ */
+
+import {useCallback, type ReactNode, type Ref} from 'react';
+import * as stylex from '@stylexjs/stylex';
+
+import type {BaseProps} from '../BaseProps';
+import {useMergedRefs} from '../hooks/useMergedRefs';
+import {Icon, type IconSize} from '../Icon/Icon';
+import {Tooltip} from '../Tooltip/Tooltip';
+import {
+ registerEnglishFallback,
+ useComponentTranslator,
+} from '../i18n/useComponentTranslator';
+import english from '../i18n/generated-english/InfoTip/InfoTip.generated';
+import {
+ colorVars,
+ durationVars,
+ easeVars,
+ radiusVars,
+ spacingVars,
+} from '../theme/tokens.stylex';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
+import {mergeProps} from '../utils/mergeProps';
+import {watchHitArea, writeHitInsets} from '../utils/hitArea';
+
+registerEnglishFallback(english);
+
+/**
+ * Size of the info icon. Maps 1:1 to Icon sizes
+ * (xsm: 12px, sm: 16px, md: 20px, lg: 24px).
+ */
+export type InfoTipSize = IconSize;
+
+export interface InfoTipProps extends Pick<
+ BaseProps,
+ 'xstyle' | 'className' | 'style'
+> {
+ /** Ref forwarded to the info button. */
+ ref?: Ref<HTMLButtonElement>;
+ /**
+ * The help the button reveals. Short, noninteractive text; for links or
+ * buttons, use HoverCard.
+ */
+ content: ReactNode;
+ /**
+ * Accessible name of the button.
+ * @default A translated "More information"
+ */
+ label?: string;
+ /**
+ * Size of the info icon.
+ * @default 'sm'
+ */
+ size?: InfoTipSize;
+}
+
+const styles = stylex.create({
+ trigger: {
+ position: 'relative',
+ display: 'inline-flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ verticalAlign: 'middle',
+ padding: spacingVars['--spacing-0-5'],
+ margin: 0,
+ borderStyle: 'none',
+ backgroundColor: 'transparent',
+ borderRadius: radiusVars['--radius-full'],
+ cursor: {
+ default: 'pointer',
+ ':is(:disabled,[aria-disabled="true"])': 'default',
+ },
+ color: {
+ default: colorVars['--color-icon-secondary'],
+ ':hover:where(:not(:disabled,[aria-disabled="true"]))': {
+ default: null,
+ '@media (hover: hover)': colorVars['--color-icon-primary'],
+ },
+ },
+ transitionProperty: 'color',
+ transitionDuration: durationVars['--duration-fast'],
+ transitionTimingFunction: easeVars['--ease-standard'],
+ },
+ // The invisible hit area. Under a coarse pointer, the shared hit area writes
+ // how far the button may grow toward 44 px on each side. It never takes a
+ // neighbour's tap, and it writes 0 elsewhere. This layer takes taps out to
+ // there.
+ // SYNC: /packages/core/src/utils/hitArea.ts (HIT_INSET_PROPERTIES)
+ hitArea: {
+ '::after': {
+ content: '""',
+ position: 'absolute',
+ // Physical sides on purpose: the shared hit area measures each side
+ // from the page's rects, left and right included, in any direction.
+ inset:
+ 'calc(var(--astryx-hit-inset-top, 0px) * -1) calc(var(--astryx-hit-inset-right, 0px) * -1) calc(var(--astryx-hit-inset-bottom, 0px) * -1) calc(var(--astryx-hit-inset-left, 0px) * -1)',
+ },
+ },
+});
+
+/**
+ * An info icon that reveals help: a small "i" button. Hover and keyboard
+ * focus preview the help. A click, tap, Enter, or Space pins it open until
+ * Escape, a second press, a press outside, or focus leaving. Use it next to
+ * labels, values, and metrics for permission notes, metric definitions, and
+ * field help.
+ *
+ * InfoTip is Tooltip with `triggerBehavior="toggle"` on a named button: Tooltip
+ * opens, pins, announces, and closes the help. The info icon resolves from
+ * the icon registry, so themes can replace it.
+ *
+ * @example
+ * ```
+ * <InfoTip content="Editors can change this field; viewers cannot." />
+ * <InfoTip content="30-day rolling average." label="About this metric" />
+ * ```
+ */
+export function InfoTip({
+ content,
+ label,
+ size = 'sm',
+ ref,
+ xstyle,
+ className,
+ style,
+}: InfoTipProps): ReactNode {
+ const t = useComponentTranslator();
+ // Under a coarse pointer the button takes taps out toward 44 px. The watch
+ // lives as long as the button is attached: the ref's cleanup stops it, and a
+ // replaced button starts its own.
+ const watchButtonHitArea = useCallback((button: HTMLButtonElement | null) => {
+ if (button == null) {
+ return;
+ }
+ return watchHitArea(button, insets => writeHitInsets(button, insets));
+ }, []);
+ const mergedRef = useMergedRefs(ref, watchButtonHitArea);
+
+ // No Escape handler of its own. Tooltip's entry in the shared dismissal
+ // stack takes Escape, so one press never closes both the help and an
+ // enclosing Dialog.
+ return (
+ <Tooltip
+ content={content}
+ // The tooltip is the button's only purpose. A click, a tap, Enter, or
+ // Space pins it open, and the press stops at the button. So an InfoTip's
+ // content is reachable on a phone and from the keyboard alike.
+ triggerBehavior="toggle">
+ <button
+ ref={mergedRef}
+ type="button"
+ aria-label={label ?? t('@astryx.infoTip.label')}
+ {...mergeProps(
+ stylex.props(
+ focusOutlineStyles.focusVisible,
+ styles.trigger,
+ styles.hitArea,
+ xstyle,
+ ),
+ className,
+ style,
+ )}>
+ <Icon icon="info" size={size} />
+ </button>
+ </Tooltip>
+ );
+}
+
+InfoTip.displayName = 'InfoTip';
diff --git a/packages/core/src/InfoTip/__tests__/InfoTipTouch.a11y.chromium.spec.ts b/packages/core/src/InfoTip/__tests__/InfoTipTouch.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..f8890c975e
--- /dev/null
+++ b/packages/core/src/InfoTip/__tests__/InfoTipTouch.a11y.chromium.spec.ts
@@ -0,0 +1,200 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file InfoTipTouch.a11y.chromium.spec.ts
+ * @input The built Storybook's Core/InfoTip stories in Chromium, with a fine
+ * and a coarse primary pointer
+ * @output Proofs that under a coarse pointer the info button takes taps out
+ * toward 44 px and stops halfway to a neighbouring button, and grows nothing
+ * under a fine pointer (component:InfoTip AR1)
+ * @position Browser test for InfoTip.tsx's hit area; the geometry itself is
+ * utils/hitArea.ts's, unit-tested there
+ */
+
+import {expect, test, type Browser, type Page} from '@playwright/test';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+const MIN_TOUCH_TARGET = 44;
+let storybook: StaticServer;
+
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+async function pageWith(
+ browser: Browser,
+ pointer: 'coarse' | 'fine',
+): Promise<Page> {
+ const context = await browser.newContext(
+ pointer === 'coarse'
+ ? {hasTouch: true, isMobile: true, viewport: {width: 402, height: 874}}
+ : {viewport: {width: 1024, height: 768}},
+ );
+ return context.newPage();
+}
+
+async function openStory(page: Page, story: string): Promise<void> {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-infotip--${story}&viewMode=story&globals=astryxTheme:neutral;colorMode:light;direction:ltr`,
+ {waitUntil: 'load'},
+ );
+ // The story has rendered once its button is in the document, however long
+ // a loaded machine takes to boot the preview.
+ await page
+ .locator('#storybook-root')
+ .getByRole('button')
+ .first()
+ .waitFor({state: 'attached'});
+}
+
+/** The one info button, present and painted, and its box. */
+async function infoButton(page: Page) {
+ const button = page.getByRole('button', {name: /./});
+ await expect(button).toHaveCount(1);
+ const box = await button.boundingBox();
+ expect(box, 'the info button has a layout box').not.toBeNull();
+ if (box == null) {
+ throw new Error('unreachable');
+ }
+ expect(box.width).toBeGreaterThan(0);
+ expect(box.height).toBeGreaterThan(0);
+ return {button, box};
+}
+
+/** Whether a tap at (x, y) would land on the info button. */
+async function hitsButton(page: Page, x: number, y: number): Promise<boolean> {
+ return page.evaluate(
+ ([px, py]) => {
+ const hit = document.elementFromPoint(px, py);
+ return hit?.closest('button') != null;
+ },
+ [x, y] as const,
+ );
+}
+
+test('under a coarse pointer the info button takes taps out toward 44 px', async ({
+ browser,
+}) => {
+ const page = await pageWith(browser, 'coarse');
+ await openStory(page, 'default');
+ const {button, box} = await infoButton(page);
+ expect(box.width).toBeLessThan(MIN_TOUCH_TARGET);
+ // The shared hit area measures in its next frame pass.
+ await expect
+ .poll(async () =>
+ button.evaluate(element =>
+ Number.parseFloat(
+ getComputedStyle(element).getPropertyValue('--astryx-hit-inset-left'),
+ ),
+ ),
+ )
+ .toBeGreaterThan(0);
+ const centerX = box.x + box.width / 2;
+ const centerY = box.y + box.height / 2;
+ const reach = MIN_TOUCH_TARGET / 2;
+ for (const [dx, dy] of [
+ [-(reach - 1), 0],
+ [reach - 1, 0],
+ [0, -(reach - 1)],
+ [0, reach - 1],
+ ]) {
+ expect(
+ await hitsButton(page, centerX + dx, centerY + dy),
+ `a tap ${dx}, ${dy} px from the center`,
+ ).toBe(true);
+ }
+ // No further than 44 px across.
+ expect(await hitsButton(page, centerX - (reach + 2), centerY)).toBe(false);
+ expect(await hitsButton(page, centerX + reach + 2, centerY)).toBe(false);
+});
+
+test('the hit area stops halfway to a neighbouring button', async ({
+ browser,
+}) => {
+ const page = await pageWith(browser, 'coarse');
+ await openStory(page, 'sizes');
+ const buttons = page.locator('#storybook-root').getByRole('button');
+ await expect(buttons).toHaveCount(4);
+ const boxes = await Promise.all(
+ [0, 1, 2, 3].map(async index => buttons.nth(index).boundingBox()),
+ );
+ for (const box of boxes) {
+ expect(box, 'each info button has a layout box').not.toBeNull();
+ expect(box?.width ?? 0).toBeGreaterThan(0);
+ }
+ await expect
+ .poll(async () =>
+ buttons
+ .first()
+ .evaluate(element =>
+ Number.parseFloat(
+ getComputedStyle(element).getPropertyValue(
+ '--astryx-hit-inset-top',
+ ),
+ ),
+ ),
+ )
+ .toBeGreaterThan(0);
+ // Which of the four buttons a tap at (x, y) lands on, or -1.
+ const hitIndex = async (x: number, y: number) =>
+ page.evaluate(
+ ([px, py]) => {
+ const all = Array.from(
+ document.querySelectorAll('#storybook-root button'),
+ );
+ const hit = document.elementFromPoint(px, py)?.closest('button');
+ return hit == null ? -1 : all.indexOf(hit);
+ },
+ [x, y] as const,
+ );
+ for (let index = 0; index < 3; index += 1) {
+ const left = boxes[index];
+ const right = boxes[index + 1];
+ if (left == null || right == null) {
+ throw new Error('unreachable');
+ }
+ const gap = right.x - (left.x + left.width);
+ expect(gap, 'the buttons sit apart').toBeGreaterThan(4);
+ const middle = left.x + left.width + gap / 2;
+ const y = left.y + left.height / 2;
+ // Each side of the middle belongs to the nearer button.
+ expect(await hitIndex(middle - 1, y)).toBe(index);
+ expect(await hitIndex(middle + 1, y)).toBe(index + 1);
+ }
+});
+
+test('under a fine pointer the info button grows nothing', async ({
+ browser,
+}) => {
+ const page = await pageWith(browser, 'fine');
+ await openStory(page, 'default');
+ const {button, box} = await infoButton(page);
+ // Give the shared hit area the frames it would take to measure.
+ await page.evaluate(async () => {
+ await new Promise<void>(resolve => {
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
+ });
+ });
+ // Unset, or 0 where the shared hit area answers a fine pointer.
+ expect(
+ await button.evaluate(element =>
+ Number.parseFloat(
+ getComputedStyle(element).getPropertyValue('--astryx-hit-inset-left') ||
+ '0',
+ ),
+ ),
+ ).toBe(0);
+ const centerY = box.y + box.height / 2;
+ expect(await hitsButton(page, box.x + 1, centerY)).toBe(true);
+ expect(await hitsButton(page, box.x - 2, centerY)).toBe(false);
+});
diff --git a/packages/core/src/InfoTip/index.ts b/packages/core/src/InfoTip/index.ts
new file mode 100644
index 0000000000..7fb38a753e
--- /dev/null
+++ b/packages/core/src/InfoTip/index.ts
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file InfoTip component barrel export
+ * @input InfoTip.tsx
+ * @output Exports InfoTip, InfoTipProps, InfoTipSize
+ * @position Barrel; consumed by packages/core/src/index.ts and the
+ * `@astryxdesign/core/InfoTip` entry
+ */
+
+export {InfoTip} from './InfoTip';
+export type {InfoTipProps, InfoTipSize} from './InfoTip';
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index da746066d7..e768052a92 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -71,6 +71,7 @@ export * from './SelectableCard';
export * from './Selector';
export * from './MultiSelector';
export * from './Icon';
+export * from './InfoTip';
export * from './Indicator';
export * from './InputGroup';
export * from './Item';
diff --git a/packages/lab/src/InfoTip/InfoTip.doc.mjs b/packages/lab/src/InfoTip/InfoTip.doc.mjs
deleted file mode 100644
index f3dfb20589..0000000000
--- a/packages/lab/src/InfoTip/InfoTip.doc.mjs
+++ /dev/null
@@ -1,100 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
-
-export const docs = {
- name: 'InfoTip',
- displayName: 'Info Tip',
- category: 'Feedback & Status',
- keywords: ["info","tooltip","help","hint","affordance","icon","label","field","metric","definition"],
- props: [
- {
- name: 'content',
- type: 'ReactNode',
- description: 'Content to display in the tooltip. Typically short, non-interactive text. Mirrors Tooltip\'s content prop.',
- required: true,
- },
- {
- name: 'label',
- type: 'string',
- description: 'Accessible name for the trigger button.',
- default: "'More information'",
- },
- {
- name: 'size',
- type: "'xsm' | 'sm' | 'md' | 'lg'",
- description: 'Size of the info icon (12px, 16px, 20px, 24px). Maps 1:1 to Icon sizes.',
- default: "'sm'",
- },
- ],
- usage: {
- description:
- 'An inline info-icon help affordance: a small "i" button that reveals a tooltip on hover, keyboard focus, and tap. Use it next to labels, values, and metrics for permission notes, metric definitions, and field help. Its value over hand-composing Icon inside Tooltip is the pre-wired accessible trigger: a real button with an aria-label, Tab-reachable, tooltip on hover AND focus AND tap, and Escape dismissal.',
- bestPractices: [
- { guidance: true, description: 'Keep tooltip content concise, plain, and non-interactive; use Popover or HoverCard for links and buttons.' },
- { guidance: true, description: 'Override label when "More information" is too generic, e.g. "About this metric".' },
- { guidance: true, description: 'Rely on InfoTip rather than a hand-rolled info button on touch: it sets Tooltip touchTrigger to tap, so a tap opens the tooltip even though the trigger is a button, and a tap outside dismisses it.' },
- { guidance: false, description: 'Hand-compose Icon inside Tooltip for info affordances; the bare Icon is aria-hidden and unfocusable, so keyboard and screen-reader users never see it.' },
- { guidance: false, description: 'Use InfoTip for essential information users must see to complete a task; put that text inline instead.' },
- ],
- },
-};
-
-/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
-export const docsZh = {
- name: 'InfoTip',
- displayName: 'Info Tip',
- props: [
- {
- name: 'content',
- type: 'ReactNode',
- description: '工具提示中显示的内容。通常为简短的非交互文本。与 Tooltip 的 content 属性一致。',
- required: true,
- },
- {
- name: 'label',
- type: 'string',
- description: '触发按钮的无障碍名称。',
- default: "'More information'",
- },
- {
- name: 'size',
- type: "'xsm' | 'sm' | 'md' | 'lg'",
- description: '信息图标的尺寸(12px、16px、20px、24px)。与 Icon 尺寸一一对应。',
- default: "'sm'",
- },
- ],
- usage: {
- description:
- 'An inline info-icon help affordance: a small "i" button that reveals a tooltip on hover, keyboard focus, and tap. Use it next to labels, values, and metrics for permission notes, metric definitions, and field help.',
- bestPractices: [
- { guidance: true, description: 'Keep tooltip content concise, plain, and non-interactive; use Popover or HoverCard for links and buttons.' },
- { guidance: true, description: 'Override label when "More information" is too generic, e.g. "About this metric".' },
- { guidance: true, description: 'Rely on InfoTip rather than a hand-rolled info button on touch: it sets Tooltip touchTrigger to tap, so a tap opens the tooltip even though the trigger is a button, and a tap outside dismisses it.' },
- { guidance: false, description: 'Hand-compose Icon inside Tooltip for info affordances; the bare Icon is aria-hidden and unfocusable, so keyboard and screen-reader users never see it.' },
- { guidance: false, description: 'Use InfoTip for essential information users must see to complete a task; put that text inline instead.' },
- ],
- },
-};
-
-/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */
-export const docsDense = {
- description:
- 'Inline info-icon help affordance: accessible "i" button trigger pre-wired into a Tooltip.',
- usage: {
- description:
- 'A small "i" button that reveals a tooltip on hover, keyboard focus, and tap. Use next to labels, values, and metrics for permission notes, metric definitions, and field help. Pre-wired accessible trigger: real button, aria-label, Tab-reachable, tooltip on hover AND focus AND tap, Escape dismissal.',
- bestPractices: [
- { guidance: true, description: 'Keep tooltip content concise, plain, and non-interactive; use Popover or HoverCard for links and buttons.' },
- { guidance: true, description: 'Override label when "More information" is too generic, e.g. "About this metric".' },
- { guidance: true, description: 'Rely on InfoTip rather than a hand-rolled info button on touch: it sets Tooltip touchTrigger to tap, so a tap opens the tooltip even though the trigger is a button, and a tap outside dismisses it.' },
- { guidance: false, description: 'Hand-compose Icon inside Tooltip for info affordances; the bare Icon is aria-hidden and unfocusable.' },
- { guidance: false, description: 'Use InfoTip for essential information users must see to complete a task; put that text inline instead.' },
- ],
- },
- propDescriptions: {
- content: 'Tooltip content. Short, non-interactive text. Mirrors Tooltip content prop.',
- label: "Accessible name for the trigger button. Default 'More information'.",
- size: 'Info icon size (12/16/20/24px). Maps 1:1 to Icon sizes.',
- },
-};
diff --git a/packages/lab/src/InfoTip/InfoTip.test.tsx b/packages/lab/src/InfoTip/InfoTip.test.tsx
index 7edd6079b7..54cdea9164 100644
--- a/packages/lab/src/InfoTip/InfoTip.test.tsx
+++ b/packages/lab/src/InfoTip/InfoTip.test.tsx
@@ -2,237 +2,32 @@
/**
* @file InfoTip.test.tsx
- * @input Uses vitest, @testing-library/react, @testing-library/user-event, InfoTip component
- * @output Unit tests for InfoTip trigger accessibility and tooltip behavior
- * @position Testing; validates InfoTip.tsx implementation
- *
- * SYNC: When InfoTip.tsx changes, update tests to match new behavior
+ * @input The Lab InfoTip entry and the Core component
+ * @output Tests that the Lab entry re-exports the Core component, deprecated
+ * @position Testing; validates index.ts (component:InfoTip FR4)
*/
-import {describe, it, expect, vi, beforeAll, afterAll} from 'vitest';
-import {render, screen, fireEvent, waitFor, act} from '@testing-library/react';
-import userEvent from '@testing-library/user-event';
-import {InfoTip} from './InfoTip';
-
-// Store original matches to restore later
-const originalMatches = HTMLElement.prototype.matches;
-
-// Track popover open state per element
-const popoverOpenState = new WeakMap<HTMLElement, boolean>();
-
-// Mock Popover API for jsdom, and :focus-visible for keyboard-focus tests
-// (same harness as core Tooltip.test.tsx, plus :focus-visible)
-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);
- });
-
- // Intercept :popover-open and :focus-visible, delegate everything else
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- (HTMLElement.prototype as any).matches = function (
- selector: string,
- ): boolean {
- if (selector === ':popover-open') {
- return popoverOpenState.get(this) ?? false;
- }
- if (selector === ':focus-visible') {
- // Treat any focused element as keyboard-focused in tests
- return this === document.activeElement;
+import {readFileSync} from 'node:fs';
+import path from 'node:path';
+import {describe, expect, it} from 'vitest';
+import {InfoTip as CoreInfoTip} from '@astryxdesign/core/InfoTip';
+import {InfoTip} from './index';
+
+describe('Lab InfoTip', () => {
+ it('is the Core component', () => {
+ expect(InfoTip).toBe(CoreInfoTip);
+ });
+
+ it('marks each of its exports deprecated', () => {
+ // Static metadata only: editors and type checkers show it, and nothing
+ // warns at runtime.
+ const source = readFileSync(path.join(__dirname, 'index.ts'), 'utf8');
+ for (const name of ['InfoTip', 'InfoTipProps', 'InfoTipSize']) {
+ // The doc comment right above the export, whatever it contains.
+ const comment = new RegExp(
+ String.raw`/\*\*((?:(?!\*/)[\s\S])*)\*/\nexport (?:const|type) ${name}\b`,
+ ).exec(source);
+ expect(comment?.[1], name).toContain('@deprecated');
}
- return originalMatches.call(this, selector);
- };
-});
-
-afterAll(() => {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- (HTMLElement.prototype as any).matches = originalMatches;
-});
-
-/** Focus the trigger the way a keyboard user would land on it. */
-function focusTrigger(trigger: HTMLElement) {
- act(() => {
- trigger.focus();
- });
- fireEvent.focusIn(trigger);
-}
-
-describe('InfoTip', () => {
- it('renders a button trigger with the default accessible name', () => {
- render(<InfoTip content="Helpful context" />);
- expect(
- screen.getByRole('button', {name: 'More information'}),
- ).toBeInTheDocument();
- });
-
- it('uses a custom label as the accessible name', () => {
- render(
- <InfoTip content="30-day rolling average." label="About this metric" />,
- );
- const trigger = screen.getByRole('button', {name: 'About this metric'});
- expect(trigger).toHaveAttribute('aria-label', 'About this metric');
- });
-
- it('links the trigger to the tooltip layer via aria-describedby', () => {
- render(<InfoTip content="Helpful context" />);
- const layer = screen.getByRole('tooltip', {hidden: true});
- expect(layer).toHaveTextContent('Helpful context');
- const trigger = screen.getByRole('button', {name: 'More information'});
- expect(trigger.getAttribute('aria-describedby')).toBe(layer.id);
- });
-
- it('is reachable with Tab', async () => {
- const user = userEvent.setup();
- render(<InfoTip content="Helpful context" />);
- const trigger = screen.getByRole('button', {name: 'More information'});
- await user.tab();
- expect(trigger).toHaveFocus();
- });
-
- it('shows the tooltip on hover', async () => {
- vi.mocked(HTMLElement.prototype.showPopover).mockClear();
- render(<InfoTip content="Helpful context" />);
- const trigger = screen.getByRole('button', {name: 'More information'});
-
- fireEvent.mouseEnter(trigger);
-
- await waitFor(() => {
- expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();
- });
- });
-
- it('shows the tooltip on keyboard focus', async () => {
- vi.mocked(HTMLElement.prototype.showPopover).mockClear();
- render(<InfoTip content="Helpful context" />);
- const trigger = screen.getByRole('button', {name: 'More information'});
-
- focusTrigger(trigger);
-
- await waitFor(() => {
- expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();
- });
- const layer = screen.getByRole('tooltip', {hidden: true});
- expect(popoverOpenState.get(layer)).toBe(true);
- });
-
- it('closes the tooltip on Escape', async () => {
- render(<InfoTip content="Helpful context" />);
- const trigger = screen.getByRole('button', {name: 'More information'});
- const layer = screen.getByRole('tooltip', {hidden: true});
-
- focusTrigger(trigger);
- await waitFor(() => {
- expect(popoverOpenState.get(layer)).toBe(true);
- });
-
- fireEvent.keyDown(trigger, {key: 'Escape'});
-
- await waitFor(() => {
- expect(popoverOpenState.get(layer)).toBe(false);
- });
- });
-
- it('re-opens after Escape once the trigger is left and re-hovered', async () => {
- render(<InfoTip content="Helpful context" />);
- const trigger = screen.getByRole('button', {name: 'More information'});
- const layer = screen.getByRole('tooltip', {hidden: true});
-
- focusTrigger(trigger);
- await waitFor(() => {
- expect(popoverOpenState.get(layer)).toBe(true);
- });
-
- fireEvent.keyDown(trigger, {key: 'Escape'});
- await waitFor(() => {
- expect(popoverOpenState.get(layer)).toBe(false);
- });
-
- // Leave (resets dismissal), then re-enter
- act(() => {
- trigger.blur();
- });
- fireEvent.focusOut(trigger);
- fireEvent.mouseLeave(trigger);
-
- fireEvent.mouseEnter(trigger);
- await waitFor(() => {
- expect(popoverOpenState.get(layer)).toBe(true);
- });
- });
-
- it('renders ReactNode tooltip content', () => {
- render(<InfoTip content={<span data-testid="rich-content">Rich</span>} />);
- expect(screen.getByTestId('rich-content')).toBeInTheDocument();
- });
- describe('touch', () => {
- /**
- * A tap, in the order a browser dispatches it: the finger's pointer events,
- * the hover it synthesizes, then the `click` that says the touch was a tap.
- */
- const tap = (element: HTMLElement) => {
- fireEvent.pointerEnter(element, {pointerType: 'touch'});
- fireEvent.pointerDown(element, {pointerType: 'touch'});
- fireEvent.pointerUp(element, {pointerType: 'touch'});
- fireEvent.mouseEnter(element);
- fireEvent.click(element);
- };
-
- it('opens on a tap, though the trigger is a button', async () => {
- render(<InfoTip content="30-day rolling average." />);
- const trigger = screen.getByRole('button');
- const layer = screen.getByRole('tooltip', {hidden: true});
-
- // Tooltip's `auto` rule would give this tap to the button and suppress
- // the tooltip; revealing it is the button's whole purpose, so InfoTip
- // opts in. Without this its content is unreachable on a phone.
- tap(trigger);
-
- await waitFor(() => {
- expect(popoverOpenState.get(layer)).toBe(true);
- });
- });
-
- it('closes on a second tap of the trigger', async () => {
- render(<InfoTip content="30-day rolling average." />);
- const trigger = screen.getByRole('button');
- const layer = screen.getByRole('tooltip', {hidden: true});
-
- tap(trigger);
- await waitFor(() => {
- expect(popoverOpenState.get(layer)).toBe(true);
- });
-
- tap(trigger);
- await waitFor(() => {
- expect(popoverOpenState.get(layer)).toBe(false);
- });
- });
-
- it('closes on a tap outside', async () => {
- render(
- <>
- <InfoTip content="30-day rolling average." />
- <button type="button">Elsewhere</button>
- </>,
- );
- const trigger = screen.getByRole('button', {name: 'More information'});
- const layer = screen.getByRole('tooltip', {hidden: true});
-
- tap(trigger);
- await waitFor(() => {
- expect(popoverOpenState.get(layer)).toBe(true);
- });
-
- // The tap outside counts when the finger lifts.
- const elsewhere = screen.getByRole('button', {name: 'Elsewhere'});
- fireEvent.pointerDown(elsewhere, {pointerType: 'touch'});
- fireEvent.pointerUp(elsewhere, {pointerType: 'touch'});
-
- await waitFor(() => {
- expect(popoverOpenState.get(layer)).toBe(false);
- });
- });
});
});
diff --git a/packages/lab/src/InfoTip/InfoTip.tsx b/packages/lab/src/InfoTip/InfoTip.tsx
deleted file mode 100644
index fa3e9dc46d..0000000000
--- a/packages/lab/src/InfoTip/InfoTip.tsx
+++ /dev/null
@@ -1,128 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-'use client';
-
-/**
- * @file InfoTip.tsx
- * @input Uses React, stylex, Tooltip + Icon from @astryxdesign/core, color/spacing/radius/duration/ease tokens
- * @output Exports InfoTip component, InfoTipProps, InfoTipSize types
- * @position Lab experiment (RFC meta/astryx#3349); core implementation consumed by index.ts
- *
- * SYNC: When modified, update these files to stay in sync:
- * - /packages/lab/src/InfoTip/InfoTip.doc.mjs (props table, features)
- * - /packages/lab/src/InfoTip/InfoTip.test.tsx (tests for new/changed behavior)
- * - /packages/lab/src/InfoTip/index.ts (exports if types change)
- */
-
-import {type ReactNode} from 'react';
-import * as stylex from '@stylexjs/stylex';
-
-import {Icon, type IconSize} from '@astryxdesign/core/Icon';
-import {Tooltip} from '@astryxdesign/core/Tooltip';
-import {
- colorVars,
- durationVars,
- easeVars,
- radiusVars,
- spacingVars,
-} from '@astryxdesign/core/theme/tokens.stylex';
-import {focusOutlineStyles} from '@astryxdesign/core/utils';
-
-/**
- * Size of the info icon. Maps 1:1 to Icon sizes
- * (xsm: 12px, sm: 16px, md: 20px, lg: 24px).
- */
-export type InfoTipSize = IconSize;
-
-export interface InfoTipProps {
- /**
- * Content to display in the tooltip.
- * Typically short, non-interactive text. Mirrors Tooltip's `content` prop.
- */
- content: ReactNode;
- /**
- * Accessible name for the trigger button.
- * @default 'More information'
- */
- label?: string;
- /**
- * Size of the info icon.
- * @default 'sm'
- */
- size?: InfoTipSize;
-}
-
-const styles = stylex.create({
- trigger: {
- display: 'inline-flex',
- alignItems: 'center',
- justifyContent: 'center',
- verticalAlign: 'middle',
- padding: spacingVars['--spacing-0-5'],
- margin: 0,
- borderStyle: 'none',
- backgroundColor: 'transparent',
- borderRadius: radiusVars['--radius-full'],
- cursor: {
- default: 'pointer',
- ':is(:disabled,[aria-disabled="true"])': 'default',
- },
- color: {
- default: colorVars['--color-icon-secondary'],
- ':hover:where(:not(:disabled,[aria-disabled="true"]))': {
- default: null,
- '@media (hover: hover)': colorVars['--color-icon-primary'],
- },
- },
- transitionProperty: 'color',
- transitionDuration: durationVars['--duration-fast'],
- transitionTimingFunction: easeVars['--ease-standard'],
- },
-});
-
-/**
- * An inline info-icon help affordance: a small "i" button that reveals a
- * tooltip on hover, keyboard focus, and tap. Use it next to labels, values,
- * and metrics for permission notes, metric definitions, and field help.
- *
- * The value over hand-composing Icon inside Tooltip is the pre-wired
- * accessible trigger: a real button with an aria-label, Tab-reachable,
- * tooltip on hover AND focus, and Escape dismissal.
- *
- * Composed entirely from core primitives (Tooltip + Icon); the info icon
- * resolves from the global icon registry, so themes can override it.
- *
- * @example
- * ```
- * <InfoTip content="Editors can change this field; viewers cannot." />
- * <InfoTip content="30-day rolling average." label="About this metric" />
- * ```
- */
-export function InfoTip({
- content,
- label = 'More information',
- size = 'sm',
-}: InfoTipProps): ReactNode {
- // No local Escape handler: the trigger used to stopPropagation the press,
- // which hid the tip but left the browser's close watcher to fire `cancel` on
- // an enclosing Dialog, so one press took both (#5168). Tooltip's own entry in
- // the shared dismissal stack takes it instead.
- return (
- <Tooltip
- content={content}
- // The trigger is a real button, so Tooltip's `auto` touch rule would
- // give the tap to the control and suppress the tooltip. Here the tooltip
- // IS the control's only purpose, so the tap has to open it — otherwise
- // an InfoTip's content is unreachable on a phone.
- touchTrigger="tap">
- <button
- type="button"
- aria-label={label}
- {...stylex.props(focusOutlineStyles.focusVisible, styles.trigger)}>
- <Icon icon="info" size={size} />
- </button>
- </Tooltip>
- );
-}
-
-InfoTip.displayName = 'InfoTip';
diff --git a/packages/lab/src/InfoTip/index.ts b/packages/lab/src/InfoTip/index.ts
index 7aa409a085..7ff69ba1b4 100644
--- a/packages/lab/src/InfoTip/index.ts
+++ b/packages/lab/src/InfoTip/index.ts
@@ -3,8 +3,33 @@
'use client';
/**
- * @file InfoTip component barrel export
+ * @file InfoTip deprecated re-export
+ * @input `@astryxdesign/core/InfoTip`
+ * @output Exports InfoTip, InfoTipProps, InfoTipSize, each deprecated
+ * @position Lab entry kept for one release after InfoTip moved to Core;
+ * consumed by packages/lab/src/index.ts
*/
-export {InfoTip} from './InfoTip';
-export type {InfoTipProps, InfoTipSize} from './InfoTip';
+import {
+ InfoTip as CoreInfoTip,
+ type InfoTipProps as CoreInfoTipProps,
+ type InfoTipSize as CoreInfoTipSize,
+} from '@astryxdesign/core/InfoTip';
+
+/**
+ * @deprecated InfoTip moved to Core: import it from `@astryxdesign/core`.
+ * This Lab export is removed in the next release.
+ */
+export const InfoTip = CoreInfoTip;
+
+/**
+ * @deprecated Import `InfoTipProps` from `@astryxdesign/core`. This Lab
+ * export is removed in the next release.
+ */
+export type InfoTipProps = CoreInfoTipProps;
+
+/**
+ * @deprecated Import `InfoTipSize` from `@astryxdesign/core`. This Lab export
+ * is removed in the next release.
+ */
+export type InfoTipSize = CoreInfoTipSize;