Skip to
Keyboard shortcuts

Use the up and down arrow keys to move between items. Press Alt+Shift+K to open this list again.

Alpha version out now. The API may still change.

Focus

FocusScope and useFocus move focus into your own drawer or wizard step, can hold it there, and return it when the scope ends. Neither adds a role or ARIA: you choose the element and give it a name.

Package
@kvirn-ui/react
Pattern
APG Dialog (Modal), focus rules only
Testing
Not yet verified. Automated 4 of 5, Core 0 of 2, Release 0 of 3

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 with showModal() 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#

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.

Props in this example:

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.

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.

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.

Props in this example:

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.

Props in this example:

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 the inert attribute 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.

PartElement / roleARIANotes
Scopethe consumer's elementnonetabindex="-1" is added only while the scope itself takes focus (no Tab stop inside) and removed on blur
Pagesiblings of the scopenoneWith contain: 'inert', inert is set on the siblings of the scope and its ancestors while active and removed after. Elements already inert stay inert
LiveAnnouncer, ToastnoneLive 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-label or aria-labelledby) and the role that fits (dialog, a landmark). The scope adds neither, and nav and form are landmarks that need a name.
  • With contain, pass onEscape and close the scope in it: holding focus needs an exit (2.1.2 No Keyboard Trap, A).
  • Keep scroll-padding on 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, default true): to finalFocusRef, else triggerRef, else the element that had focus before the scope, else the button that opened the popup that element was in, never body (focus management › focus goes to finalFocusRef first, then the trigger, then the opener). Only when focus was inside the scope or lost to body: focus the user moved elsewhere is never taken (› focus the user moved elsewhere is not taken back). restore: false returns nothing (› restore false leaves focus where it is).
  • onLost is called when nothing could take focus on return or when moveOn finds 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 when key changes, 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: inert is applied when the scope becomes active. A sibling added to the page while it is open is not made inert.

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 needs scroll-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 when active or moveOn's key changes, 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.

KeyWhereWhat happens
Tabcontain: 'loop', on the last stopMoves to the first stop in the scope
Test: use-focus.test.tsx › keyboard › Tab on the last stop wraps to the first
Tabcontain: 'loop', elsewhereNative: the next stop
Test: use-focus.test.tsx › keyboard › Tab inside the loop moves on as the browser does
Shift+Tabcontain: 'loop', on the first stopMoves to the last stop in the scope
Test: use-focus.test.tsx › keyboard › Shift+Tab on the first stop wraps to the last
Tabcontain: '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
Escapecontain setCalls onEscape; the consumer closes the scope
Test: use-focus.test.tsx › keyboard › Escape calls onEscape, use-focus.test.tsx › keyboard › Escape does nothing when contain is off
Tabafter a moveOn changeContinues after the moved-to element
Test: use-focus.test.tsx › keyboard › Tab after a move continues after the target
Shift+Tabafter a moveOn changeGoes 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.

PropTypeDefaultDescription
activebooleanfalseWhether the scope is showing. Focus moves in when it becomes true and returns when it becomes false.
restorebooleantrueReturns focus when active ends. Focus the user moved elsewhere is never taken back, and focus never goes to body.
finalFocusRefRefObject<HTMLElement | null>–Where focus returns first. After it come triggerRef, then the element that had focus before the scope.
triggerRefRefObject<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.
containfalse | '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.
refRef<HTMLElement>–Reaches the element, whichever it is.
Class or attributeValuesMeaning
tabindex="-1"while the scope itself has focusAdded so the scope can take focus without becoming a Tab stop, and removed on blur.
inerton the siblings of the scope and its ancestorsSet 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

PropTypeDefaultDescription
activebooleanfalseWhether the scope is showing. Focus moves in when it becomes true and returns when it becomes false.
restorebooleantrueReturns focus when active ends. Focus the user moved elsewhere is never taken back, and focus never goes to body.
finalFocusRefRefObject<HTMLElement | null>–Where focus returns first. After it come triggerRef, then the element that had focus before the scope.
triggerRefRefObject<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.
containfalse | '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

PropTypeDefaultDescription
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 + OSAgent checkHuman checkResultNotes
Automated (re-runnable tests)
axe, WCAG 2.2 A and AA, every story, 4 themespassn/apassfocus.stories.tsx, every story, 4 themes
Markup and ARIA (roles, names, ids, states)pendingn/apendinga hook that renders nothing: no markup of its own to assert
Keyboard contract rows (Vitest browser)passn/apass7 rows, each names a test in use-focus.test.tsx
Focus order and managementpassn/apassuse-focus.test.tsx asserts focus
Display modes (forced colours, 320px reflow, text spacing, reduced motion)n/an/an/arenders nothing: no visible part
Core (required for beta)
NVDA + Chrome + Windowspendingpendingpending
VoiceOver + Safari + iOSpendingpendingpending
Release (before 1.0 and each minor)
JAWS + Chrome + Windowspendingpendingpending
TalkBack + Chrome + Androidpendingpendingpending
VoiceOver + Safari + macOSpendingpendingpending