When to use it#
- Use it for a change a screen reader user can’t otherwise perceive without moving focus: a count, a result, a rejected character, a finished upload.
- Don’t announce what focus already reads, such as a focused control’s own label or state. Don’t add your own
role="status"oraria-livefor the same message either: it would be read twice. - Keep a message short, with the number or the name in it: “3 services found”, not “The list has been updated”. Send it from an event handler or an effect, never while the component renders.
- For a status message that is also shown on the page, use an Alert with
announce. It calls the Announcer for you. - There is no part to render. You call a hook and pass a message that is already translated, because the Announcer has no text of its own.
Example#
import { Button, useAnnouncer } from '@kvirn-ui/react'
import { useState } from 'react'
import { useAnnouncerTexts } from './texts.ts'
export function DefaultAnnouncer() {
const { texts } = useAnnouncerTexts()
const { announce } = useAnnouncer()
const [isSaved, setIsSaved] = useState(false)
return (
<>
<Button
onClick={() => {
setIsSaved(true)
announce(texts.saved.message)
}}
>
{texts.saved.button}
</Button>
{isSaved ? <p>{texts.saved.message}</p> : null}
</>
)
}Use cases#
Say how many results there are
A search list changes while the user types and focus stays in the field. Show the count on the page, and send the same words to the Announcer once the user pauses, so people who can’t see the list hear the result too.
5 services found
- Building permit
- Housing allowance
- Library card
- Parking permit
- Waste collection
import { Field, Stack, TextInput, useAnnouncer } from '@kvirn-ui/react'
import { useEffect, useState } from 'react'
import { useAnnouncerTexts } from './texts.ts'
export function ResultCountAnnouncer() {
const { texts } = useAnnouncerTexts()
const { announce } = useAnnouncer()
const [query, setQuery] = useState('')
const needle = query.trim().toLocaleLowerCase()
const matches = texts.search.services.filter((service) =>
service.toLocaleLowerCase().includes(needle),
)
const message = texts.search.results(matches.length)
useEffect(() => {
if (needle === '') {
return
}
// Wait until the user pauses, so one search is one message.
const timer = setTimeout(() => announce(message), 500)
return () => clearTimeout(timer)
}, [announce, message, needle])
return (
<Stack className="kv-stack--gap-4">
<Field.Root>
<Field.Label marker="none">{texts.search.label}</Field.Label>
<TextInput
autoComplete="off"
value={query}
onChange={(event) => setQuery(event.currentTarget.value)}
/>
</Field.Root>
<p>{message}</p>
<ul>
{matches.map((service) => (
<li key={service}>{service}</li>
))}
</ul>
</Stack>
)
}Information: Did you know?
Showing the message on the page as well is right: not everyone hears it. The visible text is not a live region, so it is not read twice.
Something to act on now
Assertive interrupts the screen reader, so keep it for what the user must act on right now, such as a session that has ended. Use it rarely. An announcement after a session has expired is not enough: warn before it expires and let people extend it (2.2.1 Timing Adjustable, A), for example with an AlertDialog.
import { Button, useAnnouncer } from '@kvirn-ui/react'
import { useState } from 'react'
import { useAnnouncerTexts } from './texts.ts'
export function AssertiveAnnouncer() {
const { texts } = useAnnouncerTexts()
const { announce } = useAnnouncer()
const [isExpired, setIsExpired] = useState(false)
return (
<>
<Button
onClick={() => {
setIsExpired(true)
announce(texts.expired.message, { politeness: 'assertive' })
}}
>
{texts.expired.button}
</Button>
{isExpired ? <p>{texts.expired.message}</p> : null}
</>
)
}Props in this example:
politenesson announce
A message that can repeat quickly
Typing or holding a key can send the same message again and again. Give it a key, such as the field’s id, and later messages with that key are dropped for three seconds.
Digits only, without spaces
import { Field, TextInput, useAnnouncer } from '@kvirn-ui/react'
import { useAnnouncerTexts } from './texts.ts'
export function ThrottledAnnouncer() {
const { texts } = useAnnouncerTexts()
const { announce } = useAnnouncer()
return (
<Field.Root>
<Field.Label marker="none">{texts.digits.label}</Field.Label>
<TextInput
inputMode="numeric"
autoComplete="tel"
onChange={(event) => {
const input = event.currentTarget
const digits = input.value.replaceAll(/\D/g, '')
if (digits !== input.value) {
input.value = digits
announce(texts.digits.message, { key: 'phone-number' })
}
}}
/>
<Field.HelpText>{texts.digits.hint}</Field.HelpText>
</Field.Root>
)
}Props in this example:
keyon announce
Information: Did you know?
Two messages of the same politeness within 100 ms replace each other. Batch related changes into one sentence.
A message from inside a dialog
A modal dialog makes the rest of the page silent, including the page’s live regions. A Dialog or an AlertDialog has its own live regions while it is open, so a message sent from a component inside it is still spoken. You call announce as usual.
import { Button, Dialog, useAnnouncer } from '@kvirn-ui/react'
import { useState } from 'react'
import { useAnnouncerTexts } from './texts.ts'
// useAnnouncer is called in a component inside the dialog, so it finds the dialog's own live region.
function FreeTimes() {
const { texts } = useAnnouncerTexts()
const { announce } = useAnnouncer()
const [message, setMessage] = useState('')
const check = (day: string, freeTimes: number) => {
const text = texts.booking.freeTimes(day, freeTimes)
setMessage(text)
announce(text)
}
return (
<>
<div className="kv-button-group">
<Button onClick={() => check(texts.booking.monday, 3)}>{texts.booking.monday}</Button>
<Button onClick={() => check(texts.booking.tuesday, 0)}>{texts.booking.tuesday}</Button>
</div>
<p>{message}</p>
</>
)
}
export function InsideDialog() {
const { texts } = useAnnouncerTexts()
return (
<Dialog.Root>
<Dialog.Trigger className="kv-button">{texts.booking.open}</Dialog.Trigger>
<Dialog.Popup>
<Dialog.Title>{texts.booking.title}</Dialog.Title>
<Dialog.Close />
<Dialog.Body>
<FreeTimes />
</Dialog.Body>
<Dialog.Actions>
<Dialog.Close className="kv-button">{texts.booking.close}</Dialog.Close>
</Dialog.Actions>
</Dialog.Popup>
</Dialog.Root>
)
}Warning: Don't forget
Call useAnnouncer in a component that sits inside the dialog, as FreeTimes does here. Inside a dialog you build yourself, with a native <dialog> or inert, put a live region of your own inside it (4.1.3 Status Messages, AA).
A draft that saves itself
A form saves the draft each time a field loses focus, so tabbing through it saves many times. Show “Draft saved” on the page each time, and give the spoken message a key and a longer window, so it is read at most once every 30 seconds.
import { Field, Stack, TextInput, Textarea, useAnnouncer } from '@kvirn-ui/react'
import { useState } from 'react'
import { useAnnouncerTexts } from './texts.ts'
export function AutosaveAnnouncer() {
const { texts } = useAnnouncerTexts()
const { announce } = useAnnouncer()
const [isSaved, setIsSaved] = useState(false)
// A real app saves to the server here. Tabbing through the fields saves on every blur, so the
// spoken message is limited to once every 30 seconds. The visible text stays.
const save = () => {
setIsSaved(true)
announce(texts.draft.saved, { key: 'draft', throttleMilliseconds: 30_000 })
}
return (
<Stack className="kv-stack--gap-4">
<Field.Root>
<Field.Label marker="none">{texts.draft.street}</Field.Label>
<TextInput autoComplete="street-address" onBlur={save} />
</Field.Root>
<Field.Root>
<Field.Label marker="none">{texts.draft.description}</Field.Label>
<Textarea onBlur={save} />
</Field.Root>
{isSaved ? <p>{texts.draft.saved}</p> : null}
</Stack>
)
}Props in this example:
keyon announcethrottleMillisecondson announce
Information: Did you know?
A throttled message is dropped, not delayed. That suits a message that never changes. For a count that changes, wait until the user pauses and send the latest value, as in the search above.
Accessibility#
What it does for you#
- APG pattern: none. The Announcer is not a widget. It is the pair of live regions that WCAG 4.1.3 Status Messages (AA) needs (ARIA `status` role, `alert` role, technique ARIA22 and ARIA19).
- Deviations: none.
- Native elements used:
<output>for the polite region (its implicit role isstatus) and a<div role="alert">for the assertive one, which has no native element.
The Announcer is how a component tells a screen reader that something changed without moving focus (4.1.3 Status Messages, AA). The outermost KvirnProvider renders two live regions once, empty, after its children. Components and apps call useAnnouncer().announce(message, options). The regions are the only part, and Announcer is not exported: rendering a second pair would make a screen reader read every message twice.
The Announcer has no strings of its own. The caller passes text already resolved from i18n, in the provider's language.
| Part | Element / role | ARIA | Notes |
|---|---|---|---|
| Polite region | <output> → status | aria-live="polite", aria-atomic="true" | Default for announce. Waits for the screen reader to finish speaking. Empty on the server and on first render |
| Assertive region | <div> → alert | aria-live="assertive", aria-atomic="true" | announce(message, { politeness: 'assertive' }). Interrupts the screen reader: only for what the user must act on right now. Empty on the server and on first render |
| both regions | visually hidden | no aria-hidden, no hidden, no display: none | Hidden with inline styles only (a clipped box one pixel across), so they stay in the accessibility tree and need no stylesheet. No tabindex, no focusable content, no text of their own |
| the text | a text node in a region | none | Added after the region was already in the page, and emptied first, so that a repeated message is read again. Removed after 5 seconds, so stale text isn't found in browse mode |
What you need to do#
- Mount
KvirnProvider. Without a provideruseAnnouncer()warns in development andannouncedoes nothing, so screen reader users get nothing. The provider is where the regions are. - One provider at the top. Nested providers share the outermost one's regions.
- Language. The regions have no
lang: they inherit the page's. Set<html lang>to the root provider's locale (3.1.1 Language of Page, A). A message in another language than the page's is read with the page's voice (3.1.2 Language of Parts, AA), a known issue. <output>is form-associated. The polite region sits after the provider's children. If you mount the provider inside a<form>, it joins that form'selements(it is never submitted). Mount the provider at the top of the app.- Your own modal silences the provider's regions. They sit in the app tree after the provider's children, so a modal that makes the rest of the page inert or hidden (a native
<dialog>opened withshowModal(),inerton the app root,aria-modalin Safari) also silences them, and nothing announced from inside it is heard (4.1.3 Status Messages, AA). KvirnUI's Dialog and AlertDialog host their own regions while open, so a component inside them announces as usual. In a modal you built yourself, put a live region of your own inside it. - Don't add your own
role="status"oraria-livefor the same message. It would be read twice. - Don't render the Announcer's text yourself. Showing the same information visibly is right, but it is a separate element.
Warning: Don't forget
Mount KvirnProvider once, at the top of your app and outside any form. Without it, announce does nothing and screen reader users hear nothing (4.1.3 Status Messages, AA). Set the page language to the provider’s language too: the live regions have no language of their own (3.1.1 Language of Page, A).
Visual and modes#
- Focus indicator: none. The regions are never focused.
- Target size: not applicable.
- forced-colors behaviour: nothing is visible, so nothing changes. The text is real page text and does not depend on colour.
- reduced-motion behaviour: no motion.
- Reflow and text spacing: a clipped box one pixel across that never affects layout, scrolling or reflow (1.4.10 Reflow, AA; 1.4.12 Text Spacing, AA).
Focus management#
- Initial focus: not moved. The Announcer never moves focus.
- Trap: no.
- Restore to: not applicable.
- Never obscured by: the regions are tiny clipped boxes, out of the layout flow, and are never focused.
WCAG success criteria#
- 4.1.3 Status Messages (AA): a polite and an assertive live region that exist before their text: tests check that a polite message is added to a region that was already in the page and that an assertive message goes to the alert region.
- 1.3.1 Info and Relationships (A), 4.1.2 Name, Role, Value (A):
statusandalertare the roles for these messages. The regions are neveraria-hidden. - 3.2.1 On Focus (A): the regions can't take focus (a test checks that the regions are not focusable).
- 2.1.1 Keyboard (A), 2.4.3 Focus Order (A): the regions add no stop to the Tab order (a test checks that the regions are not focusable).
- 3.1.2 Language of Parts (AA): text is passed through unchanged, in the provider's language (a test checks that text is passed through unchanged in Swedish and Finnish). A message in another language than the page's is not marked up, which is a known issue.
- Axe finds no violations with both regions empty and with both holding a message.
Keyboard#
Announcer has no keys of its own. What you put in it keeps its own keys.
Announcements#
Announcer tells screen reader users about these changes without moving focus. Each message waits until the screen reader is quiet (polite) or interrupts it (assertive).
| When | What it says | Message key | Politeness |
|---|---|---|---|
announce(message) | Polite | ||
announce(message, { politeness }) | Assertive | ||
announce(message, { key }) | Polite or assertive, as you choose |
Warning: Don't forget
Announcements need a KvirnProvider around your app, outside any <form>, or an Announcer of your own. Without one nothing is announced, and a development warning says so.
API reference#
import { useAnnouncer } from '@kvirn-ui/react'useAnnouncer
Takes no options. The provider renders the live regions.
Result
| Prop | Type | Default | Description |
|---|---|---|---|
announce | (message: string, options?: AnnounceOptions) => boolean | – | Says the message in the shared live region. Returns true when it was accepted, and false when it was dropped: blank, throttled by key, or no provider. |
announce
Options
| Prop | Type | Default | Description |
|---|---|---|---|
politeness | 'polite' | 'assertive' | 'polite' | Polite waits for the screen reader to finish speaking. Assertive interrupts it: only for what the user must act on right now. |
key | string | – | Throttles by key, such as a field’s id: later messages with the same key inside the window are dropped. |
throttleMilliseconds | number | 3000 | The throttle window for key, in milliseconds. 0 turns it off. |
const { announce } = useAnnouncer()
announce(messages.saved, { politeness: 'polite', key: 'save' })Known issues#
- Language of a message. The regions inherit the page's
lang. A message from a nestedKvirnProviderwith another locale is read with the page's voice. - Latest wins. Two messages for the same politeness inside 100 ms: the second replaces the first. There is no queue.
- Without a provider nothing is announced. Components that announce (a masked TextInput, for example) do nothing for screen reader users when no provider is mounted.
- Nested providers with their own
env(an iframe) share the outermost provider's regions, which live in the outer document.
Information: Did you know?
If an issue here affects your service, list it in your accessibility statement with its workaround.
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 | announcer.stories.tsx, every story, 4 themes |
| Markup and ARIA (roles, names, ids, states) | pass | n/a | pass | announcer.test.tsx (axe and role, name and state): a polite and an assertive region exist, empty, as soon as the provider mounts |
| Keyboard contract rows (Vitest browser) | pass | n/a | pass | 3 rows, each names a test in announcer.test.tsx |
| Focus order and management | pass | n/a | pass | announcer.test.tsx: the regions are not focusable; announcing never moves focus |
| Display modes (forced colours, 320px reflow, text spacing, reduced motion) | n/a | n/a | n/a | nothing is visible: the regions are clipped one-pixel boxes |
| 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 |
What to check#
- A polite message sent while the screen reader is speaking is read after the current speech.
- An assertive message interrupts the speech.
- The same message sent twice with a pause between is read twice.
- A keyed message sent repeatedly is read once in the window.
- Nothing is read twice, in each screen reader and browser pair.