mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 19:07:41 +00:00
fix(ui): open tooltips on keyboard focus only, not on restored focus (#42902)
* fix(ui): open tooltips on keyboard focus only, not on restored focus Radix Tooltip opens on any focus that was not preceded by a pointerdown on the trigger, so focus returned to an icon button after an overlay closes popped its tooltip with no hover. Track the latest input modality and skip open-on-focus unless the focus followed keyboard input. * fix(ui): keep tooltips for assistive-tech focus; clean up modality listeners on hot reload Focus that arrives with no keyboard or pointer input and is not moved by our own script focus() (e.g. screen-reader navigation) now counts as virtual focus and opens the tooltip, so its description stays available. Script-restored focus keeps the modality that caused it. The module's window listeners and focus() wrapper are removed on hot-module disposal. * fix(ui): count focus from a label click as pointer focus A label focuses its control after pointerup and the click listeners, in the same task, so clearing the pointer window on pointerup classified that focus as assistive-tech focus. Clear it after the release task instead. * fix(ui): end the pointer window on pointercancel too A touch that turns into a scroll ends with pointercancel instead of pointerup, which left the pending-pointer flag set and hid the next screen-reader focus.
This commit is contained in:
+2
@@ -45,6 +45,7 @@ it('exposes the current selection on keyboard focus and follows the chat snapsho
|
||||
</TooltipProvider>
|
||||
)
|
||||
const view = render(picker([model, effort]))
|
||||
fireEvent.keyDown(window, { key: 'Tab' })
|
||||
fireEvent.focus(screen.getByRole('button'))
|
||||
const tooltip = await screen.findByRole('tooltip')
|
||||
expect(tooltip.textContent).toBe('Chat model · Extra high')
|
||||
@@ -105,6 +106,7 @@ it('keeps a working model-only picker inspectable without allowing changes', asy
|
||||
const view = render(picker(true))
|
||||
const informationalTrigger = screen.getByRole('button', { name: 'Model Chat model' })
|
||||
expect(informationalTrigger.getAttribute('aria-disabled')).toBe('true')
|
||||
fireEvent.keyDown(window, { key: 'Tab' })
|
||||
act(() => informationalTrigger.focus())
|
||||
expect(document.activeElement).toBe(informationalTrigger)
|
||||
expect((await screen.findByRole('tooltip')).textContent).toBe('Chat model')
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { act } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from './tooltip'
|
||||
|
||||
let root: Root | null = null
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
root = createRoot(document.body.appendChild(document.createElement('div')))
|
||||
act(() =>
|
||||
root!.render(
|
||||
<TooltipProvider delayDuration={0}>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button type="button">Settings</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Open settings</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root?.unmount())
|
||||
root = null
|
||||
document.body.innerHTML = ''
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
function trigger(): HTMLButtonElement {
|
||||
return document.querySelector('button')!
|
||||
}
|
||||
|
||||
function tooltipOpen(): boolean {
|
||||
act(() => vi.runAllTimers())
|
||||
return document.querySelector('[role="tooltip"]') !== null
|
||||
}
|
||||
|
||||
it('opens on keyboard focus', () => {
|
||||
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab' }))
|
||||
act(() => trigger().focus())
|
||||
expect(tooltipOpen()).toBe(true)
|
||||
})
|
||||
|
||||
it('stays closed when focus is restored after a pointer interaction', () => {
|
||||
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab' }))
|
||||
document.body.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }))
|
||||
act(() => trigger().focus())
|
||||
expect(tooltipOpen()).toBe(false)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['a click', ['pointerdown', 'mousedown', 'pointerup']],
|
||||
['a touch that became a scroll', ['pointerdown', 'pointercancel']]
|
||||
])('opens when assistive tech moves focus after %s', (_, events) => {
|
||||
for (const type of events) {
|
||||
document.body.dispatchEvent(new PointerEvent(type, { bubbles: true }))
|
||||
}
|
||||
vi.runAllTimers()
|
||||
// Screen-reader focus arrives as a focus event with no preceding input or script focus() call.
|
||||
act(() => {
|
||||
trigger().dispatchEvent(new FocusEvent('focusin', { bubbles: true }))
|
||||
})
|
||||
expect(tooltipOpen()).toBe(true)
|
||||
})
|
||||
|
||||
it('opens on hover', () => {
|
||||
act(() => {
|
||||
trigger().dispatchEvent(
|
||||
new PointerEvent('pointermove', { bubbles: true, pointerType: 'mouse' })
|
||||
)
|
||||
})
|
||||
expect(tooltipOpen()).toBe(true)
|
||||
})
|
||||
@@ -3,6 +3,7 @@ import * as TooltipPrimitive from 'radix-ui/tooltip'
|
||||
|
||||
import { cva, type VariantProps } from 'class-variance-authority'
|
||||
import { cn } from '@/lib/class-names'
|
||||
import { isKeyboardOrVirtualFocus } from '@/lib/keyboard/keyboard-input-modality'
|
||||
import { PortalContainerContext, usePortalContainer } from './portal-container-context'
|
||||
|
||||
function TooltipProvider({
|
||||
@@ -27,8 +28,24 @@ function Tooltip({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Root
|
||||
return <TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
||||
}
|
||||
|
||||
function TooltipTrigger({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
|
||||
function TooltipTrigger({
|
||||
onFocus,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
||||
return (
|
||||
<TooltipPrimitive.Trigger
|
||||
data-slot="tooltip-trigger"
|
||||
onFocus={(event) => {
|
||||
onFocus?.(event)
|
||||
// Why: focus restored to the trigger after a mouse-closed dialog/menu/panel must not pop the
|
||||
// label; preventDefault skips Radix's open-on-focus unless keyboard or assistive tech moved focus.
|
||||
if (!isKeyboardOrVirtualFocus()) {
|
||||
event.preventDefault()
|
||||
}
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const TAB_PREVIEW_CLASSES =
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { expect, it } from 'vitest'
|
||||
import { isKeyboardOrVirtualFocus, stopFocusModalityTracking } from './keyboard-input-modality'
|
||||
|
||||
it('counts focus from clicking a label as pointer focus', () => {
|
||||
const input = document.body.appendChild(document.createElement('input'))
|
||||
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab' }))
|
||||
for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) {
|
||||
document.body.dispatchEvent(new PointerEvent(type, { bubbles: true }))
|
||||
}
|
||||
// The browser focuses a label's control after the release events, in the same task.
|
||||
input.dispatchEvent(new FocusEvent('focusin', { bubbles: true }))
|
||||
expect(isKeyboardOrVirtualFocus()).toBe(false)
|
||||
})
|
||||
|
||||
it('stops following input once tracking is stopped', () => {
|
||||
const button = document.body.appendChild(document.createElement('button'))
|
||||
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab' }))
|
||||
expect(isKeyboardOrVirtualFocus()).toBe(true)
|
||||
|
||||
stopFocusModalityTracking()
|
||||
document.body.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }))
|
||||
button.focus()
|
||||
expect(isKeyboardOrVirtualFocus()).toBe(true)
|
||||
})
|
||||
@@ -0,0 +1,101 @@
|
||||
// 'virtual' is focus moved by assistive tech (e.g. VoiceOver), which sends no DOM input first.
|
||||
type FocusModality = 'keyboard' | 'pointer' | 'virtual'
|
||||
|
||||
let modality: FocusModality | null = null
|
||||
let inputSinceLastFocus = false
|
||||
let windowBlurredSinceLastFocus = false
|
||||
let scriptFocusDepth = 0
|
||||
let stopTracking: (() => void) | null = null
|
||||
|
||||
function onKeyDown(event: KeyboardEvent): void {
|
||||
inputSinceLastFocus = true
|
||||
// Shortcuts like Cmd+, are commands, not keyboard navigation.
|
||||
if (!event.metaKey && !event.ctrlKey && !event.altKey) {
|
||||
modality = 'keyboard'
|
||||
}
|
||||
}
|
||||
|
||||
function onPointerDown(): void {
|
||||
inputSinceLastFocus = true
|
||||
modality = 'pointer'
|
||||
}
|
||||
|
||||
// A press has moved focus once its release task ends (a <label> click focuses its control after
|
||||
// pointerup and click listeners); later focus without new input isn't the pointer's.
|
||||
function onPointerUp(): void {
|
||||
setTimeout(() => {
|
||||
inputSinceLastFocus = false
|
||||
}, 0)
|
||||
}
|
||||
|
||||
function onFocusIn(): void {
|
||||
// Focus with no input, not moved by our own scripts, and not the window regaining focus came from assistive tech.
|
||||
if (!inputSinceLastFocus && !windowBlurredSinceLastFocus && scriptFocusDepth === 0) {
|
||||
modality = 'virtual'
|
||||
}
|
||||
inputSinceLastFocus = false
|
||||
windowBlurredSinceLastFocus = false
|
||||
}
|
||||
|
||||
function startTracking(target: Window & typeof globalThis): () => void {
|
||||
const onWindowBlur = (event: FocusEvent): void => {
|
||||
if (event.target === target) {
|
||||
windowBlurredSinceLastFocus = true
|
||||
}
|
||||
}
|
||||
const prototype = target.HTMLElement.prototype
|
||||
const nativeFocus = prototype.focus
|
||||
// Script focus (e.g. an overlay returning focus to its trigger) keeps the modality that caused it.
|
||||
const trackedFocus = function (this: HTMLElement, options?: FocusOptions): void {
|
||||
scriptFocusDepth += 1
|
||||
try {
|
||||
nativeFocus.call(this, options)
|
||||
} finally {
|
||||
scriptFocusDepth -= 1
|
||||
}
|
||||
}
|
||||
prototype.focus = trackedFocus
|
||||
// Capture on window so handlers that stop propagation can't hide the input.
|
||||
target.addEventListener('keydown', onKeyDown, true)
|
||||
target.addEventListener('pointerdown', onPointerDown, true)
|
||||
target.addEventListener('mousedown', onPointerDown, true)
|
||||
target.addEventListener('pointerup', onPointerUp, true)
|
||||
// A touch that turns into a scroll ends with pointercancel instead of pointerup.
|
||||
target.addEventListener('pointercancel', onPointerUp, true)
|
||||
target.addEventListener('focusin', onFocusIn, true)
|
||||
target.addEventListener('blur', onWindowBlur, true)
|
||||
return () => {
|
||||
target.removeEventListener('keydown', onKeyDown, true)
|
||||
target.removeEventListener('pointerdown', onPointerDown, true)
|
||||
target.removeEventListener('mousedown', onPointerDown, true)
|
||||
target.removeEventListener('pointerup', onPointerUp, true)
|
||||
target.removeEventListener('pointercancel', onPointerUp, true)
|
||||
target.removeEventListener('focusin', onFocusIn, true)
|
||||
target.removeEventListener('blur', onWindowBlur, true)
|
||||
if (prototype.focus === trackedFocus) {
|
||||
prototype.focus = nativeFocus
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function stopFocusModalityTracking(): void {
|
||||
stopTracking?.()
|
||||
stopTracking = null
|
||||
}
|
||||
|
||||
if (
|
||||
typeof window !== 'undefined' &&
|
||||
typeof window.addEventListener === 'function' &&
|
||||
typeof window.HTMLElement === 'function'
|
||||
) {
|
||||
stopTracking = startTracking(window)
|
||||
}
|
||||
|
||||
if (import.meta.hot) {
|
||||
import.meta.hot.dispose(stopFocusModalityTracking)
|
||||
}
|
||||
|
||||
/** Whether the latest focus came from keyboard navigation or assistive tech, not a pointer. */
|
||||
export function isKeyboardOrVirtualFocus(): boolean {
|
||||
return modality === 'keyboard' || modality === 'virtual'
|
||||
}
|
||||
Reference in New Issue
Block a user