From 62ec20f7a8e4b39df1d8f1483af771e32d90ea58 Mon Sep 17 00:00:00 2001 From: Daniel Barion Date: Mon, 26 Oct 2026 11:32:53 -0300 Subject: [PATCH 1/3] fix: open tooltips on visible focus only Keyboard focus still opens the tooltip. Focus moved by a script does not, unless openEvents.focus is true. Focus the browser restores when the window is focused again never opens it. Fixes #1287 --- docs/docs/accessibility.mdx | 4 +- docs/docs/options.mdx | 2 +- src/components/Tooltip/TooltipTypes.d.ts | 18 +- src/components/Tooltip/focus-open.ts | 162 ++++++++ src/components/Tooltip/use-tooltip-events.tsx | 16 +- src/test/tooltip-focus-visible.spec.js | 367 ++++++++++++++++++ 6 files changed, 562 insertions(+), 7 deletions(-) create mode 100644 src/components/Tooltip/focus-open.ts create mode 100644 src/test/tooltip-focus-visible.spec.js diff --git a/docs/docs/accessibility.mdx b/docs/docs/accessibility.mdx index a00e3995..1fe278ee 100644 --- a/docs/docs/accessibility.mdx +++ b/docs/docs/accessibility.mdx @@ -43,7 +43,7 @@ The rest of this page shows how each of these maps to ReactTooltip props and mar :::info -ReactTooltip already opens the tooltip when the anchor receives keyboard focus (not just on hover), so most of the work is making sure your anchor is focusable and correctly associated with the tooltip. +ReactTooltip opens the tooltip when the anchor receives keyboard focus (`:focus-visible`), not only on hover. Focus moved by a script, or focus the browser restores when you return to the window, does not open it. Most of the remaining work is making sure your anchor is focusable and correctly associated with the tooltip. ::: @@ -72,7 +72,7 @@ Users must be able to close the tooltip without moving the pointer or focus. Ena ## Keyboard-accessible anchor (2.1.1) -ReactTooltip opens the tooltip when the anchor receives focus, but only focusable elements can receive keyboard focus. Interactive elements such as ``, ` + ), + }) + + const anchor = screen.getByRole('button', { name: 'Model' }) + + act(() => { + anchor.focus() + }) + await waitForTooltip('restore-focus') + act(() => { + jest.advanceTimersByTime(30) + }) + expect(describedBy(anchor)).toContain('restore-focus') + + act(() => { + fireEvent.mouseOut(anchor, { relatedTarget: document.body }) + }) + await waitForTooltipToStopShowing('restore-focus') + act(() => { + jest.runOnlyPendingTimers() + }) + expect(describedBy(anchor)).not.toContain('restore-focus') + expect(document.activeElement).toBe(anchor) + + act(() => { + window.dispatchEvent(new Event('blur')) + window.dispatchEvent(new Event('focus')) + fireEvent.focus(anchor) + jest.advanceTimersByTime(30) + }) + + expect(describedBy(anchor)).not.toContain('restore-focus') + }) + + test('does not keep blocking focus when the window never fires focus', async () => { + renderTip({ + id: 'restore-no-window-focus', + children: ( + + ), + }) + const anchor = screen.getByRole('button', { name: 'Model' }) + + act(() => { + anchor.focus() + }) + await waitForTooltip('restore-no-window-focus') + act(() => { + fireEvent.mouseOut(anchor, { relatedTarget: document.body }) + jest.runOnlyPendingTimers() + }) + + act(() => { + window.dispatchEvent(new Event('blur')) + fireEvent.focus(anchor) + jest.advanceTimersByTime(30) + }) + expect(describedBy(anchor)).not.toContain('restore-no-window-focus') + + focusAndFlush(anchor) + expect(describedBy(anchor)).toContain('restore-no-window-focus') + }) + + test('stops ignoring the anchor after focus moves somewhere else', async () => { + renderTip({ + id: 'restore-moved', + children: ( + <> + + + + ), + }) + const anchor = screen.getByRole('button', { name: 'Model' }) + const other = screen.getByRole('button', { name: 'Other' }) + + act(() => { + anchor.focus() + }) + await waitForTooltip('restore-moved') + act(() => { + fireEvent.mouseOut(anchor, { relatedTarget: document.body }) + jest.runOnlyPendingTimers() + }) + + act(() => { + window.dispatchEvent(new Event('blur')) + other.focus() + jest.runOnlyPendingTimers() + }) + + focusAndFlush(anchor) + expect(describedBy(anchor)).toContain('restore-moved') + }) + + test('opens on a later focus after an ignored window restore', async () => { + renderTip({ + id: 'restore-later', + children: ( + + ), + }) + const anchor = screen.getByRole('button', { name: 'Model' }) + + act(() => { + anchor.focus() + }) + await waitForTooltip('restore-later') + act(() => { + fireEvent.mouseOut(anchor, { relatedTarget: document.body }) + jest.runOnlyPendingTimers() + }) + + act(() => { + window.dispatchEvent(new Event('blur')) + window.dispatchEvent(new Event('focus')) + fireEvent.focus(anchor) + jest.runOnlyPendingTimers() + }) + expect(describedBy(anchor)).not.toContain('restore-later') + + focusAndFlush(anchor) + expect(describedBy(anchor)).toContain('restore-later') + }) + + test('does not open when programmatic focus is not :focus-visible', () => { + installBrowserFocusVisible(() => false) + renderTip({ + id: 'programmatic-focus', + children: ( + + ), + }) + const anchor = screen.getByRole('button', { name: 'Model' }) + + focusAndFlush(anchor) + + expect(describedBy(anchor)).not.toContain('programmatic-focus') + }) + + test('opens for keyboard focus that matches :focus-visible', () => { + installBrowserFocusVisible(() => true) + renderTip({ + id: 'keyboard-focus', + children: ( + + ), + }) + const anchor = screen.getByRole('button', { name: 'Model' }) + + focusAndFlush(anchor) + + expect(describedBy(anchor)).toContain('keyboard-focus') + }) + + test('opens for :focus-visible on a control inside the anchor', () => { + installBrowserFocusVisible((element) => element.tagName === 'BUTTON') + renderTip({ + id: 'inner-focus', + children: ( +
+ Wrapper + +
+ ), + }) + const anchor = screen.getByText('Wrapper').closest('div') + const inner = screen.getByRole('button', { name: 'Inner' }) + + focusAndFlush(inner) + + expect(describedBy(anchor)).toContain('inner-focus') + }) + + test('openEvents focus true still opens when focus is not :focus-visible', () => { + installBrowserFocusVisible(() => false) + renderTip({ + id: 'any-focus', + openEvents: { focus: true }, + children: ( + + ), + }) + const anchor = screen.getByRole('button', { name: 'Model' }) + + focusAndFlush(anchor) + + expect(describedBy(anchor)).toContain('any-focus') + }) + + test("openEvents focus 'visible' does not open on programmatic focus", () => { + installBrowserFocusVisible(() => false) + renderTip({ + id: 'visible-focus', + openEvents: { focus: 'visible', mouseenter: true }, + children: ( + + ), + }) + const anchor = screen.getByRole('button', { name: 'Model' }) + + focusAndFlush(anchor) + + expect(describedBy(anchor)).not.toContain('visible-focus') + }) + + test('Mac Safari ignores pointer focus from outside the document', () => { + installMacSafari() + renderTip({ + id: 'safari-pointer', + children: ( + + ), + }) + const anchor = screen.getByRole('button', { name: 'Model' }) + + act(() => { + fireEvent.pointerDown(anchor) + }) + focusAndFlush(anchor, { relatedTarget: null }) + + expect(describedBy(anchor)).not.toContain('safari-pointer') + }) + + test('Mac Safari opens keyboard focus from outside the document', () => { + installMacSafari() + renderTip({ + id: 'safari-key', + children: ( + + ), + }) + const anchor = screen.getByRole('button', { name: 'Model' }) + + act(() => { + fireEvent.keyDown(anchor, { key: 'Tab' }) + }) + focusAndFlush(anchor, { relatedTarget: null }) + + expect(describedBy(anchor)).toContain('safari-key') + }) + + test('Mac Safari still opens pointer focus on a text field', () => { + installMacSafari() + renderTip({ + id: 'safari-input', + children: , + }) + const anchor = screen.getByRole('textbox', { name: 'Name' }) + + act(() => { + fireEvent.pointerDown(anchor) + }) + focusAndFlush(anchor, { relatedTarget: null }) + + expect(describedBy(anchor)).toContain('safari-input') + }) +}) From d7eac0b2ac615cf84e07fe2ef531c86d306cf0d8 Mon Sep 17 00:00:00 2001 From: Daniel Barion Date: Mon, 26 Oct 2026 11:37:09 -0300 Subject: [PATCH 2/3] perf: skip Safari focus listeners in other browsers keydown and pointerdown were attached for every mounted tooltip. Only Mac Safari reads that input modality, so other browsers keep the window blur and focus listeners only. --- src/components/Tooltip/focus-open.ts | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/src/components/Tooltip/focus-open.ts b/src/components/Tooltip/focus-open.ts index 16d6168b..67df21c0 100644 --- a/src/components/Tooltip/focus-open.ts +++ b/src/components/Tooltip/focus-open.ts @@ -14,15 +14,24 @@ const TYPEABLE_SELECTOR = let restoredFocusElement: Element | null = null let clearTimer: ReturnType | null = null let listening = false +let modalityListening = false let subscribers = 0 let session = 0 let lastInputWasKeyboard = true +let macSafari: boolean | null = null function isJSDOM(): boolean { return typeof navigator !== 'undefined' && navigator.userAgent.includes('jsdom') } function isMacSafari(): boolean { + if (macSafari === null) { + macSafari = detectMacSafari() + } + return macSafari +} + +function detectMacSafari(): boolean { // JSDOM reports an Apple vendor. Never treat the test environment as Safari, // or a Mac platform string would skip :focus-visible entirely. if (isJSDOM() || typeof navigator === 'undefined') { @@ -78,10 +87,13 @@ function detach() { if (listening && typeof window !== 'undefined') { window.removeEventListener('blur', onWindowBlur) window.removeEventListener('focus', onWindowFocus) - window.removeEventListener('keydown', onKeyDown, true) - window.removeEventListener('pointerdown', onPointerDown, true) + if (modalityListening) { + window.removeEventListener('keydown', onKeyDown, true) + window.removeEventListener('pointerdown', onPointerDown, true) + } } listening = false + modalityListening = false restoredFocusElement = null lastInputWasKeyboard = true if (clearTimer !== null) { @@ -97,8 +109,13 @@ export function subscribeFocusOpenGuards(): () => void { listening = true window.addEventListener('blur', onWindowBlur) window.addEventListener('focus', onWindowFocus) - window.addEventListener('keydown', onKeyDown, true) - window.addEventListener('pointerdown', onPointerDown, true) + // Only Mac Safari reads this, and only when :focus-visible is wrong. + // Other browsers must not pay for a listener on every key and click. + if (isMacSafari()) { + window.addEventListener('keydown', onKeyDown, true) + window.addEventListener('pointerdown', onPointerDown, true) + modalityListening = true + } } return () => { @@ -158,5 +175,6 @@ export function shouldOpenOnVisibleFocus(event: Event): boolean { export function resetFocusOpenGuards(): void { session += 1 subscribers = 0 + macSafari = null detach() } From 90218d473b5127c8f9c7d4320ef9e2b538d3a06a Mon Sep 17 00:00:00 2001 From: Daniel Barion Date: Wed, 4 Nov 2026 09:02:12 -0300 Subject: [PATCH 3/3] fix: keep the window-focus guard across tooltip close The guard lived in the listener effect, which re-runs when the tooltip leaves the DOM. With one tooltip that dropped the subscriber count to zero and forgot the focused element. Skip focus that does not resolve to an anchor before the show debounce, so tabbing onto an anchor within 50ms still opens the tooltip. --- src/components/Tooltip/use-tooltip-events.tsx | 23 +++++-- src/test/tooltip-focus-visible.spec.js | 65 +++++++++++++++++++ 2 files changed, 83 insertions(+), 5 deletions(-) diff --git a/src/components/Tooltip/use-tooltip-events.tsx b/src/components/Tooltip/use-tooltip-events.tsx index a3e5cde0..4f030043 100644 --- a/src/components/Tooltip/use-tooltip-events.tsx +++ b/src/components/Tooltip/use-tooltip-events.tsx @@ -289,6 +289,14 @@ const useTooltipEvents = ({ debouncedShow.setCallback((anchor: Element | null) => handleShowTooltipRef.current(anchor)) debouncedHide.setCallback(() => handleHideTooltipRef.current()) + const focusOpens = Boolean(actualOpenEvents.focus) + useEffect(() => { + if (!focusOpens) { + return undefined + } + return subscribeFocusOpenGuards() + }, [focusOpens]) + // --- Effect 1: Delegated anchor events + tooltip hover --- // Only re-runs when the set of active event types or interaction mode changes. // Handlers read reactive values (activeAnchor, show, etc.) from refs at invocation @@ -358,22 +366,27 @@ const useTooltipEvents = ({ addDelegatedHoverCloseListener() } if (actualOpenEvents.focus) { - cleanupFns.push(subscribeFocusOpenGuards()) addDelegatedListener('focusin', (event) => { if (isWindowRestoredFocus(event.target)) { return } - // `true` keeps the old behavior and opens on any focus. The default, - // and `'visible'`, open only when the user moved focus there. + const anchor = resolveAnchorElementRef.current(event.target) + if (!anchor) { + return + } if (actualOpenEvents.focus !== true && !shouldOpenOnVisibleFocus(event)) { return } - debouncedHandleShowTooltip(resolveAnchorElementRef.current(event.target)) + debouncedHandleShowTooltip(anchor) }) } if (actualOpenEvents.mouseenter || actualOpenEvents.mouseover || actualOpenEvents.focus) { addDelegatedListener('touchstart', (event) => { - debouncedHandleShowTooltip(resolveAnchorElementRef.current(event.target)) + const anchor = resolveAnchorElementRef.current(event.target) + if (!anchor) { + return + } + debouncedHandleShowTooltip(anchor) }) } if (actualCloseEvents.blur) { diff --git a/src/test/tooltip-focus-visible.spec.js b/src/test/tooltip-focus-visible.spec.js index 6a63d965..a41a74a3 100644 --- a/src/test/tooltip-focus-visible.spec.js +++ b/src/test/tooltip-focus-visible.spec.js @@ -123,6 +123,71 @@ describe('tooltip focus visibility', () => { expect(describedBy(anchor)).not.toContain('restore-focus') }) + test('does not reopen an open tooltip when the window regains focus', async () => { + renderTip({ + id: 'restore-open', + children: ( + + ), + }) + const anchor = screen.getByRole('button', { name: 'Model' }) + + act(() => { + anchor.focus() + }) + await waitForTooltip('restore-open') + act(() => { + jest.advanceTimersByTime(30) + }) + expect(describedBy(anchor)).toContain('restore-open') + + act(() => { + window.dispatchEvent(new Event('blur')) + fireEvent.focusOut(anchor) + }) + act(() => { + jest.runOnlyPendingTimers() + }) + act(() => { + jest.runOnlyPendingTimers() + }) + expect(document.getElementById('restore-open')).not.toBeInTheDocument() + expect(describedBy(anchor)).not.toContain('restore-open') + + act(() => { + window.dispatchEvent(new Event('focus')) + fireEvent.focus(anchor) + jest.advanceTimersByTime(30) + }) + expect(describedBy(anchor)).not.toContain('restore-open') + }) + + test('opens when focus moves from a non-anchor onto an anchor within the show debounce', () => { + renderTip({ + id: 'tab-sequence', + children: ( + <> + + + + ), + }) + const other = screen.getByRole('button', { name: 'Other' }) + const anchor = screen.getByRole('button', { name: 'Model' }) + + act(() => { + fireEvent.focus(other) + fireEvent.focus(anchor) + jest.advanceTimersByTime(30) + }) + + expect(describedBy(anchor)).toContain('tab-sequence') + }) + test('does not keep blocking focus when the window never fires focus', async () => { renderTip({ id: 'restore-no-window-focus',