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.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
A page's accessibility in a crate of its own (raea-page-ax), one reading of its elements for both its trees; the window's scheme and rest in raea-page-window
shinyobjectz2ff6676cb135
diff --git a/Cargo.lock b/Cargo.lockindex 2a1279bd..c9c1c30a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -14886,10 +14886,23 @@ dependencies = [][[package]]-name = "raea-page-host"+name = "raea-page-ax"version = "0.1.0"dependencies = ["accesskit 0.24.1",+ "bevy",+ "blitz-dom",+ "raea-runtime-dom",+ "raea-sys-a11y",+ "raea-sys-page",+ "serde_json",+ "stylo",+]++[[package]]+name = "raea-page-host"+version = "0.1.0"+dependencies = ["base64 0.22.1","bevy","blitz-dom",@@ -14903,6 +14916,7 @@ dependencies = ["raea-io-os","raea-io-trace","raea-page",+ "raea-page-ax","raea-page-sound","raea-page-stage","raea-page-window",@@ -14912,7 +14926,6 @@ dependencies = ["raea-runtime-js","raea-runtime-plugins","raea-runtime-view",- "raea-sys-a11y","raea-sys-fonts","raea-sys-page","serde_json",@@ -14956,12 +14969,14 @@ name = "raea-page-window"version = "0.1.0"dependencies = ["bevy",+ "blitz-traits","block2 0.6.2","objc2 0.6.5","objc2-app-kit 0.3.2","objc2-foundation 0.3.2","raea-io-os","raea-runtime-js",+ "raea-sys-page","raw-window-handle","serde_json","windows 0.62.2",diff --git a/Cargo.toml b/Cargo.tomlindex b21b8c74..cc82e319 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -47,6 +47,7 @@ members = ["engine/native","io/npm","engine/page",+ "engine/page/ax","engine/page/host","engine/rune","engine/rune/page",diff --git a/engine/page/ax/Cargo.toml b/engine/page/ax/Cargo.tomlnew file mode 100644index 00000000..1fe44baf--- /dev/null+++ b/engine/page/ax/Cargo.toml@@ -0,0 +1,22 @@+[package]+name = "raea-page-ax"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "A Blitz page's accessibility: its elements read for raea-sys-a11y, as the parity harness's records, and (on screen) published to the OS's assistive clients, whose asks come back as input"++[features]+# on screen (raea-page-host's --window): the tree in the window's AccessKit adapter, bevy_winit's+window = ["bevy/bevy_winit", "dep:accesskit"]++[dependencies]+bevy = { version = "=0.20.0", default-features = false, features = ["std", "bevy_window"] }+raea-sys-a11y = { path = "../../../systems/a11y" }+raea-sys-page = { path = "../../../systems/page" }+raea-runtime-dom = { path = "../../../runtime/dom" }+# the AccessKit Bevy's winit adapter takes, its version exactly+accesskit = { version = "=0.24.1", default-features = false, optional = true }+blitz-dom = { version = "=0.3.0-beta.4", default-features = false }+stylo = "=0.22.0"+serde_json = "1"diff --git a/engine/page/ax/src/lib.rs b/engine/page/ax/src/lib.rsnew file mode 100644index 00000000..a11fbeec--- /dev/null+++ b/engine/page/ax/src/lib.rs@@ -0,0 +1,112 @@+//! A Blitz page's accessibility:+//! the document's elements as raea-sys-a11y computes their roles, names and states from, read two ways. `records` is the+//! parity harness's, by the wire's element ids (what React made); publish.rs is the OS's, the whole document by its own+//! nodes (raea's window, the `window` feature).+#[cfg(feature = "window")]+mod publish;+#[cfg(feature = "window")]+pub use publish::{AxPlugin, Host};++use std::collections::HashMap;++use bevy::prelude::*;+use blitz_dom::{BaseDocument, Node};+use raea_runtime_dom::host::Roots;+use raea_sys_a11y::El;+use raea_sys_page::Docs;+use raea_sys_page::ops::Nodes;+use serde_json::{Map, Value, json};++/// A page's Blitz document and its wire ids, for `f`. None before the page is up.+fn with_doc<R>(world: &World, page: Entity, f: impl FnOnce(&BaseDocument, &Nodes) -> R) -> Option<R> {+ let roots = world.get_non_send::<Roots>()?;+ let docs = world.get_non_send::<Docs>()?;+ let (r, doc) = (roots.0.iter().find(|r| r.page == page)?, docs.0.get(&page)?);+ Some(f(doc, &r.nodes))+}++/// What raea-sys-a11y asks of the document, an element's computed style and its control's state, by either reader's ids.+struct Facts<'a, K> {+ /// the element with an id+ node: &'a dyn Fn(K) -> Option<&'a Node>,+ test_id: &'a dyn Fn(K) -> Option<String>,+ /// the whole document's: an element with no style isn't drawn (it or an ancestor is display: none), and a name+ /// spaces what's laid out as blocks+ drawn: bool,+}++impl<K: Copy> raea_sys_a11y::Facts<K> for Facts<'_, K> {+ fn display_none(&self, k: K) -> bool {+ let Some(n) = (self.node)(k) else { return false };+ n.primary_styles().map_or(self.drawn, |s| s.get_box().display.is_none())+ }+ fn invisible(&self, k: K) -> bool {+ use style::computed_values::visibility::T as V;+ (self.node)(k).and_then(|n| n.primary_styles()).is_some_and(|s| matches!(s.clone_visibility(), V::Hidden | V::Collapse))+ }+ fn natively_disabled(&self, _: K) -> bool {+ false+ }+ fn editor_value(&self, k: K) -> Option<String> {+ (self.node)(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: K) -> bool {+ (self.node)(k).is_some_and(|n| n.is_focussable())+ }+ fn checked(&self, k: K) -> bool {+ (self.node)(k).and_then(|n| n.element_data()).and_then(|e| e.checkbox_input_checked()).unwrap_or(false)+ }+ fn block(&self, k: K) -> Option<bool> {+ use style::values::specified::box_::DisplayOutside;+ let d = (self.node)(k).filter(|_| self.drawn)?.primary_styles()?.get_box().display;+ Some(d.outside() == DisplayOutside::Block)+ }+ fn test_id(&self, k: K) -> Option<String> {+ (self.test_id)(k)+ }+}++/// An svg's `<title>`.+fn svg_title(doc: &BaseDocument, n: &Node) -> Option<String> {+ let title = n.children.iter().filter_map(|c| doc.get_node(*c)).find(|c| c.element_data().is_some_and(|e| &*e.name.local == "title"))?;+ Some(title.text_content())+}++/// The tag raea-sys-a11y knows an element of kind `kind` by: an editable text is a field.+fn tag_of<'a>(kind: &'a str, props: &Map<String, Value>) -> &'a str {+ match kind {+ "editableText" if props.get("multiline") == Some(&Value::Bool(true)) => "textarea",+ "editableText" => "input",+ k => k,+ }+}++fn wire_test_id(nodes: &Nodes, id: u64) -> Option<String> {+ nodes.props.get(&id)?.get("data-testid")?.as_str().map(str::to_string)+}++/// The `a11y` method on a 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 records(world: &World, page: Entity) -> Value {+ with_doc(world, page, |doc, n| {+ let mut els = HashMap::new();+ for (&id, &node) in &n.by_id {+ let Some(dn) = doc.get_node(node) else { continue };+ let kind = n.kind(id).unwrap_or("div");+ let props = n.props.get(&id).cloned().unwrap_or_default();+ let tag = tag_of(kind, &props).to_string();+ let text = (kind == "text").then(|| dn.text_content());+ let title = if kind == "svg" { svg_title(doc, dn) } else { None };+ let parent = dn.parent.and_then(|p| n.id_of(p)).filter(|p| n.by_id.contains_key(p));+ let kids = dn.children.iter().filter_map(|c| n.id_of(*c)).filter(|c| n.by_id.contains_key(c)).collect();+ els.insert(id, El { tag, props, parent, kids, text, title });+ }+ let tops = els.keys().map(|k| (*k, 0)).collect();+ let node = |id: u64| n.by_id.get(&id).and_then(|k| doc.get_node(*k));+ let test_id = |id: u64| wire_test_id(n, id);+ let facts = Facts { node: &node, test_id: &test_id, drawn: false };+ let focus = doc.get_focussed_node_id().and_then(|f| n.id_of(f));+ raea_sys_a11y::records(els, tops, &facts, focus, |k| k)+ })+ .unwrap_or_else(|| json!({"nodes": {}}))+}diff --git a/engine/page/host/src/ax.rs b/engine/page/ax/src/publish.rssimilarity index 73%rename from engine/page/host/src/ax.rsrename to engine/page/ax/src/publish.rsindex 32a1cf0c..edd3b46f 100644--- a/engine/page/host/src/ax.rs+++ b/engine/page/ax/src/publish.rs@@ -9,7 +9,7 @@//!//! 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.+//! cloud's dashboard builds its rail so) has no wire ids, and the BRP `a11y` method's elements (lib.rs `records`) leave it out.use std::cell::RefCell;use std::collections::{HashMap, HashSet};use std::time::{Duration, Instant};@@ -20,12 +20,12 @@ 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 blitz_dom::{BaseDocument, 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};+use crate::{Facts, svg_title, tag_of, wire_test_id, with_doc};/// 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)@@ -34,7 +34,22 @@ const EVERY: Duration = Duration::from_millis(250);/// what a page never draws, and an assistive client has no use forconst UNDRAWN: &[&str] = &["head", "script", "style", "template", "noscript", "link", "meta", "title"];-pub struct AxPlugin;+/// The page host's side: the page shown, the frame it's on, and an input event queued for a frame or later as a person's+/// is (the frame it lands before).+#[derive(Resource, Clone, Copy)]+pub struct Host {+ pub page: fn(&World) -> Option<Entity>,+ pub frame: fn(&World) -> u64,+ pub queue: fn(&mut World, Value, u64) -> u64,+}++impl Host {+ fn doc<R>(self, world: &World, f: impl FnOnce(&BaseDocument, &Nodes) -> R) -> Option<R> {+ with_doc(world, (self.page)(world)?, f)+ }+}++pub struct AxPlugin(pub Host);#[derive(Resource, Default)]struct Ax {@@ -47,7 +62,7 @@ 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());+ app.insert_resource(manage).insert_resource(self.0).init_resource::<Ax>().add_systems(PostUpdate, (act, publish).chain());}}@@ -56,7 +71,8 @@ fn publish(world: &mut World) {if !world.get_resource::<AccessibilityRequested>().is_some_and(|r| r.get()) {return;}- let (now, frame) = (Instant::now(), world.resource::<Frame>().0);+ let host = *world.resource::<Host>();+ let (now, frame) = (Instant::now(), (host.frame)(world));let ax = world.resource::<Ax>();if ax.frame == frame || ax.last.is_some_and(|t| now - t < EVERY) {return;@@ -64,9 +80,14 @@ fn publish(world: &mut World) {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(mut update) = crate::page::with_doc(world, |doc, nodes| {+ let Some(mut update) = host.doc(world, |doc, nodes| {let (els, tops) = elements(doc, nodes);- let facts = Facts { doc, nodes };+ let node = |k: Id| doc.get_node(k).filter(|n| n.is_element());+ let test_id = |k: Id| {+ let wire = nodes.id_of(k).and_then(|id| wire_test_id(nodes, id));+ wire.or_else(|| node(k)?.element_data()?.attrs().iter().find(|a| &*a.name.local == "data-testid").map(|a| a.value.to_string()))+ };+ let facts = Facts { node: &node, test_id: &test_id, drawn: true };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@@ -125,14 +146,8 @@ fn elements(doc: &BaseDocument, nodes: &Nodes) -> (HashMap<Id, El<Id>>, HashMap<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 tag = wire.and_then(|id| nodes.kind(id)).filter(|k| *k == "editableText").map_or(tag, |k| tag_of(k, &props).to_string());+ let title = if tag == "svg" { svg_title(doc, n) } else { None };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 }@@ -150,50 +165,6 @@ fn elements(doc: &BaseDocument, nodes: &Nodes) -> (HashMap<Id, El<Id>>, HashMap<(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 block(&self, k: Id) -> Option<bool> {- use style::values::specified::box_::DisplayOutside;- let d = self.el(k)?.primary_styles()?.get_box().display;- Some(d.outside() == DisplayOutside::Block)- }- 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> {@@ -210,8 +181,13 @@ enum At {Nothing,}-fn at(doc: &BaseDocument, k: Id) -> At {+/// A box a wheel scrolls.+fn by_wheel(o: style::values::computed::Overflow) -> bool {use style::values::computed::Overflow as O;+ o == O::Scroll || o == O::Auto+}++fn at(doc: &BaseDocument, k: Id) -> At {// a text node is pressed where its element islet Some(k) = element(doc, k).or_else(|| doc.get_node(k)?.parent).and_then(|k| element(doc, k)) else { return At::Nothing };let Some(b) = doc.get_client_bounding_rect(k).filter(|b| b.width > 0.0 && b.height > 0.0) else { return At::Nothing };@@ -220,7 +196,7 @@ fn at(doc: &BaseDocument, k: Id) -> At {while let Some(a) = up {let Some(n) = doc.get_node(a) else { break };up = n.parent;- let scrolls = n.primary_styles().map(|s| [s.clone_overflow_x(), s.clone_overflow_y()].map(|o| matches!(o, O::Scroll | O::Auto)));+ let scrolls = n.primary_styles().map(|s| [s.clone_overflow_x(), s.clone_overflow_y()].map(by_wheel));let Some([sx, sy]) = scrolls else { continue };let Some(r) = element(doc, a).and_then(|a| doc.get_client_bounding_rect(a)) else { continue };let dx = if sx && (x < r.x || x > r.x + r.width) { r.x + r.width / 2.0 - x } else { 0.0 };@@ -251,19 +227,19 @@ fn act(world: &mut World, reader: &mut SystemState<MessageReader<ActionRequest>>// 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)let mut asks: Vec<Later> = r.read().filter(|r| matches!(r.0.action, Action::Click | Action::SetValue)).map(|r| Later(r.0.clone(), 0, 8)).collect();- let frame = world.resource::<Frame>().0;+ let host = *world.resource::<Host>();+ let frame = (host.frame)(world);for l in std::mem::take(&mut *later) {if l.1 > frame { later.push(l) } else { asks.push(l) }}for Later(ask, _, left) in asks {let Some(k) = (ask.target_node.0 & PAGE != 0).then(|| Id::from_u64(ask.target_node.0 & !PAGE)) else { continue };- let Some(place) = crate::page::with_doc(world, |doc, _| at(doc, k)) else { continue };+ let Some(place) = host.doc(world, |doc, _| at(doc, k)) else { continue };let next = frame + 1;let (x, y) = match place {At::Press(x, y) => (x, y),At::Scroll(x, y, dx, dy) if left > 0 => {- let f = world.resource_mut::<Pending>().queue(json!({"type": "wheel", "x": x, "y": y, "dx": dx, "dy": dy}), next);- crate::inject::LAST_INPUT.fetch_max(f, std::sync::atomic::Ordering::SeqCst);+ let f = (host.queue)(world, json!({"type": "wheel", "x": x, "y": y, "dx": dx, "dy": dy}), next);// laid out where it scrolled to by the frame after the wheel'slater.push(Later(ask, f + 2, left - 1));continue;@@ -273,14 +249,12 @@ fn act(world: &mut World, reader: &mut SystemState<MessageReader<ActionRequest>>continue;}};- 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);+ (host.queue)(world, json!({"type": "down", "x": x, "y": y}), next);+ (host.queue)(world, 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);+ (host.queue)(world, json!({"type": "key", "key": "a", "mods": [if cfg!(target_os = "macos") { "cmd" } else { "ctrl" }]}), next);+ (host.queue)(world, 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/Cargo.toml b/engine/page/host/Cargo.tomlindex 6e6990b2..d18c0b3f 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 JavaScriptCoreportable = ["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", "dep:accesskit"]+window = ["bevy/bevy_winit", "dep:raea-runtime-plugins", "raea-page-window/window", "raea-page-ax/window"][dependencies]raea-io-trace = { path = "../../../io/trace" }@@ -26,10 +26,8 @@ raea-io-trace = { path = "../../../io/trace" }# page decodes (raea-page's IMAGE_DECODER decodes through bevy_image): the legacy app's list, which the benches ran onbevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "default_font", "multi_threaded", "3d_bevy_render", "ui_bevy_render", "png", "tonemapping_luts", "ktx2", "zstd_rust", "bevy_picking", "ui_picking", "bevy_ui_widgets", "bevy_input_focus", "jpeg", "bevy_remote", "tga", "qoi", "tiff", "pnm", "ff", "dds", "exr", "hdr", "webp", "gif", "bmp", "ico"] }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 }+# the page's accessibility: the `a11y` method's records, and the window's tree+raea-page-ax = { path = "../ax" }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/inject.rs b/engine/page/host/src/inject.rsindex 54b00ebc..899df375 100644--- a/engine/page/host/src/inject.rs+++ b/engine/page/host/src/inject.rs@@ -96,6 +96,18 @@ impl Pending {}}+/// An input event queued in `world` (Pending::queue), and known to the `ui` answers that wait for it.+pub fn queue(world: &mut World, v: Value, next: u64) -> u64 {+ let f = world.resource_mut::<Pending>().queue(v, next);+ LAST_INPUT.fetch_max(f, std::sync::atomic::Ordering::SeqCst);+ f+}++/// The frame the host is on.+pub fn frame(world: &World) -> u64 {+ world.resource::<Frame>().0+}+/// A button going down or up: the events after it wait for the next frame, so the press is picked (and focus moves)/// before the keys typed after it are dispatched.fn edge(v: &Value) -> bool {diff --git a/engine/page/host/src/lib.rs b/engine/page/host/src/lib.rsindex cfc6728b..e786771f 100644--- a/engine/page/host/src/lib.rs+++ b/engine/page/host/src/lib.rs@@ -4,19 +4,16 @@//! 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};+/// the desktop window's side, in raea-page-window (under these names for main.rs and tests)+#[cfg(feature = "window")]+pub use raea_page_window::idle;+pub use raea_page_window::{chrome, native, scheme};/// the live stage, in raea-page-stagepub use raea_page_stage as stage;-#[cfg(feature = "window")]-pub mod idle;pub mod inject;pub mod mcp;pub mod page;-pub mod scheme;pub mod shell;pub mod tree;diff --git a/engine/page/host/src/main.rs b/engine/page/host/src/main.rsindex fa91c9c4..27866e60 100644--- a/engine/page/host/src/main.rs+++ b/engine/page/host/src/main.rs@@ -123,10 +123,10 @@ 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)+ // on screen, the page's accessibility tree is the OS's (VoiceOver, macOS accessibility clients: raea-page-ax)#[cfg(feature = "window")]if a.window {- app.add_plugins(raea_page_host::ax::AxPlugin);+ app.add_plugins(raea_page_ax::AxPlugin(raea_page_ax::Host { page: page::shown, frame: raea_page_host::inject::frame, queue: raea_page_host::inject::queue }));}// 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>() {diff --git a/engine/page/host/src/page.rs b/engine/page/host/src/page.rsindex 73390bdd..55d97e2c 100644--- a/engine/page/host/src/page.rs+++ b/engine/page/host/src/page.rs@@ -19,6 +19,11 @@ use crate::tree::r1;#[derive(Resource)]pub struct HostPage(pub Entity);+/// The page the host shows, once it's up.+pub fn shown(world: &World) -> Option<Entity> {+ world.get_resource::<HostPage>().map(|p| p.0)+}+/// The node on the UI camera that shows the page's image.#[derive(Component)]pub struct Shows;@@ -281,90 +286,9 @@ pub fn tree(page: Res<HostPage>, roots: NonSend<Roots>, docs: NonSend<Docs>, winout.0 = Some(json!({"frame": frame.0, "window": {"w": r1(size.x), "h": r1(size.y)}, "scale": target.scale, "nodes": nodes, "panels": panels, "composite": false, "substrate": "blitz"}));}-/// What raea-runtime-js's accessibility computation asks of the Blitz page: the document's computed style and its controls'-/// state, by the wire's element ids.-struct Facts<'a> {- doc: &'a blitz_dom::BaseDocument,- nodes: &'a raea_sys_page::ops::Nodes,-}--impl Facts<'_> {- fn node(&self, id: u64) -> Option<&blitz_dom::Node> {- self.nodes.by_id.get(&id).and_then(|n| self.doc.get_node(*n))- }-}--impl raea_sys_a11y::Facts<u64> for Facts<'_> {- fn display_none(&self, id: u64) -> bool {- self.node(id).and_then(|n| n.primary_styles()).is_some_and(|s| s.get_box().display.is_none())- }- fn invisible(&self, id: u64) -> bool {- use style::computed_values::visibility::T as V;- self.node(id).and_then(|n| n.primary_styles()).is_some_and(|s| matches!(s.clone_visibility(), V::Hidden | V::Collapse))- }- fn natively_disabled(&self, _id: u64) -> bool {- false- }- fn editor_value(&self, id: u64) -> Option<String> {- self.node(id).and_then(|n| n.element_data()).and_then(|e| e.text_input_data()).map(|t| t.editor.raw_text().to_string())- }- fn tabbable(&self, id: u64) -> bool {- self.node(id).is_some_and(|n| n.is_focussable())- }- fn checked(&self, id: u64) -> bool {- self.node(id).and_then(|n| n.element_data()).and_then(|e| e.checkbox_input_checked()).unwrap_or(false)- }- fn test_id(&self, id: u64) -> Option<String> {- self.nodes.props.get(&id).and_then(|p| p.get("data-testid")).and_then(Value::as_str).map(str::to_string)- }-}--/// 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 (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();- for (&id, &node) in &n.by_id {- let Some(dn) = doc.get_node(node) else { continue };- let kind = n.kind(id).unwrap_or("div");- let props = n.props.get(&id).cloned().unwrap_or_default();- let tag = match kind {- "editableText" if props.get("multiline") == Some(&Value::Bool(true)) => "textarea",- "editableText" => "input",- k => k,- };- let text = (kind == "text").then(|| dn.text_content());- let title = (kind == "svg")- .then(|| dn.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 parent = dn.parent.and_then(|p| n.id_of(p)).filter(|p| n.by_id.contains_key(p));- let kids = dn.children.iter().filter_map(|c| n.id_of(*c)).filter(|c| n.by_id.contains_key(c)).collect();- els.insert(id, raea_sys_a11y::El { tag: tag.to_string(), props, parent, kids, text, title });- tops.insert(id, 0u64);- }- let facts = Facts { doc, nodes: n };- let focus = doc.get_focussed_node_id().and_then(|f| n.id_of(f));- 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.+/// The `a11y` method on the page (raea-page-ax).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": {}}))+ shown(world).map_or_else(|| json!({"nodes": {}}), |p| raea_page_ax::records(world, p))}/// The system's faces as Chrome on macOS has them (Times, Helvetica and Courier boosted, Menlo for monospace, CoreText'sdiff --git a/engine/page/host/tests/pointer.rs b/engine/page/host/tests/pointer.rsindex e3fd69ac..34572072 100644--- a/engine/page/host/tests/pointer.rs+++ b/engine/page/host/tests/pointer.rs@@ -42,7 +42,13 @@ fn left() -> WindowEvent {}fn releases(got: &[(Vec2, PointerAction)]) -> Vec<Vec2> {- got.iter().filter(|g| matches!(g.1, PointerAction::Release(_))).map(|g| g.0).collect()+ let mut at = vec![];+ for (p, act) in got {+ if let PointerAction::Release(_) = act {+ at.push(*p);+ }+ }+ at}#[test]diff --git a/engine/page/window/Cargo.toml b/engine/page/window/Cargo.tomlindex 6d661ecf..51449069 100644--- a/engine/page/window/Cargo.toml+++ b/engine/page/window/Cargo.toml@@ -13,6 +13,9 @@ window = ["bevy/bevy_winit", "dep:objc2", "dep:objc2-app-kit", "dep:objc2-founda[dependencies]bevy = { version = "=0.20.0", default-features = false, features = ["std", "bevy_window"] }raea-runtime-js = { path = "../../../runtime/js" }+# the page's colour scheme (scheme.rs), and whether a page is drawing (idle.rs)+raea-sys-page = { path = "../../../systems/page" }+blitz-traits = "=0.3.0-beta.4"serde_json = "1"# --chrome inset's unified toolbar (the traffic lights centred in a 52 pt title area) and native.rs's AppKit callsdiff --git a/engine/page/host/src/idle.rs b/engine/page/window/src/idle.rssimilarity index 100%rename from engine/page/host/src/idle.rsrename to engine/page/window/src/idle.rsdiff --git a/engine/page/window/src/lib.rs b/engine/page/window/src/lib.rsindex b393bc81..f6c173df 100644--- a/engine/page/window/src/lib.rs+++ b/engine/page/window/src/lib.rs@@ -3,7 +3,10 @@pub mod badge;pub mod chrome;+#[cfg(feature = "window")]+pub mod idle;pub mod native;+pub mod scheme;#[cfg(all(windows, feature = "window"))]mod win;diff --git a/engine/page/host/src/scheme.rs b/engine/page/window/src/scheme.rssimilarity index 100%rename from engine/page/host/src/scheme.rsrename to engine/page/window/src/scheme.rsdiff --git a/sdk/ui/test/dom-dashboard.tsx b/sdk/ui/test/dom-dashboard.tsxnew file mode 100644index 00000000..7830a610--- /dev/null+++ b/sdk/ui/test/dom-dashboard.tsx@@ -0,0 +1,136 @@+// The DOM-like surface as raea cloud's dashboard uses it in raea.app (markup set as HTML, sheets as <dialog>s, a second+// React root over the page, properties set on fields it makes), on the stand-in host (dom.test.tsx's).+import { beforeAll, describe, expect, test } from "bun:test";+import { useEffect, useRef } from "react";+import { install } from "../src/dom";+import { mount } from "../src/react";+import { flush } from "../src/wire";+import { fresh, snap } from "./host";++beforeAll(() => install());+const g = globalThis as any;++const press = (x: number, y: number, detail = 1) => ({ x: 0, y: 0, clientX: x, clientY: y, button: 0, detail });++describe("a dashboard's page", () => {+ test("a link's press follows it: its fragment becomes location's hash, unless a listener prevents it", () => {+ const host = fresh();+ function App() {+ const r = useRef<any>(null);+ // markup set as HTML, as raea cloud's dashboard builds its rail in raea.app+ useEffect(() => void (r.current.innerHTML = '<a data-testid="go" href="#/projects">Projects</a><a data-testid="stay" href="#/agents">Agents</a>'), []);+ return <nav data-testid="root" ref={r} onClick={() => {}} />;+ }+ mount(<App />, 0, { dom: true });+ flush();+ snap(host, { root: [0, 0, 200, 100], go: [0, 0, 200, 40], stay: [0, 50, 200, 40] });+ const was = g.location.hash;+ host.send("root", "pointerdown", { ...press(10, 10), target: host.tid("go") });+ host.send("root", "pointerup", { ...press(10, 10), target: host.tid("go") });+ expect(g.location.hash).toBe("#/projects");+ g.document.querySelector('[data-testid="stay"]').addEventListener("click", (e: any) => e.preventDefault());+ host.send("root", "pointerdown", { ...press(10, 60), target: host.tid("stay") });+ host.send("root", "pointerup", { ...press(10, 60), target: host.tid("stay") });+ expect(g.location.hash).toBe("#/projects");+ g.location.hash = was;+ });++ test("a dialog opened with showModal (raea cloud's sheets): open, its first control focused, Escape's cancel closes it, close fires after", async () => {+ fresh();+ mount(<main data-testid="page">dashboard</main>, 0, { dom: true });+ flush();+ const d = g.document.createElement("dialog");+ d.innerHTML = '<p>New</p><button type="button" data-testid="first">Project</button>';+ g.document.body.append(d);+ const seen: string[] = [];+ d.addEventListener("cancel", () => seen.push("cancel"));+ d.addEventListener("close", () => seen.push("close"));+ d.showModal();+ flush();+ expect(d.open).toBe(true);+ expect(d.hasAttribute("open")).toBe(true);+ expect(g.document.activeElement).toBe(d.querySelector("button"));+ // Escape at what's focused: cancel, then closed; close comes after, as a task+ g.__ui_deliver(JSON.stringify({ t: "named", name: "keydown", value: { key: "Escape" } }));+ expect(d.open).toBe(false);+ expect(seen).toEqual(["cancel"]);+ await new Promise((r) => setTimeout(r, 0));+ expect(seen).toEqual(["cancel", "close"]);+ // a prevented cancel keeps it open; close() keeps its returnValue+ d.showModal();+ d.addEventListener("cancel", (e: any) => e.preventDefault());+ g.__ui_deliver(JSON.stringify({ t: "named", name: "keydown", value: { key: "Escape" } }));+ expect(d.open).toBe(true);+ d.close("done");+ expect(d.open).toBe(false);+ expect(d.returnValue).toBe("done");+ d.remove();+ });++ test("a second React root on a layer over the page (raea.app's welcome) takes its button's click", () => {+ const host = fresh();+ const log: string[] = [];+ mount(<main data-testid="page" onClick={() => log.push("page")}>dashboard</main>, 0, { dom: true });+ flush();+ const layer = g.document.createElement("div");+ layer.setAttribute("data-testid", "layer");+ g.document.body.appendChild(layer);+ flush();+ mount(+ <div data-testid="over" className="fixed inset-0">+ <button data-testid="start" onClick={() => log.push("start")}>Start</button>+ </div>,+ layer.__wid,+ { dom: true },+ );+ flush();+ snap(host, { page: [0, 0, 800, 600], layer: [0, 0, 0, 0], over: [0, 0, 800, 600], start: [600, 500, 60, 30] });+ const target = host.tid("start");+ // to the nearest element up from the button that listens, as the host sends it+ const hearer = ["start", "over", "layer", "page"].find((t) => (host as any).get(host.tid(t)).on.has("pointerdown"));+ host.send(hearer!, "pointerdown", { ...press(620, 510), target });+ host.send(hearer!, "pointerup", { ...press(620, 510), target });+ expect(log).toEqual(["start"]);+ });+});++describe("outerHTML", () => {+ test("set, the element is replaced by its markup in its place; out of a tree, nothing happens", () => {+ fresh();+ let box: any;+ mount(<div ref={(e: any) => (box = e)} />, 0, { dom: true });+ box.innerHTML = "<header class='a'><b>one</b></header><p>after</p>";+ box.firstChild.outerHTML = "<header class='b'><i>two</i></header>";+ expect(box.innerHTML).toBe('<header class="b"><i>two</i></header><p>after</p>');+ box.lastChild.outerHTML = "";+ expect(box.innerHTML).toBe('<header class="b"><i>two</i></header>');+ const off: any = document.createElement("u");+ off.outerHTML = "<s></s>";+ expect(off.outerHTML).toBe("<u></u>");+ });+});++describe("writable properties", () => {+ test("a property set on a field made by the page reaches its attribute, as Chrome's do", () => {+ fresh();+ let box: any;+ mount(<div ref={(e: any) => (box = e)} />, 0, { dom: true });+ const input: any = document.createElement("input");+ box.append(input);+ input.placeholder = "Search";+ input.required = true;+ input.readOnly = true;+ input.readOnly = false;+ expect(input.outerHTML).toBe('<input placeholder="Search" required="">');+ const a: any = document.createElement("a");+ a.href = "#/projects";+ a.draggable = false;+ expect([a.getAttribute("href"), a.getAttribute("draggable")]).toEqual(["#/projects", "false"]);+ const label: any = document.createElement("label");+ label.htmlFor = "q";+ expect(label.getAttribute("for")).toBe("q");+ box.innerHTML = "<select><option value='a'>A</option><option value='b'>B</option></select>";+ box.firstChild.selectedIndex = 1;+ expect([box.firstChild.value, box.firstChild.selectedIndex]).toEqual(["b", 1]);+ });+});diff --git a/sdk/ui/test/dom.test.tsx b/sdk/ui/test/dom.test.tsxindex 22ba77ee..50ab7db0 100644--- a/sdk/ui/test/dom.test.tsx+++ b/sdk/ui/test/dom.test.tsx@@ -8,6 +8,7 @@ import { getComputedStyle, install, layout } from "../src/dom";import { createPortal, flushSync, mount } from "../src/react";import { flush } from "../src/wire";import { fresh, snap } from "./host";+import "./dom-dashboard"; // its tests run here, after parity.test.tsx, which wants no DOM installedbeforeAll(() => install());const g = globalThis as any;@@ -117,86 +118,6 @@ describe("P18 DOM surface", () => {expect(log).toEqual(["allowed", "behind"]);});- test("a link's press follows it: its fragment becomes location's hash, unless a listener prevents it", () => {- const host = fresh();- function App() {- const r = useRef<any>(null);- // markup set as HTML, as raea cloud's dashboard builds its rail in raea.app- useEffect(() => void (r.current.innerHTML = '<a data-testid="go" href="#/projects">Projects</a><a data-testid="stay" href="#/agents">Agents</a>'), []);- return <nav data-testid="root" ref={r} onClick={() => {}} />;- }- mount(<App />, 0, { dom: true });- flush();- snap(host, { root: [0, 0, 200, 100], go: [0, 0, 200, 40], stay: [0, 50, 200, 40] });- const was = g.location.hash;- host.send("root", "pointerdown", { ...press(10, 10), target: host.tid("go") });- host.send("root", "pointerup", { ...press(10, 10), target: host.tid("go") });- expect(g.location.hash).toBe("#/projects");- g.document.querySelector('[data-testid="stay"]').addEventListener("click", (e: any) => e.preventDefault());- host.send("root", "pointerdown", { ...press(10, 60), target: host.tid("stay") });- host.send("root", "pointerup", { ...press(10, 60), target: host.tid("stay") });- expect(g.location.hash).toBe("#/projects");- g.location.hash = was;- });-- test("a dialog opened with showModal (raea cloud's sheets): open, its first control focused, Escape's cancel closes it, close fires after", async () => {- fresh();- mount(<main data-testid="page">dashboard</main>, 0, { dom: true });- flush();- const d = g.document.createElement("dialog");- d.innerHTML = '<p>New</p><button type="button" data-testid="first">Project</button>';- g.document.body.append(d);- const seen: string[] = [];- d.addEventListener("cancel", () => seen.push("cancel"));- d.addEventListener("close", () => seen.push("close"));- d.showModal();- flush();- expect(d.open).toBe(true);- expect(d.hasAttribute("open")).toBe(true);- expect(g.document.activeElement).toBe(d.querySelector("button"));- // Escape at what's focused: cancel, then closed; close comes after, as a task- g.__ui_deliver(JSON.stringify({ t: "named", name: "keydown", value: { key: "Escape" } }));- expect(d.open).toBe(false);- expect(seen).toEqual(["cancel"]);- await new Promise((r) => setTimeout(r, 0));- expect(seen).toEqual(["cancel", "close"]);- // a prevented cancel keeps it open; close() keeps its returnValue- d.showModal();- d.addEventListener("cancel", (e: any) => e.preventDefault());- g.__ui_deliver(JSON.stringify({ t: "named", name: "keydown", value: { key: "Escape" } }));- expect(d.open).toBe(true);- d.close("done");- expect(d.open).toBe(false);- expect(d.returnValue).toBe("done");- d.remove();- });-- test("a second React root on a layer over the page (raea.app's welcome) takes its button's click", () => {- const host = fresh();- const log: string[] = [];- mount(<main data-testid="page" onClick={() => log.push("page")}>dashboard</main>, 0, { dom: true });- flush();- const layer = g.document.createElement("div");- layer.setAttribute("data-testid", "layer");- g.document.body.appendChild(layer);- flush();- mount(- <div data-testid="over" className="fixed inset-0">- <button data-testid="start" onClick={() => log.push("start")}>Start</button>- </div>,- layer.__wid,- { dom: true },- );- flush();- snap(host, { page: [0, 0, 800, 600], layer: [0, 0, 0, 0], over: [0, 0, 800, 600], start: [600, 500, 60, 30] });- const target = host.tid("start");- // to the nearest element up from the button that listens, as the host sends it- const hearer = ["start", "over", "layer", "page"].find((t) => (host as any).get(host.tid(t)).on.has("pointerdown"));- host.send(hearer!, "pointerdown", { ...press(620, 510), target });- host.send(hearer!, "pointerup", { ...press(620, 510), target });- expect(log).toEqual(["start"]);- });-test("a press: capture and bubble through native and React listeners in Chrome's order, then click", () => {const host = fresh();const log: string[] = [];@@ -546,44 +467,3 @@ describe("P18 DOM surface: computed style", () => {expect(getComputedStyle(el).color).toBe("red");});});--describe("outerHTML", () => {- test("set, the element is replaced by its markup in its place; out of a tree, nothing happens", () => {- fresh();- let box: any;- mount(<div ref={(e: any) => (box = e)} />, 0, { dom: true });- box.innerHTML = "<header class='a'><b>one</b></header><p>after</p>";- box.firstChild.outerHTML = "<header class='b'><i>two</i></header>";- expect(box.innerHTML).toBe('<header class="b"><i>two</i></header><p>after</p>');- box.lastChild.outerHTML = "";- expect(box.innerHTML).toBe('<header class="b"><i>two</i></header>');- const off: any = document.createElement("u");- off.outerHTML = "<s></s>";- expect(off.outerHTML).toBe("<u></u>");- });-});--describe("writable properties", () => {- test("a property set on a field made by the page reaches its attribute, as Chrome's do", () => {- fresh();- let box: any;- mount(<div ref={(e: any) => (box = e)} />, 0, { dom: true });- const input: any = document.createElement("input");- box.append(input);- input.placeholder = "Search";- input.required = true;- input.readOnly = true;- input.readOnly = false;- expect(input.outerHTML).toBe('<input placeholder="Search" required="">');- const a: any = document.createElement("a");- a.href = "#/projects";- a.draggable = false;- expect([a.getAttribute("href"), a.getAttribute("draggable")]).toEqual(["#/projects", "false"]);- const label: any = document.createElement("label");- label.htmlFor = "q";- expect(label.getAttribute("for")).toBe("q");- box.innerHTML = "<select><option value='a'>A</option><option value='b'>B</option></select>";- box.firstChild.selectedIndex = 1;- expect([box.firstChild.value, box.firstChild.selectedIndex]).toEqual(["b", 1]);- });-});diff --git a/systems/a11y/src/lib.rs b/systems/a11y/src/lib.rsindex d5bd5578..303ac070 100644--- a/systems/a11y/src/lib.rs+++ b/systems/a11y/src/lib.rs@@ -75,6 +75,10 @@ impl<K> El<K> {fn p(&self, k: &str) -> Option<&Value> {self.props.get(k)}+ /// a text node of only white space+ fn blank(&self) -> bool {+ matches!(&self.text, Some(t) if t.trim().is_empty())+ }fn ty(&self) -> String {s(self.p("type")).unwrap_or_default().to_ascii_lowercase()}@@ -266,7 +270,7 @@ pub fn tree<K: Copy + Eq + std::hash::Hash>(els: HashMap<K, El<K>>, roots: HashMlet 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()));+ let blank = |k: &K| cx.els.get(k).is_some_and(El::blank);for (&k, el) in &cx.els {if blank(&k) {continue;@@ -424,144 +428,4 @@ fn fmt_num(v: f64) -> String {}#[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 }));- }-- #[test]- fn a_field_takes_a_value_unless_it_is_read_only() {- let els = HashMap::from([(1, el("input", None, vec![], None, json!({"aria-label": "Title"}))), (2, el("input", None, vec![], None, json!({"readOnly": true})))]);- let roots = HashMap::from([(1, 0), (2, 0)]);- let (u, _) = tree(els, roots, &NoFacts, None, |k| k + 100, NodeId(7), None, |_| None);- let field = |id| u.nodes.iter().find(|(i, _)| *i == NodeId(id)).unwrap().1.clone();- assert!(field(101).supports_action(Action::SetValue));- assert!(!field(102).supports_action(Action::SetValue));- }-- /// AccessKit's filtered walk (what macOS lists) stops at a hidden node after an empty container, and what follows- /// is gone: unhide takes hidden nodes out so it isn't. When the first assert fails AccessKit has fixed it.- #[test]- fn what_follows_an_empty_container_and_a_hidden_one_is_listed_once_hidden_nodes_are_out() {- use accesskit::Tree;- let (win, body, layer, panel, inside, welcome, nav) = (NodeId(1), NodeId(2), NodeId(3), NodeId(4), NodeId(5), NodeId(6), NodeId(8));- let named = |r, l: &str| {- let mut n = AkNode::new(r);- n.set_label(l);- n- };- let update = || {- let mut root = AkNode::new(Role::Window);- root.set_children(vec![body]);- let mut b = AkNode::new(Role::GenericContainer);- // the rail, an empty layer, the closed side panel (hidden), raea.app's welcome- b.set_children(vec![nav, layer, panel, welcome]);- let mut p = AkNode::new(Role::Complementary);- p.set_hidden();- p.set_children(vec![inside]);- TreeUpdate {- nodes: vec![(win, root), (body, b), (layer, AkNode::new(Role::GenericContainer)), (panel, p), (inside, AkNode::new(Role::Button)), (welcome, named(Role::Button, "Welcome")), (nav, named(Role::Navigation, "Rail"))],- tree: Some(Tree::new(win)),- tree_id: TreeId::ROOT,- focus: win,- }- };- let listed = |u: TreeUpdate| {- let t = accesskit_consumer::Tree::new(u, true);- let root = t.state().root();- root.filtered_children(accesskit_consumer::common_filter).filter_map(|n| n.label()).collect::<Vec<_>>()- };- assert_eq!(listed(update()), vec!["Rail".to_string()], "AccessKit lists what follows now: unhide may go");- let mut u = update();- unhide(&mut u, win);- assert_eq!(listed(u), vec!["Rail".to_string(), "Welcome".to_string()], "the welcome is listed");- }-- /// A name's parts are spaced by how they're laid out, where the host says: spans styled as blocks don't run together.- #[test]- fn a_name_spaces_parts_laid_out_as_blocks() {- struct Blocks(bool);- impl Facts<u64> for Blocks {- 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, _: u64) -> bool { false }- fn checked(&self, _: u64) -> bool { false }- fn test_id(&self, _: u64) -> Option<String> { None }- fn block(&self, _: u64) -> Option<bool> { Some(self.0) }- }- let name = |block| {- let els = HashMap::from([- (1, el("button", None, vec![2, 4], None, json!({}))),- (2, el("span", Some(1), vec![3], None, json!({}))),- (3, el("text", Some(2), vec![], Some("Sonnet 5.5"), json!({}))),- (4, el("span", Some(1), vec![5], None, json!({}))),- (5, el("text", Some(4), vec![], Some("Most efficient"), json!({}))),- ]);- let roots = (1..=5).map(|k| (k, 0)).collect();- let (u, _) = tree(els, roots, &Blocks(block), None, |k| k + 100, NodeId(7), None, |_| None);- u.nodes.iter().find(|(i, _)| *i == NodeId(101)).unwrap().1.label().map(str::to_string)- };- assert_eq!(name(true).as_deref(), Some("Sonnet 5.5 Most efficient"));- assert_eq!(name(false).as_deref(), Some("Sonnet 5.5Most efficient"));- }-}+mod tests;diff --git a/systems/a11y/src/tests.rs b/systems/a11y/src/tests.rsnew file mode 100644index 00000000..6ce630d9--- /dev/null+++ b/systems/a11y/src/tests.rs@@ -0,0 +1,139 @@+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 }));+}++#[test]+fn a_field_takes_a_value_unless_it_is_read_only() {+ let els = HashMap::from([(1, el("input", None, vec![], None, json!({"aria-label": "Title"}))), (2, el("input", None, vec![], None, json!({"readOnly": true})))]);+ let roots = HashMap::from([(1, 0), (2, 0)]);+ let (u, _) = tree(els, roots, &NoFacts, None, |k| k + 100, NodeId(7), None, |_| None);+ let field = |id| u.nodes.iter().find(|(i, _)| *i == NodeId(id)).unwrap().1.clone();+ assert!(field(101).supports_action(Action::SetValue));+ assert!(!field(102).supports_action(Action::SetValue));+}++/// AccessKit's filtered walk (what macOS lists) stops at a hidden node after an empty container, and what follows+/// is gone: unhide takes hidden nodes out so it isn't. When the first assert fails AccessKit has fixed it.+#[test]+fn what_follows_an_empty_container_and_a_hidden_one_is_listed_once_hidden_nodes_are_out() {+ use accesskit::Tree;+ let (win, body, layer, panel, inside, welcome, nav) = (NodeId(1), NodeId(2), NodeId(3), NodeId(4), NodeId(5), NodeId(6), NodeId(8));+ let named = |r, l: &str| {+ let mut n = AkNode::new(r);+ n.set_label(l);+ n+ };+ let update = || {+ let mut root = AkNode::new(Role::Window);+ root.set_children(vec![body]);+ let mut b = AkNode::new(Role::GenericContainer);+ // the rail, an empty layer, the closed side panel (hidden), raea.app's welcome+ b.set_children(vec![nav, layer, panel, welcome]);+ let mut p = AkNode::new(Role::Complementary);+ p.set_hidden();+ p.set_children(vec![inside]);+ TreeUpdate {+ nodes: vec![(win, root), (body, b), (layer, AkNode::new(Role::GenericContainer)), (panel, p), (inside, AkNode::new(Role::Button)), (welcome, named(Role::Button, "Welcome")), (nav, named(Role::Navigation, "Rail"))],+ tree: Some(Tree::new(win)),+ tree_id: TreeId::ROOT,+ focus: win,+ }+ };+ let listed = |u: TreeUpdate| {+ let t = accesskit_consumer::Tree::new(u, true);+ let root = t.state().root();+ root.filtered_children(accesskit_consumer::common_filter).filter_map(|n| n.label()).collect::<Vec<_>>()+ };+ assert_eq!(listed(update()), vec!["Rail".to_string()], "AccessKit lists what follows now: unhide may go");+ let mut u = update();+ unhide(&mut u, win);+ assert_eq!(listed(u), vec!["Rail".to_string(), "Welcome".to_string()], "the welcome is listed");+}++/// A name's parts are spaced by how they're laid out, where the host says: spans styled as blocks don't run together.+#[test]+fn a_name_spaces_parts_laid_out_as_blocks() {+ struct Blocks(bool);+ impl Facts<u64> for Blocks {+ 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, _: u64) -> bool { false }+ fn checked(&self, _: u64) -> bool { false }+ fn test_id(&self, _: u64) -> Option<String> { None }+ fn block(&self, _: u64) -> Option<bool> { Some(self.0) }+ }+ let name = |block| {+ let els = HashMap::from([+ (1, el("button", None, vec![2, 4], None, json!({}))),+ (2, el("span", Some(1), vec![3], None, json!({}))),+ (3, el("text", Some(2), vec![], Some("Sonnet 5.5"), json!({}))),+ (4, el("span", Some(1), vec![5], None, json!({}))),+ (5, el("text", Some(4), vec![], Some("Most efficient"), json!({}))),+ ]);+ let roots = (1..=5).map(|k| (k, 0)).collect();+ let (u, _) = tree(els, roots, &Blocks(block), None, |k| k + 100, NodeId(7), None, |_| None);+ u.nodes.iter().find(|(i, _)| *i == NodeId(101)).unwrap().1.label().map(str::to_string)+ };+ assert_eq!(name(true).as_deref(), Some("Sonnet 5.5 Most efficient"));+ assert_eq!(name(false).as_deref(), Some("Sonnet 5.5Most efficient"));+}diff --git a/tools/layers.toml b/tools/layers.tomlindex 2cacb4ef..ba2c1090 100644--- a/tools/layers.toml+++ b/tools/layers.toml@@ -239,6 +239,7 @@ raea-rune-layer = "runtime"raea-rune-slots = "runtime"raea-page-stage = "runtime"raea-page-window = "runtime"+raea-page-ax = "runtime"raea-page-sound = "runtime"raea-runtime-react = "runtime"raea-runtime-track = "runtime"