Skip to content

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

TypeScript

feat(Tooltip, HoverCard): tap to open where there is no hover (#5248)

rubyycheung5d8ece19c465
diff --git a/.changeset/tooltip-and-hovercard-tap-to-open-where-there-is-tzru.md b/.changeset/tooltip-and-hovercard-tap-to-open-where-there-is-tzru.md
new file mode 100644
index 0000000000..556cbb3bec
--- /dev/null
+++ b/.changeset/tooltip-and-hovercard-tap-to-open-where-there-is-tzru.md
@@ -0,0 +1,41 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Tooltip and HoverCard: tap to open where there is no hover
+
+Hover is the one trigger a touch screen cannot express, and both components
+were answering that badly. `Tooltip` suppressed itself on any device reporting
+`(hover: none)`, so its content — often the only label an icon button has —
+was simply unreachable on a phone. `HoverCard` did nothing at all: the
+`mouseenter` a tap synthesizes opened the card on every tap of its trigger,
+over the control the user was aiming at, with no gesture that closed it again.
+
+Both now take a `touchTrigger` prop, and what the trigger DOES decides the
+default. A trigger that performs an action — a button, a link, a form control
+— keeps its tap under `auto`: the layer stays shut, because the tap already
+has somewhere to go and a hint about a control the user just operated is
+noise. A trigger that performs no action — an info icon, an abbreviation, a
+truncated label — has nothing to lose, so the tap opens the layer, with no
+show delay (a tap is a decision, not the hover intent the delay exists to
+filter) and a tap outside to dismiss it. `tap` and `none` state the choice
+outright; `tap` is what an info icon rendered as a button wants, since it
+looks like an action to the DOM while revealing the layer is the only thing it
+does.
+
+Hover-capable devices are unaffected, hybrid ones included: the decision is
+made per interaction from the pointer type rather than once per device from a
+media query, so the same trigger opens on hover under a mouse and on tap under
+a finger. A stylus is a hover device by the same rule — a pen in detection
+range fires hover events with nothing in contact, so it opens the layer on
+hover, and only a pen that lands counts as a tap. Neither layer opens from the
+focus a tap leaves behind any more — the second way a tap could bury the
+control it activated, and on `Tooltip` it is the tapped text fields that were
+affected, since those match `:focus-visible` by design.
+
+[fix] InfoTip (lab): opts into `touchTrigger="tap"`. Its trigger is a real
+button, so the `auto` rule would hand the tap to the control — but revealing
+the tooltip is that button's only purpose, and suppressing it left an
+InfoTip's content unreachable on a phone.
+
+@rubycheung
diff --git a/apps/storybook/stories/HoverCard.stories.tsx b/apps/storybook/stories/HoverCard.stories.tsx
index f0e1c1dcb8..4dac4d156b 100644
--- a/apps/storybook/stories/HoverCard.stories.tsx
+++ b/apps/storybook/stories/HoverCard.stories.tsx
@@ -32,6 +32,12 @@ const meta: Meta<typeof HoverCard> = {
control: 'boolean',
description: 'Enable/disable the hover card',
},
+ touchTrigger: {
+ control: 'select',
+ options: ['auto', 'tap', 'none'],
+ description:
+ 'What a tap does where there is no hover: auto (tap unless the trigger acts), tap, or none',
+ },
},
};
@@ -91,9 +97,7 @@ export const CustomDelay: Story = {
delay: 500,
hideDelay: 300,
content: <ProfileCard />,
- children: (
- <Button label="Slow hover (500ms)">Slow hover (500ms)</Button>
- ),
+ children: <Button label="Slow hover (500ms)">Slow hover (500ms)</Button>,
},
};
@@ -210,3 +214,24 @@ export const TextNodeMultiple: Story = {
</div>
),
};
+
+/**
+ * Touch has no hover, so a tap decides instead. A tap-opened card is dismissed
+ * by a tap outside it, and a tap on the card's own content leaves it open.
+ */
+export const TouchTriggers: Story = {
+ render: () => (
+ <div style={{padding: 100}}>
+ <HStack gap={4}>
+ {/* Acts on tap: the tap belongs to the button, so no card. */}
+ <HoverCard content={<ProfileCard />} placement="above">
+ <Button label="Open profile">Open profile</Button>
+ </HoverCard>
+ {/* Does nothing on tap: the tap opens the card. */}
+ <HoverCard content={<ProfileCard />} placement="above">
+ Jane Doe
+ </HoverCard>
+ </HStack>
+ </div>
+ ),
+};
diff --git a/apps/storybook/stories/InfoTip.stories.tsx b/apps/storybook/stories/InfoTip.stories.tsx
new file mode 100644
index 0000000000..c9aad4bd65
--- /dev/null
+++ b/apps/storybook/stories/InfoTip.stories.tsx
@@ -0,0 +1,76 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {InfoTip} from '@astryxdesign/lab/InfoTip';
+import {HStack} from '@astryxdesign/core/Layout';
+import {Text} from '@astryxdesign/core/Text';
+
+const meta: Meta<typeof InfoTip> = {
+ title: 'Lab/InfoTip',
+ component: InfoTip,
+ tags: ['autodocs'],
+ argTypes: {
+ size: {
+ control: 'select',
+ options: ['xsm', 'sm', 'md', 'lg'],
+ description: 'Size of the info icon',
+ },
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof InfoTip>;
+
+export const Default: Story = {
+ args: {
+ content: 'Editors can change this field; viewers cannot.',
+ },
+};
+
+export const NextToALabel: Story = {
+ render: () => (
+ <div style={{padding: 100}}>
+ <HStack gap={1} align="center">
+ <Text>Rolling average</Text>
+ <InfoTip
+ content="30-day rolling average, recomputed nightly."
+ label="About this metric"
+ />
+ </HStack>
+ </div>
+ ),
+};
+
+/**
+ * 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.
+ */
+export const Touch: Story = {
+ render: () => (
+ <div style={{padding: 100}}>
+ <HStack gap={1} align="center">
+ <Text>Rolling average</Text>
+ <InfoTip
+ content="30-day rolling average, recomputed nightly."
+ label="About this metric"
+ />
+ </HStack>
+ </div>
+ ),
+};
+
+export const Sizes: Story = {
+ render: () => (
+ <div style={{padding: 100}}>
+ <HStack gap={4} align="center">
+ <InfoTip content="Extra small" size="xsm" />
+ <InfoTip content="Small (default)" size="sm" />
+ <InfoTip content="Medium" size="md" />
+ <InfoTip content="Large" size="lg" />
+ </HStack>
+ </div>
+ ),
+};
diff --git a/apps/storybook/stories/Tooltip.stories.tsx b/apps/storybook/stories/Tooltip.stories.tsx
index 0881e8ef4e..71892f9fca 100644
--- a/apps/storybook/stories/Tooltip.stories.tsx
+++ b/apps/storybook/stories/Tooltip.stories.tsx
@@ -32,6 +32,12 @@ const meta: Meta<typeof Tooltip> = {
control: 'boolean',
description: 'Enable/disable the tooltip',
},
+ touchTrigger: {
+ control: 'select',
+ options: ['auto', 'tap', 'none'],
+ description:
+ 'What a tap does where there is no hover: auto (tap unless the trigger acts), tap, or none',
+ },
},
};
@@ -142,9 +148,7 @@ export const LongContent: Story = {
placement: 'above',
content:
'This is a longer tooltip that contains more detailed information about the element.',
- children: (
- <Button label="Hover for more info">Hover for more info</Button>
- ),
+ children: <Button label="Hover for more info">Hover for more info</Button>,
},
};
@@ -201,3 +205,34 @@ export const TextNodeInline: Story = {
</div>
),
};
+
+/**
+ * Touch has no hover, so a tap decides instead — and what the trigger does
+ * decides for it. Try these on a phone, or in a device emulator with touch
+ * emulation on.
+ */
+export const TouchTriggers: Story = {
+ render: () => (
+ <div style={{padding: 100}}>
+ <HStack gap={4}>
+ {/* Acts on tap: the tap belongs to the button, so no tooltip. */}
+ <Tooltip content="Saves your changes" placement="above">
+ <Button label="Save">Save</Button>
+ </Tooltip>
+ {/* Does nothing on tap: the tap opens the tooltip. */}
+ <Tooltip content="Tooltip on inline text!" placement="above">
+ hover-able term
+ </Tooltip>
+ {/* A button whose only job is the tooltip — say so with `tap`. */}
+ <Tooltip
+ content="Rows are ranked by how many places import the icon"
+ placement="above"
+ touchTrigger="tap">
+ <Button label="What is this?" variant="secondary">
+ ?
+ </Button>
+ </Tooltip>
+ </HStack>
+ </div>
+ ),
+};
diff --git a/packages/core/src/HoverCard/HoverCard.doc.mjs b/packages/core/src/HoverCard/HoverCard.doc.mjs
index e0d7769a32..4fbad801b1 100644
--- a/packages/core/src/HoverCard/HoverCard.doc.mjs
+++ b/packages/core/src/HoverCard/HoverCard.doc.mjs
@@ -73,6 +73,13 @@ export const docs = {
description: 'Controls when focus events trigger the hover card.',
default: "'auto'",
},
+ {
+ name: 'touchTrigger',
+ type: "'auto' | 'tap' | 'none'",
+ description:
+ 'What a tap does where there is no hover. auto opens on tap unless the trigger performs an action of its own (a button, link, or form control), whose tap belongs to the control. tap always opens. none never opens on touch. A tap-opened card is dismissed by a tap outside it.',
+ default: "'auto'",
+ },
{
name: 'isEnabled',
type: 'boolean',
@@ -111,6 +118,7 @@ export const docs = {
{ guidance: true, description: 'Keep content supplementary; hover cards should enhance understanding without blocking the primary workflow.' },
{ guidance: true, description: 'Provide a dashed underline on text triggers so users know the element is hoverable.' },
{ guidance: true, description: 'Use the hook API (useHoverCard) when you need more control over timing or placement.' },
+ { guidance: true, description: 'Leave touchTrigger on auto so a tap opens the card on triggers that do nothing else, and stays out of the way on triggers that perform an action.' },
{ guidance: false, description: 'Place critical actions or required information inside a hover card; users may miss content that only appears on hover.' },
{ guidance: false, description: 'Use a hover card when a simple Tooltip or Popover would suffice.' },
{ guidance: false, description: 'Use a HoverCard for content the user must interact with; it disappears when the cursor leaves.' },
@@ -188,6 +196,13 @@ export const docsZh = {
description: '控制焦点事件何时触发悬浮卡片。',
default: "'auto'",
},
+ {
+ name: 'touchTrigger',
+ type: "'auto' | 'tap' | 'none'",
+ description:
+ '在没有悬停的触摸设备上,轻点的行为。auto:轻点即打开,除非触发元素本身会执行操作(按钮、链接、表单控件),此时轻点归该控件所有。tap:始终轻点打开。none:触摸永不打开。轻点打开的卡片可通过点击卡片外部关闭。',
+ default: "'auto'",
+ },
{
name: 'isEnabled',
type: 'boolean',
@@ -226,6 +241,7 @@ export const docsZh = {
{ guidance: true, description: 'Keep content supplementary; hover cards should enhance understanding without blocking the primary workflow.' },
{ guidance: true, description: 'Provide a dashed underline on text triggers so users know the element is hoverable.' },
{ guidance: true, description: 'Use the hook API (useHoverCard) when you need more control over timing or placement.' },
+ { guidance: true, description: 'Leave touchTrigger on auto so a tap opens the card on triggers that do nothing else, and stays out of the way on triggers that perform an action.' },
{ guidance: false, description: 'Place critical actions or required information inside a hover card; users may miss content that only appears on hover.' },
{ guidance: false, description: 'Use a hover card when a simple Tooltip or Popover would suffice.' },
{ guidance: false, description: 'Use a HoverCard for content the user must interact with; it disappears when the cursor leaves.' },
@@ -244,6 +260,7 @@ export const docsDense = {
{ guidance: true, description: 'Keep content supplementary; hover cards should enhance understanding without blocking the primary workflow.' },
{ guidance: true, description: 'Provide a dashed underline on text triggers so users know the element is hoverable.' },
{ guidance: true, description: 'Use the hook API (useHoverCard) when you need more control over timing or placement.' },
+ { guidance: true, description: 'Leave touchTrigger on auto so a tap opens the card on triggers that do nothing else, and stays out of the way on triggers that perform an action.' },
{ guidance: false, description: 'Place critical actions or required information inside a hover card; users may miss content that only appears on hover.' },
{ guidance: false, description: 'Use a hover card when a simple Tooltip or Popover would suffice.' },
{ guidance: false, description: 'Use a HoverCard for content the user must interact with; it disappears when the cursor leaves.' },
@@ -263,6 +280,7 @@ export const docsDense = {
delay: 'Show delay in ms.',
hideDelay: 'Hide delay in ms.',
focusTrigger: 'Controls when focus events trigger hover card.',
+ touchTrigger: 'Tap behavior where there is no hover. auto = tap opens unless the trigger acts (button/link/control); tap = always opens; none = never on touch. Tap-opened cards close on a tap outside.',
isEnabled: 'Enable/disable hover + focus triggers.',
label: 'Accessible name for the popup. With label: named role="dialog"; without: role="group".',
onOpenChange: 'Callback when visibility changes; true=shown, false=hidden.',
diff --git a/packages/core/src/HoverCard/HoverCard.test.tsx b/packages/core/src/HoverCard/HoverCard.test.tsx
index b1fbcf892f..204a299ccd 100644
--- a/packages/core/src/HoverCard/HoverCard.test.tsx
+++ b/packages/core/src/HoverCard/HoverCard.test.tsx
@@ -25,6 +25,7 @@ import {StrictMode} from 'react';
import {Button} from '../Button/Button';
import {Theme, defineTheme} from '../theme';
import {HoverCard} from './HoverCard';
+import {__resetInteractionModalityForTest} from '../utils/interactionModality';
// Store original matches to restore later
const originalMatches = HTMLElement.prototype.matches;
@@ -804,4 +805,192 @@ describe('HoverCard', () => {
container.remove();
});
});
+
+ describe('touch', () => {
+ // The modality is document-global; a tap in one case must not decide the
+ // next one's answer.
+ beforeEach(() => {
+ __resetInteractionModalityForTest();
+ });
+
+ /** A tap: the pointer sequence a finger produces before hover is faked. */
+ const tap = (element: HTMLElement) => {
+ // A finger's arrival fires pointerenter too, and that is the path a pen
+ // must not take — cover it here rather than starting at pointerdown.
+ fireEvent.pointerEnter(element, {pointerType: 'touch'});
+ fireEvent.pointerDown(element, {pointerType: 'touch'});
+ fireEvent.pointerUp(element, {pointerType: 'touch'});
+ // Touch synthesizes hover after the press; the card must not act on it.
+ fireEvent.mouseEnter(element);
+ };
+
+ it('opens on a tap when the trigger performs no action', async () => {
+ const onOpenChange = vi.fn();
+ render(
+ <HoverCard
+ content={<span>Card content</span>}
+ onOpenChange={onOpenChange}
+ delay={300}>
+ Ruby Cheung
+ </HoverCard>,
+ );
+
+ tap(screen.getByText('Ruby Cheung'));
+
+ // Immediately: a tap is a decision, not hover intent, so no delay applies.
+ await waitFor(() => {
+ expect(onOpenChange).toHaveBeenCalledWith(true);
+ });
+ });
+
+ it('stays shut on a tap when the trigger performs an action', async () => {
+ const onOpenChange = vi.fn();
+ render(
+ <HoverCard
+ content={<span>Card content</span>}
+ onOpenChange={onOpenChange}
+ delay={0}>
+ <button type="button">Save</button>
+ </HoverCard>,
+ );
+
+ const trigger = screen.getByRole('button', {name: 'Save'});
+ tap(trigger);
+ // A tap focuses what it activates; that focus must not reopen the card.
+ fireEvent.focusIn(trigger);
+
+ await new Promise(resolve => setTimeout(resolve, 50));
+ expect(onOpenChange).not.toHaveBeenCalledWith(true);
+ });
+
+ it('opens on a tap of an action trigger when touchTrigger is "tap"', async () => {
+ const onOpenChange = vi.fn();
+ render(
+ <HoverCard
+ content={<span>Card content</span>}
+ onOpenChange={onOpenChange}
+ touchTrigger="tap"
+ delay={0}>
+ <button type="button">Details</button>
+ </HoverCard>,
+ );
+
+ tap(screen.getByRole('button', {name: 'Details'}));
+
+ await waitFor(() => {
+ expect(onOpenChange).toHaveBeenCalledWith(true);
+ });
+ });
+
+ it('survives a tap on its own content', async () => {
+ const onOpenChange = vi.fn();
+ render(
+ <HoverCard
+ content={<button type="button">Follow</button>}
+ onOpenChange={onOpenChange}
+ delay={0}
+ hideDelay={0}>
+ Ruby Cheung
+ </HoverCard>,
+ );
+
+ tap(screen.getByText('Ruby Cheung'));
+ await waitFor(() => {
+ expect(onOpenChange).toHaveBeenCalledWith(true);
+ });
+ onOpenChange.mockClear();
+
+ const action = await screen.findByRole('button', {
+ name: 'Follow',
+ hidden: true,
+ });
+ fireEvent.pointerDown(action, {pointerType: 'touch'});
+
+ await new Promise(resolve => setTimeout(resolve, 50));
+ expect(onOpenChange).not.toHaveBeenCalledWith(false);
+ });
+
+ it('closes on a tap outside', async () => {
+ const onOpenChange = vi.fn();
+ render(
+ <>
+ <HoverCard
+ content={<span>Card content</span>}
+ onOpenChange={onOpenChange}
+ delay={0}
+ hideDelay={0}>
+ Ruby Cheung
+ </HoverCard>
+ <button type="button">Elsewhere</button>
+ </>,
+ );
+
+ tap(screen.getByText('Ruby Cheung'));
+ await waitFor(() => {
+ expect(onOpenChange).toHaveBeenCalledWith(true);
+ });
+
+ fireEvent.pointerDown(screen.getByRole('button', {name: 'Elsewhere'}), {
+ pointerType: 'touch',
+ });
+
+ await waitFor(() => {
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+ });
+
+ it('closes on a second tap of the trigger', async () => {
+ const onOpenChange = vi.fn();
+ render(
+ <HoverCard
+ content={<span>Card content</span>}
+ onOpenChange={onOpenChange}
+ delay={0}
+ hideDelay={0}>
+ Ruby Cheung
+ </HoverCard>,
+ );
+
+ const trigger = screen.getByText('Ruby Cheung');
+ tap(trigger);
+ await waitFor(() => {
+ expect(onOpenChange).toHaveBeenCalledWith(true);
+ });
+
+ tap(trigger);
+ await waitFor(() => {
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+ });
+
+ it('ignores the focus a tap leaves behind, but not keyboard focus', async () => {
+ const onOpenChange = vi.fn();
+ render(
+ <HoverCard
+ content={<span>Card content</span>}
+ onOpenChange={onOpenChange}
+ delay={0}>
+ <button type="button">Save</button>
+ </HoverCard>,
+ );
+
+ const trigger = screen.getByRole('button', {name: 'Save'});
+ // The tap goes to the button, as `auto` decides for an action trigger —
+ // and the focus it leaves behind must not put the card over the control
+ // the user just pressed.
+ tap(trigger);
+ fireEvent.focusIn(trigger);
+ await new Promise(resolve => setTimeout(resolve, 50));
+ expect(onOpenChange).not.toHaveBeenCalledWith(true);
+
+ // Reaching for the keyboard ends the touch interaction: the same trigger,
+ // focused by Tab, still opens.
+ fireEvent.keyDown(document, {key: 'Tab'});
+ fireEvent.focusIn(trigger);
+
+ await waitFor(() => {
+ expect(onOpenChange).toHaveBeenCalledWith(true);
+ });
+ });
+ });
});
diff --git a/packages/core/src/HoverCard/HoverCard.tsx b/packages/core/src/HoverCard/HoverCard.tsx
index d1355da155..ee534c44d3 100644
--- a/packages/core/src/HoverCard/HoverCard.tsx
+++ b/packages/core/src/HoverCard/HoverCard.tsx
@@ -18,12 +18,19 @@
import {useCallback, useRef, type ReactElement, type ReactNode} from 'react';
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import * as stylex from '@stylexjs/stylex';
-import {useHoverCard, type HoverCardFocusTrigger} from './useHoverCard';
+import {
+ useHoverCard,
+ type HoverCardFocusTrigger,
+ type HoverCardTouchTrigger,
+} from './useHoverCard';
import type {LayerAlignment, LayerPlacement} from '../Layer/useLayer';
import type {BaseProps} from '../BaseProps';
import {colorVars, spacingVars} from '../theme/tokens.stylex';
-export type {HoverCardFocusTrigger} from './useHoverCard';
+export type {
+ HoverCardFocusTrigger,
+ HoverCardTouchTrigger,
+} from './useHoverCard';
const styles = stylex.create({
wrapperContents: {
@@ -88,6 +95,17 @@ export interface HoverCardProps extends Pick<
*/
focusTrigger?: HoverCardFocusTrigger;
+ /**
+ * What a tap does on a touch pointer, where there is no hover:
+ * - `auto`: tap opens the card, unless the trigger performs an action of its
+ * own (a button, a link, a form control) — that tap belongs to the control
+ * - `tap`: tap always opens the card, even on a trigger that acts
+ * - `none`: touch never opens the card
+ *
+ * @default 'auto'
+ */
+ touchTrigger?: HoverCardTouchTrigger;
+
/**
* Whether the hover card is enabled.
* When false, hover/focus triggers are disabled.
@@ -174,6 +192,7 @@ export function HoverCard({
delay = 300,
hideDelay = 200,
focusTrigger = 'auto',
+ touchTrigger = 'auto',
isEnabled = true,
label,
onOpenChange,
@@ -206,6 +225,7 @@ export function HoverCard({
delay,
hideDelay,
focusTrigger,
+ touchTrigger,
isEnabled,
label,
isOpen,
diff --git a/packages/core/src/HoverCard/index.ts b/packages/core/src/HoverCard/index.ts
index c0bdf8dcdf..bde055b078 100644
--- a/packages/core/src/HoverCard/index.ts
+++ b/packages/core/src/HoverCard/index.ts
@@ -15,6 +15,7 @@
export {useHoverCard} from './useHoverCard';
export type {
HoverCardFocusTrigger,
+ HoverCardTouchTrigger,
HoverCardOptions,
HoverCardReturn,
} from './useHoverCard';
diff --git a/packages/core/src/HoverCard/useHoverCard.doc.mjs b/packages/core/src/HoverCard/useHoverCard.doc.mjs
index f8261c0629..4c6c8ee456 100644
--- a/packages/core/src/HoverCard/useHoverCard.doc.mjs
+++ b/packages/core/src/HoverCard/useHoverCard.doc.mjs
@@ -12,6 +12,7 @@ export const docs = {
{name: 'delay', type: 'number', description: 'Delay before showing the hover card on hover, in milliseconds.', default: '300'},
{name: 'hideDelay', type: 'number', description: 'Delay before hiding after mouse or focus leaves, in milliseconds.', default: '200'},
{name: 'focusTrigger', type: "'auto' | 'always' | 'never'", description: 'When focus should open the hover card. auto only attaches focus listeners to naturally focusable elements.', default: "'auto'"},
+ {name: 'touchTrigger', type: "'auto' | 'tap' | 'none'", description: 'What a tap does where there is no hover. auto opens on tap unless the trigger performs an action of its own; tap always opens; none never opens on touch.', default: "'auto'"},
{name: 'isEnabled', type: 'boolean', description: 'Whether hover and focus triggers are enabled.', default: 'true'},
{name: 'label', type: 'string', description: 'Accessible name for the hover card popup. When provided, the popup is exposed as a named role="dialog"; when omitted, it falls back to role="group" (a group may validly be unnamed).'},
{name: 'isOpen', type: 'boolean', description: 'Controlled open state. true force-shows, false force-hides, undefined lets hover/focus manage visibility.'},
@@ -52,6 +53,7 @@ export const docsDense = {
delay: 'show delay in ms.',
hideDelay: 'hide delay after mouse/focus leave in ms.',
focusTrigger: 'when focus opens hover card; auto = naturally focusable elements only.',
+ touchTrigger: 'tap behavior with no hover; auto = tap unless trigger acts, tap = always, none = never.',
isEnabled: 'whether hover/focus triggers are enabled.',
label: 'accessible name for popup. with label: named role="dialog"; without: role="group".',
isOpen: 'controlled open state: true force-show, false force-hide, undefined unmanaged.',
diff --git a/packages/core/src/HoverCard/useHoverCard.tsx b/packages/core/src/HoverCard/useHoverCard.tsx
index f374d4b5be..822eb17e55 100644
--- a/packages/core/src/HoverCard/useHoverCard.tsx
+++ b/packages/core/src/HoverCard/useHoverCard.tsx
@@ -4,8 +4,8 @@
/**
* @file useHoverCard.ts
- * @input Uses useLayer, React hooks
- * @output Exports useHoverCard hook for hover/focus triggered layers
+ * @input Uses useLayer, useTouchTrigger, React hooks
+ * @output Exports useHoverCard hook for hover/focus/tap triggered layers
* @position Layer hook; builds on useLayer for hover card behavior
*
* SYNC: When modified, update:
@@ -26,6 +26,10 @@ import {
type LayerAlignment,
type LayerPlacement,
} from '../Layer/useLayer';
+import {
+ useTouchTrigger,
+ type LayerTouchTrigger,
+} from '../Layer/useTouchTrigger';
import {layerAnimations} from '../Layer/layerAnimations.stylex';
import {
colorVars,
@@ -58,6 +62,11 @@ const styles = stylex.create({
*/
export type HoverCardFocusTrigger = 'auto' | 'always' | 'never';
+/**
+ * Touch trigger behavior for hover cards
+ */
+export type HoverCardTouchTrigger = LayerTouchTrigger;
+
export interface HoverCardOptions {
/**
* Position placement relative to anchor
@@ -93,6 +102,17 @@ export interface HoverCardOptions {
*/
focusTrigger?: HoverCardFocusTrigger;
+ /**
+ * What a tap does on a touch pointer, where there is no hover:
+ * - `auto`: tap opens the card, unless the trigger performs an action of its
+ * own (a button, a link, a form control) — that tap belongs to the control
+ * - `tap`: tap always opens the card, even on a trigger that acts
+ * - `none`: touch never opens the card
+ *
+ * @default 'auto'
+ */
+ touchTrigger?: HoverCardTouchTrigger;
+
/**
* Whether the hover card is enabled.
* When false, hover/focus triggers are disabled.
@@ -240,6 +260,7 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
delay = 300,
hideDelay = 200,
focusTrigger = 'auto',
+ touchTrigger = 'auto',
isEnabled = true,
label,
isOpen,
@@ -276,6 +297,30 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
}
}, []);
+ // Touch resolves immediately: the hover delays exist to filter out a pointer
+ // passing across the trigger, and a tap is never that.
+ const showNow = useCallback(() => {
+ clearTimeouts();
+ layer.show();
+ }, [clearTimeouts, layer]);
+
+ const hideNow = useCallback(() => {
+ clearTimeouts();
+ isHoveringContentRef.current = false;
+ layer.hide();
+ }, [clearTimeouts, layer]);
+
+ const touch = useTouchTrigger({
+ touchTrigger,
+ isEnabled,
+ isControlled: isOpen !== undefined,
+ isOpen: layer.isOpen,
+ layerId: layer.id,
+ triggerRef,
+ show: showNow,
+ hide: hideNow,
+ });
+
// Schedule show with delay (suppressed when isOpen is false)
const scheduleShow = useCallback(() => {
if (!isEnabled || isOpen === false) {
@@ -303,17 +348,42 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
// Event handlers
const handleMouseEnter = useCallback(() => {
+ // A tap synthesizes mouseenter. On touch the tap path owns the decision,
+ // so hover must not also fire — without this a hover card opens on every
+ // tap of its trigger and has nothing to close it.
+ if (touch.isTouchPointerRef.current) {
+ return;
+ }
scheduleShow();
- }, [scheduleShow]);
+ }, [touch, scheduleShow]);
const handleMouseLeave = useCallback(() => {
+ // On touch the synthesized mouseleave arrives with the next tap elsewhere,
+ // which the outside-tap dismissal already handles.
+ if (touch.isTouchPointerRef.current) {
+ return;
+ }
scheduleHide();
- }, [scheduleHide]);
+ }, [touch, scheduleHide]);
+
+ // Tap-to-open on touch; on a mouse this does nothing and hover still rules.
+ const handlePointerDown = useCallback(
+ (event: PointerEvent) => {
+ touch.handlePointerDown(event);
+ },
+ [touch],
+ );
const handleFocusIn = useCallback(() => {
if (!isEnabled) {
return;
}
+ // A tap focuses the trigger it activates. Opening on that focus would
+ // reinstate exactly the behavior the touch path just decided against —
+ // and on an action trigger it covers the thing the user tapped.
+ if (touch.isTouchInteraction()) {
+ return;
+ }
// Skip showing if we're in the middle of an Escape dismiss
if (isEscapeDismissingRef.current) {
isEscapeDismissingRef.current = false;
@@ -321,7 +391,7 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
}
clearTimeouts();
layer.show();
- }, [isEnabled, clearTimeouts, layer]);
+ }, [isEnabled, touch, clearTimeouts, layer]);
const handleFocusOut = useCallback(
(e: FocusEvent) => {
@@ -346,13 +416,15 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
e.stopPropagation();
// Hide immediately without refocusing (we're already on trigger)
clearTimeouts();
+ touch.clearTapOpen();
layer.hide();
}
},
- [clearTimeouts, layer],
+ [touch, clearTimeouts, layer],
);
// Interaction ref that handles event listeners only
+ const {handlePointerEnter} = touch;
const interactionRef: RefCallback<HTMLElement> = useCallback(
(el: HTMLElement | null) => {
// Cleanup previous element
@@ -365,12 +437,24 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
handleFocusOut as EventListener,
);
triggerRef.current.removeEventListener('keydown', handleKeyDown);
+ triggerRef.current.removeEventListener(
+ 'pointerenter',
+ handlePointerEnter,
+ );
+ triggerRef.current.removeEventListener(
+ 'pointerdown',
+ handlePointerDown,
+ );
}
if (el) {
- // Attach hover listeners
+ // Attach hover listeners. `pointerenter` runs before the synthesized
+ // `mouseenter` a tap produces, which is what lets the hover path know
+ // it is looking at a finger.
+ el.addEventListener('pointerenter', handlePointerEnter);
el.addEventListener('mouseenter', handleMouseEnter);
el.addEventListener('mouseleave', handleMouseLeave);
+ el.addEventListener('pointerdown', handlePointerDown);
// Attach focus listeners based on focusTrigger option
const shouldAttachFocus =
@@ -395,6 +479,8 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
handleFocusIn,
handleFocusOut,
handleKeyDown,
+ handlePointerEnter,
+ handlePointerDown,
],
);
@@ -475,10 +561,18 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
<div
{...stylex.props(styles.content)}
onMouseEnter={() => {
+ // Touch synthesizes these over the card too; letting a tap inside
+ // register as "hovering content" would block every later hide.
+ if (touch.isTouchPointerRef.current) {
+ return;
+ }
isHoveringContentRef.current = true;
clearTimeouts();
}}
onMouseLeave={() => {
+ if (touch.isTouchPointerRef.current) {
+ return;
+ }
isHoveringContentRef.current = false;
scheduleHide();
}}
@@ -490,6 +584,7 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
isEscapeDismissingRef.current = true;
// Hide immediately
clearTimeouts();
+ touch.clearTapOpen();
layer.hide();
// Refocus the trigger
triggerRef.current?.focus();
@@ -526,6 +621,7 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
clearTimeouts,
scheduleHide,
popoverXstyle,
+ touch,
],
);
diff --git a/packages/core/src/Layer/index.ts b/packages/core/src/Layer/index.ts
index f6af03bee4..32d4f38183 100644
--- a/packages/core/src/Layer/index.ts
+++ b/packages/core/src/Layer/index.ts
@@ -29,6 +29,14 @@ export type {
FixedLayerReturn,
} from './useLayer';
+// Shared touch behavior for the hover layers
+export {useTouchTrigger, isActionTrigger} from './useTouchTrigger';
+export type {
+ LayerTouchTrigger,
+ UseTouchTriggerOptions,
+ UseTouchTriggerReturn,
+} from './useTouchTrigger';
+
// Layer provider
export {LayerProvider} from './LayerProvider';
export type {LayerProviderProps} from './LayerProvider';
@@ -50,6 +58,7 @@ export type {
export {useHoverCard, HoverCard} from '../HoverCard';
export type {
HoverCardFocusTrigger,
+ HoverCardTouchTrigger,
HoverCardOptions,
HoverCardReturn,
HoverCardProps,
@@ -59,6 +68,7 @@ export type {
export {useTooltip, Tooltip} from '../Tooltip';
export type {
TooltipFocusTrigger,
+ TooltipTouchTrigger,
TooltipOptions,
TooltipReturn,
TooltipProps,
diff --git a/packages/core/src/Layer/useTouchTrigger.test.ts b/packages/core/src/Layer/useTouchTrigger.test.ts
new file mode 100644
index 0000000000..d72d85f808
--- /dev/null
+++ b/packages/core/src/Layer/useTouchTrigger.test.ts
@@ -0,0 +1,70 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useTouchTrigger.test.ts
+ * @input Uses vitest, isActionTrigger
+ * @output Unit tests for the action-trigger rule behind touchTrigger="auto"
+ * @position Testing; validates useTouchTrigger.ts implementation
+ *
+ * SYNC: When useTouchTrigger.ts changes, update tests to match new behavior
+ *
+ * The tap-versus-suppress decision rests entirely on this predicate, and it is
+ * the part a new element type silently falls through. The per-component tests
+ * (Tooltip.test.tsx, HoverCard.test.tsx) cover the gestures it feeds.
+ */
+
+import {describe, it, expect} from 'vitest';
+import {isActionTrigger} from './useTouchTrigger';
+
+function element(html: string): HTMLElement {
+ const host = document.createElement('div');
+ host.innerHTML = html;
+ return host.firstElementChild as HTMLElement;
+}
+
+describe('isActionTrigger', () => {
+ it.each([
+ ['<button type="button">Save</button>'],
+ ['<input type="text" />'],
+ ['<select></select>'],
+ ['<textarea></textarea>'],
+ ['<summary>More</summary>'],
+ ['<label>Name</label>'],
+ ['<a href="/somewhere">Link</a>'],
+ ])('treats %s as an action', html => {
+ expect(isActionTrigger(element(html))).toBe(true);
+ });
+
+ it.each([
+ ['<span>Plain text</span>'],
+ ['<svg></svg>'],
+ ['<abbr title="what">WCAG</abbr>'],
+ // An anchor without href is a link that goes nowhere.
+ ['<a>Not a link</a>'],
+ ])('treats %s as inert', html => {
+ expect(isActionTrigger(element(html))).toBe(false);
+ });
+
+ it('reads an explicit role over the tag it sits on', () => {
+ expect(isActionTrigger(element('<span role="button">Go</span>'))).toBe(
+ true,
+ );
+ // Scenery: the role says this button is not the control it looks like.
+ expect(
+ isActionTrigger(element('<button role="presentation">x</button>')),
+ ).toBe(false);
+ });
+
+ it('does not treat mere focusability as an action', () => {
+ // The wrapper a text-only Tooltip renders: reachable by keyboard so the
+ // hint is not mouse-only, and it still does nothing when activated.
+ expect(isActionTrigger(element('<span tabindex="0">Term</span>'))).toBe(
+ false,
+ );
+ });
+
+ it('treats a contenteditable surface as an action', () => {
+ const editable = element('<div contenteditable="true"></div>');
+ expect(isActionTrigger(editable)).toBe(true);
+ });
+});
diff --git a/packages/core/src/Layer/useTouchTrigger.ts b/packages/core/src/Layer/useTouchTrigger.ts
new file mode 100644
index 0000000000..41d859683b
--- /dev/null
+++ b/packages/core/src/Layer/useTouchTrigger.ts
@@ -0,0 +1,366 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useTouchTrigger.ts
+ * @input Touch trigger mode, layer open state, trigger ref, show/hide callbacks
+ * @output Exports useTouchTrigger hook, isActionTrigger, LayerTouchTrigger type
+ * @position Layer hook; shared touch behavior for useTooltip and useHoverCard
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/Layer/index.ts
+ *
+ * Hover is the one trigger a touch screen cannot express. A tap synthesizes
+ * `mouseenter`, so an untreated hover layer either opens on every tap and
+ * lingers with nothing to close it, or swallows the tap the user aimed at the
+ * control underneath.
+ *
+ * What the trigger DOES decides which of those the tap deserves. A trigger
+ * that performs an action — a button, a link, a form control — keeps its tap:
+ * the layer stays shut, because the tap already has somewhere to go and a hint
+ * about a control the user just operated is noise. A trigger that performs no
+ * action — an info icon, an abbreviation, a truncated label — has nothing to
+ * lose, so the tap opens the layer and the next tap outside dismisses it. That
+ * is `auto`; `tap` and `none` state the choice outright, which is what an
+ * icon-button whose only job is to reveal the layer needs.
+ */
+
+import {useCallback, useEffect, useRef, type RefObject} from 'react';
+import {
+ getInteractionModality,
+ trackInteractionModality,
+} from '../utils/interactionModality';
+
+/**
+ * How a hover layer behaves on a touch pointer.
+ *
+ * - `auto`: tap-to-open, unless the trigger performs an action of its own
+ * - `tap`: always tap-to-open, even on a trigger that performs an action
+ * - `none`: never open on touch
+ */
+export type LayerTouchTrigger = 'auto' | 'tap' | 'none';
+
+/**
+ * Pointer types whose *press* is a tap rather than a click.
+ *
+ * A pen belongs here but not in the arrival path: in detection range it hovers
+ * — firing `pointerenter`/`pointermove` with no contact, exactly as a mouse
+ * does, on a device where `(hover: hover)` matches — and only becomes a tap
+ * once it lands. See `handlePointerEnter`.
+ */
+const TOUCH_POINTER_TYPES = new Set(['touch', 'pen']);
+
+/**
+ * ARIA roles that make an element do something when activated. An explicit
+ * role wins over the tag: `<button role="presentation">` is scenery, and a
+ * `<span role="button">` is a real control.
+ */
+const ACTION_ROLES = new Set([
+ 'button',
+ 'checkbox',
+ 'combobox',
+ 'link',
+ 'menuitem',
+ 'menuitemcheckbox',
+ 'menuitemradio',
+ 'option',
+ 'radio',
+ 'searchbox',
+ 'slider',
+ 'spinbutton',
+ 'switch',
+ 'tab',
+ 'textbox',
+]);
+
+/**
+ * Whether activating this element does something other than reveal the layer.
+ *
+ * Deliberately narrower than "focusable": the wrapper a text-only Tooltip
+ * renders carries `tabindex=0` so keyboard users can reach the hint, and it
+ * still performs no action.
+ *
+ * True only decides that the layer stays shut — the tap itself is never
+ * swallowed. Nothing here calls `preventDefault` or `stopPropagation`, so an
+ * inert trigger that happens to carry its own `onClick` (a `<div onClick>`
+ * with no role) gets both: the layer opens and the handler runs.
+ */
+export function isActionTrigger(element: HTMLElement): boolean {
+ const role = element.getAttribute('role');
+ if (role != null && role !== '') {
+ return ACTION_ROLES.has(role);
+ }
+
+ switch (element.tagName) {
+ case 'BUTTON':
+ case 'INPUT':
+ case 'LABEL':
+ case 'SELECT':
+ case 'SUMMARY':
+ case 'TEXTAREA':
+ return true;
+ case 'A':
+ case 'AREA':
+ return element.hasAttribute('href');
+ default:
+ return isEditable(element);
+ }
+}
+
+/**
+ * Whether typing into this element edits it. Reads the attribute as well as
+ * the property: jsdom does not implement `isContentEditable`, and an editor
+ * that is an action in the browser must not be inert under test.
+ */
+function isEditable(element: HTMLElement): boolean {
+ if (element.isContentEditable === true) {
+ return true;
+ }
+ const attribute = element.getAttribute('contenteditable');
+ return attribute != null && attribute !== 'false';
+}
+
+export interface UseTouchTriggerOptions {
+ /** How the layer should behave on a touch pointer. */
+ touchTrigger: LayerTouchTrigger;
+
+ /** Whether the layer's triggers are live at all. */
+ isEnabled: boolean;
+
+ /**
+ * Whether the consumer controls visibility. A controlled layer is never
+ * toggled by a tap — its visibility is the consumer's to own.
+ */
+ isControlled: boolean;
+
+ /** Whether the layer is currently open. */
+ isOpen: boolean;
+
+ /** Element id of the layer surface, so taps inside it count as inside. */
+ layerId: string;
+
+ /** The trigger element the layer is anchored to. */
+ triggerRef: RefObject<HTMLElement | null>;
+
+ /** Open the layer immediately, with no hover delay. */
+ show: () => void;
+
+ /** Close the layer immediately. */
+ hide: () => void;
+}
+
+export interface UseTouchTriggerReturn {
+ /**
+ * Whether the pointer in play on this trigger has no hover of its own: a
+ * finger, or a pen that has landed. A hovering pen reads as false, because
+ * it hovers.
+ */
+ isTouchPointerRef: RefObject<boolean>;
+
+ /**
+ * Whether the interaction in flight is a touch one. Unlike the raw ref this
+ * goes false again as soon as the user reaches for the keyboard, so
+ * focus-driven triggers stay available after a tap.
+ */
+ isTouchInteraction: () => boolean;
+
+ /**
+ * Attach to the trigger: records pointer type ahead of synthesized hover.
+ * Arrival alone only marks a finger — a pen hovers, so it is left to the
+ * hover path until it presses.
+ */
+ handlePointerEnter: (event: PointerEvent) => void;
+
+ /**
+ * Attach to the trigger. Returns true when the press was a touch one and
+ * this hook has dealt with it, meaning the caller's own pointer-down
+ * behavior must not also run.
+ */
+ handlePointerDown: (event: PointerEvent) => boolean;
+
+ /** Forget a tap-open. Call from every other close path (Escape, controlled). */
+ clearTapOpen: () => void;
+}
+
+/**
+ * Touch behavior shared by the hover layers.
+ *
+ * @example
+ * ```
+ * const touch = useTouchTrigger({
+ * touchTrigger,
+ * isEnabled,
+ * isControlled: isOpen !== undefined,
+ * isOpen: layer.isOpen,
+ * layerId: layer.id,
+ * triggerRef,
+ * show: showNow,
+ * hide: hideNow,
+ * });
+ * ```
+ */
+export function useTouchTrigger(
+ options: UseTouchTriggerOptions,
+): UseTouchTriggerReturn {
+ const {
+ touchTrigger,
+ isEnabled,
+ isControlled,
+ isOpen,
+ layerId,
+ triggerRef,
+ show,
+ hide,
+ } = options;
+
+ const isTouchPointerRef = useRef(false);
+ // Mirrors `isOpen` for synchronous reads inside the pointer handler, which
+ // runs outside React's render and would otherwise close over a stale value.
+ const isOpenRef = useRef(isOpen);
+ isOpenRef.current = isOpen;
+
+ // Latest values for the document listener, which outlives the render that
+ // armed it.
+ const hideRef = useRef(hide);
+ hideRef.current = hide;
+ const layerIdRef = useRef(layerId);
+ layerIdRef.current = layerId;
+
+ // Whether a tap is what opened the layer. Only a tap-open owes the user an
+ // outside-tap dismissal: a hover-opened layer already closes on
+ // pointer-leave, and a controlled one is not ours to close.
+ const isTapOpenRef = useRef(false);
+ const outsideListenerRef = useRef<((event: PointerEvent) => void) | null>(
+ null,
+ );
+
+ useEffect(() => {
+ trackInteractionModality();
+ }, []);
+
+ const disarmOutsideDismiss = useCallback(() => {
+ isTapOpenRef.current = false;
+ const listener = outsideListenerRef.current;
+ if (listener == null) {
+ return;
+ }
+ outsideListenerRef.current = null;
+ document.removeEventListener('pointerdown', listener, true);
+ }, []);
+
+ // Capture phase, so a trigger that stops propagation cannot strand an open
+ // layer. The opening tap's own capture phase at the document has already
+ // passed by the time this runs, so the listener never sees it.
+ const armOutsideDismiss = useCallback(() => {
+ isTapOpenRef.current = true;
+ if (outsideListenerRef.current != null) {
+ return;
+ }
+
+ const handleOutsidePointerDown = (event: PointerEvent) => {
+ const target = event.target as Node | null;
+ if (target != null) {
+ // The trigger's own handler owns the toggle.
+ if (triggerRef.current?.contains(target) === true) {
+ return;
+ }
+ // Hover card content is interactive; a tap inside it is not a dismiss.
+ if (
+ document.getElementById(layerIdRef.current)?.contains(target) === true
+ ) {
+ return;
+ }
+ }
+ disarmOutsideDismiss();
+ hideRef.current();
+ };
+
+ outsideListenerRef.current = handleOutsidePointerDown;
+ document.addEventListener('pointerdown', handleOutsidePointerDown, true);
+ }, [triggerRef, disarmOutsideDismiss]);
+
+ useEffect(() => disarmOutsideDismiss, [disarmOutsideDismiss]);
+
+ const isTouchInteraction = useCallback(
+ () => isTouchPointerRef.current && getInteractionModality() === 'pointer',
+ [],
+ );
+
+ const handlePointerEnter = useCallback((event: PointerEvent) => {
+ // Only a finger is hoverless on arrival. A pen in detection range hovers
+ // like a mouse, and treating its arrival as touch would bail out of the
+ // hover path and leave a stylus user with no tooltip at all. A pen that
+ // presses is a tap, and `handlePointerDown` still reads it as one.
+ isTouchPointerRef.current = event.pointerType === 'touch';
+ }, []);
+
+ const handlePointerDown = useCallback(
+ (event: PointerEvent): boolean => {
+ const isTouch = TOUCH_POINTER_TYPES.has(event.pointerType);
+ isTouchPointerRef.current = isTouch;
+
+ if (!isTouch || isControlled) {
+ return false;
+ }
+
+ const trigger = triggerRef.current;
+ const mode =
+ touchTrigger === 'auto'
+ ? trigger != null && isActionTrigger(trigger)
+ ? 'none'
+ : 'tap'
+ : touchTrigger;
+
+ if (mode === 'none' || !isEnabled) {
+ // A layer left open by an earlier tap must not survive the next one.
+ disarmOutsideDismiss();
+ hide();
+ return true;
+ }
+
+ // A lazily mounted layer reports `isOpen` a tick after `show()`, so the
+ // tap's own bookkeeping is what makes the second tap a close.
+ if (isOpenRef.current || isTapOpenRef.current) {
+ disarmOutsideDismiss();
+ hide();
+ return true;
+ }
+
+ armOutsideDismiss();
+ show();
+ return true;
+ },
+ [
+ touchTrigger,
+ isEnabled,
+ isControlled,
+ triggerRef,
+ show,
+ hide,
+ armOutsideDismiss,
+ disarmOutsideDismiss,
+ ],
+ );
+
+ // A layer closed by any other path (Escape, a consumer, the browser) leaves
+ // no tap-open to dismiss. Only a true open→closed transition counts: a
+ // lazily mounted layer still reports `false` for a tick after the tap asked
+ // it to open, and reading that as a close would disarm the dismissal the
+ // tap-open just armed.
+ const wasOpenRef = useRef(isOpen);
+ useEffect(() => {
+ if (wasOpenRef.current && !isOpen) {
+ disarmOutsideDismiss();
+ }
+ wasOpenRef.current = isOpen;
+ }, [isOpen, disarmOutsideDismiss]);
+
+ return {
+ isTouchPointerRef,
+ isTouchInteraction,
+ handlePointerEnter,
+ handlePointerDown,
+ clearTapOpen: disarmOutsideDismiss,
+ };
+}
diff --git a/packages/core/src/Tooltip/Tooltip.doc.mjs b/packages/core/src/Tooltip/Tooltip.doc.mjs
index 72fa7dde0b..d1ff1d7ec0 100644
--- a/packages/core/src/Tooltip/Tooltip.doc.mjs
+++ b/packages/core/src/Tooltip/Tooltip.doc.mjs
@@ -66,6 +66,13 @@ export const docs = {
description: 'Controls when focus events trigger the tooltip.',
default: "'auto'",
},
+ {
+ name: 'touchTrigger',
+ type: "'auto' | 'tap' | 'none'",
+ description:
+ 'What a tap does where there is no hover. auto opens on tap unless the trigger performs an action of its own (a button, link, or form control), whose tap belongs to the control. tap always opens — use it for an info icon rendered as a button, whose only job is to reveal the tooltip. none never opens on touch.',
+ default: "'auto'",
+ },
{
name: 'isEnabled',
type: 'boolean',
@@ -103,6 +110,7 @@ export const docs = {
bestPractices: [
{guidance: true, description: 'Keep tooltip content concise: aim for under 140 characters of plain text.'},
{guidance: true, description: 'Add a tooltip to icon-only buttons and controls that lack a visible label.'},
+ {guidance: true, description: 'Set touchTrigger to tap when the trigger is a button whose only job is revealing the tooltip, such as an info icon: touch has no hover, and auto keeps the tap for triggers that perform an action.'},
{guidance: false, description: 'Place interactive elements like links or buttons inside a tooltip; use HoverCard or Popover instead.'},
{guidance: false, description: 'Use tooltips for essential information that users must see to complete a task.'},
],
@@ -165,6 +173,13 @@ export const docsZh = {
description: '控制聚焦事件何时触发工具提示。',
default: "'auto'",
},
+ {
+ name: 'touchTrigger',
+ type: "'auto' | 'tap' | 'none'",
+ description:
+ '在没有悬停的触摸设备上,轻点的行为。auto:轻点即打开,除非触发元素本身会执行操作(按钮、链接、表单控件),此时轻点归该控件所有。tap:始终轻点打开——适用于以按钮形式呈现、唯一作用就是显示工具提示的信息图标。none:触摸永不打开。',
+ default: "'auto'",
+ },
{
name: 'isEnabled',
type: 'boolean',
@@ -202,6 +217,7 @@ export const docsZh = {
bestPractices: [
{guidance: true, description: 'Keep tooltip content concise: aim for under 140 characters of plain text.'},
{guidance: true, description: 'Add a tooltip to icon-only buttons and controls that lack a visible label.'},
+ {guidance: true, description: 'Set touchTrigger to tap when the trigger is a button whose only job is revealing the tooltip, such as an info icon: touch has no hover, and auto keeps the tap for triggers that perform an action.'},
{guidance: false, description: 'Place interactive elements like links or buttons inside a tooltip; use HoverCard or Popover instead.'},
{guidance: false, description: 'Use tooltips for essential information that users must see to complete a task.'},
],
@@ -217,6 +233,7 @@ export const docsDense = {
bestPractices: [
{guidance: true, description: 'Keep tooltip content concise: aim for under 140 characters of plain text.'},
{guidance: true, description: 'Add a tooltip to icon-only buttons and controls that lack a visible label.'},
+ {guidance: true, description: 'Set touchTrigger to tap when the trigger is a button whose only job is revealing the tooltip, such as an info icon: touch has no hover, and auto keeps the tap for triggers that perform an action.'},
{guidance: false, description: 'Place interactive elements like links or buttons inside a tooltip; use HoverCard or Popover instead.'},
{guidance: false, description: 'Use tooltips for essential information that users must see to complete a task.'},
],
@@ -235,6 +252,7 @@ export const docsDense = {
delay: 'Show delay in ms.',
hideDelay: 'Hide delay in ms.',
focusTrigger: 'Controls when focus events trigger tooltip.',
+ touchTrigger: 'Tap behavior where there is no hover. auto = tap opens unless the trigger acts (button/link/control); tap = always opens (info icon rendered as a button); none = never on touch.',
isEnabled: 'Enables/disables tooltip triggers.',
onOpenChange: 'Callback when visibility changes; true=shown, false=hidden.',
hasHoverIndication: 'Dashed underline on trigger element.',
diff --git a/packages/core/src/Tooltip/Tooltip.test.tsx b/packages/core/src/Tooltip/Tooltip.test.tsx
index ba76eabc69..0ef60e9f2f 100644
--- a/packages/core/src/Tooltip/Tooltip.test.tsx
+++ b/packages/core/src/Tooltip/Tooltip.test.tsx
@@ -9,9 +9,18 @@
* SYNC: When Tooltip.tsx changes, update tests to match new behavior
*/
-import {describe, it, expect, vi, beforeAll, afterAll} from 'vitest';
+import {
+ describe,
+ it,
+ expect,
+ vi,
+ beforeAll,
+ beforeEach,
+ afterAll,
+} from 'vitest';
import {render, screen, fireEvent, waitFor} from '@testing-library/react';
import {Tooltip} from './Tooltip';
+import {__resetInteractionModalityForTest} from '../utils/interactionModality';
// Store original matches to restore later
const originalMatches = HTMLElement.prototype.matches;
@@ -267,4 +276,248 @@ describe('Tooltip', () => {
expect(onOpenChange).not.toHaveBeenCalledWith(false);
});
});
+ describe('touch', () => {
+ // The modality is document-global; a tap in one case must not decide the
+ // next one's answer.
+ beforeEach(() => {
+ __resetInteractionModalityForTest();
+ });
+
+ /** A tap: the pointer sequence a finger produces before hover is faked. */
+ const tap = (element: HTMLElement) => {
+ // A finger's arrival fires pointerenter too, and that is the path a pen
+ // must not take — cover it here rather than starting at pointerdown.
+ fireEvent.pointerEnter(element, {pointerType: 'touch'});
+ fireEvent.pointerDown(element, {pointerType: 'touch'});
+ fireEvent.pointerUp(element, {pointerType: 'touch'});
+ // Touch synthesizes hover after the press; the tooltip must not act on it.
+ fireEvent.mouseEnter(element);
+ };
+
+ it('opens on a tap when the trigger performs no action', async () => {
+ const onOpenChange = vi.fn();
+ render(
+ <Tooltip content="Tooltip text" onOpenChange={onOpenChange} delay={200}>
+ Abbreviation
+ </Tooltip>,
+ );
+
+ tap(screen.getByText('Abbreviation'));
+
+ // Immediately: a tap is a decision, not hover intent, so no delay applies.
+ await waitFor(() => {
+ expect(onOpenChange).toHaveBeenCalledWith(true);
+ });
+ });
+
+ it('stays shut on a tap when the trigger performs an action', async () => {
+ const onOpenChange = vi.fn();
+ render(
+ <Tooltip content="Tooltip text" onOpenChange={onOpenChange} delay={0}>
+ <button type="button">Save</button>
+ </Tooltip>,
+ );
+
+ tap(screen.getByRole('button', {name: 'Save'}));
+
+ await new Promise(resolve => setTimeout(resolve, 50));
+ expect(onOpenChange).not.toHaveBeenCalledWith(true);
+ });
+
+ it('opens on a tap of an action trigger when touchTrigger is "tap"', async () => {
+ const onOpenChange = vi.fn();
+ render(
+ <Tooltip
+ content="What this metric means"
+ onOpenChange={onOpenChange}
+ touchTrigger="tap"
+ delay={0}>
+ <button type="button">Info</button>
+ </Tooltip>,
+ );
+
+ tap(screen.getByRole('button', {name: 'Info'}));
+
+ await waitFor(() => {
+ expect(onOpenChange).toHaveBeenCalledWith(true);
+ });
+ });
+
+ it('never opens on a tap when touchTrigger is "none"', async () => {
+ const onOpenChange = vi.fn();
+ render(
+ <Tooltip
+ content="Tooltip text"
+ onOpenChange={onOpenChange}
+ touchTrigger="none"
+ delay={0}>
+ Abbreviation
+ </Tooltip>,
+ );
+
+ tap(screen.getByText('Abbreviation'));
+
+ await new Promise(resolve => setTimeout(resolve, 50));
+ expect(onOpenChange).not.toHaveBeenCalledWith(true);
+ });
+
+ it('closes on a second tap of the trigger', async () => {
+ const onOpenChange = vi.fn();
+ render(
+ <Tooltip content="Tooltip text" onOpenChange={onOpenChange} delay={0}>
+ Abbreviation
+ </Tooltip>,
+ );
+
+ const trigger = screen.getByText('Abbreviation');
+ tap(trigger);
+ await waitFor(() => {
+ expect(onOpenChange).toHaveBeenCalledWith(true);
+ });
+
+ tap(trigger);
+ await waitFor(() => {
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+ });
+
+ it('closes on a tap outside — the dismissal a tap-open owes the user', async () => {
+ const onOpenChange = vi.fn();
+ render(
+ <>
+ <Tooltip content="Tooltip text" onOpenChange={onOpenChange} delay={0}>
+ Abbreviation
+ </Tooltip>
+ <button type="button">Elsewhere</button>
+ </>,
+ );
+
+ tap(screen.getByText('Abbreviation'));
+ await waitFor(() => {
+ expect(onOpenChange).toHaveBeenCalledWith(true);
+ });
+
+ fireEvent.pointerDown(screen.getByRole('button', {name: 'Elsewhere'}), {
+ pointerType: 'touch',
+ });
+
+ await waitFor(() => {
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+ });
+
+ it('still opens on a real mouse hover after a tap', async () => {
+ const onOpenChange = vi.fn();
+ render(
+ <Tooltip content="Tooltip text" onOpenChange={onOpenChange} delay={0}>
+ <button type="button">Save</button>
+ </Tooltip>,
+ );
+
+ const trigger = screen.getByRole('button', {name: 'Save'});
+ tap(trigger);
+ await new Promise(resolve => setTimeout(resolve, 20));
+ expect(onOpenChange).not.toHaveBeenCalledWith(true);
+
+ // A hybrid device: the same trigger, now under a mouse.
+ fireEvent.pointerEnter(trigger, {pointerType: 'mouse'});
+ fireEvent.mouseEnter(trigger);
+
+ await waitFor(() => {
+ expect(onOpenChange).toHaveBeenCalledWith(true);
+ });
+ });
+
+ it('opens on a hovering pen, which is a hover and not a tap', async () => {
+ const onOpenChange = vi.fn();
+ render(
+ <Tooltip content="Tooltip text" onOpenChange={onOpenChange} delay={0}>
+ <button type="button">Save</button>
+ </Tooltip>,
+ );
+
+ const trigger = screen.getByRole('button', {name: 'Save'});
+ // A stylus in detection range: pointerenter with nothing in contact, on
+ // a device where `(hover: hover)` matches. Reading that as touch would
+ // bail out of the hover path and leave the user no tooltip at all.
+ fireEvent.pointerEnter(trigger, {pointerType: 'pen', buttons: 0});
+ fireEvent.mouseEnter(trigger);
+
+ await waitFor(() => {
+ expect(onOpenChange).toHaveBeenCalledWith(true);
+ });
+ });
+
+ it('tap-opens when a pen lands on an inert trigger', async () => {
+ const onOpenChange = vi.fn();
+ render(
+ <Tooltip content="Tooltip text" onOpenChange={onOpenChange} delay={200}>
+ Abbreviation
+ </Tooltip>,
+ );
+
+ const trigger = screen.getByText('Abbreviation');
+ // Hovering first, as a real pen does — then contact, which is a tap.
+ fireEvent.pointerEnter(trigger, {pointerType: 'pen', buttons: 0});
+ fireEvent.pointerDown(trigger, {pointerType: 'pen'});
+ fireEvent.pointerUp(trigger, {pointerType: 'pen'});
+
+ await waitFor(() => {
+ expect(onOpenChange).toHaveBeenCalledWith(true);
+ });
+ });
+
+ it('does not reopen from the focus a tapped text field takes', async () => {
+ const onOpenChange = vi.fn();
+ render(
+ <Tooltip content="Tooltip text" onOpenChange={onOpenChange} delay={0}>
+ <input type="text" aria-label="Amount" />
+ </Tooltip>,
+ );
+
+ const trigger = screen.getByLabelText('Amount');
+ // A tapped text field matches `:focus-visible` in a real browser —
+ // deliberately, per Selectors 4, so typing has a visible home. jsdom
+ // does not model that, so stand it up here; without it this case cannot
+ // fail, whatever the focus path does.
+ const realMatches = trigger.matches.bind(trigger);
+ vi.spyOn(trigger, 'matches').mockImplementation((selector: string) =>
+ selector === ':focus-visible' ? true : realMatches(selector),
+ );
+
+ // An `<input>` is an action trigger, so `auto` gives it the tap — and
+ // the focus it takes must not put the tooltip back over the field the
+ // user is about to type into.
+ tap(trigger);
+ fireEvent.focusIn(trigger);
+
+ await new Promise(resolve => setTimeout(resolve, 50));
+ expect(onOpenChange).not.toHaveBeenCalledWith(true);
+ });
+
+ it('still opens on keyboard focus of a trigger a finger touched', async () => {
+ const onOpenChange = vi.fn();
+ render(
+ <Tooltip content="Tooltip text" onOpenChange={onOpenChange} delay={0}>
+ <input type="text" aria-label="Amount" />
+ </Tooltip>,
+ );
+
+ const trigger = screen.getByLabelText('Amount');
+ const realMatches = trigger.matches.bind(trigger);
+ vi.spyOn(trigger, 'matches').mockImplementation((selector: string) =>
+ selector === ':focus-visible' ? true : realMatches(selector),
+ );
+
+ tap(trigger);
+ // Reaching for the keyboard ends the touch interaction; the guard is on
+ // the gesture in flight, not on the device the trigger last saw.
+ fireEvent.keyDown(document, {key: 'Tab'});
+ fireEvent.focusIn(trigger);
+
+ await waitFor(() => {
+ expect(onOpenChange).toHaveBeenCalledWith(true);
+ });
+ });
+ });
});
diff --git a/packages/core/src/Tooltip/Tooltip.tsx b/packages/core/src/Tooltip/Tooltip.tsx
index b418787ebd..1243d875fb 100644
--- a/packages/core/src/Tooltip/Tooltip.tsx
+++ b/packages/core/src/Tooltip/Tooltip.tsx
@@ -22,11 +22,15 @@ import React, {
} from 'react';
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import * as stylex from '@stylexjs/stylex';
-import {useTooltip, type TooltipFocusTrigger} from './useTooltip';
+import {
+ useTooltip,
+ type TooltipFocusTrigger,
+ type TooltipTouchTrigger,
+} from './useTooltip';
import type {LayerAlignment, LayerPlacement} from '../Layer/useLayer';
import {colorVars} from '../theme/tokens.stylex';
-export type {TooltipFocusTrigger} from './useTooltip';
+export type {TooltipFocusTrigger, TooltipTouchTrigger} from './useTooltip';
const styles = stylex.create({
wrapperContents: {
@@ -99,6 +103,20 @@ export interface TooltipProps {
*/
focusTrigger?: TooltipFocusTrigger;
+ /**
+ * What a tap does on a touch pointer, where there is no hover:
+ * - `auto`: tap opens the tooltip, unless the trigger performs an action of
+ * its own (a button, a link, a form control) — that tap belongs to the
+ * control, and a hint about a control the user just operated is noise
+ * - `tap`: tap always opens the tooltip. This is what an info icon rendered
+ * as a button wants: it looks like an action to the DOM, but revealing the
+ * tooltip is the only thing it does
+ * - `none`: touch never opens the tooltip
+ *
+ * @default 'auto'
+ */
+ touchTrigger?: TooltipTouchTrigger;
+
/**
* Whether the tooltip is enabled.
* When false, hover/focus triggers are disabled.
@@ -176,6 +194,7 @@ export function Tooltip({
delay = 200,
hideDelay = 0,
focusTrigger = 'auto',
+ touchTrigger = 'auto',
isEnabled = true,
onOpenChange,
hasHoverIndication = 'auto',
@@ -204,6 +223,7 @@ export function Tooltip({
delay,
hideDelay,
focusTrigger,
+ touchTrigger,
isEnabled,
isOpen,
isDefaultOpen,
diff --git a/packages/core/src/Tooltip/index.ts b/packages/core/src/Tooltip/index.ts
index c4cc2ae5ba..99d411531f 100644
--- a/packages/core/src/Tooltip/index.ts
+++ b/packages/core/src/Tooltip/index.ts
@@ -15,6 +15,7 @@
export {useTooltip} from './useTooltip';
export type {
TooltipFocusTrigger,
+ TooltipTouchTrigger,
TooltipOptions,
TooltipReturn,
} from './useTooltip';
diff --git a/packages/core/src/Tooltip/useTooltip.doc.mjs b/packages/core/src/Tooltip/useTooltip.doc.mjs
index 0733885b39..13e360b6f4 100644
--- a/packages/core/src/Tooltip/useTooltip.doc.mjs
+++ b/packages/core/src/Tooltip/useTooltip.doc.mjs
@@ -12,6 +12,7 @@ export const docs = {
{name: 'delay', type: 'number', description: 'Delay before showing on hover, in milliseconds.', default: '200'},
{name: 'hideDelay', type: 'number', description: 'Delay before hiding after mouse or focus leaves, in milliseconds.', default: '0'},
{name: 'focusTrigger', type: "'auto' | 'always' | 'never'", description: 'When focus should open the tooltip. auto only attaches focus listeners to naturally focusable elements.', default: "'auto'"},
+ {name: 'touchTrigger', type: "'auto' | 'tap' | 'none'", description: 'What a tap does where there is no hover. auto opens on tap unless the trigger performs an action of its own; tap always opens (an info icon rendered as a button); none never opens on touch.', default: "'auto'"},
{name: 'isEnabled', type: 'boolean', description: 'Whether hover and focus triggers are enabled.', default: 'true'},
{name: 'isOpen', type: 'boolean', description: 'Controlled open state. true force-shows, false force-hides, undefined lets hover/focus manage visibility.'},
{name: 'isDefaultOpen', type: 'boolean', description: 'Whether the tooltip should be shown on mount.', default: 'false'},
@@ -49,6 +50,7 @@ export const docsDense = {
delay: 'show delay in ms.',
hideDelay: 'hide delay after mouse/focus leave in ms.',
focusTrigger: 'when focus opens tooltip; auto = naturally focusable elements only.',
+ touchTrigger: 'tap behavior with no hover; auto = tap unless trigger acts, tap = always, none = never.',
isEnabled: 'whether hover/focus triggers are enabled.',
isOpen: 'controlled open state: true force-show, false force-hide, undefined unmanaged.',
isDefaultOpen: 'show on mount.',
diff --git a/packages/core/src/Tooltip/useTooltip.tsx b/packages/core/src/Tooltip/useTooltip.tsx
index b0719ff3e8..79e17725dc 100644
--- a/packages/core/src/Tooltip/useTooltip.tsx
+++ b/packages/core/src/Tooltip/useTooltip.tsx
@@ -4,8 +4,8 @@
/**
* @file useTooltip.tsx
- * @input Uses useLayer, React hooks
- * @output Exports useTooltip hook for hover/focus triggered tooltips
+ * @input Uses useLayer, useTouchTrigger, React hooks
+ * @output Exports useTooltip hook for hover/focus/tap triggered tooltips
* @position Layer hook; builds on useLayer for tooltip behavior
*
* SYNC: When modified, update:
@@ -26,6 +26,10 @@ import {
type LayerAlignment,
type LayerPlacement,
} from '../Layer/useLayer';
+import {
+ useTouchTrigger,
+ type LayerTouchTrigger,
+} from '../Layer/useTouchTrigger';
import {layerAnimations} from '../Layer/layerAnimations.stylex';
import {themeProps} from '../utils/themeProps';
import {isImeKeyEvent} from '../utils/ime';
@@ -73,6 +77,11 @@ const styles = stylex.create({
*/
export type TooltipFocusTrigger = 'auto' | 'always' | 'never';
+/**
+ * Touch trigger behavior for tooltips
+ */
+export type TooltipTouchTrigger = LayerTouchTrigger;
+
export interface TooltipOptions {
/**
* Position placement relative to anchor
@@ -108,6 +117,20 @@ export interface TooltipOptions {
*/
focusTrigger?: TooltipFocusTrigger;
+ /**
+ * What a tap does on a touch pointer, where there is no hover:
+ * - `auto`: tap opens the tooltip, unless the trigger performs an action of
+ * its own (a button, a link, a form control) — that tap belongs to the
+ * control, and a hint about a control the user just operated is noise
+ * - `tap`: tap always opens the tooltip. This is what an info icon rendered
+ * as a button wants: it looks like an action to the DOM, but revealing the
+ * tooltip is the only thing it does
+ * - `none`: touch never opens the tooltip
+ *
+ * @default 'auto'
+ */
+ touchTrigger?: TooltipTouchTrigger;
+
/**
* Whether the tooltip is enabled.
* When false, hover/focus triggers are disabled.
@@ -218,6 +241,7 @@ function isFocusable(element: HTMLElement): boolean {
* Builds on useLayer to add:
* - Hover triggers with configurable delay
* - Focus triggers with auto-detection for focusable elements
+ * - Tap triggers on touch, where there is no hover (see useTouchTrigger)
* - Inverted color palette for high contrast
*
* Unlike HoverCard, tooltips:
@@ -242,6 +266,7 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
delay = 200,
hideDelay = 0,
focusTrigger = 'auto',
+ touchTrigger = 'auto',
isEnabled = true,
isOpen,
isDefaultOpen = false,
@@ -273,6 +298,29 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
}
}, []);
+ // Touch resolves immediately: the hover delays exist to filter out a pointer
+ // passing across the trigger, and a tap is never that.
+ const showNow = useCallback(() => {
+ clearTimeouts();
+ layer.show();
+ }, [clearTimeouts, layer]);
+
+ const hideNow = useCallback(() => {
+ clearTimeouts();
+ layer.hide();
+ }, [clearTimeouts, layer]);
+
+ const touch = useTouchTrigger({
+ touchTrigger,
+ isEnabled,
+ isControlled: isOpen !== undefined,
+ isOpen: layer.isOpen,
+ layerId: layer.id,
+ triggerRef,
+ show: showNow,
+ hide: hideNow,
+ });
+
// Schedule show with delay (suppressed when isOpen is false)
const scheduleShow = useCallback(() => {
if (!isEnabled || isOpen === false) {
@@ -309,26 +357,38 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
// Event handlers
const handleMouseEnter = useCallback(() => {
- // Suppress tooltips on touch devices — hover is simulated and eats a tap
- if (
- typeof window !== 'undefined' &&
- typeof window.matchMedia === 'function' &&
- window.matchMedia('(hover: none)').matches
- ) {
+ // A tap synthesizes mouseenter. On touch the tap path owns the decision,
+ // so hover must not also fire — including the tap that just opened the
+ // tooltip, which would otherwise be double-handled.
+ if (touch.isTouchPointerRef.current) {
return;
}
scheduleShow();
- }, [scheduleShow]);
+ }, [touch, scheduleShow]);
const handleMouseLeave = useCallback(() => {
+ // On touch the synthesized mouseleave arrives with the next tap elsewhere,
+ // which the outside-tap dismissal already handles — and handling it here
+ // too would close the tooltip behind the tap-open bookkeeping's back.
+ if (touch.isTouchPointerRef.current) {
+ return;
+ }
scheduleHide();
- }, [scheduleHide]);
+ }, [touch, scheduleHide]);
const handleFocusIn = useCallback(
(e: Event) => {
if (!isEnabled) {
return;
}
+ // A tap focuses the trigger it activates, and `:focus-visible` does not
+ // filter that out on every element: a tapped `<input>` or contenteditable
+ // matches it. Those are exactly the action triggers `auto` just decided
+ // to keep shut, so without this the focus reopens what the tap
+ // suppressed, over the field the user is trying to type into.
+ if (touch.isTouchInteraction()) {
+ return;
+ }
// Only show tooltip for keyboard focus (:focus-visible),
// not programmatic focus (e.g. dialog auto-focus, touch tap)
const target = e.target as HTMLElement;
@@ -338,7 +398,7 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
clearTimeouts();
layer.show();
},
- [isEnabled, clearTimeouts, layer],
+ [isEnabled, touch, clearTimeouts, layer],
);
const handleFocusOut = useCallback(() => {
@@ -350,15 +410,24 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
// just-pressed control reads as stale. Fires on pointerdown so it feels
// immediate. Uncontrolled tooltips only — a controlled tooltip's visibility
// is owned by the consumer. `layer.hide()` self-guards when already closed.
- const handlePointerDown = useCallback(() => {
- if (isOpen !== undefined) {
- return;
- }
- clearTimeouts();
- layer.hide();
- }, [isOpen, clearTimeouts, layer]);
+ // A touch press is a different gesture (it may be the only way to open the
+ // tooltip at all), so the touch path answers it first.
+ const handlePointerDown = useCallback(
+ (event: PointerEvent) => {
+ if (touch.handlePointerDown(event)) {
+ return;
+ }
+ if (isOpen !== undefined) {
+ return;
+ }
+ clearTimeouts();
+ layer.hide();
+ },
+ [touch, isOpen, clearTimeouts, layer],
+ );
// Interaction ref that handles event listeners only
+ const {handlePointerEnter, clearTapOpen} = touch;
const interactionRef: RefCallback<HTMLElement> = useCallback(
(el: HTMLElement | null) => {
// Cleanup previous element
@@ -367,6 +436,10 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
triggerRef.current.removeEventListener('mouseleave', handleMouseLeave);
triggerRef.current.removeEventListener('focusin', handleFocusIn);
triggerRef.current.removeEventListener('focusout', handleFocusOut);
+ triggerRef.current.removeEventListener(
+ 'pointerenter',
+ handlePointerEnter,
+ );
triggerRef.current.removeEventListener(
'pointerdown',
handlePointerDown,
@@ -374,10 +447,13 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
}
if (el) {
- // Attach hover listeners
+ // Attach hover listeners. `pointerenter` runs before the synthesized
+ // `mouseenter` a tap produces, which is what lets the hover path know
+ // it is looking at a finger.
+ el.addEventListener('pointerenter', handlePointerEnter);
el.addEventListener('mouseenter', handleMouseEnter);
el.addEventListener('mouseleave', handleMouseLeave);
- // Press-to-dismiss: activating the trigger hides its own tooltip.
+ // Press-to-dismiss on a mouse; tap-to-open on a touch pointer.
el.addEventListener('pointerdown', handlePointerDown);
// Attach focus listeners based on focusTrigger option
@@ -399,6 +475,7 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
handleMouseLeave,
handleFocusIn,
handleFocusOut,
+ handlePointerEnter,
handlePointerDown,
],
);
@@ -461,13 +538,14 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
return;
}
clearTimeouts();
+ clearTapOpen();
layer.hide();
};
document.addEventListener('keydown', handleKeyDown);
return () => {
document.removeEventListener('keydown', handleKeyDown);
};
- }, [isOpen, layer, clearTimeouts]);
+ }, [isOpen, layer, clearTimeouts, clearTapOpen]);
// Render function that wraps layer.render with tooltip styling
const renderTooltip = useCallback(
diff --git a/packages/lab/src/InfoTip/InfoTip.doc.mjs b/packages/lab/src/InfoTip/InfoTip.doc.mjs
index 55573492aa..f3dfb20589 100644
--- a/packages/lab/src/InfoTip/InfoTip.doc.mjs
+++ b/packages/lab/src/InfoTip/InfoTip.doc.mjs
@@ -29,10 +29,11 @@ export const docs = {
],
usage: {
description:
- 'An inline info-icon help affordance: a small "i" button that reveals a tooltip on hover and keyboard focus. 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 Escape dismissal.',
+ '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.' },
],
@@ -65,10 +66,11 @@ export const docsZh = {
],
usage: {
description:
- 'An inline info-icon help affordance: a small "i" button that reveals a tooltip on hover and keyboard focus. Use it next to labels, values, and metrics for permission notes, metric definitions, and field help.',
+ '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.' },
],
@@ -81,10 +83,11 @@ export const docsDense = {
'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 and keyboard focus. 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, Escape dismissal.',
+ '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.' },
],
diff --git a/packages/lab/src/InfoTip/InfoTip.test.tsx b/packages/lab/src/InfoTip/InfoTip.test.tsx
index 59de8ffceb..1fc5966af3 100644
--- a/packages/lab/src/InfoTip/InfoTip.test.tsx
+++ b/packages/lab/src/InfoTip/InfoTip.test.tsx
@@ -166,4 +166,68 @@ describe('InfoTip', () => {
render(<InfoTip content={<span data-testid="rich-content">Rich</span>} />);
expect(screen.getByTestId('rich-content')).toBeInTheDocument();
});
+ describe('touch', () => {
+ /** A tap: the pointer sequence a finger produces before hover is faked. */
+ const tap = (element: HTMLElement) => {
+ fireEvent.pointerEnter(element, {pointerType: 'touch'});
+ fireEvent.pointerDown(element, {pointerType: 'touch'});
+ fireEvent.pointerUp(element, {pointerType: 'touch'});
+ fireEvent.mouseEnter(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);
+ });
+
+ fireEvent.pointerDown(screen.getByRole('button', {name: '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
index b276399256..ff93dbe496 100644
--- a/packages/lab/src/InfoTip/InfoTip.tsx
+++ b/packages/lab/src/InfoTip/InfoTip.tsx
@@ -79,8 +79,8 @@ const styles = stylex.create({
/**
* An inline info-icon help affordance: a small "i" button that reveals a
- * tooltip on hover and keyboard focus. Use it next to labels, values, and
- * metrics for permission notes, metric definitions, and field help.
+ * 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,
@@ -130,6 +130,11 @@ export function InfoTip({
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"
isOpen={isDismissed ? false : undefined}
onOpenChange={handleOpenChange}>
<button