Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/docs/accessibility.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.

:::

Expand Down Expand Up @@ -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 `<a href="...">`, `<button>`, and form controls are focusable by default.
ReactTooltip opens the tooltip when the anchor receives keyboard focus, but only focusable elements can receive keyboard focus. Interactive elements such as `<a href="...">`, `<button>`, and form controls are focusable by default.

If your anchor is a non-interactive element (like a `<span>` or `<div>`), make it focusable by adding `tabIndex={0}`.

Expand Down
2 changes: 1 addition & 1 deletion docs/docs/options.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ import { Tooltip } from 'react-tooltip';
| ~~`closeOnEsc`~~ | ~~`boolean`~~ | ~~no~~ | ~~`false`~~ | ~~`true` `false`~~ | ~~Pressing escape key will close the tooltip~~ <br/>**Removed in v6.**<br/>Use `globalCloseEvents` instead. |
| ~~`closeOnScroll`~~ | ~~`boolean`~~ | ~~no~~ | ~~`false`~~ | ~~`true` `false`~~ | ~~Scrolling will close the tooltip~~ <br/>**Removed in v6.**<br/>Use `globalCloseEvents` instead. |
| ~~`closeOnResize`~~ | ~~`boolean`~~ | ~~no~~ | ~~`false`~~ | ~~`true` `false`~~ | ~~Resizing the window will close the tooltip~~ <br/>**Removed in v6.**<br/>Use `globalCloseEvents` instead. |
| `openEvents` | `Record<string, boolean>` | no | `mouseover` `focus` | `mouseover` `focus` `mouseenter` `click` `dblclick` `mousedown` | Events to be listened on the anchor elements to open the tooltip |
| `openEvents` | `object` | no | `mouseover` `focus` | `mouseover` `focus` `mouseenter` `click` `dblclick` `mousedown`. `focus` may be `true`, `false`, or `'visible'` | Events that open the tooltip. `focus` defaults to keyboard focus only (`:focus-visible`). `focus: true` also opens when a script moves focus. Focus the browser restores when the window is focused again does not open it. |
| `closeEvents` | `Record<string, boolean>` | no | `mouseout` `blur` | `mouseout` `blur` `mouseleave` `click` `dblclick` `mouseup` | Events to be listened on the anchor elements to close the tooltip |
| `globalCloseEvents` | `Record<string, boolean>` | no | | `escape` `scroll` `resize` `clickOutsideAnchor` | Global events to be listened to close the tooltip (`escape` closes on pressing `ESC`, `clickOutsideAnchor` is useful with click events on `openEvents`) |
| `imperativeModeOnly` | `boolean` | no | `false` | `true` `false` | When enabled, default tooltip behavior is disabled. Check [the examples](./examples/imperative-mode.mdx) for more details |
Expand Down
18 changes: 15 additions & 3 deletions src/components/Tooltip/TooltipTypes.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,21 @@ export interface TooltipRefProps {

type AnchorClickEvents = 'click' | 'dblclick' | 'mousedown' | 'mouseup'

export type AnchorOpenEvents = Partial<
Record<'mouseenter' | 'focus' | 'mouseover' | AnchorClickEvents, boolean>
>
export type AnchorOpenEvents = {
mouseenter?: boolean
mouseover?: boolean
/**
* `true` also opens when a script moves focus. `'visible'` (the default when
* `openEvents` is omitted) opens only for keyboard focus, matching
* `:focus-visible`. Neither opens when the browser restores focus after the
* window blurs.
*/
focus?: boolean | 'visible'
click?: boolean
dblclick?: boolean
mousedown?: boolean
mouseup?: boolean
}
export type AnchorCloseEvents = Partial<
Record<'mouseleave' | 'blur' | 'mouseout' | AnchorClickEvents, boolean>
>
Expand Down
180 changes: 180 additions & 0 deletions src/components/Tooltip/focus-open.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
/**
* Shared focus guards for every tooltip.
*
* One window listener records the focused element on window blur and ignores
* the focus the browser fires for that element when the window returns.
* `:focus-visible` decides whether any other focus should open a tooltip.
* Mac Safari can miss `:focus-visible` when focus arrives from outside the
* document, so that case follows the last key or pointer instead.
*/

const TYPEABLE_SELECTOR =
"input:not([type='hidden']):not([disabled]),[contenteditable]:not([contenteditable='false']),textarea:not([disabled])"

let restoredFocusElement: Element | null = null
let clearTimer: ReturnType<typeof setTimeout> | 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') {
return false
}
const isSafari =
/apple/i.test(navigator.vendor) && !/chrome|android|crios|fxios/i.test(navigator.userAgent)
const isMac = navigator.platform.toLowerCase().startsWith('mac') && !navigator.maxTouchPoints
return isSafari && isMac
}

