# 3. Values Announcements and Keeping in Sync Part of [[Screen Reader Accessibility]]. Previous: [[2. Exposing a UI Toolkit Menu]]. Next: [[4. Game World Objects and Screen Coordinates]]. ## 3.1 A11yText.cs **`A11yText.cs`** ```csharp using System; using System.Globalization; /// <summary> /// Text a screen reader speaks for common controls. The label says what it is ("Music volume"), the /// value what it's set to ("70 percent"), and the hint what activating it does. Keep labels short and /// never put the role in the label: the screen reader already says "button" or "slider". /// </summary> public static class A11yText { public static string ToggleValue(bool on) => on ? "On" : "Off"; public static string Percent(float value01) => Math.Round(Math.Clamp(value01, 0f, 1f) * 100f).ToString("0", CultureInfo.InvariantCulture) + " percent"; public static string SliderValue(float value, float min, float max, string unit = null) { if (string.IsNullOrEmpty(unit)) return Percent(max > min ? (value - min) / (max - min) : 0f); return Math.Round(value, 1).ToString("0.#", CultureInfo.InvariantCulture) + " " + unit; } public static string Choice(string current, int index, int count) => count > 0 ? quot;{current}, {index + 1} of {count}" : current; /// <summary>Cleans a visible caption for speech: strips rich text tags and decorative symbols.</summary> public static string Clean(string caption) { if (string.IsNullOrEmpty(caption)) return ""; var noTags = System.Text.RegularExpressions.Regex.Replace(caption, "<[^<>]+>", ""); var sb = new System.Text.StringBuilder(noTags.Length); foreach (var ch in noTags) if (ch != '»' && ch != '►' && ch != '▶' && ch != '★' && ch != '•') sb.Append(ch); return string.Join(" ", sb.ToString().Split((char[])null, StringSplitOptions.RemoveEmptyEntries)); } } /// <summary>Moves a slider one step for screen-reader swipe or arrow gestures, snapping to the step grid.</summary> public static class SliderStepper { public static float Step(float value, float min, float max, float step, int direction) { if (max <= min) return min; if (step <= 0f) step = (max - min) / 10f; var steps = Math.Round((value - min) / step) + Math.Sign(direction); var v = (float)(min + steps * step); return Math.Clamp(v, min, max); } } ``` - **Toggle values** are "On" and "Off". Platforms may add their own "switch" or "checkbox" wording from the role; don't repeat it. - **Slider values** default to a percentage of the range, rounded to whole numbers, because "0.70000001" is unpleasant to hear. Pass a unit for real quantities: `SliderValue(1.5f, 0, 5, "seconds")` gives "1.5 seconds". - **Dropdown values** include the position: "High, 3 of 4", so the user knows how many options there are. - **Clean** removes rich-text tags (`<b>`, `<color=...>`) and decorative symbols like `►` and `»`, and collapses spaces. A lone `<` in "< Back" is kept, because only `<...>` pairs count as tags. - All numbers use the invariant culture. If you localize the game, localize these strings too; see [[Localization]]. `SliderStepper.Step` snaps to the step grid before moving, so a slider at 0.512 goes to 0.55, not 0.562, and clamps at the ends. `AccessibleMenu` uses 20 steps across the range; for a volume slider that's 5 % per swipe. ## 3.2 Keeping values current `AccessibleMenu` listens to `ChangeEvent`s on toggles, sliders and dropdowns and updates `node.value` straight away, whether the change came from the screen reader, the mouse or a gamepad. The screen reader reads the new value when it next reads the node; after an increment or decrement gesture it usually reads it immediately *(platform-dependent; check in part 5)*. ## 3.3 Layout changed or screen changed | Situation | Call | Effect | |---|---|---| | A few nodes added, removed, relabelled or moved; a toggle's value changed | `LayoutChanged(null)` or `LayoutChanged(node)` | The reader refreshes its view; focus stays, or moves to `node` | | A new screen or menu opened, a scene loaded | `ScreenChanged(node)` | The reader treats it as a new page and focuses `node` (typically the first item or the title) | `AccessibleMenu.Rebuild(newScreen: true)` sends a screen change focused on the first node; a plain `Rebuild()` sends a layout change. Opening a pause menu should be a screen change, so the user isn't left focused on a node that's now hidden. ## 3.4 Announcements Some things sighted players notice without a menu: a checkpoint banner, "Health low" flashing red, a new objective. Speak them with `SendAnnouncement`. Sent naively, they interrupt each other and whatever the user was reading. `AnnouncementQueue` paces them: **`AnnouncementQueue.cs`** ```csharp using System; using System.Collections.Generic; public enum AnnouncementPriority { Low = 0, Normal = 1, High = 2 } /// <summary> /// Collects things to announce ("Checkpoint reached", "Health low") and releases them one at a time /// with a gap, so the screen reader isn't interrupted mid-sentence. Duplicates within the window are /// dropped, High jumps the queue, and old Low items expire instead of being read late. /// Pure C#: time is passed in. /// </summary> public sealed class AnnouncementQueue { struct Item { public string Text; public AnnouncementPriority Priority; public double Time; } readonly List<Item> _items = new List<Item>(); readonly Dictionary<string, double> _lastSaid = new Dictionary<string, double>(StringComparer.OrdinalIgnoreCase); double _nextFree = double.NegativeInfinity; public double Gap { get; set; } = 1.5; // seconds between announcements public double DuplicateWindow { get; set; } = 4.0; // same text again within this is dropped public double LowExpiry { get; set; } = 3.0; // Low items older than this are discarded public int MaxQueued { get; set; } = 5; public int Count => _items.Count; public bool Enqueue(string text, AnnouncementPriority priority, double now) { if (string.IsNullOrWhiteSpace(text)) return false; if (_lastSaid.TryGetValue(text, out var t) && now - t < DuplicateWindow) return false; foreach (var i in _items) if (string.Equals(i.Text, text, StringComparison.OrdinalIgnoreCase)) return false; _items.Add(new Item { Text = text, Priority = priority, Time = now }); if (_items.Count > MaxQueued) DropLowest(); return true; } /// <summary>Returns the next announcement if one is due, otherwise null.</summary> public string Next(double now) { _items.RemoveAll(i => i.Priority == AnnouncementPriority.Low && now - i.Time > LowExpiry); if (_items.Count == 0 || now < _nextFree) return null; var best = 0; for (var i = 1; i < _items.Count; i++) if (_items[i].Priority > _items[best].Priority) best = i; // earliest wins ties var item = _items[best]; _items.RemoveAt(best); _lastSaid[item.Text] = now; _nextFree = now + Gap; return item.Text; } public void Clear() => _items.Clear(); void DropLowest() { var worst = 0; for (var i = 1; i < _items.Count; i++) if (_items[i].Priority < _items[worst].Priority) worst = i; // oldest of the lowest _items.RemoveAt(worst); } } ``` - **Gap**: at most one announcement every 1.5 s. - **Priority**: High goes first. Ties go to the oldest. - **Duplicates**: the same text (ignoring case) already queued, or said in the last 4 s, is dropped. Five "Picked up coin" in a row become one. - **Expiry**: Low items older than 3 s are discarded; "Picked up coin" is useless ten seconds later. - **Cap**: at most 5 waiting; when full, the lowest-priority, oldest item goes. `ScreenReaderService.Announce(text, priority)` feeds it, only while a reader is on. Keep announcements short and factual, and don't announce what the user just did themselves ("Button pressed"). Next: [[4. Game World Objects and Screen Coordinates]].