When to use it#
- Use it for a panel, a drawer or a step in a form that is not a dialog. Focus (the part of the page the keyboard is acting on) moves in when it opens and goes back to where it was when it closes.
- Prefer the native elements. A
<dialog>opened withshowModal()holds focus, makes the rest of the page inert (unreachable) and returns focus with no code. For a dialog built from KvirnUI’s parts, use Dialog. - Hold focus inside the scope (
contain) only when you must, and always give a way out. - Not for moving focus to the title of a new page after a client-side navigation: use Route focus.
Example#
import { Button, useFocus } from '@kvirn-ui/react'
import { useState } from 'react'
import { useFocusTexts } from './texts.ts'
export function RestoreDrawer() {
const { texts } = useFocusTexts()
const [open, setOpen] = useState(false)
const { scopeProps } = useFocus({ active: open })
return (
<div>
<Button onClick={() => setOpen(true)}>{texts.open}</Button>
<aside {...scopeProps} aria-label={texts.filterLabel} hidden={!open}>
<label>
{texts.search} <input type="text" />
</label>{' '}
<Button onClick={() => setOpen(false)}>{texts.close}</Button>
</aside>
</div>
)
}Use cases#
A filter panel that gives focus back
When someone using a keyboard opens the panel, focus moves to its first field. When they close it, focus returns to the button that opened it, so they carry on where they were. Tab can still leave the panel, as it can leave the page.
import { Button, useFocus } from '@kvirn-ui/react'
import { useState } from 'react'
import { useFocusTexts } from './texts.ts'
export function RestoreDrawer() {
const { texts } = useFocusTexts()
const [open, setOpen] = useState(false)
const { scopeProps } = useFocus({ active: open })
return (
<div>
<Button onClick={() => setOpen(true)}>{texts.open}</Button>
<aside {...scopeProps} aria-label={texts.filterLabel} hidden={!open}>
<label>
{texts.search} <input type="text" />
</label>{' '}
<Button onClick={() => setOpen(false)}>{texts.close}</Button>
</aside>
</div>
)
}Props in this example:
activeon useFocus (options)
Warning: Don't forget
Neither FocusScope nor useFocus adds a name to your element, so give it one, as the example does with aria-label. A nav scope is a landmark and needs a name. See What it does for you.
A panel that keeps Tab inside until it is closed
Use it when the panel covers the page and the rest of the page is no use while it is open. With contain set to loop, Tab on the last control goes to the first, and Shift+Tab on the first goes to the last. Escape calls onEscape, where you close the panel.
import { Button, FocusScope } from '@kvirn-ui/react'
import { useState } from 'react'
import { useFocusTexts } from './texts.ts'
export function LoopDrawer() {
const { texts } = useFocusTexts()
const [open, setOpen] = useState(false)
return (
<div>
<Button onClick={() => setOpen(true)}>{texts.open}</Button>
<FocusScope
as="aside"
active={open}
contain="loop"
onEscape={() => setOpen(false)}
hidden={!open}
aria-label={texts.filterLabel}
>
<label>
{texts.search} <input type="text" />
</label>{' '}
<Button>{texts.apply}</Button> <Button onClick={() => setOpen(false)}>{texts.close}</Button>
</FocusScope>
</div>
)
}Props in this example:
Warning: Don't forget
Without onEscape a keyboard user has no way out (2.1.2 No Keyboard Trap), and a development warning says so. See Focus management.
A side panel that shuts the rest of the page out
With contain set to inert, the rest of the page can’t be reached with the keyboard or the pointer while the panel is open, and it is reachable again when the panel closes. Use it for a panel that covers the page, such as notes on a case. It still needs a way out, so Escape calls onEscape.
import { Button, FocusScope } from '@kvirn-ui/react'
import { useState } from 'react'
import { useFocusTexts } from './texts.ts'
export function InertPanel() {
const { texts } = useFocusTexts()
const [open, setOpen] = useState(false)
return (
<div>
<Button onClick={() => setOpen(true)}>{texts.openNotes}</Button>
{/*
contain="inert" makes the rest of the page inert while the panel is open, and removes it
again when it closes. A way out is still needed: onEscape closes the panel.
*/}
<FocusScope
as="aside"
active={open}
contain="inert"
onEscape={() => setOpen(false)}
hidden={!open}
aria-label={texts.notesLabel}
>
<label>
{texts.note} <textarea />
</label>{' '}
<Button onClick={() => setOpen(false)}>{texts.saveNote}</Button>{' '}
<Button onClick={() => setOpen(false)}>{texts.closeNotes}</Button>
</FocusScope>
</div>
)
}Props in this example:
A help panel that starts at its top
By default focus starts on the first control in the panel. When the panel is mostly text, that control is a button after it, and the text is skipped. With initialFocus set to container, focus starts on the panel and Tab goes on to the first control.
import { Button, FocusScope } from '@kvirn-ui/react'
import { useState } from 'react'
import { useFocusTexts } from './texts.ts'
export function HelpPanel() {
const { texts } = useFocusTexts()
const [open, setOpen] = useState(false)
return (
<div>
<Button onClick={() => setOpen(true)}>{texts.openHelp}</Button>
{/*
The only control is the Close button, after the text. The default start, the first Tab
stop, would skip the text. "container" starts at the panel itself, and Tab then goes on
to the first control.
*/}
<FocusScope
as="aside"
active={open}
initialFocus="container"
hidden={!open}
aria-label={texts.helpLabel}
>
<p>{texts.helpFirst}</p>
<p>{texts.helpSecond}</p>
<p>{texts.helpThird}</p>
<Button onClick={() => setOpen(false)}>{texts.closeHelp}</Button>
</FocusScope>
</div>
)
}Props in this example:
initialFocuson FocusScope
A form step that moves focus to its heading
When someone goes to the next or the previous step, focus moves to that step’s heading and Tab continues after it. It needs no scope, and it never moves focus on the first render.
Step 1 of 3: Your details
Enter your name and how we can reach you.
import { Button, Heading, useFocus } from '@kvirn-ui/react'
import { useRef, useState } from 'react'
import { useFocusTexts } from './texts.ts'
export function WizardStep() {
const { texts } = useFocusTexts()
const [step, setStep] = useState(1)
const stepRef = useRef<HTMLDivElement>(null)
const total = texts.steps.length
const current = texts.steps[step - 1] ?? texts.steps[0]!
// The docs page already has an h1, so this example uses an h4.
useFocus({ moveOn: { key: String(step), selector: 'h4', containerRef: stepRef } })
return (
<div>
<div ref={stepRef}>
<Heading as="h4">{texts.stepHeading({ step, total, title: current.title })}</Heading>
<p>{current.body}</p>
</div>
<p>
{step > 1 && <Button onClick={() => setStep(step - 1)}>{texts.back}</Button>}{' '}
{step < total && <Button onClick={() => setStep(step + 1)}>{texts.next}</Button>}
</p>
</div>
)
}Props in this example:
moveOnon useFocus (options)
Accessibility#
What it does for you#
- APG pattern: Dialog (Modal) focus rules: initial focus, Tab loop, return. The WCAG technique for moving focus on a view change (see the Route focus page).
- Deviations: none. Dialog itself keeps the native Tab order (approved by the maintainer) and uses only the shared return code.
- Native elements used: the consumer's own element (
<aside>,<div>,<section>). Native<dialog>.showModal()and theinertattribute are the first choice; this is for what they don't cover.
useFocus moves focus into a scope when it becomes active, can hold it there (contain), and returns it when the scope ends. It renders nothing and adds no role or ARIA: the consumer picks role="dialog", aria-modal, a label.
Allowed elements for FocusScope's as: div (default), section, aside, nav or form. Another tag warns once (as-not-allowed) and falls back to div. The scope adds no role or ARIA, so the element's own semantics apply: nav and form are landmarks and need a name, which is the consumer's.
| Part | Element / role | ARIA | Notes |
|---|---|---|---|
| Scope | the consumer's element | none | tabindex="-1" is added only while the scope itself takes focus (no Tab stop inside) and removed on blur |
| Page | siblings of the scope | none | With contain: 'inert', inert is set on the siblings of the scope and its ancestors while active and removed after. Elements already inert stay inert |
| Live | Announcer, Toast | none | Live regions and the Toast region are never made inert |
It announces nothing.
What you need to do#
- Name the scope: give your element a label (
aria-labeloraria-labelledby) and the role that fits (dialog, a landmark). The scope adds neither, andnavandformare landmarks that need a name. - With
contain, passonEscapeand close the scope in it: holding focus needs an exit (2.1.2 No Keyboard Trap, A). - Keep
scroll-paddingon the page when a sticky header can cover the element that gets focus (2.4.11 Focus Not Obscured (Minimum), AA).
Focus management#
- Initial focus (
initialFocus):'first'(default),'container','none', a selector or a ref. A target that is gone or disabled falls through to the first stop, then the container (focus management › initialFocus as a selector falls through to the first stop when it matches nothing,› a scope with no focusable stop focuses the container). Focus already inside the scope is left alone. - Restore (
restore, defaulttrue): tofinalFocusRef, elsetriggerRef, else the element that had focus before the scope, else the button that opened the popup that element was in, neverbody(focus management › focus goes to finalFocusRef first, then the trigger, then the opener). Only when focus was inside the scope or lost tobody: focus the user moved elsewhere is never taken (› focus the user moved elsewhere is not taken back).restore: falsereturns nothing (› restore false leaves focus where it is). onLostis called when nothing could take focus on return or whenmoveOnfinds no element (› onLost is called when nothing can take focus on return,moveOn › onLost is called when no element matches the selector).moveOn: focus moves whenkeychanges, never on the first render, and the target is made temporarily focusable (moveOn › does not move on the first render, and adds no tabindex that stays).- React's StrictMode (a development check that runs effects twice) leaves the result the same (
› survives StrictMode). On the server nothing runs (imperative and types › renders nothing on the server). - Trap: only by choice (
contain). Both modes need an exit:onEscape, and a development warning says when it is missing (development warning › contain without onEscape warns once with focus-scope-no-exit text, 2.1.2 No Keyboard Trap, level A). - Limit:
inertis applied when the scope becomes active. A sibling added to the page while it is open is not madeinert.
Information: Did you know?
With contain="inert" the rest of the page is made inert at the moment the scope opens. Something added to the page while the scope is open is not made inert.
WCAG success criteria#
- 2.1.1 Keyboard (A): the Tab loop and Escape are in the Keyboard table, and every other key is the browser's.
- 2.1.2 No Keyboard Trap (A): holding focus (
contain) is your choice and needs an exit,onEscape. A development warning says when it is missing. - 2.4.3 Focus Order (A): focus moves into the scope, returns to where it was, and Tab continues after a heading that focus moved to.
- 2.4.7 Focus Visible (AA): focus goes to an element that can show a focus ring, never to the page body.
- 2.4.11 Focus Not Obscured (Minimum) (AA): the scope draws nothing over the page, and each element it focuses is scrolled into view (
use-focus.test.tsx › focus management › a stop far below the fold is scrolled into view when the scope opens (2.4.11)). A sticky header still needsscroll-padding(consumer). - 3.2.1 On Focus (A): an element in the scope getting focus never moves focus or changes context (
use-focus.test.tsx › focus management › focus moving to another element in the scope, or a re-render, never moves focus again (3.2.1)). The scope moves focus only whenactiveormoveOn'skeychanges, never on the first render (moveOn › does not move on the first render, and adds no tabindex that stays). - No axe violations with an open scope (
accessibility › an open scope has no axe violations).
Keyboard#
- Focus
- native
- Selection follows focus
- n/a
- Arrows wrap
- n/a
- Shortcuts
- none
Focus moves programmatically when active changes. With contain: 'loop' only the two ends of the scope are handled; every other Tab is the browser's.
| Key | Where | What happens |
|---|---|---|
| Tab | contain: 'loop', on the last stop | Moves to the first stop in the scope Test: use-focus.test.tsx › keyboard › Tab on the last stop wraps to the first |
| Tab | contain: 'loop', elsewhere | Native: the next stop Test: use-focus.test.tsx › keyboard › Tab inside the loop moves on as the browser does |
| Shift+Tab | contain: 'loop', on the first stop | Moves to the last stop in the scope Test: use-focus.test.tsx › keyboard › Shift+Tab on the first stop wraps to the last |
| Tab | contain: 'inert' | Never reaches an element outside the scope; the browser decides at the ends Test: use-focus.test.tsx › keyboard › inert keeps Tab inside and restores siblings |
| Escape | contain set | Calls onEscape; the consumer closes the scopeTest: use-focus.test.tsx › keyboard › Escape calls onEscape, use-focus.test.tsx › keyboard › Escape does nothing when contain is off |
| Tab | after a moveOn change | Continues after the moved-to element Test: use-focus.test.tsx › keyboard › Tab after a move continues after the target |
| Shift+Tab | after a moveOn change | Goes back to the stop before the moved-to element Test: use-focus.test.tsx › keyboard › Shift+Tab after a move goes back to the stop before the target |
API reference#
import { FocusScope, useFocus } from '@kvirn-ui/react'FocusScope
Renders <div> by default, with no role and no ARIA. It takes the options of useFocus, every attribute of the element, and passes ref to it. It is useFocus and the element in one part.
| Prop | Type | Default | Description |
|---|---|---|---|
active | boolean | false | Whether the scope is showing. Focus moves in when it becomes true and returns when it becomes false. |
restore | boolean | true | Returns focus when active ends. Focus the user moved elsewhere is never taken back, and focus never goes to body. |
finalFocusRef | RefObject<HTMLElement | null> | – | Where focus returns first. After it come triggerRef, then the element that had focus before the scope. |
triggerRef | RefObject<HTMLElement | null> | – | The element that opened the scope, when it is not the one that had focus. |
initialFocus | 'first' | 'container' | 'none' | string | RefObject<HTMLElement | null> | 'first' | Where focus goes when active becomes true: the first Tab stop, the scope itself, nowhere, a selector or a ref. A target that is gone or disabled falls through to the first stop, then the scope. |
contain | false | 'loop' | 'inert' | false | "loop" wraps Tab and Shift+Tab at the ends of the scope. "inert" makes the rest of the page inert while active. Both need a way out: pass onEscape. |
onEscape | (event: KeyboardEvent<HTMLElement>) => void | – | Called on Escape inside the scope when contain is set. You close the scope. Without it a development warning says the user has no way out. |
moveOn | { key: string; selector?: string; containerRef?: RefObject<Element | null> } | – | Moves focus to selector (default "h1") when key changes, never on the first render. For a wizard step or a route. Works with or without active. |
onLost | () => void | – | Called when nothing could take focus: the return found no target, or moveOn found no element. |
as | 'div' | 'section' | 'aside' | 'nav' | 'form' | 'div' | Changes the element. FocusScope adds no role or ARIA, so nav and form are landmarks and need a name from you. Another tag warns once and renders a div. |
ref | Ref<HTMLElement> | – | Reaches the element, whichever it is. |
| Class or attribute | Values | Meaning |
|---|---|---|
tabindex="-1" | while the scope itself has focus | Added so the scope can take focus without becoming a Tab stop, and removed on blur. |
inert | on the siblings of the scope and its ancestors | Set with contain="inert" while active and removed after. Live regions and the Toast region are left alone. |
useFocus
Spread scopeProps on your own element. FocusScope does that for you.
Options
| Prop | Type | Default | Description |
|---|---|---|---|
active | boolean | false | Whether the scope is showing. Focus moves in when it becomes true and returns when it becomes false. |
restore | boolean | true | Returns focus when active ends. Focus the user moved elsewhere is never taken back, and focus never goes to body. |
finalFocusRef | RefObject<HTMLElement | null> | – | Where focus returns first. After it come triggerRef, then the element that had focus before the scope. |
triggerRef | RefObject<HTMLElement | null> | – | The element that opened the scope, when it is not the one that had focus. |
initialFocus | 'first' | 'container' | 'none' | string | RefObject<HTMLElement | null> | 'first' | Where focus goes when active becomes true: the first Tab stop, the scope itself, nowhere, a selector or a ref. A target that is gone or disabled falls through to the first stop, then the scope. |
contain | false | 'loop' | 'inert' | false | "loop" wraps Tab and Shift+Tab at the ends of the scope. "inert" makes the rest of the page inert while active. Both need a way out: pass onEscape. |
onEscape | (event: KeyboardEvent<HTMLElement>) => void | – | Called on Escape inside the scope when contain is set. You close the scope. Without it a development warning says the user has no way out. |
moveOn | { key: string; selector?: string; containerRef?: RefObject<Element | null> } | – | Moves focus to selector (default "h1") when key changes, never on the first render. For a wizard step or a route. Works with or without active. |
onLost | () => void | – | Called when nothing could take focus: the return found no target, or moveOn found no element. |
Result
| Prop | Type | Default | Description |
|---|---|---|---|
scopeProps | { ref: RefObject<HTMLElement | null>; onKeyDown: (event) => void } | – | Spread on the scope’s element: its ref, and the keys for contain and onEscape. |
captureOpener | () => void | – | Call it just before showing the scope when focus is read earlier than active flips. Optional: active captures it too. |
wasFocusSeen | () => boolean | – | true once focus was in the scope or a real opener existed. |
focusFirstAvailable | (candidates) => boolean | – | Focuses the first candidate that takes focus, never body. false when none does. |
isFocusTarget | (element) => boolean | – | Whether an element can take focus now: in the document, enabled and not inert. |
Testing#
The automated tests prove the keyboard behaviour, the names and states, that axe finds no violations in every story and theme, and, for the components they cover, that the stories hold up in forced colours, reduced motion, text spacing and a 320 pixel width. An Automated row passes on these tests alone. A Core or Release row passes only when an automated agent check and a person on the real assistive technology have both checked it. "agent-verified" means automated tests in the repository (with a virtual screen reader for the screen reader rows), not the real assistive technology.
| AT + browser + OS | Agent check | Human check | Result | Notes |
|---|---|---|---|---|
| Automated (re-runnable tests) | ||||
| axe, WCAG 2.2 A and AA, every story, 4 themes | pass | n/a | pass | focus.stories.tsx, every story, 4 themes |
| Markup and ARIA (roles, names, ids, states) | pending | n/a | pending | a hook that renders nothing: no markup of its own to assert |
| Keyboard contract rows (Vitest browser) | pass | n/a | pass | 7 rows, each names a test in use-focus.test.tsx |
| Focus order and management | pass | n/a | pass | use-focus.test.tsx asserts focus |
| Display modes (forced colours, 320px reflow, text spacing, reduced motion) | n/a | n/a | n/a | renders nothing: no visible part |
| Core (required for beta) | ||||
| NVDA + Chrome + Windows | pending | pending | pending | |
| VoiceOver + Safari + iOS | pending | pending | pending | |
| Release (before 1.0 and each minor) | ||||
| JAWS + Chrome + Windows | pending | pending | pending | |
| TalkBack + Chrome + Android | pending | pending | pending | |
| VoiceOver + Safari + macOS | pending | pending | pending |