function isTypeableElement(element: EventTarget | null): boolean {
return element instanceof HTMLElement && element.matches(TYPEABLE_SELECTOR)
}

function onKeyDown() {
lastInputWasKeyboard = true
}

function onPointerDown() {
lastInputWasKeyboard = false
}

function onWindowBlur() {
const active = document.activeElement
restoredFocusElement =
active instanceof Element && active !== document.body && active !== document.documentElement
? active
: null
if (clearTimer !== null) {
clearTimeout(clearTimer)
clearTimer = null
}
}

function scheduleClearRestoredFocus() {
if (clearTimer !== null) {
return
}
clearTimer = setTimeout(() => {
restoredFocusElement = null
clearTimer = null
}, 0)
}

function onWindowFocus() {
// Element focus can land in the same turn as window focus, or just before it.
// Drop the record on the next turn so a later real Tab still opens.
scheduleClearRestoredFocus()
}

function detach() {
if (listening && typeof window !== 'undefined') {
window.removeEventListener('blur', onWindowBlur)
window.removeEventListener('focus', onWindowFocus)
if (modalityListening) {
window.removeEventListener('keydown', onKeyDown, true)
window.removeEventListener('pointerdown', onPointerDown, true)
}
}
listening = false
modalityListening = false
restoredFocusElement = null
lastInputWasKeyboard = true
if (clearTimer !== null) {
clearTimeout(clearTimer)
clearTimer = null
}
}

export function subscribeFocusOpenGuards(): () => void {
const subscribedSession = session
subscribers += 1
if (!listening && typeof window !== 'undefined') {
listening = true
window.addEventListener('blur', onWindowBlur)
window.addEventListener('focus', onWindowFocus)
// 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 () => {
if (subscribedSession !== session) {
return
}
subscribers -= 1
if (subscribers <= 0) {
subscribers = 0
detach()
}
}
}

export function isWindowRestoredFocus(target: EventTarget | null): boolean {
if (!(target instanceof Node) || restoredFocusElement === null) {
return false
}
const restored = target === restoredFocusElement || restoredFocusElement.contains(target)
if (!restored) {
// The user focused something else, so this was not a window restore.
scheduleClearRestoredFocus()
return false
}
// Keep the record until the next turn so every tooltip handler for this
// event sees it, including when the browser never fires window focus.
scheduleClearRestoredFocus()
return true
}

export function shouldOpenOnVisibleFocus(event: Event): boolean {
const { target } = event
const relatedTarget = event instanceof FocusEvent ? event.relatedTarget : null

if (isMacSafari() && !relatedTarget) {
if (!lastInputWasKeyboard && !isTypeableElement(target)) {
return false
}
return true
}

if (!(target instanceof Element)) {
return false
}
// JSDOM parses :focus-visible but never matches it, which would hide every
// keyboard tooltip under test. Old browsers that reject the selector throw.
if (isJSDOM()) {
return true
}
try {
return target.matches(':focus-visible')
} catch {
return true
}
}

export function resetFocusOpenGuards(): void {
session += 1
subscribers = 0
macSafari = null
detach()
}
33 changes: 30 additions & 3 deletions src/components/Tooltip/use-tooltip-events.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ import type {
IPosition,
} from './TooltipTypes'
import { addDelegatedEventListener } from './event-delegation'
import {
isWindowRestoredFocus,
shouldOpenOnVisibleFocus,
subscribeFocusOpenGuards,
} from './focus-open'

const useTooltipEvents = ({
activeAnchor,
Expand Down Expand Up @@ -100,7 +105,7 @@ const useTooltipEvents = ({
? { ...openEvents }
: {
mouseenter: true,
focus: true,
focus: 'visible',
click: false,
dblclick: false,
mousedown: false,
Expand Down Expand Up @@ -284,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
Expand Down Expand Up @@ -354,12 +367,26 @@ const useTooltipEvents = ({
}
if (actualOpenEvents.focus) {
addDelegatedListener('focusin', (event) => {
debouncedHandleShowTooltip(resolveAnchorElementRef.current(event.target))
if (isWindowRestoredFocus(event.target)) {
return
}
const anchor = resolveAnchorElementRef.current(event.target)
if (!anchor) {
return
}
if (actualOpenEvents.focus !== true && !shouldOpenOnVisibleFocus(event)) {
return
}
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) {
Expand Down
Loading
Loading