zgui

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 is Role::GenericContainer, which assistive technology skips.
  • Name: derived from the element's own text child, "Add one".
  • Keyboard: control is focusable by default, so Tab reaches it and Enter or Space dispatch click.

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:

RoleFor
Buttonan action
Switchon/off that takes effect immediately
CheckBoxa choice applied later; may be Mixed
RadioButton inside RadioGroupone choice of several
Linknavigation
Heading with a11y:levela section title
TextInput, MultilineTextInput, SearchInput, PasswordInputtext entry
Slider, SpinButton, ProgressIndicator, Metera number
Tab, TabList, TabPaneltabs
Menu, MenuBar, MenuItem, MenuItemCheckBox, MenuItemRadiomenus
ListBox, ListBoxOption, ComboBoxchoosers
List, ListItem, Tree, TreeItemcollections
Table, Row, Cell, RowHeader, ColumnHeader, Grid, GridCelltabular data
Dialog, AlertDialog with a11y:modaldialogs
Alert, Status, Logcontent that should be read out when it appears
Group, Region, Section, Toolbar, Navigation, Mainstructure

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:

  1. a declared a11y:label;
  2. an a11y:labelled_by relation (the assistive technology reads the target's name);
  3. 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:

RuleDetail
focusable by defaultcontrol, field, editor
focusable by declarationtabindex = Focus::Sequential (in the Tab order) or Focus::Programmatic (focusable, not in the Tab order)
never focusablean element with state:disabled, or one without a visible box
Tab orderdocument 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.

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=button

owns 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=option

Announce 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())}
    }
}
ValueBehaviour
Live::Offnot a live region
Live::Politeread at the next pause
Live::Assertiveinterrupts 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 an A11yBinding.
  • Role::Alert and Role::Status are live by default. Use Role::Alert for a toast and Live::Polite on 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; }"
);
WrittenEffect
controlfocusable; Tab reaches it, Enter and Space activate it
a11y:role = Role::Switchannounced as a switch
a11y:labelled_by = namenamed by the caption next to it
a11y:toggled_onthe state, announced on change
state:checkedthe state, for :checked in CSS
a11y:disabled + state:disabledannounced as disabled, ignores pointer input, leaves the Tab order
a11y:state_descriptionsays "on"/"off" instead of the default wording
on:clickhandles 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-visible an 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:

PartExample
a rolebutton, switch, list item, heading
a name"Delete", "Wi-Fi"
stateon, expanded, disabled, invalid
boundsa rectangle in CSS pixels
actionsclick, 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.

DerivedFrom
namethe element's own text children, joined with single spaces
boundsthe union of the element's fragments, in CSS pixels, relative to the parent node; the root carries the window scale factor
hiddenthe element generated no box
clips childrena fragment of the element clips its content
childrenelement children in document order
Action::Clicka click listener
Action::Focus, Action::Blurthe element is focusable; Blur only while it has focus
Action::Increment, Action::Decrementa declared numeric value, range or step
Action::SetValuea declared value, or a change listener
focusthe 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

AttributeType
a11y:roleRole

Text

AttributeTypeMeaning
a11y:labelSharedStringthe name
a11y:descriptionSharedStringa longer description, read after the name
a11y:valueSharedStringthe value as text
a11y:placeholderSharedStringtext shown when a field is empty
a11y:role_descriptionSharedStringa custom name for the role
a11y:state_descriptionSharedStringthe current value in words
a11y:keyboard_shortcutSharedStringthe key that activates the element
a11y:tooltipSharedStringthe element's tooltip

Flags

AttributeTypeMeaning
a11y:disabledboolcannot be used
a11y:read_onlyboolvalue cannot be changed
a11y:requiredboolmust have a value
a11y:modalboolblocks the rest of the window
a11y:busyboolstill loading
a11y:hiddenboolremoved from the presented tree, with its subtree
a11y:expandedboolits content is showing
a11y:selectedboolselected
a11y:toggled_onboola toggle that is on

Enumerations

AttributeTypeValues
a11y:toggledToggledFalse, True, Mixed
a11y:invalidInvalidTrue, Grammar, Spelling
a11y:liveLiveOff, Polite, Assertive
a11y:orientationOrientationHorizontal, Vertical
a11y:has_popupHasPopupMenu, Listbox, Tree, Grid, Dialog
a11y:sort_directionSortDirectionAscending, Descending, Other
a11y:currentAriaCurrentFalse, True, Page, Step, Location, Date, Time
a11y:auto_completeAutoCompleteInline, List, Both

All are in zgui::vocab.

Numbers

AttributeTypeMeaning
a11y:numeric_valuef64the value as a number
a11y:levelusizeheading level, from 1
a11y:row_index, a11y:column_indexusizeposition in a table, from 0
a11y:row_span, a11y:column_spanusizecells covered

Relations

AttributePoints at
a11y:labelled_bythe element whose text names this one
a11y:described_bythe element whose text describes this one
a11y:controlsthe element this one controls
a11y:ownsan element that belongs to this one but is not its child in the document
a11y:active_descendantthe descendant that acts as if it had focus
a11y:popup_forthe element this popup belongs to
a11y:error_messagethe element holding this control's error

All relation attributes take a NodeId; pass a NodeRef.

Values and merging

  • Text properties take a SharedString. A &str literal 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.

RequestResult
Clicka click on the node, along the normal capture/target/bubble path
Focus, Blurfocus moves to the node, or away from it
Increment, Decrementa change event with the stepped value
SetValue, ReplaceSelectedTexta change event with the new value
ShowContextMenua context_menu event
ScrollIntoViewthe same as NodeRef::scroll_to
SetScrollOffsetscrolls the container to an absolute offset in CSS pixels
ScrollUp, ScrollDown, ScrollLeft, ScrollRightone line of scrolling
Collapse, Expand, CustomAction, ShowTooltip, HideTooltip, ScrollToPoint, SetTextSelectionignored

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

Next

On this page