An open source design system that's fully customizable and agent ready
TypeScript
fix(Tooltip, HoverCard): a touch opens them only once it is a tap (#8165)
Christopher Chedeau1554dc62628d
diff --git a/.changeset/hover-layers-open-on-tap.md b/.changeset/hover-layers-open-on-tap.mdnew file mode 100644index 0000000000..f147ebbe3b--- /dev/null+++ b/.changeset/hover-layers-open-on-tap.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Tooltip and HoverCard answer a touch only once it is a tap. On a touch screen they used to open as soon as a finger landed on a trigger that performs no action, so a scroll that started on an info icon or an abbreviation opened its tooltip and left it open, and a finger resting on the trigger opened it too. Now the tap opens the layer when the finger lifts, and a touch that turns into a scroll never opens it, the way a tap on iOS behaves. A tap-opened tooltip or card closes when a tap outside lifts, or as soon as a scroll that starts outside takes the touch, which is when iOS dismisses a popover; before, it closed the moment a finger landed anywhere else. Triggers that perform an action keep their tap, and `touchTrigger` keeps its meaning.++@vjeuxdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 292228278f..d3b49978a2 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1597,6 +1597,18 @@ jobs:--project chromium \--output submenu-header-footer-output+ # Tooltip and HoverCard answer a touch only once it is a tap: they open+ # when the finger lifts, never for a touch that turns into a scroll, and+ # a tap-opened layer closes when a tap outside lifts. Whether a touch is+ # a tap, a scroll or a long press is the engine's own gesture decision,+ # which only real touch input reaches.+ - name: Run hover layer touch contract+ run: |+ pnpm exec playwright test \+ packages/core/src/Layer/__tests__/TouchTrigger.a11y.chromium.spec.ts \+ --project chromium \+ --output hover-layer-touch-output+# A pointer that crosses from a Tooltip's trigger onto the tooltip in one# step must not lose it (WCAG 1.4.13 hoverable). The defect is in the# order the engine dispatches mouseout and mouseleave on that step, whichdiff --git a/packages/core/src/HoverCard/HoverCard.test.tsx b/packages/core/src/HoverCard/HoverCard.test.tsxindex aafe9b4fdc..124768daec 100644--- a/packages/core/src/HoverCard/HoverCard.test.tsx+++ b/packages/core/src/HoverCard/HoverCard.test.tsx@@ -1049,7 +1049,11 @@ describe('HoverCard', () => {__resetInteractionModalityForTest();});- /** A tap: the pointer sequence a finger produces before hover is faked. */+ /**+ * A tap, in the order a browser dispatches it: the finger's pointer events,+ * then the hover it synthesizes, then the `click` that says the touch was a+ * tap and not the start of a scroll.+ */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.@@ -1058,6 +1062,7 @@ describe('HoverCard', () => {fireEvent.pointerUp(element, {pointerType: 'touch'});// Touch synthesizes hover after the press; the card must not act on it.fireEvent.mouseEnter(element);+ fireEvent.click(element);};it('opens on a tap when the trigger performs no action', async () => {@@ -1141,6 +1146,8 @@ describe('HoverCard', () => {hidden: true,});fireEvent.pointerDown(action, {pointerType: 'touch'});+ fireEvent.pointerUp(action, {pointerType: 'touch'});+ fireEvent.click(action);await new Promise(resolve => setTimeout(resolve, 50));expect(onOpenChange).not.toHaveBeenCalledWith(false);@@ -1166,10 +1173,93 @@ describe('HoverCard', () => {expect(onOpenChange).toHaveBeenCalledWith(true);});- fireEvent.pointerDown(screen.getByRole('button', {name: 'Elsewhere'}), {- pointerType: 'touch',+ const elsewhere = screen.getByRole('button', {name: 'Elsewhere'});+ fireEvent.pointerDown(elsewhere, {pointerType: 'touch'});+ // Not yet: a popover closes when the outside tap lifts.+ await new Promise(resolve => setTimeout(resolve, 50));+ expect(onOpenChange).not.toHaveBeenCalledWith(false);++ fireEvent.pointerUp(elsewhere, {pointerType: 'touch'});+ await waitFor(() => {+ expect(onOpenChange).toHaveBeenCalledWith(false);+ });+ });++ it('opens when the finger lifts, not when it lands', async () => {+ const onOpenChange = vi.fn();+ render(+ <HoverCard+ content={<span>Card content</span>}+ onOpenChange={onOpenChange}+ delay={0}>+ Ruby Cheung+ </HoverCard>,+ );++ const trigger = screen.getByText('Ruby Cheung');+ fireEvent.pointerEnter(trigger, {pointerType: 'touch'});+ fireEvent.pointerDown(trigger, {pointerType: 'touch'});+ await new Promise(resolve => setTimeout(resolve, 50));+ expect(onOpenChange).not.toHaveBeenCalled();++ fireEvent.pointerUp(trigger, {pointerType: 'touch'});+ fireEvent.click(trigger);+ await waitFor(() => {+ expect(onOpenChange).toHaveBeenCalledWith(true);+ });+ });++ it('never opens for a touch that turns into a scroll', async () => {+ const onOpenChange = vi.fn();+ render(+ <HoverCard+ content={<span>Card content</span>}+ onOpenChange={onOpenChange}+ delay={0}>+ Ruby Cheung+ </HoverCard>,+ );++ const trigger = screen.getByText('Ruby Cheung');+ fireEvent.pointerEnter(trigger, {pointerType: 'touch'});+ fireEvent.pointerDown(trigger, {pointerType: 'touch'});+ fireEvent.pointerCancel(trigger, {pointerType: 'touch'});++ await new Promise(resolve => setTimeout(resolve, 50));+ expect(onOpenChange).not.toHaveBeenCalled();+ });++ it('closes when a scroll starts outside, but not for one inside the card', async () => {+ const onOpenChange = vi.fn();+ render(+ <>+ <HoverCard+ content={<p>Card content</p>}+ onOpenChange={onOpenChange}+ delay={0}+ hideDelay={0}>+ Ruby Cheung+ </HoverCard>+ <p>Page content</p>+ </>,+ );++ tap(screen.getByText('Ruby Cheung'));+ await waitFor(() => {+ expect(onOpenChange).toHaveBeenCalledWith(true);});+ onOpenChange.mockClear();++ // Scrolling the card's own content keeps it.+ const inside = await screen.findByText('Card content');+ fireEvent.pointerDown(inside, {pointerType: 'touch'});+ fireEvent.pointerCancel(inside, {pointerType: 'touch'});+ await new Promise(resolve => setTimeout(resolve, 50));+ expect(onOpenChange).not.toHaveBeenCalledWith(false);+ const page = screen.getByText('Page content');+ fireEvent.pointerDown(page, {pointerType: 'touch'});+ fireEvent.pointerCancel(page, {pointerType: 'touch'});await waitFor(() => {expect(onOpenChange).toHaveBeenCalledWith(false);});diff --git a/packages/core/src/Layer/__tests__/TouchTrigger.a11y.chromium.spec.ts b/packages/core/src/Layer/__tests__/TouchTrigger.a11y.chromium.spec.tsnew file mode 100644index 0000000000..edc9495cfd--- /dev/null+++ b/packages/core/src/Layer/__tests__/TouchTrigger.a11y.chromium.spec.ts@@ -0,0 +1,199 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file TouchTrigger.a11y.chromium.spec.ts+ * @input The `Core/Tooltip` and `Core/HoverCard` Touch Triggers stories in a+ * built Storybook, driven by real Chromium touch input (CDP) in a phone-sized+ * viewport.+ * @output Real-engine proof that a hover layer answers a touch only once it is+ * a tap: it opens when the finger lifts, stays shut while a finger rests on+ * the trigger, never opens for a touch that turns into a scroll, and a+ * tap-opened layer closes when a tap outside lifts or a scroll starts+ * outside.+ * @position Run with `pnpm test:a11y-contract`. Only a real engine decides+ * whether a touch is a tap, a scroll or a long press, so these outcomes+ * cannot be shown in jsdom; the unit suites (Tooltip.test.tsx,+ * HoverCard.test.tsx) cover the same rules on synthetic events.+ */++import {+ expect,+ test,+ type CDPSession,+ type Locator,+ type Page,+} from '@playwright/test';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => {+ await storybook?.close();+});++test.use({hasTouch: true, isMobile: true, viewport: {width: 390, height: 844}});++interface Finger {+ down(x: number, y: number): Promise<void>;+ move(x: number, y: number): Promise<void>;+ up(): Promise<void>;+}++async function openStory(page: Page, id: string): Promise<Finger> {+ await page.goto(`${storybook.origin}/iframe.html?id=${id}&viewMode=story`);+ // Room to scroll, so a drag is a page scroll the browser takes from us.+ await page.evaluate(() => {+ const spacer = document.createElement('div');+ spacer.style.height = '2000px';+ document.body.append(spacer);+ });+ const cdp: CDPSession = await page.context().newCDPSession(page);+ return {+ down: async (x, y) => {+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchStart',+ touchPoints: [{x, y}],+ });+ },+ move: async (x, y) => {+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchMove',+ touchPoints: [{x, y}],+ });+ },+ up: async () => {+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchEnd',+ touchPoints: [],+ });+ },+ };+}++async function centerOf(target: Locator): Promise<[number, number]> {+ const box = await target.boundingBox();+ if (box == null) {+ throw new Error('the trigger has no layout box');+ }+ return [+ Math.round(box.x + box.width / 2),+ Math.round(box.y + box.height / 2),+ ];+}++/** A blank point of the page, away from every trigger. */+const OUTSIDE: [number, number] = [360, 700];++const cases = [+ {+ name: 'Tooltip',+ story: 'core-tooltip--touch-triggers',+ trigger: (page: Page) => page.getByText('hover-able term', {exact: true}),+ action: (page: Page) => page.getByRole('button', {name: 'Save'}),+ layer: '.astryx-tooltip:popover-open',+ },+ {+ name: 'HoverCard',+ story: 'core-hovercard--touch-triggers',+ trigger: (page: Page) => page.getByText('Jane Doe', {exact: true}),+ action: (page: Page) => page.getByRole('button', {name: 'Open profile'}),+ layer: '.astryx-hover-card:popover-open',+ },+];++for (const {name, story, trigger, action, layer} of cases) {+ test.describe(`${name} under a finger`, () => {+ test('opens when the tap lifts, not when the finger lands', async ({+ page,+ }) => {+ const finger = await openStory(page, story);+ const [x, y] = await centerOf(trigger(page));+ await finger.down(x, y);+ await page.waitForTimeout(150);+ // The finger is still down: it may yet be starting a scroll.+ await expect(page.locator(layer)).toHaveCount(0);+ await finger.up();+ await expect(page.locator(layer)).toHaveCount(1);+ });++ test('never opens for a touch that turns into a scroll', async ({page}) => {+ const finger = await openStory(page, story);+ const [x, y] = await centerOf(trigger(page));+ await finger.down(x, y);+ for (let step = 1; step <= 8; step += 1) {+ await finger.move(x, y - step * 10);+ await page.waitForTimeout(16);+ }+ await finger.up();+ await page.waitForTimeout(300);+ await expect(page.locator(layer)).toHaveCount(0);+ });++ test('stays shut while a finger rests on the trigger', async ({page}) => {+ const finger = await openStory(page, story);+ const [x, y] = await centerOf(trigger(page));+ await finger.down(x, y);+ await page.waitForTimeout(900);+ // Nothing is decided until the finger lifts; whether a long hold still+ // counts as a tap then is the engine's call (UIKit's own tap allows a+ // hold of up to 1.5 s).+ await expect(page.locator(layer)).toHaveCount(0);+ await finger.up();+ });++ test('closes when a tap outside lifts, not when it lands', async ({+ page,+ }) => {+ const finger = await openStory(page, story);+ const [x, y] = await centerOf(trigger(page));+ await finger.down(x, y);+ await finger.up();+ await expect(page.locator(layer)).toHaveCount(1);++ await finger.down(...OUTSIDE);+ await page.waitForTimeout(150);+ await expect(page.locator(layer)).toHaveCount(1);+ await finger.up();+ await expect(page.locator(layer)).toHaveCount(0);+ });++ test('closes as soon as a scroll that starts outside takes the touch', async ({+ page,+ }) => {+ const finger = await openStory(page, story);+ const [x, y] = await centerOf(trigger(page));+ await finger.down(x, y);+ await finger.up();+ await expect(page.locator(layer)).toHaveCount(1);++ const [ox, oy] = OUTSIDE;+ await finger.down(ox, oy);+ for (let step = 1; step <= 8; step += 1) {+ await finger.move(ox, oy - step * 10);+ await page.waitForTimeout(16);+ }+ // Still down: the scroll took the touch, which is the dismissal.+ await expect(page.locator(layer)).toHaveCount(0);+ await finger.up();+ });++ test('leaves a tap on a trigger that acts to that trigger', async ({+ page,+ }) => {+ const finger = await openStory(page, story);+ const [x, y] = await centerOf(action(page));+ await finger.down(x, y);+ await finger.up();+ await page.waitForTimeout(300);+ await expect(page.locator(layer)).toHaveCount(0);+ });+ });+}diff --git a/packages/core/src/Layer/useTouchTrigger.ts b/packages/core/src/Layer/useTouchTrigger.tsindex cb027d3ffc..d9299a7b90 100644--- a/packages/core/src/Layer/useTouchTrigger.ts+++ b/packages/core/src/Layer/useTouchTrigger.ts@@ -24,9 +24,21 @@* 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.+ *+ * A touch decides nothing until it is a tap. A finger landing on the trigger+ * may be starting a scroll, a pinch or a long press, and only the browser+ * knows which once the finger moves or lifts. Its `click` is that verdict (on+ * iOS it comes from UIKit's own tap recognizer), so the press only records+ * itself and the tap's `click` opens or closes the layer; a press the browser+ * takes for scrolling ends in `pointercancel` and never gets there. That is+ * how a UIKit tap behaves: it recognizes when the finger lifts and fails once+ * the scroll view claims the touch. The tap outside that closes a tap-opened+ * layer counts when the finger lifts too, or when a scroll takes the touch,+ * which is when UIKit dismisses a popover.*/import {useCallback, useEffect, useRef, type RefObject} from 'react';+import {currentGesture} from './gestureCounter';import {getInteractionModality,useInteractionModalityTracking,@@ -175,7 +187,9 @@ export interface UseTouchTriggerReturn {/*** 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.+ * behavior must not also run. A touch press opens or closes nothing by+ * itself: the hook waits for that press's tap (the `click` the browser+ * fires when the finger lifts without scrolling) on the same element.*/handlePointerDown: (event: PointerEvent) => boolean;@@ -234,6 +248,9 @@ export function useTouchTrigger(const outsideListenerRef = useRef<((event: PointerEvent) => void) | null>(null,);+ // A touch press on the trigger still waiting for its tap: calling it stops+ // waiting. The next press, a cancel, the tap itself or unmounting calls it.+ const forgetPendingTapRef = useRef<(() => void) | null>(null);useInteractionModalityTracking();@@ -244,23 +261,30 @@ export function useTouchTrigger(return;}outsideListenerRef.current = null;- document.removeEventListener('pointerdown', listener, true);+ document.removeEventListener('pointerup', listener, true);+ document.removeEventListener('pointercancel', 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.+ // layer. It is armed by the opening tap's `click`, after that tap's own+ // `pointerup`, so the listener never sees the tap that opened the layer.+ // A tap outside counts when it lifts (`pointerup`); a scroll or pinch that+ // starts outside counts as soon as the browser takes it (`pointercancel`).const armOutsideDismiss = useCallback(() => {isTapOpenRef.current = true;if (outsideListenerRef.current != null) {return;}- const handleOutsidePointerDown = (event: PointerEvent) => {+ const handleOutsidePointerEnd = (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) {+ // A tap on the trigger is the trigger's to toggle. A scroll that+ // starts there is a scroll outside the layer, and it does close it.+ if (+ event.type === 'pointerup' &&+ triggerRef.current?.contains(target) === true+ ) {return;}// Hover card content is interactive; a tap inside it is not a dismiss.@@ -274,11 +298,13 @@ export function useTouchTrigger(hideRef.current();};- outsideListenerRef.current = handleOutsidePointerDown;- document.addEventListener('pointerdown', handleOutsidePointerDown, true);+ outsideListenerRef.current = handleOutsidePointerEnd;+ document.addEventListener('pointerup', handleOutsidePointerEnd, true);+ document.addEventListener('pointercancel', handleOutsidePointerEnd, true);}, [triggerRef, disarmOutsideDismiss]);useEffect(() => disarmOutsideDismiss, [disarmOutsideDismiss]);+ useEffect(() => () => forgetPendingTapRef.current?.(), []);const isTouchInteraction = useCallback(() => isTouchPointerRef.current && getInteractionModality() === 'pointer',@@ -293,52 +319,80 @@ export function useTouchTrigger(isTouchPointerRef.current = event.pointerType === 'touch';}, []);+ // What a tap on the trigger does. It runs from the tap's `click`, after the+ // render that armed it, so it reads the latest props through this ref.+ const answerTapRef = useRef<() => void>(() => {});+ answerTapRef.current = () => {+ 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;+ }++ // 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;+ }++ armOutsideDismiss();+ show();+ };+const handlePointerDown = useCallback((event: PointerEvent): boolean => {const isTouch = TOUCH_POINTER_TYPES.has(event.pointerType);isTouchPointerRef.current = isTouch;+ // A new press replaces one that never became a tap.+ forgetPendingTapRef.current?.();if (!isTouch || isControlled) {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();+ const trigger =+ event.currentTarget instanceof Element+ ? event.currentTarget+ : triggerRef.current;+ if (trigger == null) {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();+ // The tap must belong to this press. A key press or a new pointer press+ // advances the gesture, so a keyboard activation that later fires+ // `click` on the trigger (Enter on a button) is not mistaken for it.+ const gesture = currentGesture();+ const forget = () => {+ trigger.removeEventListener('click', handleTap);+ trigger.removeEventListener('pointercancel', forget);+ if (forgetPendingTapRef.current === forget) {+ forgetPendingTapRef.current = null;+ }+ };+ const handleTap = () => {+ forget();+ if (currentGesture() === gesture) {+ answerTapRef.current();+ }+ };+ trigger.addEventListener('click', handleTap);+ // The browser took the touch for a scroll or a pinch: no tap is coming.+ trigger.addEventListener('pointercancel', forget);+ forgetPendingTapRef.current = forget;return true;},- [- touchTrigger,- isEnabled,- isControlled,- triggerRef,- show,- hide,- armOutsideDismiss,- disarmOutsideDismiss,- ],+ [isControlled, triggerRef],);// A layer closed by any other path (Escape, a consumer, the browser) leavesdiff --git a/packages/core/src/Tooltip/Tooltip.test.tsx b/packages/core/src/Tooltip/Tooltip.test.tsxindex c5470cdb79..7e2a5b1108 100644--- a/packages/core/src/Tooltip/Tooltip.test.tsx+++ b/packages/core/src/Tooltip/Tooltip.test.tsx@@ -365,7 +365,11 @@ describe('Tooltip', () => {__resetInteractionModalityForTest();});- /** A tap: the pointer sequence a finger produces before hover is faked. */+ /**+ * A tap, in the order a browser dispatches it: the finger's pointer events,+ * then the hover it synthesizes, then the `click` that says the touch was a+ * tap and not the start of a scroll.+ */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.@@ -374,6 +378,14 @@ describe('Tooltip', () => {fireEvent.pointerUp(element, {pointerType: 'touch'});// Touch synthesizes hover after the press; the tooltip must not act on it.fireEvent.mouseEnter(element);+ fireEvent.click(element);+ };++ /** A tap outside: what a finger landing and lifting elsewhere dispatches. */+ const tapOutside = (element: HTMLElement) => {+ fireEvent.pointerDown(element, {pointerType: 'touch'});+ fireEvent.pointerUp(element, {pointerType: 'touch'});+ fireEvent.click(element);};it('opens on a tap when the trigger performs no action', async () => {@@ -479,9 +491,141 @@ describe('Tooltip', () => {expect(onOpenChange).toHaveBeenCalledWith(true);});- fireEvent.pointerDown(screen.getByRole('button', {name: 'Elsewhere'}), {- pointerType: 'touch',+ tapOutside(screen.getByRole('button', {name: 'Elsewhere'}));++ await waitFor(() => {+ expect(onOpenChange).toHaveBeenCalledWith(false);+ });+ });++ it('opens when the finger lifts, not when it lands', async () => {+ const onOpenChange = vi.fn();+ render(+ <Tooltip content="Tooltip text" onOpenChange={onOpenChange} delay={0}>+ Abbreviation+ </Tooltip>,+ );++ const trigger = screen.getByText('Abbreviation');+ fireEvent.pointerEnter(trigger, {pointerType: 'touch'});+ fireEvent.pointerDown(trigger, {pointerType: 'touch'});+ // The finger is still down: it may be starting a scroll.+ await new Promise(resolve => setTimeout(resolve, 50));+ expect(onOpenChange).not.toHaveBeenCalled();++ fireEvent.pointerUp(trigger, {pointerType: 'touch'});+ fireEvent.click(trigger);+ await waitFor(() => {+ expect(onOpenChange).toHaveBeenCalledWith(true);});+ });++ it('never opens for a touch that turns into a scroll', async () => {+ const onOpenChange = vi.fn();+ render(+ <Tooltip content="Tooltip text" onOpenChange={onOpenChange} delay={0}>+ Abbreviation+ </Tooltip>,+ );++ const trigger = screen.getByText('Abbreviation');+ fireEvent.pointerEnter(trigger, {pointerType: 'touch'});+ fireEvent.pointerDown(trigger, {pointerType: 'touch'});+ // The browser takes the touch for the page scroll: no tap follows.+ fireEvent.pointerCancel(trigger, {pointerType: 'touch'});++ await new Promise(resolve => setTimeout(resolve, 50));+ expect(onOpenChange).not.toHaveBeenCalled();+ });++ it('never opens for a press the browser did not count as a tap', async () => {+ const onOpenChange = vi.fn();+ render(+ <Tooltip content="Tooltip text" onOpenChange={onOpenChange} delay={0}>+ Abbreviation+ </Tooltip>,+ );++ const trigger = screen.getByText('Abbreviation');+ // A long press: the finger lifts, but the browser fires no click+ // (it selected text or showed its own menu instead).+ fireEvent.pointerDown(trigger, {pointerType: 'touch'});+ fireEvent.pointerUp(trigger, {pointerType: 'touch'});++ await new Promise(resolve => setTimeout(resolve, 50));+ expect(onOpenChange).not.toHaveBeenCalled();+ });++ it('does not take a later keyboard click for the tap of an earlier press', async () => {+ const onOpenChange = vi.fn();+ render(+ <Tooltip+ content="What this metric means"+ onOpenChange={onOpenChange}+ touchTrigger="tap"+ delay={0}>+ <button type="button">Info</button>+ </Tooltip>,+ );++ const trigger = screen.getByRole('button', {name: 'Info'});+ // A press that never became a tap ...+ fireEvent.pointerDown(trigger, {pointerType: 'touch'});+ fireEvent.pointerUp(trigger, {pointerType: 'touch'});+ // ... then Enter on the focused button, which fires its own click.+ fireEvent.keyDown(trigger, {key: 'Enter'});+ fireEvent.click(trigger);++ await new Promise(resolve => setTimeout(resolve, 50));+ expect(onOpenChange).not.toHaveBeenCalledWith(true);+ });++ it('closes on a tap outside when the finger lifts, not when it lands', 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);+ });++ const elsewhere = screen.getByRole('button', {name: 'Elsewhere'});+ fireEvent.pointerDown(elsewhere, {pointerType: 'touch'});+ await new Promise(resolve => setTimeout(resolve, 50));+ expect(onOpenChange).not.toHaveBeenCalledWith(false);++ fireEvent.pointerUp(elsewhere, {pointerType: 'touch'});+ await waitFor(() => {+ expect(onOpenChange).toHaveBeenCalledWith(false);+ });+ });++ it('closes when a scroll starts outside', async () => {+ const onOpenChange = vi.fn();+ render(+ <>+ <Tooltip content="Tooltip text" onOpenChange={onOpenChange} delay={0}>+ Abbreviation+ </Tooltip>+ <p>Page content</p>+ </>,+ );++ tap(screen.getByText('Abbreviation'));+ await waitFor(() => {+ expect(onOpenChange).toHaveBeenCalledWith(true);+ });++ const page = screen.getByText('Page content');+ fireEvent.pointerDown(page, {pointerType: 'touch'});+ fireEvent.pointerCancel(page, {pointerType: 'touch'});await waitFor(() => {expect(onOpenChange).toHaveBeenCalledWith(false);@@ -543,6 +687,7 @@ describe('Tooltip', () => {fireEvent.pointerEnter(trigger, {pointerType: 'pen', buttons: 0});fireEvent.pointerDown(trigger, {pointerType: 'pen'});fireEvent.pointerUp(trigger, {pointerType: 'pen'});+ fireEvent.click(trigger);await waitFor(() => {expect(onOpenChange).toHaveBeenCalledWith(true);diff --git a/packages/core/src/Tooltip/__tests__/Tooltip.a11y.states.ts b/packages/core/src/Tooltip/__tests__/Tooltip.a11y.states.tsindex 4e95448185..60fd94164f 100644--- a/packages/core/src/Tooltip/__tests__/Tooltip.a11y.states.ts+++ b/packages/core/src/Tooltip/__tests__/Tooltip.a11y.states.ts@@ -98,9 +98,9 @@ export const TOOLTIP_EXCLUSIONS = [{id: 'touch-trigger',owner:- 'useTooltip.test.tsx and Tooltip.test.tsx (touchTrigger suites) through the shared useTouchTrigger hook',+ 'useTooltip.test.tsx and Tooltip.test.tsx (touchTrigger suites) through the shared useTouchTrigger hook, and TouchTrigger.a11y.chromium.spec.ts for real touch input',reason:- 'On a touch pointer there is no hover, so a tap opens the tooltip or leaves it to the control the tap operates; the APG defines no touch behaviour, and the Chromium lane drives a mouse and a keyboard only.',+ 'On a touch pointer there is no hover, so a tap opens the tooltip or leaves it to the control the tap operates; the APG defines no touch behaviour, and this contract drives a mouse and a keyboard only, so the touch outcomes have their own real-touch Chromium proof.',},{id: 'controlled-and-disabled',diff --git a/packages/lab/src/InfoTip/InfoTip.test.tsx b/packages/lab/src/InfoTip/InfoTip.test.tsxindex 1fc5966af3..7edd6079b7 100644--- a/packages/lab/src/InfoTip/InfoTip.test.tsx+++ b/packages/lab/src/InfoTip/InfoTip.test.tsx@@ -167,12 +167,16 @@ describe('InfoTip', () => {expect(screen.getByTestId('rich-content')).toBeInTheDocument();});describe('touch', () => {- /** A tap: the pointer sequence a finger produces before hover is faked. */+ /**+ * 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 () => {@@ -221,9 +225,10 @@ describe('InfoTip', () => {expect(popoverOpenState.get(layer)).toBe(true);});- fireEvent.pointerDown(screen.getByRole('button', {name: 'Elsewhere'}), {- pointerType: 'touch',- });+ // 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);