Skip to main content

egui_pop_core/
a11y.rs

1//! Accessibility helpers: names for custom widgets, and an announcer
2//! whose messages screen readers read out (an AccessKit live region).
3//!
4//! ```
5//! use egui_pop_core::a11y::{self, Politeness};
6//!
7//! let ctx = egui::Context::default();
8//! a11y::announce(&ctx, "Saved", Politeness::Polite);
9//! assert_eq!(a11y::announcements(&ctx)[0].text, "Saved");
10//! ```
11
12use egui::accesskit::{Live, Role};
13use egui::{Context, Id, Response, Ui, WidgetInfo};
14use serde::Serialize;
15
16use crate::state::{lock, pass, shared};
17
18/// Names the window's root node after the window's title, each pass: a
19/// screen reader says that name when the focus lands on the window itself
20/// (a dialog closed, Tab past the last stop), not a bare "frame". Run for
21/// every window by the focus plugin (`focus::install`).
22pub(crate) fn name_window(ctx: &Context) {
23    let Some(title) = ctx
24        .input(|i| i.viewport().title.clone())
25        .filter(|t| !t.is_empty())
26    else {
27        return;
28    };
29    ctx.accesskit_node_builder(egui::accesskit_root_id(), |node| node.set_label(title));
30}
31
32/// Gives a custom widget its role and accessible name.
33pub fn name(response: &Response, kind: Role, label: &str) {
34    let enabled = response.enabled();
35    let label = label.to_string();
36    response.widget_info(move || WidgetInfo::labeled(kind, enabled, &label));
37}
38
39/// The input bricks drawn, pass by pass.
40#[derive(Debug, Default)]
41struct Inputs {
42    pass: u64,
43    building: Vec<Id>,
44    last: Vec<Id>,
45}
46
47fn rotate(ctx: &Context, s: &mut Inputs) {
48    let now = pass(ctx);
49    if s.pass != now {
50        s.pass = now;
51        s.last = std::mem::take(&mut s.building);
52    }
53}
54
55/// Names an input brick (a text input, a number input, a slider, a
56/// descriptor's drop-down) by its own `label`, so assistive technologies
57/// read a name whether or not its caller also points it at a label drawn
58/// beside it (`labelled_by`), and records it as drawn this pass, its node
59/// `id`, for the check that every one has a name ([`inputs`]).
60///
61/// A blank label leaves the brick without a name: a debug build stops on
62/// it (give the brick its label); a release build records it unnamed, and
63/// the test kit's `assert_inputs_named` lists it.
64pub fn input(ctx: &Context, id: Id, label: &str) {
65    let named = !label.trim().is_empty();
66    debug_assert!(
67        named,
68        "an input brick without a name ({id:?}): give it a label, which screen readers say"
69    );
70    if named {
71        let label = label.to_string();
72        ctx.accesskit_node_builder(id, |n| n.set_label(label));
73    }
74    drawn(ctx, id);
75}
76
77/// Records an input brick named otherwise (a range's thumbs, each by its
78/// end) as drawn this pass, for [`inputs`].
79pub(crate) fn drawn(ctx: &Context, id: Id) {
80    let st = shared::<Inputs>(ctx, "core.a11y.inputs");
81    let mut s = lock(&st);
82    rotate(ctx, &mut s);
83    s.building.push(id);
84}
85
86/// The input bricks drawn in the last complete pass, by node id: what a
87/// test checks has a name of its own.
88pub fn inputs(ctx: &Context) -> Vec<Id> {
89    let st = shared::<Inputs>(ctx, "core.a11y.inputs");
90    let mut s = lock(&st);
91    rotate(ctx, &mut s);
92    s.last.clone()
93}
94
95/// How urgently a message is read.
96#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
97#[serde(rename_all = "lowercase")]
98pub enum Politeness {
99    /// When the reader is idle.
100    Polite,
101    /// At once, interrupting.
102    Assertive,
103}
104
105/// One message.
106#[derive(Clone, Debug, PartialEq, Serialize)]
107pub struct Announcement {
108    pub text: String,
109    pub politeness: Politeness,
110    /// Input time it was made at, in seconds.
111    pub time: f64,
112}
113
114#[derive(Debug, Default)]
115struct State {
116    all: Vec<Announcement>,
117    /// How many messages each politeness was given (polite, assertive),
118    /// never trimmed: its parity marks a repeat.
119    made: [u64; 2],
120}
121
122/// The mark a region's text alternates with, so the same text announced
123/// twice in a row still changes the region: a no-break space at its end,
124/// which readers do not say.
125const REPEAT_MARK: char = '\u{a0}';
126
127/// How many announcements are kept.
128pub const KEPT: usize = 32;
129
130/// Queues a message for screen readers.
131pub fn announce(ctx: &Context, text: impl Into<String>, politeness: Politeness) {
132    let time = ctx.input(|i| i.time);
133    let st = shared::<State>(ctx, "core.a11y");
134    let mut s = lock(&st);
135    s.made[usize::from(politeness == Politeness::Assertive)] += 1;
136    s.all.push(Announcement {
137        text: text.into(),
138        politeness,
139        time,
140    });
141    let len = s.all.len();
142    if len > KEPT {
143        s.all.drain(..len - KEPT);
144    }
145    ctx.request_repaint();
146}
147
148/// The messages kept, oldest first.
149pub fn announcements(ctx: &Context) -> Vec<Announcement> {
150    let st = shared::<State>(ctx, "core.a11y");
151    lock(&st).all.clone()
152}
153
154/// Draws the live regions (one polite, one assertive) holding the latest
155/// messages. Invisible; call it once per pass, anywhere (the app shell
156/// does). Every other message of a region ends with an invisible no-break
157/// space, so the same text announced twice in a row changes the region
158/// and is read twice.
159pub fn live_regions(ui: &mut Ui) {
160    let (all, made) = {
161        let st = shared::<State>(ui.ctx(), "core.a11y");
162        let s = lock(&st);
163        (s.all.clone(), s.made)
164    };
165    for (politeness, live, salt) in [
166        (Politeness::Polite, Live::Polite, "polite"),
167        (Politeness::Assertive, Live::Assertive, "assertive"),
168    ] {
169        let mut text = all
170            .iter()
171            .rev()
172            .find(|a| a.politeness == politeness)
173            .map(|a| a.text.clone())
174            .unwrap_or_default();
175        if made[usize::from(politeness == Politeness::Assertive)] % 2 == 0 && !text.is_empty() {
176            text.push(REPEAT_MARK);
177        }
178        let id = ui.scope_id().with(("egui_pop_live_region", salt));
179        let (rect, _) = ui.allocate_exact_size(egui::Vec2::ZERO, egui::Sense::hover());
180        let _ = rect;
181        ui.ctx().accesskit_node_builder(id, |node| {
182            node.set_role(Role::Status);
183            node.set_live(live);
184            node.set_label(text);
185        });
186    }
187}