When to use it#
- Use a toast for a small confirmation that needs no reply: a setting saved, a link copied, a draft saved, a background export finished. A toast is a second channel, so show the result in place as well. Nothing needed to finish a task lives only in a toast.
- Not for an error the user must fix or the outcome of a submit: use the field’s error message and the ErrorSummary, an Alert in the content, or a confirmation page. There is no warning or error toast.
- Not for a decision the user must make: use an AlertDialog.
- Not for a state already visible at the control, such as a Switch that is now on.
- Not inside a dialog: a new toast waits until the dialog closes. Raise the message with the dialog’s own Alert.
Example#
Your notification settings are not saved yet.
import { Button, useToast } from '@kvirn-ui/react'
import { useState } from 'react'
import { useToastTexts } from './texts.ts'
export function DefaultToast() {
const { texts } = useToastTexts()
const toast = useToast()
const [isSaved, setIsSaved] = useState(false)
return (
<>
{/* The result is shown in place as well: the toast is the second channel, never the only one. */}
<p>{isSaved ? texts.settingsAreSaved : texts.settingsNotSavedYet}</p>
<Button
onClick={() => {
setIsSaved(true)
toast.show({ variant: 'success', title: texts.settingsSaved })
}}
>
{texts.saveSettings}
</Button>
</>
)
}Use cases#
Deleting a draft, with Undo
An action keeps the toast on screen until it is closed, whatever autoDismiss says. The page has the same Undo, so nobody has to find the toast.
The draft exists
import { Button, ButtonGroup, useToast } from '@kvirn-ui/react'
import { useState } from 'react'
import { useToastTexts } from './texts.ts'
export function WithAnUndo() {
const { texts } = useToastTexts()
const toast = useToast()
const [deleted, setDeleted] = useState(false)
return (
<>
<p>
{texts.draftLabel} {deleted ? texts.draftRemoved : texts.draftKept}
</p>
<ButtonGroup aria-label={texts.draftActions}>
<Button
disabled={deleted}
focusableWhenDisabled
onClick={() => {
setDeleted(true)
toast.show({
variant: 'success',
title: texts.draftDeleted,
action: { label: texts.undo, onPress: () => setDeleted(false) },
})
}}
>
{texts.deleteDraft}
</Button>
{/* The same undo on the page: the toast is a shortcut, never the only way back. */}
<Button disabled={!deleted} focusableWhenDisabled onClick={() => setDeleted(false)}>
{texts.restoreDraft}
</Button>
</ButtonGroup>
</>
)
}Props in this example:
Warning: Don't forget
Keep the other way to undo. A toast can be closed, and a screen reader user may never reach it.
Messages that close by themselves
With autoDismiss on, a confirmation closes by itself, and a ring on the toast counts down the time left. The timer pauses while you hover over or focus the toast, while the tab is hidden and while a dialog is open. A toast with an action, such as Undo, never closes by itself. Offer the timer as a user setting, not a fixed choice. The switch here changes this site’s own KvirnProvider. In your app you set autoDismiss in its toast prop.
With the switch on, the confirmation closes by itself and a ring counts down the time. The message with Undo stays until you close it, because a message with an action must never disappear before you can use it. Hover or focus a message and the timer pauses.
import { Button, ButtonGroup, Field, Switch, useToast } from '@kvirn-ui/react'
import { useEffect } from 'react'
import { useDocsAutoDismiss } from '../../app/(docs)/providers.tsx'
import { useToastTexts } from './texts.ts'
export function AutoClose() {
const { texts } = useToastTexts()
const toast = useToast()
// Only the outermost KvirnProvider takes `toast`, so the setting lives in this site's provider.
// In your app it is `<KvirnProvider toast={{ autoDismiss }}>`, driven by your own state or user preference.
const [autoDismiss, setAutoDismiss] = useDocsAutoDismiss()
// Leave the site as it was when the reader goes to another page.
useEffect(() => () => setAutoDismiss(false), [setAutoDismiss])
return (
<>
<Field.Root>
<Switch
name="auto-close"
checked={autoDismiss !== false}
onCheckedChange={(checked) => setAutoDismiss(checked ? 6000 : false)}
/>
<Field.Label marker="none">{texts.closeAfterSixSeconds}</Field.Label>
</Field.Root>
<ButtonGroup aria-label={texts.autoCloseActions}>
<Button
onClick={() => toast.show({ variant: 'success', title: texts.autoCloseConfirmation })}
>
{texts.showConfirmation}
</Button>
<Button
onClick={() =>
toast.show({
variant: 'success',
title: texts.autoCloseWithUndo,
action: { label: texts.undo, onPress: () => {} },
})
}
>
{texts.showWithUndo}
</Button>
</ButtonGroup>
<p>{texts.autoCloseExplanation}</p>
</>
)
}Props in this example:
actionon show
Warning: Don't forget
Never time out an error or anything the person must act on (2.2.1 Timing Adjustable). Use the toast only for a confirmation, and let the user turn the timer off.
A job that takes a while
Show a toast with busy while a job runs. Then show the result with the same id, so one toast updates in place and a second one does not stack. The spinner is replaced, and the result is announced once. The words carry the wait: the status word and the title say what is happening. A busy toast stays even with autoDismiss on, and only the result that replaces it times out, if it has no action.
There is no report yet.
import { Button, useToast } from '@kvirn-ui/react'
import { useEffect, useRef, useState } from 'react'
import { useToastTexts } from './texts.ts'
export function JobInProgress() {
const { texts } = useToastTexts()
const toast = useToast()
const [status, setStatus] = useState<'idle' | 'working' | 'ready'>('idle')
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
useEffect(() => () => clearTimeout(timer.current), [])
const exportReport = () => {
setStatus('working')
toast.show({ id: 'export', busy: true, title: texts.preparingReport })
// A real app waits for the server. The same id replaces the busy toast with the result.
timer.current = setTimeout(() => {
setStatus('ready')
toast.show({ id: 'export', variant: 'success', title: texts.reportReady })
}, 3000)
}
return (
<>
<p>
{status === 'idle'
? texts.noReportYet
: status === 'working'
? texts.preparingReport
: texts.reportReady}
</p>
<Button busy={status === 'working'} onClick={exportReport}>
{texts.exportReport}
</Button>
</>
)
}Props in this example:
Warning: Don't forget
An indicator that can keep moving for more than 5 seconds alongside other content needs a visible control on the page that stops or hides it (2.2.2 Pause, Stop, Hide). An indicator that is the only content during a wait where nothing else can be done is exempt. prefers-reduced-motion alone is not that control. See Moving indicators and WCAG 2.2.2.
Removing a file from an application
The button the user pressed leaves the page with its row, so focus has nowhere to go. Focus a heading that stays, then show the toast with focus: true. The user hears the message where focus is, and one Tab reaches Undo. When the toast closes, focus goes back to the heading.
Attachments
- floor-plan.pdf
- fence-photo.jpg
import { Button, Heading, Stack, useToast } from '@kvirn-ui/react'
import { useRef, useState } from 'react'
import { useToastTexts } from './texts.ts'
export function RemoveAttachment() {
const { texts } = useToastTexts()
const toast = useToast()
const [files, setFiles] = useState(texts.attachments)
const headingReference = useRef<HTMLHeadingElement>(null)
const restore = (file: string) =>
setFiles((current) =>
texts.attachments.filter((name) => name === file || current.includes(name)),
)
const remove = (file: string) => {
// The button that was pressed leaves with its row. Focus a heading that stays first, so focus
// has a place to return to when the toast closes.
headingReference.current?.focus()
setFiles((current) => current.filter((name) => name !== file))
toast.show({
variant: 'success',
title: texts.fileRemoved(file),
focus: true,
action: { label: texts.undo, onPress: () => restore(file) },
})
}
return (
<>
<Heading as="h4" ref={headingReference} tabIndex={-1}>
{texts.attachmentsTitle}
</Heading>
{files.length === 0 ? (
<p>{texts.noAttachments}</p>
) : (
<Stack as="ul" className="kv-stack--gap-4">
{files.map((file) => (
<Stack as="li" key={file} className="kv-stack--gap-2">
<span>{file}</span>
<Button aria-label={texts.removeFile(file)} onClick={() => remove(file)}>
{texts.remove}
</Button>
</Stack>
))}
</Stack>
)}
{/* The same way back on the page: the toast is a shortcut, never the only way. */}
{files.length < texts.attachments.length ? (
<Button onClick={() => setFiles(texts.attachments)}>{texts.restoreFiles}</Button>
) : null}
</>
)
}Props in this example:
Warning: Don't forget
Move focus to something that stays on the page before you show the toast. If the element that had focus before is gone, the browser puts focus on the page and the user loses their place (2.4.3 Focus Order). A development warning says so.
Sending a form that has an error
A persistent toast from earlier stays on screen. Call dismissAll before the error summary appears, so nothing competes with it. Show the problem in the summary and beside the field, never in a toast.
import {
Button,
ButtonGroup,
ErrorSummary,
Field,
Stack,
TextInput,
useToast,
} from '@kvirn-ui/react'
import { useId, useState } from 'react'
import { useToastTexts } from './texts.ts'
export function ClearBeforeSummary() {
const { texts } = useToastTexts()
const toast = useToast()
const placeId = `${useId()}-place`
const [submitCount, setSubmitCount] = useState(0)
const [hasError, setHasError] = useState(false)
const [isSent, setIsSent] = useState(false)
return (
<Stack className="kv-stack--gap-8">
{hasError ? (
<ErrorSummary.Root focusKey={submitCount}>
{/* The docs page already has an h1, so the summary's title is an h4. On your pages the default is h2. */}
<ErrorSummary.Title as="h4" />
<ErrorSummary.List>
<ErrorSummary.Item>
<ErrorSummary.Link controlId={placeId}>{texts.faultPlaceError}</ErrorSummary.Link>
</ErrorSummary.Item>
</ErrorSummary.List>
</ErrorSummary.Root>
) : null}
<form
noValidate
onSubmit={(event) => {
event.preventDefault()
// A toast from earlier would compete with the summary. The problem is shown in the form.
toast.dismissAll()
const place = new FormData(event.currentTarget).get('place')
const isMissing = place === ''
setHasError(isMissing)
setIsSent(!isMissing)
setSubmitCount((count) => count + 1)
}}
>
<Field.Root controlId={placeId} invalid={hasError}>
<Field.Label>{texts.faultPlace}</Field.Label>
<TextInput name="place" />
<Field.ErrorMessage>{texts.faultPlaceError}</Field.ErrorMessage>
</Field.Root>
<ButtonGroup aria-label={texts.reportActions}>
<Button
onClick={() => {
setHasError(false)
setIsSent(false)
toast.show({ variant: 'success', title: texts.savedForLater })
}}
>
{texts.saveForLater}
</Button>
<Button type="submit" className="kv-button--primary">
{texts.sendFault}
</Button>
</ButtonGroup>
</form>
<output>{isSent ? texts.faultSent : null}</output>
</Stack>
)
}Props in this example:
dismissAllon useToast
Accessibility#
What it does for you#
- APG pattern: none for a toast. The announcement is APG's Alert pattern in the Announcer's polite region, which already exists; the region of toasts is never a live region. The items are the Alert component's parts.
- Deviations: none from APG. Two defaults to know: toasts are persistent by default (
autoDismiss: false), and a toast is only info or success, never a warning or an error. - Native elements used:
<section>(the region, apopover="manual"in the top layer),<ul role="list">and<li>, the Alert's<div>root,<p>(the Title),<span>(the status word),<button type="button">(the action and Close).
A toast is a short status message after something worked: "The draft was saved". It looks like an Alert, is heard through the Announcer, never moves focus on its own and stays until dismissed by default. With autoDismiss a toast goes after the app's chosen time and pauses on hover, focus, a hidden tab and a blurred window. Nothing needed to finish a task lives only in a toast: the result is also shown in place, and an action (Undo) has a persistent alternative on the page. Alert with announce stays the default for a message in the content, and for every error.
One shared list serves the whole page: every KvirnProvider uses the same controller, and exactly one region exists. The first provider that mounted is the host: its toast={{ limit, autoDismiss }}, locale and messages apply and it renders the region after its children. A later provider's toast is ignored, with a development warning. When the host unmounts the next provider takes over: the toasts stay, nothing is announced again, and focus and the pointer pause carry over. Make the host the page-level provider: an inert or aria-hidden container around the first provider would make the page-wide region inert too. A nested provider takes no part (its toast is ignored, with a development warning). useToast() returns { show, dismiss, dismissAll, focus }.
| Part | Element / role | ARIA | Notes |
|---|---|---|---|
| Region | <section class="kv-toast-region" popover="manual"> → region | aria-label from toast.regionLabel (Messages in English), lang and dir of the provider | Rendered only while at least one toast shows, so the landmark exists only then. The browser's popover feature is used when it exists, and the default theme places the region at a fixed position when it doesn't. No role, no aria-live, no aria-atomic |
| List | <ul role="list" class="kv-toast-list"> → list | none | Oldest first: DOM order, visual order and Tab order agree |
| Item | <li class="kv-toast-item"> → listitem | none | Wraps the toast |
| Toast | <div class="kv-alert kv-alert--<status> kv-toast"> → generic | none | Alert.Info or Alert.Success, so the colour, the icon and the status word agree. No tabindex, no role |
| Icon | <span class="kv-alert-icon kv-spinner"> (job) | aria-hidden="true" | With busy: true the spinner replaces the status icon. Decorative: the status word and the title carry the meaning. Loops until the result replaces it, and the default theme draws it still under reduced motion (the reduced-motion sweep fails on a long or looping animation; 2.2.2 Pause, Stop, Hide, A: see Consumer responsibilities); the same id with the result replaces it. A busy toast never times out, whatever autoDismiss is: it stays until the result replaces it or it is dismissed |
| Title | <p class="kv-alert-title" tabindex="-1"> | none | The status word (alert.infoPrefix, alert.successPrefix) first, then title. tabindex="-1" makes it a target for script (focus: true, toast.focus()) and never a Tab stop |
| Body | <div class="kv-alert-body"> | none | Only when body is given |
| Action | <div class="kv-alert-actions"> with a <button> (the Button) | the button's own name (action.label) | At most one. A toast with an action never times out. Pressing it runs onPress, then dismisses the toast |
| Close | <button type="button" class="kv-alert-close"> → button | aria-label from alert.close (Close message in English) | Always present and last in the toast: the user can always dismiss |
Rules, each proved by a test:
- Persistent by default. With
autoDismiss: falseno toast has a timer. WithautoDismissa number of milliseconds, only an info or success toast without an action and not busy times out, after exactly that time. There is no minimum floor: a short value can remove a toast before it is read. This is a trade-off against 2.2.1 (Timing Adjustable); the mitigations are below.0, a negative number orNaNacts asfalseand warns once in development. A toast with an action, or a busy one, stays until dismissed, and a development warning says when a requested timer was dropped. - The timer pauses while the pointer is over the region, while focus is inside it, while the tab is hidden and while the window is blurred. When it resumes at least 5 s remain. A toast the user focused is never removed under them.
- Limit. At most
limit(default 10) toasts show, at any width. When full, the oldest toast that may time out is evicted for the new one, never a toast that cannot time out and never while the pointer or focus is on a toast. Otherwise the new toast is ignored, not queued:showreturns''and a development warning says so; withfocus: truethe caller must place focus itself then. The region is capped in height and scrolls, and a new toast scrolls into view in the region only (never the page, never animated), unless the user is hovering or focused in it. - The timer ring is decorative. A timed toast draws a ring around Close that drains over the time left (a
<span aria-hidden="true">inside Close: no text, no role, no Tab stop; Close keeps its namealert.close). Nothing is announced about the time. Underprefers-reduced-motion: reduceit steps in quarters instead of moving. A toast with an action or without a timer has no ring. - The same
idupdates in place: the text changes, the timer restarts, and it is announced once. - No toast while a modal is open. A new toast is held while a
<dialog>is shown modally (the live regions behind it are inert) and shown, then announced, when it closes or is removed. Timers stop while a modal is open (nobody can read or pause a toast behind it) and resume when it closes, with at least 5 s left, so nothing expires unread behind it. A held toast losesfocus: true(the dialog returns focus to its trigger). A message raised inside a dialog uses that dialog's own Alert. - Outside a provider
useToast()returns functions that do nothing and warns once. A toast shown before the provider has mounted (server rendering, or in the first render) is dropped with a warning. - The region uses the host provider's locale and messages. A toast shown from a provider in another language gets
langon its title text and its body (3.1.2), not on the list item: the status word and Close name follow the host's messages and stay in its language.
What you need to do#
- Use a toast sparingly, as a second channel. The result is also shown in place (a switch's state, the copy button's "Copied"). Never for an error to fix (
Field.ErrorMessageand the error summary), the outcome of a submit (anAlertor a confirmation page), or a decision (AlertDialog). No warning or danger toast exists. - An action (Undo, Open) needs a persistent alternative on the page: the toast can be closed, and a screen reader user may never reach it.
autoDismissis an app switch. Tie it to a user setting ("Keep messages until I close them", and a longer time for "keep them longer"), and never time out content the user must act on. Screen reader browse mode does not trigger the pause rules, so a timed toast can vanish under a reader: that is why the default is persistent (2.2.1).focus: trueonly for a user-initiated action whose trigger no longer exists (3.2.2).- Write one sentence in the user's words, past tense, naming the thing, at most 80 characters where possible, in the language of the provider (3.1.2).
titleis a string. - Toast sparingly: persistent toasts fill the limit and later ones are ignored.
- No toast while an error summary is up. The component does not know about the page's
ErrorSummary: do not show a toast on a failed submit, or calldismissAll()first, so nothing competes with the summary. - A sticky header or footer of the page is the consumer's: keep
scroll-paddingfor it. - WCAG 2.2.2 (Pause, Stop, Hide, A). An indicator that can keep moving for more than 5 seconds alongside other content needs a visible control on the page that stops or hides it (2.2.2). An indicator that is the only content during a wait where nothing else can be done is exempt.
prefers-reduced-motionalone is not that control. The library ships no such control. Moving indicators and WCAG 2.2.2. Show abusytoast without an auto-dismiss timer.
Warning: Don't forget
Turn autoDismiss on only as a setting the user can change, such as “Keep messages until I close them”. A toast that vanishes before it is read fails people who read slowly or use a screen reader (2.2.1 Timing Adjustable). There is no minimum time, so keep the value long enough to read.
Visual and modes#
Headless: no CSS. With the default theme (@kvirn-ui/theme/theme.css):
- Focus indicator: Close and the action keep their own focus rings. The Title has none: only script focuses it, and it shows a ring only when the keyboard put the focus there.
- Target size: Close is at least 24 by 24 CSS px, in the compact density too (2.5.8 Target Size (Minimum), AA).
- Contrast: the Alert's colour pairs are checked in the theme's contrast check (1.4.3 Contrast (Minimum), AA; 1.4.11 Non-text Contrast, AA). The toast adds a subtle edge and, in the light theme, a shadow.
- forced-colors behaviour: the Alert's. It uses the system's background and text colours with an edge on all four sides, and the status is carried by the icon's shape and the status word.
- reduced-motion behaviour: a fade in only when the user has not asked for reduced motion; removal is instant. The timer ring steps in quarters instead of moving.
- Timer ring (decorative): drawn in the toast's accent colour on a light tint, with contrast checked by the theme's contrast check (1.4.11). It uses the system's button text colour in forced colours. It is a clock, so it is not mirrored in right-to-left languages.
- Reflow: full width below 40rem, no fixed sizes, and a capped region that scrolls. No horizontal scrolling at 320 CSS px (1.4.10 Reflow, AA): the reflow sweep runs every story at 320 CSS px and fails on horizontal overflow, with Finnish text. Text spacing grows the height (1.4.12 Text Spacing, AA): the text-spacing sweep applies the 1.4.12 spacing to every story and fails on a box that clips more content than it holds.
- RTL: placement follows the reading direction: the inline end is the left. Hidden in print.
- Without the theme: the region is a
popoverin the top layer with the browser's default popover box; the toasts are plain Alerts. Usable, unstyled.
Focus management#
- Initial focus: never moved by showing a toast (3.2.2). Two ways to move it, both opt-in:
show({ focus: true }), for a user-initiated action whose trigger is gone, focuses the toast's Title and skips the announcement (focus reads it);toast.focus()focuses the newest toast's Title, for a button of the consumer's own. - Trap: no.
- Restore to, when a toast that holds focus is removed (Close, the action, Escape,
dismiss,dismissAll): the element that had focus before focus entered the region, if it is still in the document and takes focus, else the Close of the next toast, else of the previous one, else nothing: the component never moves focus tobodyitself, so the browser puts it where it does (the page), and a development warning says the user lost their place. A press with the pointer returns focus without scrolling the page. A toast that does not hold focus is removed without moving anything. - A toast the user focused is never removed by its timer: focus inside pauses it.
- Never obscured by (2.4.11): the region sits at the block-end edge, up to 10 toasts show, the region is capped in height and scrolls, and the default theme keeps room at the end of the page while a region exists. When the focused element would sit under the region, the region moves to block-start (
data-placement="block-start"). Close is always reachable. A region taller than the viewport (400% zoom, a long body) scrolls, and is a Tab stop (tabindex="0", named bytoast.regionLabel) only while it overflows (1.4.10, 2.1.1), and it keeps the tabindex while it has focus, so focus never falls tobody: when its last toast goes, focus returns to the element focused before.
Warning: Don't forget
Use focus: true only for an action the user just took, when the button they pressed is gone. Moving focus without a reason is a surprise (3.2.2 On Input).
WCAG success criteria#
- 1.3.1 Info and Relationships (A), 1.3.2 Meaningful Sequence (A), 2.4.3 Focus Order (A): a named region, an ordered list, DOM order = visual order = Tab order.
- 1.4.1 Use of Color (A), 1.4.3 Contrast (Minimum) (AA), 1.4.10 Reflow (AA; asserted at 320 CSS px, also with ten toasts at once), 1.4.11 Non-text Contrast (AA): the Alert's icon shape and word, the theme's colour pairs are checked automatically in every theme, one column below 40rem, a capped region.
- 1.4.12 Text Spacing (AA): the toast grows in height with the text; the text-spacing sweep applies the 1.4.12 spacing to every story and fails on a box that clips more content than it holds.
- 2.1.1 Keyboard (A): Close, the action and Escape; no trap (2.1.2 No Keyboard Trap, A).
- 2.2.1 Timing Adjustable (A), 2.2.2 Pause, Stop, Hide (A): persistent by default; timers only by an app switch the user can turn off, paused by hover, focus, hidden tab and blurred window, a visible timer ring, Close and Escape always. There is no minimum time: a trade-off against 2.2.1.
- 2.4.7 Focus Visible (AA), 2.4.11 Focus Not Obscured (Minimum) (AA): block-end edge, a limit, room kept at the end of the page, block-start placement when the focus is under it.
- 2.5.8 Target Size (Minimum) (AA): Close and the action.
- 3.1.2 Language of Parts (AA): the region carries the host provider's
langanddir; a toast from another language marks its title and body. - 3.2.2 On Input (A): showing never moves focus;
focus: trueis for a user-initiated action only. - 4.1.2 Name, Role, Value (A): the region's name, Close's name from i18n, no role on the box.
- 4.1.3 Status Messages (AA): one polite announcement through the Announcer. See Known issues.
Keyboard#
- Focus
- native
- Selection follows focus
- n/a
- Arrows wrap
- n/a
- Shortcuts
- none
There is no hotkey and no key that jumps to the region (an F6 or a shortcut is out of scope): Tab reaches it in DOM order after the page's content, and screen reader users also find the named region landmark while a toast shows. Showing a toast never moves focus. No toast is a Tab stop of its own, and no roving focus or trap exists.
| Key | Where | What happens |
|---|---|---|
| Tab | before the region | Enters the first toast: its action, then its Close, then the next toast's. While the region overflows the region itself is the first stop Test: toast.test.tsx › keyboard › Tab from the page enters the first toast at its action, then its Close, then the next toast, toast.test.tsx › keyboard › Tab from the page stops on the region first while it overflows, then enters the first toast |
| Shift+Tab | after the region | Enters the last toast at its Close, and goes back in reverse order, to the region last while it overflows Test: toast.test.tsx › keyboard › Shift+Tab from after the region enters the last toast at its Close and goes back in reverse order, toast.test.tsx › keyboard › Shift+Tab from the first toast goes back to the region while it overflows |
| Tab / Shift+Tab | inside the region | Plain DOM order. Nothing traps focus: Tab from the last Close leaves the region Test: toast.test.tsx › keyboard › Tab and Shift+Tab inside the region follow DOM order and never trap |
| Enter / Space | on Close | Dismisses the toast. Focus returns to the element that had it before it entered the toast Test: toast.test.tsx › keyboard › Enter on Close dismisses the toast and returns focus to the element focused before, toast.test.tsx › keyboard › Space on Close dismisses the toast and returns focus to the element focused before |
| Enter / Space | on the action | Runs the action, then dismisses the toast. Focus returns as for Close Test: toast.test.tsx › keyboard › Enter on the action runs onPress, then dismisses the toast, toast.test.tsx › keyboard › Space on the action runs onPress, then dismisses the toast |
| Escape | focus inside a toast | Dismisses that toast only (a layer on the stack only while focus is inside). Focus returns as above Test: toast.test.tsx › keyboard › Escape with focus inside a toast dismisses that toast only |
| Escape | focus elsewhere | Not handled: the toasts stay and the page's own Escape handling is untouched Test: toast.test.tsx › keyboard › Escape with focus outside the region is not handled |
The toast handles no other key. Enter and Space on the buttons are native.
Announcements#
Toast 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 |
|---|---|---|---|
| One or more toasts shown in one commit (also held ones, when they mount) | alert.infoPrefix alert.successPrefix | Polite | |
A toast shown again with the same id | Polite |
Change the text#
For your whole app, pass messages to KvirnProvider. For one Toast, pass its messages prop.
<KvirnProvider messages={{ alert: { infoPrefix: '…' } }}>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#
Wrap your app in a KvirnProvider once, then call useToast from any component below it. The provider options below are the defaults.
<KvirnProvider locale="sv" toast={{ limit: 10, autoDismiss: false }}>
<App />
</KvirnProvider>const toast = useToast()
toast.show({ variant: 'success', title: 'Utkastet sparades' })import { KvirnProvider, useToast } from '@kvirn-ui/react'KvirnProvider toast
Renders the toast region, once, after the provider’s children, in the top layer. It is a <section> named by toast.regionLabel and exists only while a toast is shown. It has no role attribute and no aria-live. One region serves the whole page: the first KvirnProvider that mounted owns the toast options, and a later provider’s toast is ignored. See KvirnProvider for the other props.
| Prop | Type | Default | Description |
|---|---|---|---|
limit | number | 10 | The most toasts shown at once. The region scrolls when they don’t fit. When it is full, the oldest toast that can time out makes room. If none can, the new toast is ignored: show returns an empty string and a development warning says so. |
autoDismiss | false | number | false | false: nothing times out. A number is how long, in milliseconds, an info or success toast without an action stays. There is no minimum: a short value can remove a toast before it is read (2.2.1 Timing Adjustable), so tie it to a user setting. 0, a negative number or NaN acts as false and warns in development. |
useToast
Takes no options. Outside a KvirnProvider the functions do nothing and a development warning says so.
Result
| Prop | Type | Default | Description |
|---|---|---|---|
show | (options: ToastShowOptions) => string | – | Shows a toast and returns its id, or an empty string when it was dropped (no provider, before the provider mounted, or the limit is reached). Showing an id that is already shown updates it in place. |
dismiss | (id: string) => boolean | – | Removes one toast. Returns false when there is none with that id. |
dismissAll | () => void | – | Removes every toast. |
focus | () => void | – | Focuses the newest toast’s title, for a button of your own. The library adds no key for it. |
show
Options
| Prop | Type | Default | Description |
|---|---|---|---|
title | string | Required | The message: one sentence in the user’s words. The status word comes first. |
variant | 'info' | 'success' | 'info' | There is no warning or error toast: use an inline Alert, or the form’s error summary. |
busy | boolean | false | A job in progress: a decorative spinner replaces the status icon and the status word stays. Show the result with the same id to replace it. A busy toast stays even with autoDismiss on; only the result that replaces it times out, if it has no action. |
body | ReactNode | – | More to read, usually one short paragraph. |
action | { label: string; onPress: () => void } | – | At most one. Pressing it runs onPress and closes the toast. A toast with an action never times out, so give it a persistent alternative on the page. |
id | string | generated | Showing the same id again updates the toast in place and announces it once: ten saves are one toast. |
focus | boolean | false | Moves focus to the toast and skips the announcement. Only for an action the user just took whose button is gone (3.2.2 On Input). |
Strings
These are the default texts in @kvirn-ui/i18n.
For your whole app, pass messages to KvirnProvider. For one Toast, pass its messages prop.
The status word and the name of the Close button are the Alert’s strings: alert.infoPrefix, alert.successPrefix and alert.close.
toast.regionLabel
The name of the region that holds the toasts. The region exists only while a toast is shown.
| Language | Default text |
|---|---|
| Svenska | Meddelanden |
| Suomi | Ilmoitukset |
| Norsk bokmål | Meldinger |
| Norsk nynorsk | Meldingar |
| English | Messages |
Known issues#
- A timed toast can vanish under a screen reader in browse mode, which triggers neither hover nor focus. With no minimum floor a short
autoDismissmakes this worse. The default is persistent for this reason, and the docs tell the app to tieautoDismissto a user setting and keep the value long enough to read (2.2.1 Timing Adjustable, A). - 4.1.3 Status Messages (AA) and the region having no live role. The message reaches assistive technology through the Announcer's
statusregion, not through the visible box (as forAlert). Check with your own screen reader that the joined message is heard in time after the action that caused it. - Joined messages. The provider joins the toasts of one commit into one message, because the Announcer replaces a second one inside 100 ms. Two
showcalls in separate commits within 100 ms: the second replaces the first one if it was not spoken yet. - The Announcer replaces a message of the same politeness spoken within 100 ms, whoever sent it: a CopyButton's "Copied" and a toast shown in the same moment replace each other. The provider already joins the toasts of one commit; a toast and another component's
announcein separate commits within 100 ms are the app's to avoid. - A handover while a modal is open shows the new host's region in the top layer above the modal (rare: it needs the first provider to unmount while a dialog is open).
- Server rendering: the region is not rendered on the server, and a toast shown before mount is dropped (with a warning).
- Keyboard tests run in Chromium only. The keyboard rows run in Vitest browser mode on Chromium, not in WebKit. Test in Safari with your own assistive technology.
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 | toast.stories.tsx, every story, 4 themes |
| Markup and ARIA (roles, names, ids, states) | pass | n/a | pass | toast.test.tsx › a toast is a named region holding a list item, with no role or live region of its own; expectNoA11yViolations |
| Keyboard contract rows (Vitest browser) | pass | n/a | pass | 7 rows, each names a test (toast.test.tsx › keyboard › Tab from the page enters the first toast at its action, then its Close, then the next toast) |
| Focus order and management | pass | n/a | pass | toast.test.tsx asserts focus (toHaveFocus); first rule: keyboard › Tab from the page enters the first toast at its action, then its Close, then the next toast |
| Display modes (forced colours, 320px reflow, text spacing, reduced motion) | pass | n/a | pass | the four sweep projects (storybook-forced-colors, -reduced-motion, -reflow, -text-spacing), run in CI |
| 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#
With a screen reader and the keyboard, try:
- A button that shows a toast: the message is read once (status word, title, body), and focus stays on the button.
- Tab from the page reaches the action, then "Close message".
- Escape or Enter on Close removes the toast and focus returns.
- A toast with
focus: truemoves focus to its title, which is read once. - With
autoDismisson, read a toast in browse mode: does it vanish while you read? - A toast shown while a dialog is open is not read until the dialog closes.