Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

raea's window publishes the page's accessibility tree to the OS

shinyobjectz13cc0d7eb588
diff --git a/Cargo.lock b/Cargo.lock
index 2985c7e0..2a1279bd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -14889,6 +14889,7 @@ dependencies = [
name = "raea-page-host"
version = "0.1.0"
dependencies = [
+ "accesskit 0.24.1",
"base64 0.22.1",
"bevy",
"blitz-dom",
diff --git a/engine/page/host/Cargo.toml b/engine/page/host/Cargo.toml
index ff275737..6e6990b2 100644
--- a/engine/page/host/Cargo.toml
+++ b/engine/page/host/Cargo.toml
@@ -18,7 +18,7 @@ path = "src/main.rs"
# the page on QuickJS (raea-runtime-js's portable engine) in place of JavaScriptCore
portable = ["raea-runtime-js/portable"]
# raea's window on screen (--window: the desktop app, docs/app.feature AP5/AP6); the benches and tests stay headless
-window = ["bevy/bevy_winit", "dep:raea-runtime-plugins", "raea-page-window/window"]
+window = ["bevy/bevy_winit", "dep:raea-runtime-plugins", "raea-page-window/window", "dep:accesskit"]
[dependencies]
raea-io-trace = { path = "../../../io/trace" }
@@ -28,6 +28,8 @@ bevy = { version = "=0.20.0", default-features = false, features = ["std", "defa
raea-runtime-js = { path = "../../../runtime/js" }
# the page's accessibility records
raea-sys-a11y = { path = "../../../systems/a11y" }
+# the window's accessibility tree (ax.rs): the AccessKit Bevy's winit adapter takes, its version exactly
+accesskit = { version = "=0.24.1", default-features = false, optional = true }
raea-page = { path = ".." }
# the desktop window: --chrome and the native calls (clipboard, links, notifications, the dock badge, raea:// links)
raea-page-window = { path = "../window" }
diff --git a/engine/page/host/src/ax.rs b/engine/page/host/src/ax.rs
new file mode 100644
index 00000000..9fc0c303
--- /dev/null
+++ b/engine/page/host/src/ax.rs
@@ -0,0 +1,231 @@
+//! The page's accessibility tree published to the OS (raea's window, the `window` feature): VoiceOver and macOS
+//! accessibility clients (an AX test driving raea.app, Accessibility Inspector) read every element of the page as
+//! AccessKit has it, by raea-sys-a11y's computation (the role, name and states Chrome gives the same markup), with its
+//! box. Bevy's winit adapter carries it: Bevy's own tree (its UI entities' AccessibilityNode) is turned off
+//! (ManageAccessibilityUpdates), and this sends the page's instead, while a client is listening (AccessibilityRequested)
+//! and at most every 250 ms. An action a client asks of an element comes back as the input a person would give:
+//! Click and SetValue press the element's middle (a pointer down and up, as the MCP input tool queues them), and
+//! SetValue then types its text over what the field held.
+//!
+//! The tree is the Blitz document's own, walked from its root: an element's attributes are its props, and React's
+//! props over them where the element came from React (the wire's ids). A page's markup set as HTML (innerHTML: raea
+//! cloud's dashboard builds its rail so) has no wire ids, and the BRP `a11y` method's elements (page.rs) leave it out.
+use std::cell::RefCell;
+use std::collections::{HashMap, HashSet};
+use std::time::{Duration, Instant};
+
+use accesskit::{Action, ActionData, NodeId};
+use bevy::a11y::{AccessibilityRequested, ActionRequest, ManageAccessibilityUpdates};
+use bevy::ecs::system::SystemState;
+use bevy::prelude::*;
+use bevy::window::PrimaryWindow;
+use bevy::winit::accessibility::ACCESS_KIT_ADAPTERS;
+use blitz_dom::{BaseDocument, Node, NodeId as Id};
+use raea_sys_a11y::El;
+use raea_sys_page::ops::Nodes;
+use serde_json::{Map, Value, json};
+
+use crate::inject::{Frame, Pending};
+
+/// A page node's AccessKit id: its Blitz id (slot and version) with the top bit set, clear of the window entity's
+/// (Entity::to_bits: its generation never reaches it, nor does a Blitz slot's version)
+const PAGE: u64 = 1 << 63;
+const EVERY: Duration = Duration::from_millis(250);
+/// what a page never draws, and an assistive client has no use for
+const UNDRAWN: &[&str] = &["head", "script", "style", "template", "noscript", "link", "meta", "title"];
+
+pub struct AxPlugin;
+
+#[derive(Resource, Default)]
+struct Ax {
+ last: Option<Instant>,
+ /// the frame last sent: a window at rest draws none, and has nothing new to say
+ frame: u64,
+}
+
+impl Plugin for AxPlugin {
+ fn build(&self, app: &mut App) {
+ let mut manage = ManageAccessibilityUpdates::default();
+ manage.set(false);
+ app.insert_resource(manage).init_resource::<Ax>().add_systems(PostUpdate, (act, publish).chain());
+ }
+}
+
+/// The page's tree sent to the window's adapter, while a client listens.
+fn publish(world: &mut World) {
+ let listening = world.get_resource::<AccessibilityRequested>().is_some_and(|r| r.get());
+ if world.get_resource::<crate::idle::Listening>().is_none_or(|l| l.0 != listening) {
+ world.insert_resource(crate::idle::Listening(listening));
+ }
+ if !listening {
+ return;
+ }
+ let (now, frame) = (Instant::now(), world.resource::<Frame>().0);
+ let ax = world.resource::<Ax>();
+ if ax.frame == frame || ax.last.is_some_and(|t| now - t < EVERY) {
+ return;
+ }
+ let Ok((win, w)) = world.query_filtered::<(Entity, &Window), With<PrimaryWindow>>().single(world) else { return };
+ let (scale, title) = (w.scale_factor() as f64, w.title.clone());
+ let root = NodeId(win.to_bits());
+ let Some(update) = crate::page::with_doc(world, |doc, nodes| {
+ let (els, tops) = elements(doc, nodes);
+ let facts = Facts { doc, nodes };
+ let focus = doc.get_focussed_node_id().filter(|f| els.contains_key(f));
+ let memo = RefCell::new(blitz_dom::RectMemo::default());
+ // in the window's physical pixels, as Bevy's own nodes are
+ let bounds = |k: Id| {
+ let b = doc.get_client_bounding_rect_in(element(doc, k)?, &mut memo.borrow_mut())?;
+ Some([b.x * scale, b.y * scale, (b.x + b.width) * scale, (b.y + b.height) * scale])
+ };
+ raea_sys_a11y::tree(els, tops, &facts, focus, |k| k.as_u64() | PAGE, root, Some(&title), bounds).0
+ }) else {
+ return;
+ };
+ ACCESS_KIT_ADAPTERS.with_borrow_mut(|adapters| {
+ if let Some(a) = adapters.get_mut(&win) {
+ a.update_if_active(|| update);
+ }
+ });
+ let mut ax = world.resource_mut::<Ax>();
+ (ax.last, ax.frame) = (Some(now), frame);
+}
+
+/// The document's drawn nodes, from its root: elements with their attributes (React's props over them) and text.
+/// One document: every node shares one root for `id` lookups.
+fn elements(doc: &BaseDocument, nodes: &Nodes) -> (HashMap<Id, El<Id>>, HashMap<Id, Id>) {
+ let mut els = HashMap::new();
+ // from the document's root, and from any React tree drawn apart from it (a layer whose top isn't the document:
+ // raea.app's welcome over the dashboard), each top once
+ let root = doc.root_node().id;
+ let mut apart = std::collections::BTreeSet::new();
+ for &n in nodes.by_id.values() {
+ let mut top = n;
+ while let Some(p) = doc.get_node(top).and_then(|t| t.parent) {
+ top = p;
+ }
+ if top != root && doc.get_node(top).is_some() {
+ apart.insert(top.as_u64());
+ }
+ }
+ let mut stack: Vec<(Id, Option<Id>)> = apart.iter().rev().map(|t| (Id::from_u64(*t), None)).collect();
+ stack.extend(doc.root_node().children.iter().rev().map(|c| (*c, None)));
+ while let Some((k, parent)) = stack.pop() {
+ let Some(n) = doc.get_node(k) else { continue };
+ let el = if n.is_text_node() {
+ El { tag: "text".into(), props: Map::new(), parent, kids: vec![], text: Some(n.text_content()), title: None }
+ } else if let Some(e) = n.element_data() {
+ let tag = e.name.local.to_string();
+ if UNDRAWN.contains(&tag.as_str()) {
+ continue;
+ }
+ let mut props: Map<String, Value> = e.attrs().iter().map(|a| (a.name.local.to_string(), Value::String(a.value.to_string()))).collect();
+ // the computation reads React's spelling
+ if let Some(t) = props.remove("tabindex") {
+ props.insert("tabIndex".into(), t);
+ }
+ let wire = nodes.id_of(k);
+ if let Some(p) = wire.and_then(|id| nodes.props.get(&id)) {
+ props.extend(p.iter().map(|(k, v)| (k.clone(), v.clone())));
+ }
+ let tag = match wire.and_then(|id| nodes.kind(id)) {
+ Some("editableText") if props.get("multiline") == Some(&Value::Bool(true)) => "textarea".into(),
+ Some("editableText") => "input".into(),
+ _ => tag,
+ };
+ let title = (tag == "svg")
+ .then(|| n.children.iter().filter_map(|c| doc.get_node(*c)).find(|c| c.element_data().is_some_and(|e| &*e.name.local == "title")).map(|t| t.text_content()))
+ .flatten();
+ let kids: Vec<Id> = n.children.iter().copied().filter(|c| doc.get_node(*c).is_some_and(|c| c.is_text_node() || c.is_element())).collect();
+ stack.extend(kids.iter().map(|c| (*c, Some(k))));
+ El { tag, props, parent, kids, text: None, title }
+ } else {
+ continue;
+ };
+ els.insert(k, el);
+ }
+ // a kid left out (an undrawn element) is no kid
+ let have: HashSet<Id> = els.keys().copied().collect();
+ for el in els.values_mut() {
+ el.kids.retain(|c| have.contains(c));
+ }
+ let tops = els.keys().map(|k| (*k, Id::default())).collect();
+ (els, tops)
+}
+
+/// What the computation asks of the Blitz document: its computed style and its controls' state, by Blitz id.
+struct Facts<'a> {
+ doc: &'a BaseDocument,
+ nodes: &'a Nodes,
+}
+
+impl Facts<'_> {
+ fn el(&self, k: Id) -> Option<&Node> {
+ self.doc.get_node(k).filter(|n| n.is_element())
+ }
+}
+
+impl raea_sys_a11y::Facts<Id> for Facts<'_> {
+ fn display_none(&self, k: Id) -> bool {
+ // an element with no style isn't laid out (it or an ancestor is display: none, or it was never styled)
+ self.el(k).is_some_and(|n| n.primary_styles().is_none_or(|s| s.get_box().display.is_none()))
+ }
+ fn invisible(&self, k: Id) -> bool {
+ use style::computed_values::visibility::T as V;
+ self.el(k).and_then(|n| n.primary_styles()).is_some_and(|s| matches!(s.clone_visibility(), V::Hidden | V::Collapse))
+ }
+ fn natively_disabled(&self, _: Id) -> bool {
+ false
+ }
+ fn editor_value(&self, k: Id) -> Option<String> {
+ self.el(k).and_then(|n| n.element_data()).and_then(|e| e.text_input_data()).map(|t| t.editor.raw_text().to_string())
+ }
+ fn tabbable(&self, k: Id) -> bool {
+ self.el(k).is_some_and(|n| n.is_focussable())
+ }
+ fn checked(&self, k: Id) -> bool {
+ self.el(k).and_then(|n| n.element_data()).and_then(|e| e.checkbox_input_checked()).unwrap_or(false)
+ }
+ fn test_id(&self, k: Id) -> Option<String> {
+ let wire = self.nodes.id_of(k).and_then(|id| self.nodes.props.get(&id)).and_then(|p| p.get("data-testid")).and_then(Value::as_str).map(str::to_string);
+ wire.or_else(|| self.el(k)?.element_data()?.attrs().iter().find(|a| &*a.name.local == "data-testid").map(|a| a.value.to_string()))
+ }
+}
+
+/// A Blitz node when it's an element: only an element has a box to ask for (Blitz panics asking a text node's
+/// transform, which the rect's walk does: the first raea.app the AX test drove quit on its welcome, 11-23)
+fn element(doc: &BaseDocument, k: Id) -> Option<Id> {
+ doc.get_node(k).is_some_and(|n| n.is_element()).then_some(k)
+}
+
+/// What clients asked of the page's elements, as input: a press at the element's middle (and SetValue's text typed).
+fn act(world: &mut World, reader: &mut SystemState<MessageReader<ActionRequest>>) {
+ let Ok(mut r) = reader.get_mut(world) else { return };
+ let asks: Vec<accesskit::ActionRequest> = r.read().map(|r| r.0.clone()).collect();
+ for ask in asks {
+ let Some(k) = (ask.target_node.0 & PAGE != 0).then(|| Id::from_u64(ask.target_node.0 & !PAGE)) else { continue };
+ // Focus is no press: macOS asks it beside a press (AXPress), and a second press where the first one's new page
+ // has something else clicked that (a press on Projects opened Publishing, 11-23)
+ if !matches!(ask.action, Action::Click | Action::SetValue) {
+ continue;
+ }
+ // a text node is pressed where its element is
+ let at = crate::page::with_doc(world, |doc, _| {
+ let k = element(doc, k).or_else(|| doc.get_node(k)?.parent)?;
+ let b = doc.get_client_bounding_rect(element(doc, k)?)?;
+ (b.width > 0.0 && b.height > 0.0).then(|| (b.x + b.width / 2.0, b.y + b.height / 2.0))
+ })
+ .flatten();
+ let Some((x, y)) = at else { continue };
+ let next = world.resource::<Frame>().0 + 1;
+ let mut p = world.resource_mut::<Pending>();
+ p.queue(json!({"type": "down", "x": x, "y": y}), next);
+ let mut last = p.queue(json!({"type": "up", "x": x, "y": y}), next);
+ if let (Action::SetValue, Some(ActionData::Value(v))) = (ask.action, &ask.data) {
+ // what the field held selected, then the new text over it
+ p.queue(json!({"type": "key", "key": "a", "mods": [if cfg!(target_os = "macos") { "cmd" } else { "ctrl" }]}), next);
+ last = p.queue(json!({"type": "text", "text": v.to_string()}), next);
+ }
+ crate::inject::LAST_INPUT.fetch_max(last, std::sync::atomic::Ordering::SeqCst);
+ }
+}
diff --git a/engine/page/host/src/idle.rs b/engine/page/host/src/idle.rs
index 40f8c5fa..ff74d929 100644
--- a/engine/page/host/src/idle.rs
+++ b/engine/page/host/src/idle.rs
@@ -11,6 +11,10 @@ use std::time::Duration;
use bevy::prelude::*;
use bevy::winit::{UpdateMode, WinitSettings};
+/// Whether an assistive client is listening to the window (ax.rs keeps it): the window then wakes for its presses.
+#[derive(Resource, Default)]
+pub struct Listening(pub bool);
+
/// Frames in a row with nothing drawn before the window rests.
const QUIET: u32 = 30;
@@ -22,13 +26,19 @@ impl Plugin for IdlePlugin {
}
}
-fn rest(settings: Option<ResMut<WinitSettings>>, docs: Option<NonSend<raea_sys_page::Docs>>, mut last: Local<u64>, mut quiet: Local<u32>) {
+fn rest(ax: Option<Res<Listening>>, settings: Option<ResMut<WinitSettings>>, docs: Option<NonSend<raea_sys_page::Docs>>, mut last: Local<u64>, mut quiet: Local<u32>) {
let Some(mut settings) = settings else { return };
+ let listening = ax.is_some_and(|a| a.0);
let drawn = raea_sys_page::DRAWS.load(std::sync::atomic::Ordering::Relaxed);
let moved = drawn != *last || docs.is_some_and(|d| d.0.values().any(|d| d.is_animating()));
*last = drawn;
*quiet = quieter(*quiet, moved);
- let (focused, unfocused) = modes(*quiet);
+ let (focused, mut unfocused) = modes(*quiet);
+ // an assistive client listening (VoiceOver, an AX test: ax.rs): its presses arrive as the event loop's user events,
+ // which a window behind others at rest doesn't wake for; it does now, as it would for a window event
+ if listening && let UpdateMode::Reactive { react_to_user_events, .. } = &mut unfocused {
+ *react_to_user_events = true;
+ }
if settings.focused_mode != focused || settings.unfocused_mode != unfocused {
settings.focused_mode = focused;
settings.unfocused_mode = unfocused;
diff --git a/engine/page/host/src/lib.rs b/engine/page/host/src/lib.rs
index 54cb50a3..408f1b11 100644
--- a/engine/page/host/src/lib.rs
+++ b/engine/page/host/src/lib.rs
@@ -4,6 +4,8 @@
//! Protocol (src/brp.rs: page.*) and an MCP bridge to it (src/mcp.rs). The bin (src/main.rs) mounts a bundle; an app
//! adds [`HostPlugin`] and mounts its own (page::mount), its systems around the host's.
+#[cfg(feature = "window")]
+pub mod ax;
pub mod brp;
/// the desktop window's chrome and native calls, in raea-page-window (kept under these names for main.rs and tests)
pub use raea_page_window::{chrome, native};
diff --git a/engine/page/host/src/main.rs b/engine/page/host/src/main.rs
index 59323869..3e32b217 100644
--- a/engine/page/host/src/main.rs
+++ b/engine/page/host/src/main.rs
@@ -123,6 +123,11 @@ fn main() {
if a.window && raea_io_home::setting("RAEA_IDLE_GATE").as_deref() != Some("0") {
app.add_plugins(raea_page_host::idle::IdlePlugin);
}
+ // on screen, the page's accessibility tree is the OS's (VoiceOver, macOS accessibility clients: raea_page_host::ax)
+ #[cfg(feature = "window")]
+ if a.window {
+ app.add_plugins(raea_page_host::ax::AxPlugin);
+ }
// on screen, bevy_winit's event loop is the runner (a ScheduleRunner here replaced it: no window, 11-04)
if !a.window && !app.is_plugin_added::<ScheduleRunnerPlugin>() {
// 60 frames a second, as most screens; RAEA_PAGE_FPS stands in for another screen's rate (a 120 Hz one, to
diff --git a/engine/page/host/src/page.rs b/engine/page/host/src/page.rs
index 8b366f19..73390bdd 100644
--- a/engine/page/host/src/page.rs
+++ b/engine/page/host/src/page.rs
@@ -319,16 +319,22 @@ impl raea_sys_a11y::Facts<u64> for Facts<'_> {
}
}
-/// The `a11y` method on the page: each element with a data-testid as AccessKit has it, by the computation bevy_ui's page
-/// uses (raea-runtime-js's a11y.rs), over the document's elements and the props React set on them.
-pub fn a11y(world: &mut World) -> Value {
- if !world.contains_resource::<HostPage>() {
- return json!({"nodes": {}});
- }
- let page = world.resource::<HostPage>().0;
+/// The page's Blitz document and its wire ids, for `f`. None before the page is up.
+pub fn with_doc<R>(world: &World, f: impl FnOnce(&blitz_dom::BaseDocument, &raea_sys_page::ops::Nodes) -> R) -> Option<R> {
+ let page = world.get_resource::<HostPage>()?.0;
+ let roots = world.non_send::<Roots>();
+ let docs = world.non_send::<Docs>();
+ let (r, doc) = (roots.0.iter().find(|r| r.page == page)?, docs.0.get(&page)?);
+ Some(f(doc, &r.nodes))
+}
+
+/// The page's elements as raea-sys-a11y reads them (by the wire's element ids), with what it asks of the document and
+/// where its focus is: `f` gets them, and the document for their boxes. None before the page is up.
+pub fn with_elements<R>(world: &World, f: impl FnOnce(std::collections::HashMap<u64, raea_sys_a11y::El<u64>>, std::collections::HashMap<u64, u64>, &dyn raea_sys_a11y::Facts<u64>, Option<u64>, &blitz_dom::BaseDocument, &raea_sys_page::ops::Nodes) -> R) -> Option<R> {
+ let page = world.get_resource::<HostPage>()?.0;
let roots = world.non_send::<Roots>();
let docs = world.non_send::<Docs>();
- let (Some(r), Some(doc)) = (roots.0.iter().find(|r| r.page == page), docs.0.get(&page)) else { return json!({"nodes": {}}) };
+ let (r, doc) = (roots.0.iter().find(|r| r.page == page)?, docs.0.get(&page)?);
let n = &r.nodes;
let mut els = std::collections::HashMap::new();
let mut tops = std::collections::HashMap::new();
@@ -352,7 +358,13 @@ pub fn a11y(world: &mut World) -> Value {
}
let facts = Facts { doc, nodes: n };
let focus = doc.get_focussed_node_id().and_then(|f| n.id_of(f));
- raea_sys_a11y::records(els, tops, &facts, focus, |k| k)
+ Some(f(els, tops, &facts, focus, doc, n))
+}
+
+/// The `a11y` method on the page: each element with a data-testid as AccessKit has it, by the computation bevy_ui's page
+/// uses (raea-runtime-js's a11y.rs), over the document's elements and the props React set on them.
+pub fn a11y(world: &mut World) -> Value {
+ with_elements(world, |els, tops, facts, focus, _, _| raea_sys_a11y::records(els, tops, facts, focus, |k| k)).unwrap_or_else(|| json!({"nodes": {}}))
}
/// The system's faces as Chrome on macOS has them (Times, Helvetica and Courier boosted, Menlo for monospace, CoreText's
diff --git a/systems/a11y/src/lib.rs b/systems/a11y/src/lib.rs
index 9303902b..1153ee9d 100644
--- a/systems/a11y/src/lib.rs
+++ b/systems/a11y/src/lib.rs
@@ -139,6 +139,16 @@ fn node_of<K: Copy + Eq + std::hash::Hash>(cx: &Ctx<K>, e: K, el: &El<K>, focus:
if focus == Some(e) {
n.add_action(Action::Focus);
}
+ // a control a press works: what VoiceOver's and an AX client's press asks for (macOS sends Click only to a node
+ // that has it; raea.app's window took no press on its links or buttons without it, 11-23)
+ if !disabled
+ && matches!(
+ role,
+ Role::Button | Role::Link | Role::CheckBox | Role::RadioButton | Role::Switch | Role::MenuItem | Role::MenuItemCheckBox | Role::MenuItemRadio | Role::Tab | Role::ListBoxOption | Role::TreeItem | Role::DisclosureTriangle | Role::ComboBox
+ )
+ {
+ n.add_action(Action::Click);
+ }
// checked: a checkbox or radio (its Checked), or aria-checked; pressed: aria-pressed on a button
let checkable = matches!(role, Role::CheckBox | Role::RadioButton | Role::Switch | Role::MenuItemCheckBox | Role::MenuItemRadio);
let tri = |v: Option<String>| match v.as_deref() {
@@ -225,10 +235,11 @@ fn node_of<K: Copy + Eq + std::hash::Hash>(cx: &Ctx<K>, e: K, el: &El<K>, focus:
n
}
-/// A page's elements (the Blitz page's, raea-page's host) as the parity harness's records, by test id, read through
-/// accesskit_consumer. `roots` is each element's root (whose `id`s it looks up), `id_of` its AccessKit id (not
-/// u64::MAX, the window's).
-pub fn records<K: Copy + Eq + std::hash::Hash>(els: HashMap<K, El<K>>, roots: HashMap<K, K>, facts: &dyn Facts<K>, focus: Option<K>, id_of: impl Fn(K) -> u64) -> Value {
+/// A page's elements as one AccessKit tree under `window` (its root, a Role::Window node): each element a node with its
+/// children, its box where `bounds` gives one ([x0, y0, x1, y1] in the root's space), and the elements with a test id
+/// beside it. raea's window publishes it to the OS (VoiceOver, macOS accessibility: raea-page-host's ax.rs); `records`
+/// reads it back for the parity harness. `id_of` must never give `window`.
+pub fn tree<K: Copy + Eq + std::hash::Hash>(els: HashMap<K, El<K>>, roots: HashMap<K, K>, facts: &dyn Facts<K>, focus: Option<K>, id_of: impl Fn(K) -> u64, window: NodeId, label: Option<&str>, bounds: impl Fn(K) -> Option<[f64; 4]>) -> (TreeUpdate, Vec<(String, NodeId)>) {
let mut ids = HashMap::new();
for (k, el) in &els {
if let (Some(id), Some(r)) = (el.props.get("id").and_then(|v| v.as_str()), roots.get(k)) {
@@ -236,17 +247,25 @@ pub fn records<K: Copy + Eq + std::hash::Hash>(els: HashMap<K, El<K>>, roots: Ha
}
}
let cx = Ctx { facts, els, ids, roots };
- let window = NodeId(u64::MAX);
let mut nodes = vec![];
let mut top = vec![];
let mut tested = vec![];
+ // a text node of only white space (the markup's line breaks and indents) is no node, as in Chrome's tree: a screen
+ // reader would stop on each
+ let blank = |k: &K| cx.els.get(k).is_some_and(|e| e.text.as_deref().is_some_and(|t| t.trim().is_empty()));
for (&k, el) in &cx.els {
+ if blank(&k) {
+ continue;
+ }
let mut n = node_of(&cx, k, el, focus);
for c in &el.kids {
- if cx.els.contains_key(c) {
+ if cx.els.contains_key(c) && !blank(c) {
n.push_child(NodeId(id_of(*c)));
}
}
+ if let Some([x0, y0, x1, y1]) = bounds(k) {
+ n.set_bounds(accesskit::Rect { x0, y0, x1, y1 });
+ }
if el.parent.is_none_or(|p| !cx.els.contains_key(&p)) {
top.push(NodeId(id_of(k)));
}
@@ -257,9 +276,19 @@ pub fn records<K: Copy + Eq + std::hash::Hash>(els: HashMap<K, El<K>>, roots: Ha
}
let mut root = AkNode::new(Role::Window);
root.set_children(top);
+ if let Some(l) = label {
+ root.set_label(l);
+ }
nodes.insert(0, (window, root));
let focus_id = focus.filter(|f| cx.els.contains_key(f)).map(|f| NodeId(id_of(f))).unwrap_or(window);
- let update = TreeUpdate { nodes, tree: Some(Tree::new(window)), tree_id: TreeId::ROOT, focus: focus_id };
+ (TreeUpdate { nodes, tree: Some(Tree::new(window)), tree_id: TreeId::ROOT, focus: focus_id }, tested)
+}
+
+/// A page's elements (the Blitz page's, raea-page's host) as the parity harness's records, by test id, read through
+/// accesskit_consumer. `roots` is each element's root (whose `id`s it looks up), `id_of` its AccessKit id (not
+/// u64::MAX, the window's).
+pub fn records<K: Copy + Eq + std::hash::Hash>(els: HashMap<K, El<K>>, roots: HashMap<K, K>, facts: &dyn Facts<K>, focus: Option<K>, id_of: impl Fn(K) -> u64) -> Value {
+ let (update, tested) = tree(els, roots, facts, focus, id_of, NodeId(u64::MAX), None, |_| None);
let tree = accesskit_consumer::Tree::new(update, true);
let state = tree.state();
let mut out = Map::new();
@@ -350,3 +379,68 @@ fn record(n: &accesskit_consumer::Node) -> Value {
fn fmt_num(v: f64) -> String {
if v.fract() == 0.0 { format!("{}", v as i64) } else { format!("{v}") }
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ struct NoFacts;
+ impl Facts<u64> for NoFacts {
+ fn display_none(&self, _: u64) -> bool {
+ false
+ }
+ fn invisible(&self, _: u64) -> bool {
+ false
+ }
+ fn natively_disabled(&self, _: u64) -> bool {
+ false
+ }
+ fn editor_value(&self, _: u64) -> Option<String> {
+ None
+ }
+ fn tabbable(&self, k: u64) -> bool {
+ k == 2
+ }
+ fn checked(&self, _: u64) -> bool {
+ false
+ }
+ fn test_id(&self, k: u64) -> Option<String> {
+ (k == 2).then(|| "go".to_string())
+ }
+ }
+
+ fn el(tag: &str, parent: Option<u64>, kids: Vec<u64>, text: Option<&str>, props: Value) -> El<u64> {
+ El { tag: tag.into(), props: props.as_object().cloned().unwrap_or_default(), parent, kids, text: text.map(str::to_string), title: None }
+ }
+
+ /// raea's window publishes this tree (raea-page-host ax.rs): its root is the window, named; each element hangs under
+ /// it with its box, a button named by its text, and the focus where the page has it.
+ #[test]
+ fn the_window_tree_has_the_page_under_its_root_with_boxes() {
+ let els = HashMap::from([
+ (1, el("main", None, vec![2, 4], None, json!({}))),
+ (2, el("button", Some(1), vec![3], None, json!({"data-testid": "go"}))),
+ (3, el("text", Some(2), vec![], Some("Start project"), json!({}))),
+ (4, el("text", Some(1), vec![], Some("\n "), json!({}))),
+ ]);
+ let roots = HashMap::from([(1, 0), (2, 0), (3, 0), (4, 0)]);
+ let window = NodeId(7);
+ let (u, tested) = tree(els, roots, &NoFacts, Some(2), |k| k + 100, window, Some("raea"), |k| (k == 2).then_some([10.0, 20.0, 110.0, 50.0]));
+ assert_eq!(tested, vec![("go".to_string(), NodeId(102))]);
+ assert_eq!(u.focus, NodeId(102));
+ assert_eq!(u.tree.as_ref().map(|t| t.root), Some(window));
+ let (_, root) = u.nodes.iter().find(|(id, _)| *id == window).unwrap();
+ assert_eq!(root.label(), Some("raea"));
+ assert_eq!(root.children(), &[NodeId(101)]);
+ // the markup's white space is no node
+ assert!(u.nodes.iter().all(|(id, _)| *id != NodeId(104)));
+ let (_, main) = u.nodes.iter().find(|(id, _)| *id == NodeId(101)).unwrap();
+ assert_eq!(main.children(), &[NodeId(102)]);
+ let state = accesskit_consumer::Tree::new(u, true);
+ let b = state.state().node_by_tree_local_id(NodeId(102), TreeId::ROOT).unwrap();
+ assert_eq!(b.role(), Role::Button);
+ assert!(b.data().supports_action(Action::Click), "a button takes a press");
+ assert_eq!(b.label().as_deref(), Some("Start project"));
+ assert_eq!(b.data().bounds(), Some(accesskit::Rect { x0: 10.0, y0: 20.0, x1: 110.0, y1: 50.0 }));
+ }
+}