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.

The page's dialogs open in raea's window, and macOS lists overlays and takes typed values

shinyobjectz3081ab72c674
diff --git a/engine/page/host/src/ax.rs b/engine/page/host/src/ax.rs
index 9fc0c303..ca1592ca 100644
--- a/engine/page/host/src/ax.rs
+++ b/engine/page/host/src/ax.rs
@@ -53,11 +53,7 @@ impl Plugin for AxPlugin {
/// 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 {
+ if !world.get_resource::<AccessibilityRequested>().is_some_and(|r| r.get()) {
return;
}
let (now, frame) = (Instant::now(), world.resource::<Frame>().0);
@@ -68,7 +64,7 @@ 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(update) = crate::page::with_doc(world, |doc, nodes| {
+ let Some(mut 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));
@@ -82,6 +78,7 @@ fn publish(world: &mut World) {
}) else {
return;
};
+ raea_sys_a11y::unhide(&mut update, root);
ACCESS_KIT_ADAPTERS.with_borrow_mut(|adapters| {
if let Some(a) = adapters.get_mut(&win) {
a.update_if_active(|| update);
diff --git a/engine/page/host/src/idle.rs b/engine/page/host/src/idle.rs
index ff74d929..40f8c5fa 100644
--- a/engine/page/host/src/idle.rs
+++ b/engine/page/host/src/idle.rs
@@ -11,10 +11,6 @@ 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;
@@ -26,19 +22,13 @@ impl Plugin for IdlePlugin {
}
}
-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>) {
+fn rest(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, 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;
- }
+ let (focused, unfocused) = modes(*quiet);
if settings.focused_mode != focused || settings.unfocused_mode != unfocused {
settings.focused_mode = focused;
settings.unfocused_mode = unfocused;
diff --git a/sdk/ui/src/dom/keys.ts b/sdk/ui/src/dom/keys.ts
index 52ff091b..206d1e2a 100644
--- a/sdk/ui/src/dom/keys.ts
+++ b/sdk/ui/src/dom/keys.ts
@@ -1,6 +1,6 @@
// Keys and activation: focus targets, Space and Enter clicks, and form submission.
import * as wire from "../wire";
-import { Control_, Element_, Event_, HTMLButtonElement_, HTMLFormElement_, HTMLInputElement_, HTMLLabelElement_, HTMLOptionElement_, HTMLSelectElement_, InputEvent_, KeyboardEvent_, MODS, Node_, PointerEvent_, S, SubmitEvent_, disabledEl, dispatch, doc, editKey, focusTo, focusable, g, installed, isField, keyInit, query } from "./all";
+import { Control_, Element_, HTMLDialogElement_, modals, Event_, HTMLButtonElement_, HTMLFormElement_, HTMLInputElement_, HTMLLabelElement_, HTMLOptionElement_, HTMLSelectElement_, InputEvent_, KeyboardEvent_, MODS, Node_, PointerEvent_, S, SubmitEvent_, disabledEl, dispatch, doc, editKey, focusTo, focusable, g, installed, isField, keyInit, query } from "./all";
/** An edit's inputType and data, from a field's value before and after it: what was put in (insertText, the text),
* else what was taken out (deleteContentBackward, or Forward when the caret's side stayed). */
@@ -58,6 +58,11 @@ export function key(t: Element_, payload: any) {
break;
}
}
+ // Escape on an open modal dialog: its cancel, and it closes unless that's prevented (as Chrome's)
+ if (ok && init.key === "Escape") {
+ const top = modals.at(-1) as HTMLDialogElement_ | undefined;
+ if (top?.isConnected && top.open) top.requestClose();
+ }
const type = (t as Control_).type;
// Enter's activation is keydown's default action (before keyup); Space's is keyup's
if (ok && init.key === "Enter" && !init.altKey) {
diff --git a/sdk/ui/src/dom/media.ts b/sdk/ui/src/dom/media.ts
index 787ecca7..09488b26 100644
--- a/sdk/ui/src/dom/media.ts
+++ b/sdk/ui/src/dom/media.ts
@@ -2,7 +2,7 @@
import * as wire from "../wire";
import { canvasClass } from "../canvas";
import { outline, pointAtLength, totalLength } from "./svg-length";
-import { DocumentFragment_, Element_, Event_, HTMLAnchorElement_, HTMLButtonElement_, HTMLDivElement_, HTMLElement_, HTMLFormElement_, HTMLInputElement_, HTMLLIElement_, HTMLLabelElement_, HTMLOptionElement_, HTMLSelectElement_, HTMLSpanElement_, HTMLTextAreaElement_, HTMLUListElement_, MediaNews, Node_, S, SVG_NS, SVG_TAGS, Text_, byWid, dispatchDirect, focusTo, g, pageUrl, transition } from "./all";
+import { DocumentFragment_, Element_, Event_, HTMLAnchorElement_, HTMLButtonElement_, HTMLDivElement_, HTMLElement_, HTMLFormElement_, HTMLInputElement_, HTMLLIElement_, HTMLLabelElement_, HTMLOptionElement_, HTMLSelectElement_, HTMLSpanElement_, HTMLTextAreaElement_, HTMLUListElement_, MediaNews, Node_, S, SVG_NS, SVG_TAGS, Text_, byWid, dispatchDirect, focusTo, g, pageUrl, transition, dispatch, focusable, query } from "./all";
export class HTMLImageElement_ extends HTMLElement_ {
_media?: MediaNews;
@@ -218,7 +218,57 @@ export class HTMLIFrameElement_ extends HTMLElement_ {
}
}
-export class HTMLDialogElement_ extends HTMLElement_ {}
+/** The modal dialogs open, the topmost last: Escape asks the topmost to close (its cancel event). */
+export const modals: Element_[] = [];
+
+/** <dialog>, as Chrome's: open is its attribute; show and showModal open it (showModal focuses what's in it: its
+ * autofocus, else its first focusable); close shuts it, keeps returnValue, and fires close after; Escape on a modal one
+ * fires cancel, and shuts it unless that's prevented. raea cloud's sheets (sheet.js) are one opened with showModal:
+ * without it the rail's + and every sheet threw in raea.app (11-23). Blitz never matches :modal, so a modal one is
+ * placed by the page's CSS (the sheet's is fixed) and not raised to a top layer. */
+export class HTMLDialogElement_ extends HTMLElement_ {
+ _returnValue = "";
+ get open() {
+ return this.hasAttribute("open");
+ }
+ set open(v: boolean) {
+ this.toggleAttribute("open", !!v);
+ }
+ get returnValue() {
+ return this._returnValue;
+ }
+ set returnValue(v: string) {
+ this._returnValue = String(v);
+ }
+ show() {
+ if (!this.open) this.setAttribute("open", "");
+ }
+ showModal() {
+ if (this.open) {
+ if (modals.includes(this)) return;
+ throw new DOMException("The dialog is already open as a non-modal dialog.", "InvalidStateError");
+ }
+ if (!this.isConnected) throw new DOMException("The dialog is not connected.", "InvalidStateError");
+ this.setAttribute("open", "");
+ modals.push(this);
+ const all = query(this, "*", false) as Element_[];
+ const first = all.find((e) => e.hasAttribute("autofocus") && focusable(e)) ?? all.find((e) => focusable(e));
+ if (first) focusTo(first, true);
+ }
+ close(returnValue?: string) {
+ if (!this.open) return;
+ if (returnValue !== undefined) this._returnValue = String(returnValue);
+ this.removeAttribute("open");
+ const i = modals.indexOf(this);
+ if (i >= 0) modals.splice(i, 1);
+ // after, as a task (Chrome queues it): what closed it has finished first
+ setTimeout(() => dispatch(this, new Event_("close"), true), 0);
+ }
+ requestClose(returnValue?: string) {
+ if (!this.open) return;
+ if (dispatch(this, new Event_("cancel", { cancelable: true }), true)) this.close(returnValue);
+ }
+}
/** canvas: getContext("2d") draws on the host (src/canvas.ts) */
export const HTMLCanvasElement_ = canvasClass(HTMLElement_);
diff --git a/sdk/ui/test/dom.test.tsx b/sdk/ui/test/dom.test.tsx
index 20133b44..6bf0d89e 100644
--- a/sdk/ui/test/dom.test.tsx
+++ b/sdk/ui/test/dom.test.tsx
@@ -139,6 +139,38 @@ describe("P18 DOM surface", () => {
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[] = [];
diff --git a/systems/a11y/src/lib.rs b/systems/a11y/src/lib.rs
index 1153ee9d..cc078d57 100644
--- a/systems/a11y/src/lib.rs
+++ b/systems/a11y/src/lib.rs
@@ -149,6 +149,14 @@ fn node_of<K: Copy + Eq + std::hash::Hash>(cx: &Ctx<K>, e: K, el: &El<K>, focus:
{
n.add_action(Action::Click);
}
+ // a field typed in takes a value (macOS sends setAccessibilityValue only to a node that has it, or text ranges,
+ // which the tree doesn't carry): an AX client's or Voice Control's text, typed over what the field held (ax.rs)
+ if !disabled
+ && !(truthy(p("readOnly")) || truthy(p("readonly")) || s(p("aria-readonly")).as_deref() == Some("true"))
+ && matches!(role, Role::TextInput | Role::MultilineTextInput | Role::SearchInput | Role::EmailInput | Role::PasswordInput | Role::PhoneNumberInput | Role::UrlInput | Role::NumberInput | Role::SpinButton)
+ {
+ n.add_action(Action::SetValue);
+ }
// 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() {
@@ -239,6 +247,7 @@ fn node_of<K: Copy + Eq + std::hash::Hash>(cx: &Ctx<K>, e: K, el: &El<K>, focus:
/// 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`.
+#[allow(clippy::too_many_arguments)] // each is its own input: the page, its facts, focus, ids, the window and boxes
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 {
@@ -284,6 +293,35 @@ pub fn tree<K: Copy + Eq + std::hash::Hash>(els: HashMap<K, El<K>>, roots: HashM
(TreeUpdate { nodes, tree: Some(Tree::new(window)), tree_id: TreeId::ROOT, focus: focus_id }, tested)
}
+/// The update without its hidden nodes (each with what's in it), as a platform's tree from Chrome has none: AccessKit's
+/// filtered walk (accesskit_consumer 0.38's next_filtered_sibling) stops for good at a hidden node that follows an
+/// empty container (a layer with nothing in it, then raea cloud's closed side panel), and everything after them in
+/// their parent was gone from what macOS lists: raea.app's welcome and every sheet (11-23). Focus on what's gone is
+/// the window's.
+pub fn unhide(update: &mut TreeUpdate, window: NodeId) {
+ let kids: HashMap<NodeId, Vec<NodeId>> = update.nodes.iter().map(|(id, n)| (*id, n.children().to_vec())).collect();
+ let mut gone = std::collections::HashSet::new();
+ let mut stack: Vec<NodeId> = update.nodes.iter().filter(|(_, n)| n.is_hidden()).map(|(id, _)| *id).collect();
+ while let Some(id) = stack.pop() {
+ if gone.insert(id) {
+ stack.extend(kids.get(&id).into_iter().flatten().copied());
+ }
+ }
+ if gone.is_empty() {
+ return;
+ }
+ update.nodes.retain(|(id, _)| !gone.contains(id));
+ for (_, n) in &mut update.nodes {
+ if n.children().iter().any(|c| gone.contains(c)) {
+ let left: Vec<NodeId> = n.children().iter().copied().filter(|c| !gone.contains(c)).collect();
+ n.set_children(left);
+ }
+ }
+ if gone.contains(&update.focus) {
+ update.focus = window;
+ }
+}
+
/// 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).
@@ -443,4 +481,52 @@ mod tests {
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");
+ }
}