Skip to main content

document_session_api/
a11y.rs

1// Copyright 2026 Mark Alan Boykin
2// This Source Code Form is subject to the terms of the Mozilla Public
3// License, v. 2.0. If a copy of the MPL was not distributed with this
4// file, You can obtain one at https://mozilla.org/MPL/2.0/.
5// SPDX-License-Identifier: MPL-2.0
6
7//! Accessibility contract — the invariant every content surface declares about
8//! what it can expose to the accessibility tree, plus the renderer-neutral
9//! document projection that carries those semantics to a host.
10//!
11//! Adopted from the donor `graphshell` `SUBSYSTEM_ACCESSIBILITY.md` (per the
12//! [docs harvest](../../../../design_docs/mere_docs/research/2026-05-27_graphshell_docs_full_harvest.md)
13//! §1 and the [adoption roadmap](../../../../design_docs/mere_docs/implementation_strategy/2026-05-27_adoption_roadmap.md)
14//! R0). This is the **contract** (the rule), not the full a11y implementation;
15//! the host's AccessKit bridge (platen domains → uxtree) consumes it when the
16//! a11y slice lands.
17//!
18//! ## The three invariants
19//!
20//! 1. **Capability-declaration** — every engine/surface declares its
21//!    [`A11yCapability`] in *one* place (`a11y_capability` /
22//!    `a11y_capability`). The host never guesses a
23//!    surface's accessibility from its kind; it reads the declaration.
24//! 2. **Non-silent-degradation** — a surface that cannot expose its content
25//!    *must* declare a lower capability ([`A11yCapability::Partial`] /
26//!    [`A11yCapability::Opaque`]). It must never present as [`A11yCapability::Full`]
27//!    while silently dropping semantics. Degradation is *declared*, never silent —
28//!    so the host can surface "you can't inspect inside this" honestly (cf. the
29//!    [scrying DOM-bridge brief](../../../../genet/docs/2026-05-26_scrying_dom_bridge.md),
30//!    which lifts a WebView tile from `Opaque` toward `Partial`).
31//! 3. **Cross-surface-parity** — every engine speaks this *one* vocabulary, so
32//!    the host treats accessibility uniformly regardless of which engine backs a
33//!    tile (a nematic document, a Genet page, a scrying WebView).
34
35/// Optional platform spelling bridge; the default contract remains renderer-neutral.
36#[cfg(feature = "accesskit")]
37mod accesskit_roles;
38#[cfg(feature = "accesskit")]
39pub use accesskit_roles::{accesskit_aria_role, accesskit_role_token};
40
41use serde::{Deserialize, Serialize};
42
43/// Stable, document-local semantic identity.
44///
45/// An engine retains this identity for the same semantic object while a
46/// session is live. Hosts must namespace it with their own tile/session
47/// identity before lowering it into a global accessibility tree.
48#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
49#[repr(transparent)]
50pub struct DocumentA11yNodeId(u64);
51
52impl DocumentA11yNodeId {
53    /// Creates an engine-local identity. The numeric value has no host-global
54    /// meaning and is never an AccessKit node id.
55    pub const fn new(value: u64) -> Self {
56        Self(value)
57    }
58
59    /// Returns the engine-local identity for storage or deterministic tests.
60    pub const fn get(self) -> u64 {
61        self.0
62    }
63}
64
65/// A point in the final, current document-session viewport coordinate space.
66///
67/// Engines apply their own document zoom before returning this value. Hosts
68/// may place it directly in their viewport transform, but retain ownership of
69/// any outer tile transform.
70#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
71pub struct DocumentA11yPoint {
72    pub x: f32,
73    pub y: f32,
74}
75
76/// Bounds in the final, current document-session viewport coordinate space.
77///
78/// Engines apply their own document zoom before returning these bounds.
79/// Structural nodes may have no bounds. A host must not invent geometry for
80/// those nodes from a differently timed paint frame.
81#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
82pub struct DocumentA11yBounds {
83    pub x: f32,
84    pub y: f32,
85    pub width: f32,
86    pub height: f32,
87}
88
89/// Semantic role vocabulary shared by retained document engines.
90///
91/// This deliberately describes document semantics rather than mirroring any
92/// particular platform accessibility API. A host owns its platform lowering.
93#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
94pub enum DocumentA11yRole {
95    Window,
96    Document,
97    Article,
98    Region,
99    Group,
100    Navigation,
101    Main,
102    Heading { level: u8 },
103    Paragraph,
104    StaticText,
105    Link,
106    Button,
107    TextField,
108    CheckBox,
109    RadioButton,
110    RadioGroup,
111    Switch,
112    ComboBox,
113    List,
114    ListItem,
115    ListBox,
116    ListBoxOption,
117    Table,
118    Row,
119    Cell,
120    Image,
121    Form,
122    Dialog,
123    Alert,
124    Menu,
125    MenuBar,
126    MenuItem,
127    MenuItemCheckBox,
128    MenuItemRadio,
129    TabList,
130    Tab,
131    TabPanel,
132    Tree,
133    TreeItem,
134    Slider,
135    SpinButton,
136    Splitter,
137    Toolbar,
138    ProgressIndicator,
139    Label,
140    Status,
141    Log,
142    Note,
143    Unknown,
144}
145
146/// Announcement priority for live regions.
147#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
148pub enum DocumentA11yLive {
149    Off,
150    Polite,
151    Assertive,
152}
153
154/// The three-value state used by switch and toggle controls.
155#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
156pub enum DocumentA11yToggled {
157    Off,
158    On,
159    Mixed,
160}
161
162/// The primary direction of an oriented control or container.
163#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
164pub enum DocumentA11yOrientation {
165    Horizontal,
166    Vertical,
167}
168
169/// The kind of popup a semantic node can present.
170#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
171pub enum DocumentA11yHasPopup {
172    Menu,
173    ListBox,
174    Tree,
175    Grid,
176    Dialog,
177}
178
179/// Platform-neutral state for one semantic node.
180#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
181pub struct DocumentA11yState {
182    pub disabled: bool,
183    pub hidden: bool,
184    pub selected: Option<bool>,
185    pub expanded: Option<bool>,
186    pub checked: Option<bool>,
187    pub toggled: Option<DocumentA11yToggled>,
188    pub focused: bool,
189    pub editable: bool,
190    pub multiline: bool,
191    pub read_only: bool,
192    pub required: bool,
193    /// `None` preserves the absence of a live-region declaration; `Off` is
194    /// an explicit declaration with distinct source semantics.
195    pub live: Option<DocumentA11yLive>,
196    pub orientation: Option<DocumentA11yOrientation>,
197    pub has_popup: Option<DocumentA11yHasPopup>,
198}
199
200/// An action the engine advertises for a semantic node.
201///
202/// `Click` remains a pointer action: hosts obtain a fresh
203/// [`DocumentA11yClickTarget`] and drive their ordinary pointer path. The
204/// remaining actions dispatch through [`crate::DocumentSession`].
205#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
206pub enum DocumentA11yAction {
207    Click,
208    Focus,
209    SetValue,
210    ScrollIntoView,
211    Increment,
212    Decrement,
213}
214
215/// Data carried by an accessibility action request.
216#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
217pub enum DocumentA11yActionData {
218    Value(String),
219}
220
221/// A host request addressed to one local semantic node.
222///
223/// Engines must revalidate `revision`, `target`, and that the requested
224/// action is advertised by their current projection before mutating state.
225#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
226pub struct DocumentA11yActionRequest {
227    pub revision: u64,
228    pub target: DocumentA11yNodeId,
229    pub action: DocumentA11yAction,
230    pub data: Option<DocumentA11yActionData>,
231}
232
233/// A current, revalidated point at which a host may issue its ordinary click
234/// path. `revision` makes a stale geometry observation detectable.
235#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
236pub struct DocumentA11yClickTarget {
237    pub revision: u64,
238    pub point: DocumentA11yPoint,
239}
240
241/// One semantic node in a renderer-neutral document projection.
242#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
243pub struct DocumentA11yNode {
244    pub id: DocumentA11yNodeId,
245    pub parent: Option<DocumentA11yNodeId>,
246    /// Ordered local child identities. This is authoritative for traversal;
247    /// `parent` is retained for efficient reverse lookup and validation.
248    pub children: Vec<DocumentA11yNodeId>,
249    pub role: DocumentA11yRole,
250    pub name: Option<String>,
251    /// Supplemental text, separate from the control name and current value.
252    #[serde(default)]
253    pub description: Option<String>,
254    pub value: Option<String>,
255    pub numeric_value: Option<f64>,
256    pub numeric_minimum: Option<f64>,
257    pub numeric_maximum: Option<f64>,
258    pub bounds: Option<DocumentA11yBounds>,
259    pub state: DocumentA11yState,
260    pub actions: Vec<DocumentA11yAction>,
261}
262
263/// Why a projection cannot claim complete semantic coverage.
264#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
265pub enum DocumentA11ySupportError {
266    MissingLimitation { capability: A11yCapability },
267}
268
269impl std::fmt::Display for DocumentA11ySupportError {
270    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
271        match self {
272            Self::MissingLimitation { capability } => {
273                write!(
274                    f,
275                    "{capability:?} accessibility support requires a limitation"
276                )
277            },
278        }
279    }
280}
281
282impl std::error::Error for DocumentA11ySupportError {}
283
284/// Coverage and explicit limitations of an accessibility projection.
285///
286/// A partial projection cannot be constructed without a non-blank limitation,
287/// so hosts can describe its aperture honestly. The projection's support is
288/// the live source of truth; an engine's registration-time capability remains
289/// only a pre-spawn declaration.
290#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
291pub struct DocumentA11ySupport {
292    capability: A11yCapability,
293    limitations: Vec<String>,
294}
295
296impl DocumentA11ySupport {
297    pub fn new(
298        capability: A11yCapability,
299        limitations: impl IntoIterator<Item = impl Into<String>>,
300    ) -> Result<Self, DocumentA11ySupportError> {
301        let limitations = limitations
302            .into_iter()
303            .map(Into::into)
304            .filter(|limitation: &String| !limitation.trim().is_empty())
305            .collect::<Vec<_>>();
306        if capability == A11yCapability::Partial && limitations.is_empty() {
307            return Err(DocumentA11ySupportError::MissingLimitation { capability });
308        }
309        Ok(Self {
310            capability,
311            limitations,
312        })
313    }
314
315    pub fn capability(&self) -> A11yCapability {
316        self.capability
317    }
318
319    pub fn limitations(&self) -> &[String] {
320        &self.limitations
321    }
322}
323
324/// Renderer-neutral semantic snapshot of the current retained document.
325///
326/// `revision` increases whenever geometry, state, or actions observable
327/// through this projection change. A semantic object's local ID remains stable
328/// across revisions for the lifetime of that object; the revision instead
329/// scopes an observation and its action requests, allowing an engine to reject
330/// stale host observations.
331#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
332pub struct DocumentA11yProjection {
333    revision: u64,
334    support: DocumentA11ySupport,
335    root: DocumentA11yNodeId,
336    nodes: Vec<DocumentA11yNode>,
337}
338
339impl DocumentA11yProjection {
340    pub fn new(
341        revision: u64,
342        support: DocumentA11ySupport,
343        root: DocumentA11yNodeId,
344        nodes: Vec<DocumentA11yNode>,
345    ) -> Self {
346        Self {
347            revision,
348            support,
349            root,
350            nodes,
351        }
352    }
353
354    pub const fn revision(&self) -> u64 {
355        self.revision
356    }
357
358    pub fn support(&self) -> &DocumentA11ySupport {
359        &self.support
360    }
361
362    pub const fn root(&self) -> DocumentA11yNodeId {
363        self.root
364    }
365
366    pub fn nodes(&self) -> &[DocumentA11yNode] {
367        &self.nodes
368    }
369
370    pub fn node(&self, id: DocumentA11yNodeId) -> Option<&DocumentA11yNode> {
371        self.nodes.iter().find(|node| node.id == id)
372    }
373}
374
375/// What a content surface can expose to the accessibility tree. The single
376/// vocabulary all engines/surfaces speak (invariant 3). Ordered worst-to-best
377/// so capability can be compared / clamped.
378#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
379pub enum A11yCapability {
380    /// No semantic content the host can expose — a raw GPU surface or an opaque
381    /// system WebView. The host surfaces this honestly (a labelled region with
382    /// "contents not inspectable"), never as if it were [`Self::Full`]. Default
383    /// for `SurfaceEngine` (frame-streaming surfaces are opaque until
384    /// they bridge their content).
385    Opaque,
386    /// Some structure available — e.g. a bridged WebView exposing a DOM
387    /// projection (links / headings / text) but not full ARIA, or a
388    /// partially-modelled document.
389    Partial,
390    /// A complete semantic tree (headings, links, roles, text). Default for
391    /// document `Engine`s: their `EngineDocument` blocks *are*
392    /// the semantic content, so they are accessible by construction.
393    Full,
394}
395
396impl A11yCapability {
397    /// Whether the host can build any semantic accessibility nodes from this
398    /// surface (everything but [`Self::Opaque`]).
399    pub fn is_inspectable(self) -> bool {
400        self != Self::Opaque
401    }
402}
403
404#[cfg(test)]
405mod tests {
406    use super::*;
407
408    fn document_node(id: u64) -> DocumentA11yNode {
409        DocumentA11yNode {
410            id: DocumentA11yNodeId::new(id),
411            parent: None,
412            children: Vec::new(),
413            role: DocumentA11yRole::Document,
414            description: None,
415            name: Some("Example".into()),
416            value: None,
417            numeric_value: None,
418            numeric_minimum: None,
419            numeric_maximum: None,
420            bounds: Some(DocumentA11yBounds {
421                x: 0.0,
422                y: 0.0,
423                width: 800.0,
424                height: 600.0,
425            }),
426            state: DocumentA11yState::default(),
427            actions: vec![DocumentA11yAction::Focus],
428        }
429    }
430
431    #[test]
432    fn partial_support_requires_a_specific_limitation() {
433        assert_eq!(
434            DocumentA11ySupport::new(A11yCapability::Partial, ["", "   "])
435                .expect_err("partial support must explain its aperture"),
436            DocumentA11ySupportError::MissingLimitation {
437                capability: A11yCapability::Partial
438            }
439        );
440
441        let support = DocumentA11ySupport::new(
442            A11yCapability::Partial,
443            ["visible links are exposed; activation is unavailable"],
444        )
445        .expect("specific limitation makes partial support honest");
446        assert_eq!(support.capability(), A11yCapability::Partial);
447        assert_eq!(support.limitations().len(), 1);
448    }
449
450    #[test]
451    fn projection_carries_stable_local_ids_revision_and_semantics() {
452        let root = DocumentA11yNodeId::new(41);
453        let projection = DocumentA11yProjection::new(
454            9,
455            DocumentA11ySupport::new(A11yCapability::Full, std::iter::empty::<String>())
456                .expect("full support needs no limitation"),
457            root,
458            vec![document_node(root.get())],
459        );
460
461        assert_eq!(projection.revision(), 9);
462        assert_eq!(projection.root(), root);
463        let node = projection
464            .node(root)
465            .expect("local root remains addressable");
466        assert_eq!(node.role, DocumentA11yRole::Document);
467        assert_eq!(node.name.as_deref(), Some("Example"));
468        assert_eq!(node.state.live, None, "absence differs from explicit Off");
469        assert_eq!(node.actions, vec![DocumentA11yAction::Focus]);
470        assert_eq!(projection.support().capability(), A11yCapability::Full);
471    }
472}