# 2. Exposing a UI Toolkit Menu
Part of [[Screen Reader Accessibility]]. Previous: [[1. Screen Readers and the Accessibility Module]]. Next: [[3. Values Announcements and Keeping in Sync]].
## 2.1 The idea
A UI Toolkit screen already knows almost everything a screen reader needs: which elements are buttons, what they say, where they are, whether they're enabled. `AccessibleMenu` reads that and builds matching nodes, so a menu becomes accessible by adding one component and, at most, a couple of USS classes.
## 2.2 AccessibleMenu.cs
**`AccessibleMenu.cs`**
```csharp
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Accessibility;
using UnityEngine.UIElements;
/// <summary>
/// Exposes a UI Toolkit screen to screen readers. Walks the document in visual order and creates a
/// node for every Button, Toggle, Slider, DropdownField and Label (classes: "a11y-header" makes a
/// Label a Header; "a11y-ignore" skips an element and its children). Keeps frames, values and
/// disabled states in sync and routes screen-reader activation, increment and decrement back to the
/// controls. Rebuild() after changing the screen's contents.
/// </summary>
[RequireComponent(typeof(UIDocument))]
public sealed class AccessibleMenu : MonoBehaviour
{
[Serializable]
public struct Override
{
public string elementName; // the element's name in UI Builder
public string label; // spoken instead of the visible text (e.g. for icon buttons)
public string hint; // what activating it does, e.g. "Starts a new game"
}
[SerializeField] string screenName = "Main menu";
[SerializeField] Override[] overrides = Array.Empty<Override>();
[Tooltip("Labels are read as plain text; turn off to expose only interactive controls and headers")]
[SerializeField] bool includeLabels = true;
readonly List<(VisualElement element, AccessibilityNode node)> _bound = new List<(VisualElement, AccessibilityNode)>();
readonly List<Action> _unbind = new List<Action>();
AccessibilityNode _root;
VisualElement _doc;
void OnEnable()
{
_doc = GetComponent<UIDocument>().rootVisualElement;
// Build after the first layout so frames are valid.
_doc.schedule.Execute(() => Rebuild(true));
}
void OnDisable() => Teardown(true);
public void Rebuild(bool newScreen = false)
{
var svc = ScreenReaderService.Instance;
if (svc == null || _doc == null) return;
Teardown(false);
_root = svc.Hierarchy.AddNode(screenName, null);
_root.role = AccessibilityRole.Container;
Walk(_doc, svc.Hierarchy);
var first = _bound.Count > 0 ? _bound[0].node : _root;
if (newScreen) svc.ScreenChanged(first); else svc.LayoutChanged(null);
}
void Walk(VisualElement e, AccessibilityHierarchy h)
{
if (e.ClassListContains("a11y-ignore")) return;
if (TryDescribe(e, out var label, out var role))
{
var node = h.AddNode(label, _root);
node.role = role;
Bind(e, node);
if (role != AccessibilityRole.Container) return; // controls' internal labels aren't separate nodes
}
foreach (var child in e.Children()) Walk(child, h);
}
bool TryDescribe(VisualElement e, out string label, out AccessibilityRole role)
{
label = null;
role = AccessibilityRole.None;
switch (e)
{
case Button b: label = b.text; role = AccessibilityRole.Button; break;
case Toggle t: label = t.label ?? t.text; role = AccessibilityRole.Toggle; break;
case Slider s: label = s.label; role = AccessibilityRole.Slider; break;
case DropdownField d: label = d.label; role = AccessibilityRole.Dropdown; break;
case Label l when e.ClassListContains("a11y-header"): label = l.text; role = AccessibilityRole.Header; break;
case Label l when includeLabels && !(e.parent is Button) && !e.ClassListContains("unity-base-field__label"):
label = l.text; role = AccessibilityRole.StaticText; break;
default: return false;
}
foreach (var o in overrides)
if (o.elementName == e.name && !string.IsNullOrEmpty(o.label)) label = o.label;
label = A11yText.Clean(label);
return label.Length > 0;
}
void Bind(VisualElement e, AccessibilityNode node)
{
_bound.Add((e, node));
foreach (var o in overrides)
if (o.elementName == e.name && !string.IsNullOrEmpty(o.hint)) node.hint = o.hint;
UpdateFrame(e, node);
UpdateState(e, node);
EventCallback<GeometryChangedEvent> geo = _ => UpdateFrame(e, node);
e.RegisterCallback(geo);
_unbind.Add(() => e.UnregisterCallback(geo));
// Screen reader focus follows into the UI so keyboard and gamepad users stay in sync.
Action<AccessibilityNode, bool> focus = (n, focused) => { if (focused && e.focusable) e.Focus(); };
node.focusChanged += focus;
switch (e)
{
case Button b:
node.invoked += () =>
{
using var evt = NavigationSubmitEvent.GetPooled();
evt.target = b;
b.SendEvent(evt);
return true;
};
break;
case Toggle t:
node.value = A11yText.ToggleValue(t.value);
node.invoked += () => { t.value = !t.value; return true; };
EventCallback<ChangeEvent<bool>> tc = ev => { node.value = A11yText.ToggleValue(ev.newValue); ScreenReaderService.Instance?.LayoutChanged(null); };
t.RegisterValueChangedCallback(tc);
_unbind.Add(() => t.UnregisterValueChangedCallback(tc));
break;
case Slider s:
node.value = A11yText.SliderValue(s.value, s.lowValue, s.highValue);
node.incremented += () => s.value = SliderStepper.Step(s.value, s.lowValue, s.highValue, (s.highValue - s.lowValue) / 20f, +1);
node.decremented += () => s.value = SliderStepper.Step(s.value, s.lowValue, s.highValue, (s.highValue - s.lowValue) / 20f, -1);
EventCallback<ChangeEvent<float>> sc = ev => node.value = A11yText.SliderValue(ev.newValue, s.lowValue, s.highValue);
s.RegisterValueChangedCallback(sc);
_unbind.Add(() => s.UnregisterValueChangedCallback(sc));
break;
case DropdownField d:
node.value = A11yText.Choice(d.value, d.index, d.choices?.Count ?? 0);
node.invoked += () =>
{
if (d.choices == null || d.choices.Count == 0) return false;
d.index = (d.index + 1) % d.choices.Count; // cycle: simpler than opening the popup
return true;
};
EventCallback<ChangeEvent<string>> dc = ev => node.value = A11yText.Choice(ev.newValue, d.index, d.choices?.Count ?? 0);
d.RegisterValueChangedCallback(dc);
_unbind.Add(() => d.UnregisterValueChangedCallback(dc));
break;
}
}
static void UpdateFrame(VisualElement e, AccessibilityNode node)
{
if (e.panel == null) return;
var r = e.worldBound;
var scale = e.panel.scaledPixelsPerPoint;
node.frame = new Rect(r.position * scale, r.size * scale);
node.isActive = e.resolvedStyle.display != DisplayStyle.None && e.visible && r.width > 0f && r.height > 0f;
}
static void UpdateState(VisualElement e, AccessibilityNode node) =>
node.state = e.enabledInHierarchy ? AccessibilityState.None : AccessibilityState.Disabled;
/// <summary>Call after enabling or disabling controls so the reader says "dimmed" or "unavailable".</summary>
public void RefreshStates()
{
foreach (var (e, n) in _bound) UpdateState(e, n);
ScreenReaderService.Instance?.LayoutChanged(null);
}
void Teardown(bool notify)
{
foreach (var u in _unbind) u();
_unbind.Clear();
_bound.Clear();
var svc = ScreenReaderService.Instance;
if (_root != null && svc != null && svc.Hierarchy.ContainsNode(_root))
{
svc.Hierarchy.RemoveNode(_root, true);
if (notify) svc.ScreenChanged(null);
}
_root = null;
}
}
```
## 2.3 How it maps elements
| Element | Role | Label | Activation |
|---|---|---|---|
| `Button` | Button | `text` | sends a `NavigationSubmitEvent`, exactly as the manual's example does, so your `clicked` handlers run |
| `Toggle` | Toggle | `label` (or `text`) | flips `value` |
| `Slider` | Slider | `label` | increment/decrement by 1/20 of the range |
| `DropdownField` | Dropdown | `label` | cycles to the next choice |
| `Label` with class `a11y-header` | Header | `text` | none |
| other `Label` | StaticText | `text` | none |
- The walk follows the visual tree in document order, which is also the order the screen reader moves through. Arrange your UXML in reading order.
- A control's own child labels (a Toggle's label element, a Button's text) aren't separate nodes; `unity-base-field__label` is the class UI Toolkit gives field labels.
- Add the class **`a11y-ignore`** to skip decorative elements and everything inside them.
- Every label passes through `A11yText.Clean` (part 3), which removes rich-text tags and decorative arrows and stars.
### Icon buttons and hints
A button that shows only a gear icon has no text. Add an entry to **Overrides** with the element's **name** (from UI Builder), a **Label** such as "Settings", and optionally a **Hint** such as "Opens audio, video and control settings". Without a label the element is skipped, because a node with no label is worse than none: the reader just says "button".
## 2.4 Frames
The reader draws its focus outline at each node's `frame`, and touch exploration on mobile finds nodes by position. The manual's formula for UI Toolkit is:
```csharp
Rect worldRect = element.worldBound;
float scale = element.panel.scaledPixelsPerPoint;
node.frame = new Rect(worldRect.position * scale, worldRect.size * scale);
```
`AccessibleMenu` applies it on every `GeometryChangedEvent`, so frames follow layout changes, resizes and animations. Hidden or zero-size elements become inactive (`isActive = false`), so the reader skips them.
The menu builds on the panel's first scheduled update after `OnEnable`, because before the first layout every `worldBound` is empty.
## 2.5 Focus both ways
When the screen reader focuses a node, `focusChanged` calls `Focus()` on the matching element. A sighted helper sees the same highlight, and keyboard or gamepad input continues from where the reader is. The other direction (keyboard focus moving the reader) isn't something the API offers; screen reader users drive focus with the reader itself.
## 2.6 Set it up
1. Open your main menu's UI Document. Make sure every interactive element is a real `Button`, `Toggle`, `Slider` or `DropdownField`, not a `VisualElement` with a click handler: those are invisible to this script and usually to keyboard users too.
2. Give the title `Label` the class `a11y-header`. Give decorative images and the background the class `a11y-ignore`.
3. Add **Accessible Menu** to the GameObject with the UI Document. Set **Screen Name** ("Main menu").
4. Add **Overrides** for icon-only buttons.
5. If the menu's contents change (a button is added, a panel is shown), call `Rebuild()`. If only enabled states change, call `RefreshStates()`.
6. Press Play with **Force Enable In Editor** on and open **Window > Accessibility > Accessibility Hierarchy Viewer** to see the nodes.
Next: [[3. Values Announcements and Keeping in Sync]].