Unverified Commit d7f57301 authored by rauno's avatar rauno Committed by GitHub

[Dev Tools] Improve keyboard interactions for menu & overlays (#76754)

This PR implements robust keyboard navigation for the Dev Tools dropdown
menu, and its nested overlays that appear.

Full list of changes:
- Use enum state `open` for making sure only one overlay can be open at
a time
- Implement proper focus trapping through `useFocusTrap` to make sure
focus can never leave the trap
- Fixed bugs related to focusing items in the menu
- Focused index in the menu is retained when closing a nested overlay
- Move all overlay-related logic to `DevToolsInfo`

_Note: We should follow up with an assessment of ARIA attributes on all
these surfaces_


https://github.com/user-attachments/assets/66a36359-1265-40dd-82cc-1032dfdcff28

Closes NDX-927
parent b400f8ec
import { useRef } from 'react'
import { MENU_DURATION_MS, useClickOutside, useFocusTrap } from '../utils'
import { useDelayedRender } from '../../../../hooks/use-delayed-render'
export interface DevToolsInfoPropsCore {
isOpen: boolean
triggerRef: React.RefObject<HTMLButtonElement | null>
close: () => void
}
export interface DevToolsInfoProps extends DevToolsInfoPropsCore {
title: string
children: React.ReactNode
learnMoreLink?: string
}
export function DevToolsInfo({ export function DevToolsInfo({
title, title,
children, children,
learnMoreLink, learnMoreLink,
setIsOpen, isOpen,
setPreviousOpen, triggerRef,
close,
...props ...props
}: { }: DevToolsInfoProps) {
title: string const ref = useRef<HTMLDivElement | null>(null)
children: React.ReactNode const closeButtonRef = useRef<HTMLButtonElement | null>(null)
learnMoreLink?: string
setIsOpen?: (isOpen: boolean) => void const { mounted, rendered } = useDelayedRender(isOpen, {
setPreviousOpen?: (isOpen: boolean) => void // Intentionally no fade in, makes the UI feel more immediate
}) { enterDelay: 0,
const hasActionButtons = Boolean( // Graceful fade out to confirm that the UI did not break
learnMoreLink && setIsOpen && setPreviousOpen exitDelay: MENU_DURATION_MS,
) })
useFocusTrap(ref, triggerRef, isOpen, () => {
// Bring focus to close button, so the user can easily close the overlay
closeButtonRef.current?.focus()
})
useClickOutside(ref, triggerRef, isOpen, close)
if (!mounted) {
return null
}
return ( return (
<div data-info-popover {...props}> <div
tabIndex={-1}
role="dialog"
ref={ref}
data-info-popover
{...props}
data-rendered={rendered}
>
<div className="dev-tools-info-container"> <div className="dev-tools-info-container">
<h1 className="dev-tools-info-title">{title}</h1> <h1 className="dev-tools-info-title">{title}</h1>
{children} {children}
{hasActionButtons && ( <div className="dev-tools-info-button-container">
<div className="dev-tools-info-button-container"> <button
<button ref={closeButtonRef}
className="dev-tools-info-close-button" className="dev-tools-info-close-button"
onClick={() => { onClick={close}
setIsOpen?.(false) >
setPreviousOpen?.(true) Close
}} </button>
> {learnMoreLink && (
Close
</button>
<a <a
className="dev-tools-info-learn-more-button" className="dev-tools-info-learn-more-button"
href={learnMoreLink} href={learnMoreLink}
...@@ -40,8 +72,8 @@ export function DevToolsInfo({ ...@@ -40,8 +72,8 @@ export function DevToolsInfo({
> >
Learn More Learn More
</a> </a>
</div> )}
)} </div>
</div> </div>
</div> </div>
) )
...@@ -72,6 +104,10 @@ export const DEV_TOOLS_INFO_STYLES = ` ...@@ -72,6 +104,10 @@ export const DEV_TOOLS_INFO_STYLES = `
opacity: 1; opacity: 1;
scale: 1; scale: 1;
} }
button:focus-visible {
outline: var(--focus-ring);
}
} }
.dev-tools-info-container { .dev-tools-info-container {
...@@ -134,7 +170,6 @@ export const DEV_TOOLS_INFO_STYLES = ` ...@@ -134,7 +170,6 @@ export const DEV_TOOLS_INFO_STYLES = `
transition: background var(--duration-short) ease; transition: background var(--duration-short) ease;
color: var(--color-background-100); color: var(--color-background-100);
border-radius: var(--rounded-md-2); border-radius: var(--rounded-md-2);
border: 1px solid var(--color-gray-1000);
background: var(--color-gray-1000); background: var(--color-gray-1000);
} }
......
import type { HTMLProps } from 'react'
import type { DevToolsInfoPropsCore } from './dev-tools-info'
import { DevToolsInfo } from './dev-tools-info' import { DevToolsInfo } from './dev-tools-info'
function StaticRouteContent({ routerType }: { routerType: 'pages' | 'app' }) { function StaticRouteContent({ routerType }: { routerType: 'pages' | 'app' }) {
...@@ -106,36 +108,28 @@ const learnMoreLink = { ...@@ -106,36 +108,28 @@ const learnMoreLink = {
dynamic: dynamic:
'https://nextjs.org/docs/app/building-your-application/rendering/server-components#dynamic-rendering', 'https://nextjs.org/docs/app/building-your-application/rendering/server-components#dynamic-rendering',
}, },
} } as const
export function RouteInfo({ export function RouteInfo({
routeType, routeType,
routerType, routerType,
isOpen,
setIsOpen,
setPreviousOpen,
...props ...props
}: { }: {
routeType: 'Static' | 'Dynamic' routeType: 'Static' | 'Dynamic'
routerType: 'pages' | 'app' routerType: 'pages' | 'app'
isOpen: boolean } & DevToolsInfoPropsCore &
setIsOpen: (isOpen: boolean) => void HTMLProps<HTMLDivElement>) {
setPreviousOpen: (isOpen: boolean) => void
style?: React.CSSProperties
ref?: React.RefObject<HTMLElement | null>
}) {
const isStaticRoute = routeType === 'Static' const isStaticRoute = routeType === 'Static'
const learnMore = isStaticRoute const learnMore = isStaticRoute
? learnMoreLink[routerType].static ? learnMoreLink[routerType].static
: learnMoreLink[routerType].dynamic : learnMoreLink[routerType].dynamic
return ( return (
<DevToolsInfo <DevToolsInfo
{...props}
title={`${routeType} Route`} title={`${routeType} Route`}
learnMoreLink={learnMore} learnMoreLink={learnMore}
setIsOpen={setIsOpen} {...props}
setPreviousOpen={setPreviousOpen}
> >
{isStaticRoute ? ( {isStaticRoute ? (
<StaticRouteContent routerType={routerType} /> <StaticRouteContent routerType={routerType} />
......
import { DevToolsInfo } from './dev-tools-info' import { DevToolsInfo, type DevToolsInfoPropsCore } from './dev-tools-info'
import { CopyButton } from '../../../copy-button' import { CopyButton } from '../../../copy-button'
import type { HTMLProps } from 'react'
export function TurbopackInfo({ export function TurbopackInfo(
isOpen, props: DevToolsInfoPropsCore & HTMLProps<HTMLDivElement>
setIsOpen, ) {
setPreviousOpen,
...props
}: {
isOpen: boolean
setIsOpen: (isOpen: boolean) => void
setPreviousOpen: (isOpen: boolean) => void
style?: React.CSSProperties
ref?: React.RefObject<HTMLElement | null>
}) {
return ( return (
<DevToolsInfo <DevToolsInfo
title="Turbopack" title="Turbopack"
learnMoreLink="https://nextjs.org/docs/app/api-reference/turbopack" learnMoreLink="https://nextjs.org/docs/app/api-reference/turbopack"
setIsOpen={setIsOpen}
setPreviousOpen={setPreviousOpen}
{...props} {...props}
> >
<article className="dev-tools-info-article"> <article className="dev-tools-info-article">
......
import { useState } from 'react' import { useState, type HTMLProps } from 'react'
import { DevToolsInfo } from './dev-tools-info'
import { css } from '../../../../../utils/css' import { css } from '../../../../../utils/css'
import type { DevToolsIndicatorPosition } from '../dev-tools-indicator'
import EyeIcon from '../../../../icons/eye-icon' import EyeIcon from '../../../../icons/eye-icon'
import { STORAGE_KEY_POSITION, STORAGE_KEY_THEME } from '../../../../../shared' import { STORAGE_KEY_POSITION, STORAGE_KEY_THEME } from '../../../../../shared'
import LightIcon from '../../../../icons/light-icon' import LightIcon from '../../../../icons/light-icon'
import DarkIcon from '../../../../icons/dark-icon' import DarkIcon from '../../../../icons/dark-icon'
import SystemIcon from '../../../../icons/system-icon' import SystemIcon from '../../../../icons/system-icon'
import type { DevToolsInfoPropsCore } from './dev-tools-info'
import { DevToolsInfo } from './dev-tools-info'
import type { DevToolsIndicatorPosition } from '../dev-tools-indicator'
function getInitialPreference() { function getInitialPreference() {
if (typeof localStorage === 'undefined') { if (typeof localStorage === 'undefined') {
...@@ -18,19 +19,16 @@ function getInitialPreference() { ...@@ -18,19 +19,16 @@ function getInitialPreference() {
} }
export function UserPreferences({ export function UserPreferences({
isOpen,
setPosition, setPosition,
position, position,
hide, hide,
...props ...props
}: { }: {
isOpen: boolean
setPosition: (position: DevToolsIndicatorPosition) => void setPosition: (position: DevToolsIndicatorPosition) => void
position: DevToolsIndicatorPosition position: DevToolsIndicatorPosition
hide: () => void hide: () => void
style?: React.CSSProperties } & DevToolsInfoPropsCore &
ref?: React.RefObject<HTMLElement | null> HTMLProps<HTMLDivElement>) {
}) {
// derive initial theme from system preference // derive initial theme from system preference
const [theme, setTheme] = useState(getInitialPreference()) const [theme, setTheme] = useState(getInitialPreference())
...@@ -253,7 +251,7 @@ export const DEV_TOOLS_INFO_USER_PREFERENCES_STYLES = css` ...@@ -253,7 +251,7 @@ export const DEV_TOOLS_INFO_USER_PREFERENCES_STYLES = css`
} }
&:focus-within { &:focus-within {
outline: 5px auto -webkit-focus-ring-color; outline: var(--focus-ring);
} }
} }
......
import { useEffect } from 'react'
export function useFocusTrap(
rootRef: React.RefObject<HTMLElement | null>,
triggerRef: React.RefObject<HTMLButtonElement | null>,
active: boolean,
onOpenFocus?: () => void
) {
useEffect(() => {
let rootNode: HTMLElement | null = null
function onTab(e: KeyboardEvent) {
if (e.key !== 'Tab' || rootNode === null) {
return
}
const [firstFocusableNode, lastFocusableNode] =
getFocusableNodes(rootNode)
const activeElement = getActiveElement(rootNode)
if (e.shiftKey) {
if (activeElement === firstFocusableNode) {
lastFocusableNode?.focus()
e.preventDefault()
}
} else {
if (activeElement === lastFocusableNode) {
firstFocusableNode?.focus()
e.preventDefault()
}
}
}
const id = setTimeout(() => {
// Grab this on next tick to ensure the content is mounted
rootNode = rootRef.current
if (active) {
if (onOpenFocus) {
onOpenFocus()
} else {
rootNode?.focus()
}
rootNode?.addEventListener('keydown', onTab)
} else {
const activeElement = getActiveElement(rootNode)
// Only restore focus if the focus was previously on the content.
// This avoids us accidentally focusing on mount when the
// user could want to interact with their own app instead.
if (rootNode?.contains(activeElement)) {
triggerRef.current?.focus()
}
}
})
return () => {
clearTimeout(id)
rootNode?.removeEventListener('keydown', onTab)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [active])
}
function getActiveElement(node: HTMLElement | null) {
const root = node?.getRootNode()
return root instanceof ShadowRoot
? (root?.activeElement as HTMLElement)
: null
}
function getFocusableNodes(node: HTMLElement): [HTMLElement, HTMLElement] | [] {
const focusableElements = node.querySelectorAll(
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
)
if (!focusableElements) return []
return [
focusableElements![0] as HTMLElement,
focusableElements![focusableElements!.length - 1] as HTMLElement,
]
}
//////////////////////////////////////////////////////////////////////////////////////
export function useClickOutside(
rootRef: React.RefObject<HTMLElement | null>,
triggerRef: React.RefObject<HTMLButtonElement | null>,
active: boolean,
close: () => void
) {
useEffect(() => {
if (!active) {
return
}
function handleClickOutside(event: MouseEvent) {
if (
!(rootRef.current?.getBoundingClientRect()
? event.clientX >= rootRef.current.getBoundingClientRect()!.left &&
event.clientX <= rootRef.current.getBoundingClientRect()!.right &&
event.clientY >= rootRef.current.getBoundingClientRect()!.top &&
event.clientY <= rootRef.current.getBoundingClientRect()!.bottom
: false) &&
!(triggerRef.current?.getBoundingClientRect()
? event.clientX >= triggerRef.current.getBoundingClientRect()!.left &&
event.clientX <=
triggerRef.current.getBoundingClientRect()!.right &&
event.clientY >= triggerRef.current.getBoundingClientRect()!.top &&
event.clientY <= triggerRef.current.getBoundingClientRect()!.bottom
: false)
) {
close()
}
}
function handleKeyDown(event: KeyboardEvent) {
if (event.key === 'Escape') {
close()
}
}
document.addEventListener('mousedown', handleClickOutside)
document.addEventListener('keydown', handleKeyDown)
return () => {
document.removeEventListener('mousedown', handleClickOutside)
document.removeEventListener('keydown', handleKeyDown)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [active])
}
//////////////////////////////////////////////////////////////////////////////////////
export const MENU_DURATION_MS = 200
export const MENU_CURVE = 'cubic-bezier(0.175, 0.885, 0.32, 1.1)'
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment