Accessibility
Give controls roles, names and keyboard access, report state, announce changes, test what screen readers see, and look up every a11y attribute and role.
Screen readers, braille displays, magnifiers and automation tools cannot read pixels. They read an accessibility tree that zgui builds from your document. zgui fills in what it can observe, such as text, bounds, focus and click handlers. You declare what it cannot know: what each element is, and its state.
Make a control accessible
Every interactive element needs three things: a role, a name, and keyboard access.
use zgui::prelude::*;
let count = RwSignal::new(0);
view! {
control(
a11y:role = Role::Button,
on:click = move |_| count.update(|n| *n += 1)
) {
"Add one"
}
}- Role: declared with
a11y:role. Without it, the element isRole::GenericContainer, which assistive technology skips. - Name: derived from the element's own text child, "Add one".
- Keyboard:
controlis focusable by default, so Tab reaches it and Enter or Space dispatchclick.
The click listener also makes zgui advertise a click action. A screen reader that activates the
button dispatches a real click along the same path as a pointer, so pointer, keyboard and screen
reader all end up in one on:click.
Give elements a role
The role decides how an element is announced, which keyboard conventions apply, and which other properties mean anything. These are the roles most applications need:
| Role | For |
|---|---|
Button | an action |
Switch | on/off that takes effect immediately |
CheckBox | a choice applied later; may be Mixed |
RadioButton inside RadioGroup | one choice of several |
Link | navigation |
Heading with a11y:level | a section title |
TextInput, MultilineTextInput, SearchInput, PasswordInput | text entry |
Slider, SpinButton, ProgressIndicator, Meter | a number |
Tab, TabList, TabPanel | tabs |
Menu, MenuBar, MenuItem, MenuItemCheckBox, MenuItemRadio | menus |
ListBox, ListBoxOption, ComboBox | choosers |
List, ListItem, Tree, TreeItem | collections |
Table, Row, Cell, RowHeader, ColumnHeader, Grid, GridCell | tabular data |
Dialog, AlertDialog with a11y:modal | dialogs |
Alert, Status, Log | content that should be read out when it appears |
Group, Region, Section, Toolbar, Navigation, Main | structure |
Leave layout-only elements without a role. Role::GenericContainer is skipped, so deep visual
nesting does not become deep spoken nesting. Each window's root node has Role::Window.
a11y:role may appear only once per element; a second one is a compile error. Role is in the
prelude. All roles are listed at the end of this page.
Name elements
An element's name comes from, in order of precedence:
- a declared
a11y:label; - an
a11y:labelled_byrelation (the assistive technology reads the target's name); - the element's own text children, joined with single spaces.
Only direct text children count:
// Named "Delete".
control(a11y:role = Role::Button) {"Delete"}
// No name: "Delete" belongs to the inner element.
control(a11y:role = Role::Button) { text {"Delete"} }When the words are nested, declare a11y:label or point a11y:labelled_by at them. An icon-only
button always needs a11y:label.
Label, TextInput, MultilineTextInput and SearchInput put their own text in the value
instead of the name. For an editable element the text is the value, so do not declare
a11y:value on a field.
Use a11y:description for hint text under a field, not for a second name.
Make elements reachable by keyboard
Tab order and assistive-technology focus requests use the same focusability rule:
| Rule | Detail |
|---|---|
| focusable by default | control, field, editor |
| focusable by declaration | tabindex = Focus::Sequential (in the Tab order) or Focus::Programmatic (focusable, not in the Tab order) |
| never focusable | an element with state:disabled, or one without a visible box |
| Tab order | document order |
// A row that is not a control but must be reachable.
row(class = "item", tabindex = Focus::Sequential, on:click = pick) { … }Enter and Space on the focused element dispatch click, as does an assistive technology's
activation request. There is no separate accessibility activation path. See
Keyboard and focus for traversal, :focus-visible, focus traps
and programmatic focus.
Report state
state: and a11y: are separate. state:checked sets the UI state that CSS matches with
:checked. a11y:toggled_on sets what a screen reader announces. Neither implies the other, so
a toggle usually needs both:
control(
a11y:role = Role::Switch,
a11y:label = "Wi-Fi",
state:checked = move || on.get(), // for CSS
a11y:toggled_on = move || on.get(), // for assistive technology
on:click = move |_| on.update(|value| *value = !*value)
)The same applies to disabled elements: state:disabled makes the element unfocusable and matches
:disabled, and a11y:disabled announces it.
a11y:expanded, a11y:selected and a11y:toggled_on have three states. Omitting the attribute
means "not expandable", "not selectable" or "not a toggle". false means "collapsed", "not
selected" or "off". Use a11y:toggled = Toggled::Mixed for a checkbox that summarises a partly
selected group.
Other state attributes include a11y:invalid, a11y:required, a11y:busy and
a11y:read_only. See All a11y: attributes.
Connect related elements
A relation points one element at another. Relation attributes take a
NodeRef:
let caption = NodeRef::new();
let hint = NodeRef::new();
view! {
column {
label(node_ref = caption) {"Full name"}
field(
a11y:role = Role::TextInput,
a11y:labelled_by = caption,
a11y:described_by = hint,
a11y:required = true
)
text(node_ref = hint) {"As it appears on your passport"}
}
}A relation to an element that has not mounted yet is empty until the target appears, and becomes
empty again when the target is removed. To switch targets, use a closure returning
Option<NodeRef>; None points at nothing:
field(a11y:described_by = move || Some(if wrong.get() { error } else { hint }))There are eight relations. Seven have attributes (Relations lists them);
radio_group goes through A11yBinding::step.
Two common patterns follow. A trigger that opened a dialog rendered in an overlay layer:
Button label="Delete" expanded=true has_popup=Dialog owns=[dialog]
Dialog modal labelled_by=[title] described_by=[body] popup_for=buttonowns makes the dialog a child of the trigger in the accessibility tree, even though it lives in
the overlay layer in the document.
A combobox that keeps focus in its input while arrow keys move through the list:
ComboBox label="Fruit" expanded=true has_popup=Listbox controls=[list]
owns=[list] active_descendant=optionAnnounce changes
There is no announce() function. Instead, mark an element as a live region, and its changes
are read out automatically:
use zgui::vocab::Live;
view! {
text(class = "status", a11y:live = Live::Polite) {
{move || format!("{} results", results.get().len())}
}
}| Value | Behaviour |
|---|---|
Live::Off | not a live region |
Live::Polite | read at the next pause |
Live::Assertive | interrupts current speech |
Use Assertive only for something the user must act on now.
- To announce the whole region rather than only the changed part, set
.step(|a| a.flag(SemanticFlags::LIVE_ATOMIC, true))on anA11yBinding. Role::AlertandRole::Statusare live by default. UseRole::Alertfor a toast andLive::Politeon a plain element for a quiet counter.
Example: an accessible toggle
A switch with a caption, usable by pointer, keyboard and screen reader, built from plain elements:
use zgui::prelude::*;
#[component]
fn Toggle(
/// Whether it is on.
on: RwSignal<bool>,
/// Its caption.
#[prop(into)]
caption: String,
/// Whether it can be used.
#[prop(into, default = Signal::stored(false))]
disabled: Signal<bool>,
) -> impl IntoView {
let name = NodeRef::new();
view! {
row(class = "toggle") {
label(class = "toggle__caption", node_ref = name) {{caption}}
control(
class = "toggle__switch",
// For CSS.
state:checked = move || on.get(),
state:disabled = move || disabled.get(),
// For assistive technology.
a11y:role = Role::Switch,
a11y:labelled_by = name,
a11y:toggled_on = move || on.get(),
a11y:disabled = move || disabled.get(),
a11y:state_description = move || {
zgui::vocab::SharedString::from(if on.get() { "on" } else { "off" })
},
on:click = move |_| {
if !disabled.get_untracked() {
on.update(|value| *value = !*value);
}
}
) {
box(class = "toggle__thumb")
}
}
}
}
const SHEET: &str = css!(
".toggle__switch { display: flex; width: 44px; height: 24px; padding: 2px; border-radius: 999px; }
.toggle__thumb { width: 20px; height: 20px; border-radius: 999px; background-color: white; }
.toggle__switch:checked { justify-content: flex-end; background-color: #3b6cf6; }
.toggle__switch:focus-visible { outline: 2px solid #7aa2ff; outline-offset: 2px; }
.toggle__switch:disabled { opacity: 0.4; }"
);| Written | Effect |
|---|---|
control | focusable; Tab reaches it, Enter and Space activate it |
a11y:role = Role::Switch | announced as a switch |
a11y:labelled_by = name | named by the caption next to it |
a11y:toggled_on | the state, announced on change |
state:checked | the state, for :checked in CSS |
a11y:disabled + state:disabled | announced as disabled, ignores pointer input, leaves the Tab order |
a11y:state_description | says "on"/"off" instead of the default wording |
on:click | handles pointer, keyboard and assistive technology |
Bounds, children, actions and focus are all derived.
Test accessibility
Test a component
With zgui-testkit-view (see Testing), mount the component, run a frame,
and read semantics(node) from the in-memory tree:
use zgui::vocab::Toggled;
let window = zgui_testkit_view::Window::open();
let on = window.scope.with(|| RwSignal::new(false));
let mut built = window.scope.with(|| {
view! {
control(
a11y:role = Role::Switch,
a11y:label = "Dark mode",
a11y:toggled_on = move || on.get()
)
}
.into_view()
.build(&mut window.cx.cx())
});
built.mount(&window.dom_handle, window.root, None);
window.frame();
let node = window.dom.tree().children(window.root)[0];
let semantics = window.dom.tree().semantics(node).expect("has semantics");
assert_eq!(semantics.role, Role::Switch);
assert_eq!(semantics.label.as_deref(), Some("Dark mode"));
assert_eq!(semantics.toggled, Some(Toggled::False));
on.set(true);
window.frame(); // without this, the tree still shows the previous state
assert_eq!(window.dom.tree().semantics(node).unwrap().toggled, Some(Toggled::True));Every Semantics field can be asserted: role, label, description, value, flags,
toggled, invalid, live, numeric, position, table and relations. The transcript also
records semantics #1 Switch and semantics #1 cleared lines, so a golden file catches a
description that stopped being written.
Test a whole window
zgui-platform-headless runs the real frame loop and records each update on the offscreen surface
(last_a11y_update(), a11y_log(), take_a11y_log(), a11y_updates()). Each update is a
difference against the ones before it, so a claim about the whole tree must consider the whole
sequence.
zgui_a11y::dump(&update) prints one update as sorted, stable text with small ordinals for node
IDs, suitable for a golden file. It shows mistakes a screenshot cannot, such as a combobox that no
longer points at its active option.
tree root=#1
focus #1
#1 Window children=[#2]
#2 GenericContainer children=[#3 #4 #5]
#3 GenericContainer label="Full name"
#4 TextInput required labelled_by=[#3] described_by=[#5]
#5 GenericContainer label="As it appears on your passport"zgui_a11y::dangling(&update, retained) lists every node ID an update mentions that resolves
neither inside the update nor among the retained IDs the consumer already holds. The runtime
checks this in debug builds.
What to check yourself
- Contrast and target size. zgui checks neither. The framework sheet gives
:focus-visiblean outline; if your sheet removes it, keyboard users cannot see where focus is. - Reading order. The tree follows document order. If CSS reorders things visually, the two disagree.
- Screen coordinates on Wayland. Wayland does not tell applications where their windows are, so features that need absolute screen position, such as a magnifier following the caret, are limited there. Partial· A platform limitation.
How the tree is built
Each node in the accessibility tree has:
| Part | Example |
|---|---|
| a role | button, switch, list item, heading |
| a name | "Delete", "Wi-Fi" |
| state | on, expanded, disabled, invalid |
| bounds | a rectangle in CSS pixels |
| actions | click, focus, increment |
| relations | "the text that names me is that node" |
zgui builds the tree from the document and hands it to AccessKit, which speaks UI Automation on Windows, NSAccessibility on macOS and AT-SPI on Linux. Layout-only boxes are dropped from what is presented, text nodes become names, and elements without a box are marked hidden.
What zgui derives
zgui derives what it can observe. It never guesses meaning.
| Derived | From |
|---|---|
| name | the element's own text children, joined with single spaces |
| bounds | the union of the element's fragments, in CSS pixels, relative to the parent node; the root carries the window scale factor |
| hidden | the element generated no box |
| clips children | a fragment of the element clips its content |
| children | element children in document order |
Action::Click | a click listener |
Action::Focus, Action::Blur | the element is focusable; Blur only while it has focus |
Action::Increment, Action::Decrement | a declared numeric value, range or step |
Action::SetValue | a declared value, or a change listener |
| focus | the window's focused element |
Everything else is declared or absent: the role, descriptions, every state flag, expanded,
selected, toggled, invalid, live, the numeric range and step, set and table positions, and
every relation.
Publishing
zgui publishes the tree at the end of each frame that changed something, after rendering, so reported bounds match what was drawn. Only changed nodes are sent, and only while an assistive technology is listening; with nothing listening, the cost is a single check. A frame that only moved focus publishes a small update. A whole tree is sent when an assistive technology connects.
Text is not a node of its own, so a changing number such as label { {count} } is one node whose
name changes. Relations to nodes that are not in the published tree are dropped before publishing.
The platform layer describes the update format.
All a11y: attributes
There are 38 properties plus the role. Each accepts a constant, a signal or a closure. Role,
Toggled, Live, NodeId and the other vocabulary types are AccessKit's own, re-exported at
zgui::vocab.
Role
| Attribute | Type |
|---|---|
a11y:role | Role |
Text
| Attribute | Type | Meaning |
|---|---|---|
a11y:label | SharedString | the name |
a11y:description | SharedString | a longer description, read after the name |
a11y:value | SharedString | the value as text |
a11y:placeholder | SharedString | text shown when a field is empty |
a11y:role_description | SharedString | a custom name for the role |
a11y:state_description | SharedString | the current value in words |
a11y:keyboard_shortcut | SharedString | the key that activates the element |
a11y:tooltip | SharedString | the element's tooltip |
Flags
| Attribute | Type | Meaning |
|---|---|---|
a11y:disabled | bool | cannot be used |
a11y:read_only | bool | value cannot be changed |
a11y:required | bool | must have a value |
a11y:modal | bool | blocks the rest of the window |
a11y:busy | bool | still loading |
a11y:hidden | bool | removed from the presented tree, with its subtree |
a11y:expanded | bool | its content is showing |
a11y:selected | bool | selected |
a11y:toggled_on | bool | a toggle that is on |
Enumerations
| Attribute | Type | Values |
|---|---|---|
a11y:toggled | Toggled | False, True, Mixed |
a11y:invalid | Invalid | True, Grammar, Spelling |
a11y:live | Live | Off, Polite, Assertive |
a11y:orientation | Orientation | Horizontal, Vertical |
a11y:has_popup | HasPopup | Menu, Listbox, Tree, Grid, Dialog |
a11y:sort_direction | SortDirection | Ascending, Descending, Other |
a11y:current | AriaCurrent | False, True, Page, Step, Location, Date, Time |
a11y:auto_complete | AutoComplete | Inline, List, Both |
All are in zgui::vocab.
Numbers
| Attribute | Type | Meaning |
|---|---|---|
a11y:numeric_value | f64 | the value as a number |
a11y:level | usize | heading level, from 1 |
a11y:row_index, a11y:column_index | usize | position in a table, from 0 |
a11y:row_span, a11y:column_span | usize | cells covered |
Relations
| Attribute | Points at |
|---|---|
a11y:labelled_by | the element whose text names this one |
a11y:described_by | the element whose text describes this one |
a11y:controls | the element this one controls |
a11y:owns | an element that belongs to this one but is not its child in the document |
a11y:active_descendant | the descendant that acts as if it had focus |
a11y:popup_for | the element this popup belongs to |
a11y:error_message | the element holding this control's error |
All relation attributes take a NodeId; pass a NodeRef.
Values and merging
- Text properties take a
SharedString. A&strliteral converts. A closure must return one:move || SharedString::from(format!("…")). - Repeating an attribute is allowed for everything except
role; the later value wins. Relation lists accumulate. - On a component call, the caller's attributes merge over the component's own. A caller that writes no role keeps the component's role:
// Adds a label; SaveButton's Role::Button stays.
view! {
SaveButton(a11y:label = "Save and close")
}Set properties that have no attribute
table_size(rows, columns), radio_group, numeric_range, numeric_step, set_position,
clips_children and raw flags have no attribute. Set them through A11yBinding::step and spread
the binding with {..}:
let semantics = A11yBinding::new(Role::Slider)
.numeric_value(move || value.get())
.step(|a11y| a11y.numeric_range(0.0, 100.0).numeric_step(5.0));
let own = Attrs::new().a11y_from(semantics);
view! {
control(class = "slider", tabindex = Focus::Sequential, {..own})
}table_size also has its own method, A11yBinding::table_size(rows, columns). The step closure
runs inside the binding's effect, so signals it reads are tracked. Semantics::access_key and the
numeric jump have no builder method; set them by building a Semantics value directly.
Actions from assistive technology
Requests are routed to the window that owns the node and run in that window's reactive scope.
| Request | Result |
|---|---|
Click | a click on the node, along the normal capture/target/bubble path |
Focus, Blur | focus moves to the node, or away from it |
Increment, Decrement | a change event with the stepped value |
SetValue, ReplaceSelectedText | a change event with the new value |
ShowContextMenu | a context_menu event |
ScrollIntoView | the same as NodeRef::scroll_to |
SetScrollOffset | scrolls the container to an absolute offset in CSS pixels |
ScrollUp, ScrollDown, ScrollLeft, ScrollRight | one line of scrolling |
Collapse, Expand, CustomAction, ShowTooltip, HideTooltip, ScrollToPoint, SetTextSelection | ignored |
Ignored requests are not reported as handled.
Increment and Decrement step by the declared numeric_step if it is above zero, otherwise by
1/100 of the declared range, otherwise by 0.01. The result is clamped to the declared bounds.
All roles
Unknown TextRun Cell Label Image Link Row ListItem ListMarker TreeItem
ListBoxOption MenuItem MenuListOption Paragraph GenericContainer CheckBox
RadioButton TextInput Button DefaultButton Pane RowHeader ColumnHeader RowGroup
List Table LayoutTableCell LayoutTableRow LayoutTable Switch Menu
MultilineTextInput SearchInput DateInput DateTimeInput WeekInput MonthInput
TimeInput EmailInput NumberInput PasswordInput PhoneNumberInput UrlInput Abbr
Alert AlertDialog Application Article Audio Banner Blockquote Canvas Caption
Caret Code ColorWell ComboBox EditableComboBox Complementary Comment
ContentDeletion ContentInsertion ContentInfo Definition DescriptionList Details
Dialog DisclosureTriangle Document EmbeddedObject Emphasis Feed FigureCaption
Figure Footer Form Grid GridCell Group Header Heading Iframe
IframePresentational ImeCandidate Keyboard Legend LineBreak ListBox Log Main
Mark Marquee Math MenuBar MenuItemCheckBox MenuItemRadio MenuListPopup Meter
Navigation Note PluginObject ProgressIndicator RadioGroup Region RootWebArea
Ruby RubyAnnotation ScrollBar ScrollView Search Section SectionFooter
SectionHeader Slider SpinButton Splitter Status Strong Suggestion SvgRoot Tab
TabList TabPanel Term Time Timer TitleBar Toolbar Tooltip Tree TreeGrid Video
WebView Window PdfActionableHighlight PdfRoot GraphicsDocument GraphicsObject
GraphicsSymbol DocAbstract DocAcknowledgements DocAfterword DocAppendix
DocBackLink DocBiblioEntry DocBibliography DocBiblioRef DocChapter DocColophon
DocConclusion DocCover DocCredit DocCredits DocDedication DocEndnote DocEndnotes
DocEpigraph DocEpilogue DocErrata DocExample DocFootnote DocForeword DocGlossary
DocGlossRef DocIndex DocIntroduction DocNoteRef DocNotice DocPageBreak
DocPageFooter DocPageHeader DocPageList DocPart DocPreface DocPrologue
DocPullquote DocQna DocSubtitle DocTip DocToc ListGrid TerminalNext
Vector and canvas
Draw icons and SVG documents with vector, draw shapes from Rust with canvas, pan and zoom with a view transform, plot data series, and keep drawings fast.
Theming
Define design tokens as CSS custom properties, add a dark palette, switch themes at run time, and build components that follow the theme.