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.

LR7: a composition's document, with LR5's style and LR8's observers. LR5: el.style reads and writes the element's style (writes send an update op; React's next commit to the property wins), and getComputedStyle answers from the page's computed style: page.layout takes { styles: [ids] } and the snapshot carries s: {id: {property: value}} for them, as stylo serializes it (engine/page read.rs computed_style), kept until the next commit (page-layout.ts computedOf). LR7: document has body (the composition's surface, the element the page draws from), documentElement, getElementById, querySelector(All), createElement (appended into the composition it's laid out and measurable, removed it's gone; a canvas is an OffscreenCanvas), createTextNode and createRange: a Range over a text node is its characters laid out in the parent's computed font, placed where the parent's line starts. An svg <text> has getComputedTextLength, getNumberOfChars, getStartPositionOfChar, getEndPositionOfChar and getSubStringLength, laid out by usvg in the element's computed font (canvas.svgText: family, size, weight, letter- and word-spacing, font-variation-settings). document.fonts loads a family the composition asked for (fonts.load), and a FontFace given by URL is fetched through raea's cache into the faces an svg's and a canvas's text are set in (fonts.face). window is globalThis with innerWidth, innerHeight, devicePixelRatio and getComputedStyle. LR8: ResizeObserver calls back after a commit whose layout changed an observed element's size, and once on observe, with contentRect, borderBoxSize and contentBoxSize; while a delayRender hold is open it checks every 16 ms, as a browser renders while a page waits. MutationObserver and IntersectionObserver exist and never call back. A pass that draws no page (the sound pass, the 3D rows' pre-pass) answers reads with a 0 x 0 page, and its holds are released (page-layout.ts noPage): a hold waiting on a measure could never end there. probes/document.tsx and probes/observe.tsx match Chrome within 1 px

shinyobjectza5d89e95c19c
diff --git a/Cargo.lock b/Cargo.lock
index b7e5f98e..59fcaa80 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -14525,6 +14525,7 @@ dependencies = [
"serde_json",
"stylo",
"url",
+ "usvg 0.48.1",
"vello",
"wgpu",
]
diff --git a/engine/page/src/motion/read.rs b/engine/page/src/motion/read.rs
index ec94bad6..bda16283 100644
--- a/engine/page/src/motion/read.rs
+++ b/engine/page/src/motion/read.rs
@@ -140,11 +140,22 @@ impl BlitzPage {
}
/// The page's layout as a composition's script reads it (`page.layout`, docs/layout-reads.feature LR1): raea-sys-page's
- /// snapshot with offsets, each element under the id `id` gives it (None leaves it out). Lay the page out first.
- pub fn layout_snapshot(&self, id: impl Fn(u64) -> Option<u64>) -> String {
+ /// snapshot with offsets, each element under the id `id` gives it (None leaves it out), and `s`, the computed style
+ /// of the elements in `styles` (op ids; getComputedStyle, LR5). Lay the page out first.
+ pub fn layout_snapshot(&self, id: impl Fn(u64) -> Option<u64>, styles: &[u64]) -> String {
let docs = self.app.world().non_send::<Docs>();
let Some(doc) = docs.0.get(&self.page) else { return "{\"vw\":0,\"vh\":0,\"n\":[],\"o\":[]}".into() };
- raea_sys_page::snapshot_by(doc, &self.nodes, id, true)
+ let snap = raea_sys_page::snapshot_by(doc, &self.nodes, &id, true);
+ if styles.is_empty() {
+ return snap;
+ }
+ let mut s = serde_json::Map::new();
+ for &op in styles {
+ let (Some(&n), Some(key)) = (self.nodes.by_id.get(&op), id(op)) else { continue };
+ let Some(cs) = doc.get_node(n).and_then(|n| n.primary_styles()) else { continue };
+ s.insert(key.to_string(), computed_style(&cs));
+ }
+ format!("{},\"s\":{}}}", &snap[..snap.len() - 1], serde_json::Value::Object(s))
}
/// The element the ops made that's topmost at the point (page px), as Blitz's hit test finds it (transforms and
@@ -210,3 +221,25 @@ impl BlitzPage {
raea_sys_layers::with(|r| r.frame((now * fps).round() as i64, w, h, &px, &layers));
}
}
+
+/// What getComputedStyle answers (LR5): these properties' computed values, as stylo serializes them (Chrome's spelling:
+/// px lengths, rgb() colours, a font list as written).
+const COMPUTED: &[&str] = &[
+ "display", "position", "visibility", "opacity", "color", "background-color", "font-family", "font-size", "font-weight", "font-style", "font-stretch",
+ "line-height", "letter-spacing", "word-spacing", "text-align", "text-transform", "text-indent", "white-space", "font-feature-settings", "font-variation-settings",
+ "width", "height", "top", "right", "bottom", "left", "margin-top", "margin-right", "margin-bottom", "margin-left", "padding-top", "padding-right",
+ "padding-bottom", "padding-left", "border-top-width", "border-right-width", "border-bottom-width", "border-left-width", "box-sizing", "transform",
+ "transform-origin", "z-index", "overflow-x", "overflow-y", "flex-direction", "justify-content", "align-items", "gap", "filter",
+];
+
+/// An element's computed style as {property: value} for [`COMPUTED`].
+fn computed_style(cs: &style::properties::ComputedValues) -> serde_json::Value {
+ use style::properties::{PropertyDeclarationId, PropertyId};
+ let mut out = serde_json::Map::new();
+ for name in COMPUTED {
+ if let Some(id) = PropertyId::parse_enabled_for_all_content(name).ok().and_then(|p| p.longhand_id()) {
+ out.insert((*name).into(), cs.computed_value_to_string(PropertyDeclarationId::Longhand(id)).into());
+ }
+ }
+ serde_json::Value::Object(out)
+}
diff --git a/runtime/canvas/Cargo.toml b/runtime/canvas/Cargo.toml
index 92827e26..8c5b6067 100644
--- a/runtime/canvas/Cargo.toml
+++ b/runtime/canvas/Cargo.toml
@@ -11,6 +11,8 @@ description = "A composition's 2D context's host calls as native calls: measureT
raea-native = { path = "../../engine/native", default-features = false }
# the canvas's replay, its text shaping and its read-back
raea-sys-canvas = { path = "../../systems/canvas" }
+# a Google family's faces fetched for a canvas now (fonts.load)
+raea-sys-fonts = { path = "../../systems/fonts" }
# the page's font database (every face the composition loaded), which a canvas draws its text in
blitz-dom = { version = "=0.3.0-beta.4", default-features = false, features = ["svg"] }
serde_json = "1"
diff --git a/runtime/canvas/src/lib.rs b/runtime/canvas/src/lib.rs
index 18080025..b05f9df7 100644
--- a/runtime/canvas/src/lib.rs
+++ b/runtime/canvas/src/lib.rs
@@ -14,6 +14,33 @@ pub fn register() {
"measureText: the text shaped as the canvas draws it, in the page's fonts; its advance, ink and font box from the alignment point (docs/layout-reads.feature LR6)",
|a| raea_sys_canvas::metrics(a),
);
+ raea_native::register(
+ "fonts.load",
+ "{ family: string }",
+ "{ faces: number }",
+ "document.fonts.load: a family the composition asked for (loadFont), its faces given to a canvas's text now, where the page fetches it only once an element names it (docs/layout-reads.feature LR7); how many faces it has",
+ |a| {
+ let family = a["family"].as_str().ok_or("fonts.load: no family")?;
+ Ok(serde_json::json!({ "faces": raea_sys_fonts::google::load_now(family) }))
+ },
+ );
+ raea_native::register(
+ "fonts.face",
+ "{ family: string; url: string }",
+ "{ faces: number }",
+ "FontFace.load for a face given by URL: fetched now, through raea's cache, into the faces an svg's and a canvas's text are set in, as `family` (docs/layout-reads.feature LR7); 0 faces when it doesn't load",
+ |a| {
+ let (Some(family), Some(url)) = (a["family"].as_str(), a["url"].as_str()) else { return Err("fonts.face: a family and a url".into()) };
+ Ok(serde_json::json!({ "faces": raea_sys_fonts::google::face_now(family, url) }))
+ },
+ );
+ raea_native::register(
+ "canvas.svgText",
+ "{ text: string; style: Record<string, string> }",
+ "{ length: number; starts: number[] }",
+ "an svg <text>'s getComputedTextLength and getStartPositionOfChar: its words laid out by usvg, as the page draws an svg, in its computed font (font-*, letter-spacing, word-spacing); x from the text's own (docs/layout-reads.feature LR7)",
+ |a| raea_sys_canvas::svg_text(a),
+ );
raea_native::register(
"canvas.advances",
"{ font: { family: string; weight: string; style: string }; chars: string }",
diff --git a/runtime/export/src/bevy_frame.rs b/runtime/export/src/bevy_frame.rs
index dab0207b..c753209c 100644
--- a/runtime/export/src/bevy_frame.rs
+++ b/runtime/export/src/bevy_frame.rs
@@ -230,11 +230,11 @@ pub(crate) fn bevy_page_frame(world: &mut World, page: &mut raea_runtime_page::B
/// A composition's layout read answered by the frame's page (`page.layout`, docs/layout-reads.feature LR1): the page made
/// to match the React World as it is mid-settle, at frame `f`'s time, laid out, and every element's boxes by React id.
/// Nothing is drawn; the frame's own sync redoes what this did once the frame settles.
-pub(crate) fn layout_answer(world: &mut World, page: &mut raea_runtime_page::BevyPage, cx: &mut Ctx, f: i64, fps: f64) -> R<String> {
+pub(crate) fn layout_answer(world: &mut World, page: &mut raea_runtime_page::BevyPage, cx: &mut Ctx, f: i64, fps: f64, request: &str) -> R<String> {
page.at_frame(f, fps);
page_with_holders(world, page, cx)?;
page.lay_out();
- Ok(page.layout_snapshot())
+ Ok(page.layout_snapshot(request))
}
/// The frame's page made to match the React tree, not drawn yet; the frame's sound, mix, marker and 3D rows collected
diff --git a/runtime/export/src/fed.rs b/runtime/export/src/fed.rs
index c56432a3..af45519a 100644
--- a/runtime/export/src/fed.rs
+++ b/runtime/export/src/fed.rs
@@ -225,7 +225,7 @@ pub(crate) fn render_fed(app: &mut App, js: &Path, w: u32, h: u32, fps: f64, tot
if asked != Some(f) {
app.world().resource::<ReactOutbox>().send(json!({"t": "event", "name": "raea-frame", "value": f}));
}
- settle_with(app, Some(f), 20.0, &mut |w| layout_answer(w, bevy, cx, f, fps))?;
+ settle_with(app, Some(f), 20.0, &mut |w, q| layout_answer(w, bevy, cx, f, fps, q))?;
cx.now = f;
// the next frame asked for now, so React renders it on its own thread while this one's 3D and page are
// drawn here: its commits wait in the inbox until the next settle applies them, so nothing this frame
diff --git a/runtime/export/src/render.rs b/runtime/export/src/render.rs
index 6c933bb0..a4b36e5d 100644
--- a/runtime/export/src/render.rs
+++ b/runtime/export/src/render.rs
@@ -276,7 +276,7 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Opti
let px = raea_gpu_device::check::frame_caught(f, || { // a panic drawing it an error naming it (#33)
engine_before(&app, &mut cx, f);
app.world().resource::<ReactOutbox>().send(json!({"t": "event", "name": "raea-frame", "value": f}));
- settle_with(&mut app, Some(f), 20.0, &mut |w| layout_answer(w, pg, &mut cx, f, fps))?;
+ settle_with(&mut app, Some(f), 20.0, &mut |w, q| layout_answer(w, pg, &mut cx, f, fps, q))?;
cx.now = f;
pg.at_frame(f, fps);
let mut px = bevy_over_3d(app.world_mut(), pg, &mut cx, fps)?;
@@ -317,7 +317,7 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Opti
for &f in &wanted {
let t0 = std::time::Instant::now();
app.world().resource::<ReactOutbox>().send(json!({"t": "event", "name": "raea-frame", "value": f}));
- settle_with(&mut app, Some(f), 20.0, &mut |w| layout_answer(w, &mut page, &mut cx, f, fps))?;
+ settle_with(&mut app, Some(f), 20.0, &mut |w, q| layout_answer(w, &mut page, &mut cx, f, fps, q))?;
cx.now = f;
let t1 = std::time::Instant::now();
page.at_frame(f, fps);
diff --git a/runtime/page/src/bevy_page.rs b/runtime/page/src/bevy_page.rs
index dfc6f06d..cbbacfdc 100644
--- a/runtime/page/src/bevy_page.rs
+++ b/runtime/page/src/bevy_page.rs
@@ -178,8 +178,13 @@ impl BevyPage {
/// Every React element's boxes as the page lays them out now (`page.layout`, docs/layout-reads.feature LR1), keyed by
/// React id: the page's own elements (the body, holders' parts) left out. Lay the page out first.
- pub fn layout_snapshot(&self) -> String {
- self.page.layout_snapshot(|id| (id >= REACT_IDS && id & TEXT_BIT == 0).then(|| id - REACT_IDS))
+ pub fn layout_snapshot(&self, request: &str) -> String {
+ // the elements whose computed style the read asks for (React ids; op ids here)
+ let styles: Vec<u64> = serde_json::from_str::<serde_json::Value>(request)
+ .ok()
+ .and_then(|v| v["styles"].as_array().map(|a| a.iter().filter_map(serde_json::Value::as_u64).map(|r| r + REACT_IDS).collect()))
+ .unwrap_or_default();
+ self.page.layout_snapshot(|id| (id >= REACT_IDS && id & TEXT_BIT == 0).then(|| id - REACT_IDS), &styles)
}
/// The React element topmost at the point (page px): its React id (none over the page's own body).
diff --git a/runtime/react/src/layout.rs b/runtime/react/src/layout.rs
index e006e0bb..9be1e1be 100644
--- a/runtime/react/src/layout.rs
+++ b/runtime/react/src/layout.rs
@@ -14,14 +14,17 @@ use bevy::prelude::{Resource, World};
use crate::scene::HANG_SECS;
/// A host's answer to a layout read: the page laid out as the React World has it now, its snapshot (raea-sys-page's,
-/// with offsets, keyed by React id) as JSON; or why it can't.
-pub type Answer<'a> = dyn FnMut(&mut World) -> Result<String, String> + 'a;
+/// with offsets, keyed by React id) as JSON; or why it can't. The read's request comes with it (page.layout's argument as
+/// JSON: `styles`, the elements whose computed style it wants, LR5).
+pub type Answer<'a> = dyn FnMut(&mut World, &str) -> Result<String, String> + 'a;
/// One runtime's layout read: asked by its JS thread, answered by its settle.
#[derive(Default)]
pub struct Ask {
/// the JS thread is waiting on a read
asked: AtomicBool,
+ /// what the read asks for (page.layout's argument)
+ request: Mutex<String>,
/// the read's answer, once settle has made it
answer: Mutex<Option<Result<String, String>>>,
told: Condvar,
@@ -49,7 +52,8 @@ pub(crate) fn answer_if_asked(ask: &Ask, world: &mut World, answer: &mut Answer)
return;
}
let t0 = Instant::now();
- let r = answer(world);
+ let q = std::mem::take(&mut *ask.request.lock().unwrap());
+ let r = answer(world, &q);
READS.fetch_add(1, Ordering::Relaxed);
READ_NS.fetch_add(t0.elapsed().as_nanos() as u64, Ordering::Relaxed);
*ask.answer.lock().unwrap() = Some(r);
@@ -61,8 +65,9 @@ pub static READS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::n
pub static READ_NS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// The JS thread's side (`page.layout`): ask, wake settle's wait, and block until the answer comes.
-fn read() -> Result<String, String> {
+fn read(request: String) -> Result<String, String> {
let ask = ASK.with(|a| a.borrow().clone()).ok_or("page.layout: this thread runs no composition")?;
+ *ask.request.lock().unwrap() = request;
let mut g = ask.answer.lock().unwrap();
*g = None;
ask.asked.store(true, Ordering::SeqCst);
@@ -84,10 +89,10 @@ fn read() -> Result<String, String> {
pub(crate) fn register() {
raea_native::register(
"page.layout",
- "{}",
+ "{ styles?: number[] }",
"string",
- "every element's boxes as the page that draws the frame lays it out now (docs/layout-reads.feature LR1): JSON {vw, vh, n: [id, x, y, w, h, scroll x y w h, padding l t r b, border l t r b, z per element], o: [id, offsetLeft, offsetTop, offsetWidth, offsetHeight, offsetParent, inline per element]}, keyed by React id; the composition's thread waits for it",
- |_| read().map(serde_json::Value::String),
+ "every element's boxes as the page that draws the frame lays it out now (docs/layout-reads.feature LR1): JSON {vw, vh, n: [id, x, y, w, h, scroll x y w h, padding l t r b, border l t r b, z per element], o: [id, offsetLeft, offsetTop, offsetWidth, offsetHeight, offsetParent, inline per element]}, keyed by React id, and s: {id: {property: computed value}} for the elements in `styles` (LR5); the composition's thread waits for it",
+ |a| read(a.to_string()).map(serde_json::Value::String),
);
}
@@ -96,11 +101,11 @@ pub(crate) fn register() {
pub const NOTHING_DRAWN: &str = "{\"vw\":0,\"vh\":0,\"dpr\":1,\"n\":[],\"o\":[]}";
/// [`NOTHING_DRAWN`] as a pass's answer.
-pub fn nothing_drawn() -> impl FnMut(&mut World) -> Result<String, String> {
- |_| Ok(NOTHING_DRAWN.into())
+pub fn nothing_drawn() -> impl FnMut(&mut World, &str) -> Result<String, String> {
+ |_, _| Ok(NOTHING_DRAWN.into())
}
/// A host's answer when it has no page to lay out.
-pub fn no_page(host: &'static str) -> impl FnMut(&mut World) -> Result<String, String> {
- move |_| Err(format!("{host} lays no page out, so a composition can't read its layout here (getBoundingClientRect, offsetWidth and the rest)"))
+pub fn no_page(host: &'static str) -> impl FnMut(&mut World, &str) -> Result<String, String> {
+ move |_, _| Err(format!("{host} lays no page out, so a composition can't read its layout here (getBoundingClientRect, offsetWidth and the rest)"))
}
diff --git a/sdk/raea/src/dom-document.ts b/sdk/raea/src/dom-document.ts
new file mode 100644
index 00000000..3e6ad509
--- /dev/null
+++ b/sdk/raea/src/dom-document.ts
@@ -0,0 +1,285 @@
+// The composition's document and window (docs/layout-reads.feature LR7), over the tree bevy-react keeps (LR4) and the
+// page's layout (LR1). document.body is the composition's root; querySelector and getElementById search it. An element
+// made with createElement is a node of the page too: appended into the composition it's laid out, measured and drawn,
+// and removed it's gone, which is how components measure a hidden copy. A canvas made there is an OffscreenCanvas
+// (canvas2d.ts). document.fonts loads a family the composition asked for (loadFont) into the faces a canvas measures
+// with. window is globalThis, with the composition's size, devicePixelRatio and getComputedStyle.
+import { native } from "@raea/app/native";
+import { OffscreenCanvas } from "./canvas2d";
+import { querySelectorAll, type El, type Node } from "./dom-tree";
+import { computed, declaration, parseCss, styleNow, writeStyle } from "./dom-style";
+import { computedOf, viewportSize } from "./page-layout";
+import { domRange } from "./dom-range";
+
+type Bevy = { BevyElement: new (id: number, type: string, kind: string, props: Record<string, unknown>) => El; BevyTextNode: new (id: number, data: string) => Node & { data: string }; containerNode: (id: number) => El };
+type Made = { made?: true; gone?: boolean };
+
+const HOST = (globalThis as any).__bevyHost;
+const send = (...ops: unknown[]) => HOST.op_flush(JSON.stringify(ops), false);
+// ids of nodes the document makes: far above React's allocator (and below cancelRender's, 2^52)
+let next = 2 ** 51;
+const isText = (n: unknown): n is Node & { data: string } => typeof (n as { data?: unknown }).data === "string" && !Array.isArray((n as El).childNodes);
+
+/** A node made here sent to the page again (one removed from it is despawned, its id forgotten), with its subtree. */
+function create(n: Node & Made): void {
+ if (isText(n)) {
+ send({ op: "createText", id: n.nodeId, text: n.data });
+ } else {
+ const el = n as El;
+ send({ op: "create", id: el.nodeId, kind: el.kind ?? el.type, props: { ...el.props, style: styleNow(el) } });
+ for (const c of el.childNodes) {
+ create(c as Node & Made);
+ send({ op: "append", parent: el.nodeId, child: c.nodeId });
+ }
+ }
+ n.gone = false;
+}
+
+function unlink(child: Node): void {
+ const p = child.parentNode;
+ if (!p) return;
+ p.childNodes.splice(p.childNodes.indexOf(child), 1);
+ (child as { parentNode: El | null }).parentNode = null;
+}
+
+/** Puts `child` under `parent`, before `before` (or last), on the page and in the tree. */
+function insert(parent: El, child: Node & Made, before: Node | null): Node {
+ if (child.parentNode) remove(child);
+ if (child.gone) create(child);
+ const at = before ? parent.childNodes.indexOf(before) : -1;
+ if (at >= 0) send({ op: "insert", parent: parent.nodeId, child: child.nodeId, before: before!.nodeId });
+ else send({ op: "append", parent: parent.nodeId, child: child.nodeId });
+ parent.childNodes.splice(at >= 0 ? at : parent.childNodes.length, 0, child);
+ (child as { parentNode: El | null }).parentNode = parent;
+ return child;
+}
+
+function remove(child: Node & Made): Node {
+ const p = child.parentNode;
+ if (!p) return child;
+ send({ op: "remove", parent: p.nodeId, child: child.nodeId });
+ unlink(child);
+ const mark = (n: Node & Made) => {
+ n.gone = true;
+ if (!isText(n)) (n as El).childNodes.forEach((c) => mark(c as Node & Made));
+ };
+ mark(child);
+ return child;
+}
+
+/** Props from an attribute (class, for and style as React names them). */
+const PROP: Record<string, string> = { class: "className", for: "htmlFor" };
+
+function writers(bevy: Bevy): void {
+ const p = bevy.BevyElement.prototype as Record<string, unknown>;
+ const def = (name: string, f: (this: El, ...a: any[]) => unknown) => Object.defineProperty(p, name, { value: f, writable: true, configurable: true });
+ def("appendChild", function (c: Node) {
+ return insert(this, c, null);
+ });
+ def("append", function (...cs: (Node | string)[]) {
+ for (const c of cs) insert(this, typeof c === "string" ? text(bevy, c) : c, null);
+ });
+ def("insertBefore", function (c: Node, b: Node | null) {
+ return insert(this, c, b);
+ });
+ def("removeChild", function (c: Node) {
+ return remove(c);
+ });
+ def("remove", function () {
+ remove(this);
+ });
+ def("replaceChildren", function (...cs: (Node | string)[]) {
+ [...this.childNodes].forEach((c) => remove(c));
+ for (const c of cs) insert(this, typeof c === "string" ? text(bevy, c) : c, null);
+ });
+ def("setAttribute", function (name: string, v: unknown) {
+ if (name === "style") return writeStyle(this, { ...Object.fromEntries(Object.keys(styleNow(this)).map((k) => [k, undefined])), ...parseCss(String(v)) });
+ const k = PROP[name] ?? name;
+ this.props = { ...this.props, [k]: String(v) };
+ send({ op: "update", id: this.nodeId, kind: this.kind ?? this.type, props: { [k]: String(v) } });
+ });
+ def("removeAttribute", function (name: string) {
+ const k = PROP[name] ?? name;
+ const { [k]: _, ...rest } = this.props;
+ this.props = rest;
+ send({ op: "update", id: this.nodeId, kind: this.kind ?? this.type, props: {}, unset: [k] });
+ });
+ def("cloneNode", function (deep = false) {
+ const c = element(bevy, this.type, { ...this.props, style: styleNow(this) });
+ if (deep) for (const k of this.childNodes) (c as any).appendChild(isText(k) ? text(bevy, k.data) : (k as any).cloneNode(true));
+ return c;
+ });
+ const set = (name: string, f: (this: El, v: any) => void) => {
+ const d = Object.getOwnPropertyDescriptor(p, name);
+ Object.defineProperty(p, name, { get: d?.get, set: f, configurable: true });
+ };
+ const setText = function (this: El, v: unknown) {
+ [...this.childNodes].forEach((c) => remove(c));
+ if (v != null && v !== "") insert(this, text(bevy, String(v)), null);
+ };
+ set("textContent", setText);
+ set("innerText", setText);
+ set("className", function (v) {
+ (this as any).setAttribute("class", v);
+ });
+ set("id", function (v) {
+ (this as any).setAttribute("id", v);
+ });
+}
+
+function element(bevy: Bevy, tag: string, props: Record<string, unknown> = {}): El {
+ const el = new bevy.BevyElement(next++, tag, tag, props) as El & Made;
+ el.made = true;
+ send({ op: "create", id: el.nodeId, kind: tag, props });
+ return el;
+}
+
+function text(bevy: Bevy, data: string): Node {
+ const t = new bevy.BevyTextNode(next++, data) as Node & Made;
+ t.made = true;
+ send({ op: "createText", id: t.nodeId, text: data });
+ return t;
+}
+
+/** A CSS font shorthand's families ("500 100px 'Instrument Serif', serif" -> ["Instrument Serif", "serif"]). */
+const families = (font: string) => (String(font).match(/\d[\d.]*(?:px|pt|em|rem|%)(?:\/\S+)?\s+(.+)$/)?.[1] ?? String(font)).split(",").map((f) => f.trim().replace(/^["']|["']$/g, "")).filter(Boolean);
+
+class FontFace_ {
+ status = "unloaded";
+ readonly loaded: Promise<FontFace_>;
+ private done!: (f: FontFace_) => void;
+ constructor(readonly family: string, readonly source: unknown, readonly descriptors: Record<string, string> = {}) {
+ this.loaded = new Promise((r) => (this.done = r));
+ }
+ /** A face given by URL is fetched now into the faces an svg's and a canvas's text are set in (fonts.face); one
+ * named only by family is the family the composition asked for (loadFont). One that doesn't load rejects, as in
+ * Chrome, so the text falls back. */
+ load(): Promise<FontFace_> {
+ const url = typeof this.source === "string" ? /url\(\s*["']?([^"')]+)["']?\s*\)/.exec(this.source)?.[1] : undefined;
+ const faces = url ? native("fonts.face", { family: this.family, url }).faces : native("fonts.load", { family: this.family }).faces;
+ if (url && !faces) {
+ this.status = "error";
+ return Promise.reject(new Error(`FontFace ${this.family}: ${url} didn't load`));
+ }
+ this.status = "loaded";
+ this.done(this);
+ return this.loaded;
+ }
+}
+
+/** document.fonts: a family loads into the faces a canvas measures with (fonts.load); the page's own text has its
+ * faces before the frame is taken, so `ready` is settled. */
+function fontSet() {
+ const faces = new Set<FontFace_>();
+ return {
+ status: "loaded",
+ ready: Promise.resolve(undefined as unknown),
+ load(font: string): Promise<FontFace_[]> {
+ for (const family of families(font)) native("fonts.load", { family });
+ return Promise.resolve([...faces].filter((f) => families(font).includes(f.family)));
+ },
+ check: () => true,
+ add(f: FontFace_) {
+ faces.add(f);
+ return this;
+ },
+ delete: (f: FontFace_) => faces.delete(f),
+ has: (f: FontFace_) => faces.has(f),
+ forEach: (cb: (f: FontFace_) => void) => faces.forEach(cb),
+ get size() {
+ return faces.size;
+ },
+ addEventListener() {},
+ removeEventListener() {},
+ [Symbol.iterator]: () => faces.values(),
+ };
+}
+
+/** The document and window, once, from dom-reads. */
+export function domDocument(bevy: Bevy): void {
+ const g = globalThis as any;
+ if (!bevy?.BevyElement || !bevy.containerNode || g.document || !HOST?.op_flush) return;
+ writers(bevy);
+ // the page's body: the composition's surface, the element the page draws from (raea-runtime-page's sync walks it),
+ // found when first asked (the composition mounts after this runs); React's root container until it's there
+ const root = bevy.containerNode(0);
+ let surface: El | null = null;
+ const bodyNow = (): El => {
+ if (surface?.parentNode) return surface;
+ const look = (e: El): El | null => {
+ for (const c of e.childNodes ?? []) {
+ const k = c as El;
+ if ((k.kind ?? k.type) === "surface" && k.props?.id === "motion") return k;
+ const f = k.childNodes ? look(k) : null;
+ if (f) return f;
+ }
+ return null;
+ };
+ surface = look(root);
+ return surface ?? root;
+ };
+ const html = {
+ tagName: "HTML",
+ nodeName: "HTML",
+ nodeType: 1,
+ get clientWidth() {
+ return viewportSize()[0];
+ },
+ get clientHeight() {
+ return viewportSize()[1];
+ },
+ get style() {
+ return declaration(bodyNow());
+ },
+ get children() {
+ return [bodyNow()];
+ },
+ getBoundingClientRect: () => (bodyNow() as any).getBoundingClientRect?.(),
+ appendChild: (c: Node) => insert(bodyNow(), c, null),
+ contains: (n: Node) => n === bodyNow() || (bodyNow() as any).contains?.(n),
+ };
+ const all = () => [bodyNow(), ...querySelectorAll(bodyNow(), "*")];
+ const document = {
+ nodeType: 9,
+ nodeName: "#document",
+ readyState: "complete",
+ visibilityState: "visible",
+ hidden: false,
+ get body() {
+ return bodyNow();
+ },
+ get head() {
+ return bodyNow();
+ },
+ documentElement: html,
+ fonts: fontSet(),
+ defaultView: g,
+ createElement: (tag: string) => (String(tag).toLowerCase() === "canvas" ? new OffscreenCanvas() : element(bevy, String(tag).toLowerCase())),
+ createElementNS: (_: string, tag: string) => element(bevy, String(tag)),
+ createTextNode: (data: string) => text(bevy, String(data)),
+ createDocumentFragment: () => element(bevy, "div"),
+ getElementById: (id: string) => all().find((e) => e.props?.id === id) ?? null,
+ getElementsByClassName: (c: string) => querySelectorAll(bodyNow(), String(c).split(/\s+/).filter(Boolean).map((x) => `.${x}`).join("")),
+ getElementsByTagName: (t: string) => querySelectorAll(bodyNow(), t),
+ querySelector: (s: string) => querySelectorAll(bodyNow(), s)[0] ?? null,
+ querySelectorAll: (s: string) => querySelectorAll(bodyNow(), s),
+ contains: (n: Node) => n === bodyNow() || all().includes(n as El),
+ addEventListener() {},
+ removeEventListener() {},
+ };
+ domRange(document);
+ g.document = document;
+ g.window ??= g;
+ g.FontFace ??= FontFace_;
+ // the values the page computed for the element (LR5)
+ g.getComputedStyle ??= (el: El) => computed(el, computedOf);
+ for (const [k, f] of [
+ ["innerWidth", () => viewportSize()[0]],
+ ["innerHeight", () => viewportSize()[1]],
+ ["devicePixelRatio", () => 1],
+ ] as const) {
+ if (!(k in g)) Object.defineProperty(g, k, { get: f, configurable: true });
+ }
+ g.addEventListener ??= () => {};
+ g.removeEventListener ??= () => {};
+}
diff --git a/sdk/raea/src/dom-observers.ts b/sdk/raea/src/dom-observers.ts
new file mode 100644
index 00000000..84df5817
--- /dev/null
+++ b/sdk/raea/src/dom-observers.ts
@@ -0,0 +1,104 @@
+// Observers (docs/layout-reads.feature LR8), from the layout the reads get (LR1). A ResizeObserver calls back after a
+// commit whose layout changed an observed element's size, and once when it starts observing one, as Chrome does: each
+// entry has contentRect, borderBoxSize and contentBoxSize. The check runs only while something is observed, on the
+// turn after a commit, so a composition with no observer lays nothing out for it.
+// MutationObserver and IntersectionObserver are here so components that make one don't throw, but they never call
+// back: no component the harness runs needs them to (the manual says so).
+
+import { DOMRect } from "./dom-reads";
+import { boxOf, type Box } from "./page-layout";
+
+type El = { nodeId: number };
+type Size = { inlineSize: number; blockSize: number };
+type Entry = { target: El; contentRect: DOMRect; borderBoxSize: Size[]; contentBoxSize: Size[]; devicePixelContentBoxSize: Size[] };
+type Callback = (entries: Entry[], observer: ResizeObserver_) => void;
+
+const HOST = (globalThis as any).__bevyHost;
+const live = new Set<ResizeObserver_>();
+let queued = false;
+
+/** The content box (layout size less padding and border) and border box of `b`. */
+function sizes(b: Box): { border: Size; content: Size; left: number; top: number } {
+ const [w, h] = [b.layout[2], b.layout[3]];
+ const cw = Math.max(0, w - b.padding[0] - b.padding[2] - b.border[0] - b.border[2]);
+ const ch = Math.max(0, h - b.padding[1] - b.padding[3] - b.border[1] - b.border[3]);
+ return { border: { inlineSize: w, blockSize: h }, content: { inlineSize: cw, blockSize: ch }, left: b.padding[0], top: b.padding[1] };
+}
+
+/** A frame held by delayRender (its holds, named in `open`): Chrome goes on rendering frames while a page waits,
+ * each checking its observers, so a held frame here checks every 16 ms as well (as frame-globals pumps rAF). */
+const holding = () => ((globalThis as { __raeaHold?: { open?: Map<number, string> } }).__raeaHold?.open?.size ?? 0) > 0;
+
+/** On the next turn, each observer whose elements changed size calls back. */
+function schedule(ms = 0): void {
+ if (queued || !live.size) return;
+ queued = true;
+ setTimeout(() => {
+ queued = false;
+ for (const o of [...live]) o._check();
+ if (holding()) schedule(16);
+ }, ms);
+}
+
+class ResizeObserver_ {
+ private seen = new Map<El, string>();
+ constructor(private cb: Callback) {}
+ observe(el: El) {
+ if (!this.seen.has(el)) this.seen.set(el, "");
+ live.add(this);
+ schedule();
+ }
+ unobserve(el: El) {
+ this.seen.delete(el);
+ if (!this.seen.size) live.delete(this);
+ }
+ disconnect() {
+ this.seen.clear();
+ live.delete(this);
+ }
+ _check() {
+ const entries: Entry[] = [];
+ for (const [el, was] of this.seen) {
+ const b = boxOf(el.nodeId);
+ const s = b ? sizes(b) : { border: { inlineSize: 0, blockSize: 0 }, content: { inlineSize: 0, blockSize: 0 }, left: 0, top: 0 };
+ const key = `${s.content.inlineSize},${s.content.blockSize},${s.border.inlineSize},${s.border.blockSize}`;
+ if (key === was) continue;
+ this.seen.set(el, key);
+ entries.push({
+ target: el,
+ contentRect: new DOMRect(s.left, s.top, s.content.inlineSize, s.content.blockSize),
+ borderBoxSize: [s.border],
+ contentBoxSize: [s.content],
+ devicePixelContentBoxSize: [s.content],
+ });
+ }
+ if (entries.length) this.cb(entries, this);
+ }
+}
+
+/** An observer that never calls back (LR8: no component the harness runs needs it to). */
+class Silent {
+ constructor(_cb?: unknown, _opts?: unknown) {}
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ takeRecords() {
+ return [];
+ }
+}
+
+/** Installs the observers on the global, once, from dom-reads; a commit schedules ResizeObserver's check. */
+export function domObservers(): void {
+ const g = globalThis as Record<string, unknown>;
+ g.ResizeObserver ??= ResizeObserver_;
+ g.MutationObserver ??= Silent;
+ g.IntersectionObserver ??= Silent;
+ if (!HOST?.op_flush || HOST.__domObservers) return;
+ HOST.__domObservers = true;
+ const flush = HOST.op_flush;
+ HOST.op_flush = (json: string, devtools: boolean) => {
+ const r = flush(json, devtools);
+ schedule();
+ return r;
+ };
+}
diff --git a/sdk/raea/src/dom-range.ts b/sdk/raea/src/dom-range.ts
new file mode 100644
index 00000000..f490d8bb
--- /dev/null
+++ b/sdk/raea/src/dom-range.ts
@@ -0,0 +1,118 @@
+// document.createRange (docs/layout-reads.feature LR7): a Range over the composition's tree whose rects are read from
+// the page. A range inside one text node (setStart(node, i), setEnd(node, j): how a component measures each
+// character's advance) is that node's words laid out in its parent's computed font (dom-svgtext.ts's layoutText, the
+// faces the page draws with), placed where the parent's line starts: an inline parent's box, or a block's content box
+// as its text-align sets the line in it. One line: a range across wrapped lines gets one rect, the width of its
+// characters. A range over elements is their boxes.
+
+import { DOMRect } from "./dom-reads";
+import { boxOf, computedOf, type Box } from "./page-layout";
+import { layoutText } from "./dom-svgtext";
+
+type Node = { nodeId: number; parentNode: El | null; data?: string };
+type El = Node & { childNodes: Node[] };
+
+const isText = (n: Node) => typeof n.data === "string";
+const rect = (x: number, y: number, w: number, h: number) => new DOMRect(x, y, w, h);
+
+/** Where a text node's line starts in its parent, and the line's top and height. */
+function line(parent: El, b: Box, width: number): [number, number, number] {
+ if (b.inline) return [b.rect[0], b.rect[1], b.rect[3]];
+ const left = b.rect[0] + b.border[0] + b.padding[0];
+ const inner = b.rect[2] - b.border[0] - b.border[2] - b.padding[0] - b.padding[2];
+ const align = computedOf(parent.nodeId)?.["text-align"] ?? "start";
+ const free = Math.max(0, inner - width);
+ const dx = align === "center" ? free / 2 : align === "right" || align === "end" ? free : 0;
+ const top = b.rect[1] + b.border[1] + b.padding[1];
+ return [left + dx, top, b.rect[3] - b.border[1] - b.border[3] - b.padding[1] - b.padding[3]];
+}
+
+class Range_ {
+ startContainer: Node | null = null;
+ startOffset = 0;
+ endContainer: Node | null = null;
+ endOffset = 0;
+ get collapsed() {
+ return this.startContainer === this.endContainer && this.startOffset === this.endOffset;
+ }
+ get commonAncestorContainer() {
+ return this.startContainer === this.endContainer ? this.startContainer : (this.startContainer?.parentNode ?? null);
+ }
+ setStart(n: Node, i: number) {
+ this.startContainer = n;
+ this.startOffset = i;
+ if (!this.endContainer) this.setEnd(n, i);
+ }
+ setEnd(n: Node, i: number) {
+ this.endContainer = n;
+ this.endOffset = i;
+ }
+ setStartBefore(n: Node) {
+ this.setStart(n.parentNode ?? n, n.parentNode ? n.parentNode.childNodes.indexOf(n) : 0);
+ }
+ setEndAfter(n: Node) {
+ this.setEnd(n.parentNode ?? n, n.parentNode ? n.parentNode.childNodes.indexOf(n) + 1 : 0);
+ }
+ selectNode(n: Node) {
+ this.setStartBefore(n);
+ this.setEndAfter(n);
+ }
+ selectNodeContents(n: Node) {
+ this.setStart(n, 0);
+ this.setEnd(n, isText(n) ? n.data!.length : (n as El).childNodes.length);
+ }
+ collapse(toStart = false) {
+ if (toStart) this.setEnd(this.startContainer!, this.startOffset);
+ else this.setStart(this.endContainer!, this.endOffset);
+ }
+ cloneRange() {
+ const r = new Range_();
+ r.startContainer = this.startContainer;
+ r.startOffset = this.startOffset;
+ r.endContainer = this.endContainer;
+ r.endOffset = this.endOffset;
+ return r;
+ }
+ detach() {}
+ toString() {
+ const s = this.startContainer;
+ if (s && s === this.endContainer && isText(s)) return s.data!.slice(this.startOffset, this.endOffset);
+ return "";
+ }
+ getClientRects(): DOMRect[] {
+ const s = this.startContainer;
+ if (!s) return [];
+ // inside one text node: its characters, as its parent sets them
+ if (s === this.endContainer && isText(s)) {
+ const parent = s.parentNode;
+ const b = parent && boxOf(parent.nodeId);
+ if (!parent || !b) return [];
+ const l = layoutText(s.data!, parent.nodeId);
+ const at = (i: number) => (i >= l.starts.length ? l.length : (l.starts[i] ?? 0));
+ const [x0, top, h] = line(parent, b, l.length);
+ return [rect(x0 + at(this.startOffset), top, at(this.endOffset) - at(this.startOffset), h)];
+ }
+ // over elements: the boxes of the children it spans
+ const holder = (s === this.endContainer ? s : this.commonAncestorContainer) as El | null;
+ const kids = holder?.childNodes?.slice(this.startOffset, s === this.endContainer ? this.endOffset : undefined) ?? [];
+ const out: DOMRect[] = [];
+ for (const k of kids) {
+ const b = isText(k) ? undefined : boxOf(k.nodeId);
+ if (b) out.push(rect(b.rect[0], b.rect[1], b.rect[2], b.rect[3]));
+ }
+ return out;
+ }
+ getBoundingClientRect(): DOMRect {
+ const rs = this.getClientRects();
+ if (!rs.length) return rect(0, 0, 0, 0);
+ const x = Math.min(...rs.map((r) => r.left)), y = Math.min(...rs.map((r) => r.top));
+ return rect(x, y, Math.max(...rs.map((r) => r.right)) - x, Math.max(...rs.map((r) => r.bottom)) - y);
+ }
+}
+
+/** `document.createRange`, and Range on the global, once, from dom-document. */
+export function domRange(document: Record<string, unknown>): void {
+ document.createRange ??= () => new Range_();
+ const g = globalThis as { Range?: unknown };
+ g.Range ??= Range_;
+}
diff --git a/sdk/raea/src/dom-reads.ts b/sdk/raea/src/dom-reads.ts
index 98977ef7..eda0df70 100644
--- a/sdk/raea/src/dom-reads.ts
+++ b/sdk/raea/src/dom-reads.ts
@@ -5,6 +5,11 @@
// offset* doesn't (and is whole px, from the offsetParent's padding edge), client* is the padding box, scroll* the
// scrolled content.
+import { domDocument } from "./dom-document";
+import { domLoad } from "./dom-load";
+import { domStyle } from "./dom-style";
+import { domSvgText } from "./dom-svgtext";
+import { domObservers } from "./dom-observers";
import { domTree } from "./dom-tree";
import { boxOf, type Box } from "./page-layout";
@@ -56,11 +61,17 @@ function ancestor(el: El, id: number): El | null {
/** An inline element (a span in a line) has no padding box: its client* and scroll* are 0. */
const inline = (b: Box) => b.inline;
-/** A ref's DOM, from the entry, given bevy-react's exports: LR3's geometry and LR4's tree on its BevyElement and BevyTextNode
- * (raea's patch; a bridge without it has neither, and refs stay plain handles). */
-export function domReads(bevy: { BevyElement?: { prototype: object }; BevyTextNode?: { prototype: object } }): void {
+/** A ref's DOM, from the entry, given bevy-react's exports: LR3's geometry, LR4's tree and LR5's style on its BevyElement and
+ * BevyTextNode, and LR7's document and window (raea's patch; a bridge without it has none, and refs stay plain handles). */
+export function domReads(bevy: { BevyElement?: { prototype: object }; BevyTextNode?: { prototype: object }; containerNode?: unknown }): void {
geometry(bevy.BevyElement);
domTree(bevy.BevyElement, bevy.BevyTextNode);
+ domStyle(bevy.BevyElement);
+ domDocument(bevy as never);
+ domLoad();
+ domSvgText(bevy.BevyElement);
+ domObservers();
+ (globalThis as { DOMRect?: unknown }).DOMRect ??= DOMRect;
}
/** LR3's reads, on `Element`'s prototype. */
diff --git a/sdk/raea/src/dom-style.ts b/sdk/raea/src/dom-style.ts
new file mode 100644
index 00000000..393a6c0e
--- /dev/null
+++ b/sdk/raea/src/dom-style.ts
@@ -0,0 +1,159 @@
+// el.style on a ref (docs/layout-reads.feature LR5): a CSSStyleDeclaration over the element's style prop. Reading it
+// answers the style React last committed with the composition's own writes over it; writing a property (assignment,
+// setProperty, removeProperty or cssText) sends an update op for that element, as canvas2d.ts sends a canvas's draws,
+// so the page lays it out and draws it. React's next commit to the same property wins, as it does in Chrome, where
+// React DOM writes only what changed: a write is forgotten once React's own update to that property lands.
+
+type El = { nodeId: number; type: string; kind?: string; props: Record<string, unknown> };
+type Css = Record<string, unknown>;
+
+const HOST = (globalThis as any).__bevyHost;
+/** The composition's writes over each element's committed style, by node id. */
+const writes = new Map<number, Css>();
+const decls = new WeakMap<object, unknown>();
+/** a write of our own going through op_flush (forget leaves it) */
+let ours = false;
+
+// React DOM's unitless properties: a number is written as it is, any other gets px
+const UNITLESS = new Set(["opacity", "zIndex", "fontWeight", "lineHeight", "flex", "flexGrow", "flexShrink", "order", "zoom", "scale", "aspectRatio", "columnCount", "gridRow", "gridColumn", "orphans", "widows", "fillOpacity", "strokeOpacity", "strokeWidth", "tabSize"]);
+export const camel = (k: string) => (k.startsWith("--") ? k : k.replace(/^-ms-/, "ms-").replace(/-([a-z])/g, (_, c: string) => c.toUpperCase()));
+export const kebab = (k: string) => (k.startsWith("--") ? k : k.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`));
+/** A style value as Chrome's style declaration answers it: a string, px on a length React wrote as a number. */
+export const cssValue = (k: string, v: unknown) => (v == null || v === false ? "" : typeof v === "number" && !UNITLESS.has(k) && v !== 0 ? `${v}px` : String(v));
+
+/** The element's style as it stands: React's committed style with the composition's writes over it. */
+export function styleNow(el: El): Css {
+ const own = (el.props?.style ?? {}) as Css;
+ const w = writes.get(el.nodeId);
+ if (!w) return own;
+ const out = { ...own, ...w };
+ for (const k in w) if (w[k] === undefined) delete out[k];
+ return out;
+}
+
+/** Writes `set` (camelCase; undefined unsets) to the element now, outside React's commits. */
+export function writeStyle(el: El, set: Css): void {
+ const w = writes.get(el.nodeId) ?? {};
+ writes.set(el.nodeId, w);
+ const style: Css = {};
+ const unset: string[] = [];
+ for (const k in set) {
+ w[k] = set[k];
+ if (set[k] === undefined || set[k] === "") unset.push(k), (w[k] = undefined);
+ else style[k] = set[k];
+ }
+ const op: Record<string, unknown> = { op: "update", id: el.nodeId, kind: el.kind ?? el.type, props: Object.keys(style).length ? { style } : {} };
+ if (unset.length) op.styleUnset = unset;
+ ours = true;
+ try {
+ HOST.op_flush(JSON.stringify([op]), false);
+ } finally {
+ ours = false;
+ }
+}
+
+/** React's own update to a property the composition wrote takes it back (React's commit wins). */
+function forget(json: string): void {
+ if (ours || !writes.size || !json.includes('"update"')) return;
+ for (const op of JSON.parse(json) as { op: string; id?: number; props?: { style?: Css }; styleUnset?: string[] }[]) {
+ const w = op.op === "update" && op.id !== undefined ? writes.get(op.id) : undefined;
+ if (!w) continue;
+ for (const k of [...Object.keys(op.props?.style ?? {}), ...(op.styleUnset ?? [])]) delete w[k];
+ if (!Object.keys(w).length) writes.delete(op.id!);
+ }
+}
+
+/** cssText's declarations, camelCase. */
+export function parseCss(text: string): Css {
+ const out: Css = {};
+ for (const d of String(text).split(";")) {
+ const at = d.indexOf(":");
+ if (at > 0) out[camel(d.slice(0, at).trim())] = d.slice(at + 1).replace(/!important\s*$/, "").trim();
+ }
+ return out;
+}
+
+/** The element's CSSStyleDeclaration. */
+export function declaration(el: El): unknown {
+ const was = decls.get(el);
+ if (was) return was;
+ const now = () => styleNow(el);
+ const methods: Record<string, unknown> = {
+ getPropertyValue: (n: string) => cssValue(camel(n), now()[camel(n)]),
+ getPropertyPriority: () => "",
+ setProperty: (n: string, v: unknown) => writeStyle(el, { [camel(n)]: v == null ? "" : String(v) }),
+ removeProperty: (n: string) => {
+ const old = cssValue(camel(n), now()[camel(n)]);
+ writeStyle(el, { [camel(n)]: undefined });
+ return old;
+ },
+ item: (i: number) => kebab(Object.keys(now())[i] ?? ""),
+ };
+ const d = new Proxy(methods, {
+ get(t, k) {
+ if (typeof k !== "string") return undefined;
+ if (k in t) return t[k];
+ if (k === "length") return Object.keys(now()).length;
+ if (k === "cssText") return Object.entries(now()).map(([p, v]) => `${kebab(p)}: ${cssValue(p, v)};`).join(" ");
+ if (/^\d+$/.test(k)) return kebab(Object.keys(now())[Number(k)] ?? "");
+ return cssValue(camel(k), now()[camel(k)]);
+ },
+ set(_, k, v) {
+ if (typeof k !== "string") return false;
+ if (k === "cssText") {
+ const next = parseCss(String(v));
+ const clear: Css = {};
+ for (const p in now()) if (!(p in next)) clear[p] = undefined;
+ writeStyle(el, { ...clear, ...next });
+ } else writeStyle(el, { [camel(k)]: v == null ? "" : v });
+ return true;
+ },
+ });
+ decls.set(el, d);
+ return d;
+}
+
+/** getComputedStyle(el) (LR5): the values the page computed for the element (`page.layout`'s styles, read when first
+ * asked and kept until the next commit), and for a property the page doesn't answer, the element's own style. Read
+ * only, as Chrome's is. */
+export function computed(el: El, of: (id: number) => Record<string, string> | undefined): unknown {
+ const value = (n: string) => {
+ const k = kebab(n);
+ const page = of(el.nodeId);
+ return page?.[k] ?? cssValue(camel(n), styleNow(el)[camel(n)]);
+ };
+ const keys = () => Object.keys(of(el.nodeId) ?? {});
+ const methods: Record<string, unknown> = { getPropertyValue: value, getPropertyPriority: () => "", item: (i: number) => keys()[i] ?? "" };
+ return new Proxy(methods, {
+ get(t, k) {
+ if (typeof k !== "string") return undefined;
+ if (k in t) return t[k];
+ if (k === "length") return keys().length;
+ if (k === "cssText") return "";
+ if (/^\d+$/.test(k)) return keys()[Number(k)] ?? "";
+ return value(k);
+ },
+ set: () => true,
+ });
+}
+
+/** `style` on the element class (bevy-react's BevyElement), once, from dom-reads. */
+export function domStyle(Element: { prototype: object } | undefined): void {
+ if (!Element || Object.getOwnPropertyDescriptor(Element.prototype, "style")) return;
+ Object.defineProperty(Element.prototype, "style", {
+ configurable: true,
+ get(this: El) {
+ return declaration(this);
+ },
+ set(this: El, v: unknown) {
+ (declaration(this) as { cssText: string }).cssText = String(v);
+ },
+ });
+ if (HOST?.op_flush) {
+ const flush = HOST.op_flush;
+ HOST.op_flush = (json: string, devtools: boolean) => {
+ forget(json);
+ return flush(json, devtools);
+ };
+ }
+}
diff --git a/sdk/raea/src/dom-svgtext.ts b/sdk/raea/src/dom-svgtext.ts
new file mode 100644
index 00000000..80ea8dd1
--- /dev/null
+++ b/sdk/raea/src/dom-svgtext.ts
@@ -0,0 +1,68 @@
+// An svg <text>'s measures on a ref (docs/layout-reads.feature LR7): getComputedTextLength, getNumberOfChars,
+// getStartPositionOfChar, getEndPositionOfChar and getSubStringLength. Components read them off hidden text (an
+// opacity-0 group) to set their words, so the words are laid out on their own by the host (canvas.svgText), with the
+// engine and faces the page draws an svg with, in the element's computed font (LR5): family, size, weight, style,
+// letter- and word-spacing, and font-variation-settings, which a canvas's font can't say.
+
+import { native } from "@raea/app/native";
+import { computedOf } from "./page-layout";
+
+type El = { nodeId: number; type: string; props: Record<string, unknown>; textContent?: string };
+type Laid = { length: number; starts: number[] };
+
+const FONT = ["font-family", "font-size", "font-weight", "font-style", "font-stretch", "letter-spacing", "word-spacing", "font-variation-settings", "font-feature-settings"];
+const laid = new Map<string, Laid>();
+
+/** `text` laid out in element `id`'s computed font: its advance and where each character starts (kept while the words
+ * and font stay the same). A range over an html text node measures with it too (dom-range.ts). */
+export function layoutText(text: string, id: number): Laid {
+ const page = computedOf(id) ?? {};
+ const style: Record<string, string> = {};
+ for (const k of FONT) if (page[k]) style[k] = page[k];
+ const key = JSON.stringify([text, style]);
+ const had = laid.get(key);
+ if (had) return had;
+ if (laid.size > 512) laid.clear();
+ const at = native("canvas.svgText", { text, style }) as Laid;
+ laid.set(key, at);
+ return at;
+}
+
+const layout = (el: El) => layoutText(String(el.textContent ?? ""), el.nodeId);
+
+/** The text's own x and y (its first), where its characters' positions count from. */
+const origin = (el: El) => [Number.parseFloat(String(el.props?.x ?? 0)) || 0, Number.parseFloat(String(el.props?.y ?? 0)) || 0];
+
+function outOfRange(i: number, n: number): void {
+ if (!(i >= 0 && i < n)) throw new RangeError(`IndexSizeError: character ${i} of ${n}`);
+}
+
+/** Installs the measures on bevy-react's element class, once, from dom-reads. */
+export function domSvgText(Element: { prototype: object } | undefined): void {
+ if (!Element || "getComputedTextLength" in Element.prototype) return;
+ Object.assign(Element.prototype, {
+ getComputedTextLength(this: El) {
+ return layout(this).length;
+ },
+ getNumberOfChars(this: El) {
+ return String(this.textContent ?? "").length;
+ },
+ getStartPositionOfChar(this: El, i: number) {
+ const l = layout(this);
+ outOfRange(i, l.starts.length);
+ const [x, y] = origin(this);
+ return { x: x + l.starts[i], y };
+ },
+ getEndPositionOfChar(this: El, i: number) {
+ const l = layout(this);
+ outOfRange(i, l.starts.length);
+ const [x, y] = origin(this);
+ return { x: x + (l.starts[i + 1] ?? l.length), y };
+ },
+ getSubStringLength(this: El, i: number, n: number) {
+ const l = layout(this);
+ outOfRange(i, l.starts.length);
+ return (l.starts[i + n] ?? l.length) - l.starts[i];
+ },
+ });
+}
diff --git a/sdk/raea/src/hold.ts b/sdk/raea/src/hold.ts
index d50266b4..d9fcf4a4 100644
--- a/sdk/raea/src/hold.ts
+++ b/sdk/raea/src/hold.ts
@@ -26,6 +26,9 @@ export function cancelRender(err: unknown): void {
/** Hold the frame until `continueRender(handle)`. `label` names it if it's still open when its time runs out. */
export function delayRender(label?: string, options?: { timeoutInMilliseconds?: number }): number {
const handle = next++;
+ // a pass that draws no page (the sound pass, the 3D rows' pre-pass) holds nothing: page-layout.ts sets this once a
+ // read says so, and releases what was open, since a hold waiting on a measure could never end there
+ if ((globalThis as { __raeaNoPage?: boolean }).__raeaNoPage) return handle;
const name = label ?? `delayRender() #${handle}`;
OPEN.set(handle, name);
HOLD.n++;
diff --git a/sdk/raea/src/native-calls.ts b/sdk/raea/src/native-calls.ts
index 12f20e44..aa7d7156 100644
--- a/sdk/raea/src/native-calls.ts
+++ b/sdk/raea/src/native-calls.ts
@@ -34,6 +34,8 @@ export interface NativeCalls {
"canvas.measure": { args: { font: { family: string; size: number; weight: string; style: string }; text: string; align?: string; baseline?: string }; answer: { width: number; actualBoundingBoxLeft: number; actualBoundingBoxRight: number; actualBoundingBoxAscent: number; actualBoundingBoxDescent: number; fontBoundingBoxAscent: number; fontBoundingBoxDescent: number } };
/** getImageData: a canvas's display list drawn on a bitmap of its own, and a rectangle of it read off as base64 RGBA */
"canvas.read": { args: { width: number; height: number; __canvas2d: unknown; x: number; y: number; w: number; h: number }; answer: { data: string } };
+ /** an svg <text>'s getComputedTextLength and getStartPositionOfChar: its words laid out by usvg, as the page draws an svg, in its computed font (font-*, letter-spacing, word-spacing); x from the text's own (docs/layout-reads.feature LR7) */
+ "canvas.svgText": { args: { text: string; style: Record<string, string> }; answer: { length: number; starts: number[] } };
/** raea's command line (render, play, guide, bundle, types; the media verbs: raea media, raea ffmpeg), run in process in cwd */
"cli.raea": { args: { args: string[]; cwd: string }; answer: { exit: number; stdout: string; stderr: string } };
/** a headless run ends with this exit code */
@@ -84,10 +86,14 @@ export interface NativeCalls {
"ecs.spawn": { args: { world: number; kind?: string; cols?: Record<string, number | string | boolean>; components?: Record<string, unknown>; parent?: number }; answer: { id: number } };
/** bevy_text's glyph atlases for a text in a font file at a size px, each page a PNG data: URL, as Bevy's FontAtlasSet holds them */
"fonts.atlases": { args: { font: string; size: number; text: string }; answer: { width: number; height: number; src: string }[] };
+ /** FontFace.load for a face given by URL: fetched now, through raea's cache, into the faces an svg's and a canvas's text are set in, as `family` (docs/layout-reads.feature LR7); 0 faces when it doesn't load */
+ "fonts.face": { args: { family: string; url: string }; answer: { faces: number } };
/** the system's font families by name, sorted, as fontique (bevy_text's FontCx) lists them */
"fonts.families": { args: {}; answer: string[] };
/** a Google Fonts family the page loads (its Latin faces, every weight and style, fetched once through raea's URL cache), as a stylesheet link loads it in Chrome (raea/text loadFont) */
"fonts.google": { args: { family: string }; answer: { family: string } };
+ /** document.fonts.load: a family the composition asked for (loadFont), its faces given to a canvas's text now, where the page fetches it only once an element names it (docs/layout-reads.feature LR7); how many faces it has */
+ "fonts.load": { args: { family: string }; answer: { faces: number } };
/** drop an engine frame */
"frame.free": { args: { frame: number }; answer: null };
/** an engine frame's size */
@@ -190,8 +196,8 @@ export interface NativeCalls {
"net.fetch": { args: { policy: number; url: string; method?: string; headers?: Record<string, string>; body?: string; followRedirects?: boolean; maxRedirects?: number; timeoutMs?: number }; answer: { status: number; statusText: string; headers: Record<string, string>; body: string; url: string; redirectChain: { status: number; statusText: string; headers: Record<string, string> }[] } };
/** a network policy (allowed URL prefixes and methods; headers injected at the boundary, secrets from the host's environment) */
"net.policy": { args: { allow: { prefix: string; methods?: string[]; headers?: Record<string, string>; secretHeaders?: Record<string, string> }[]; timeoutMs?: number; maxRedirects?: number; maxBytes?: number }; answer: { id: number } };
- /** every element's boxes as the page that draws the frame lays it out now (docs/layout-reads.feature LR1): JSON {vw, vh, n: [id, x, y, w, h, scroll x y w h, padding l t r b, border l t r b, z per element], o: [id, offsetLeft, offsetTop, offsetWidth, offsetHeight, offsetParent, inline per element]}, keyed by React id; the composition's thread waits for it */
- "page.layout": { args: {}; answer: string };
+ /** every element's boxes as the page that draws the frame lays it out now (docs/layout-reads.feature LR1): JSON {vw, vh, n: [id, x, y, w, h, scroll x y w h, padding l t r b, border l t r b, z per element], o: [id, offsetLeft, offsetTop, offsetWidth, offsetHeight, offsetParent, inline per element]}, keyed by React id, and s: {id: {property: computed value}} for the elements in `styles` (LR5); the composition's thread waits for it */
+ "page.layout": { args: { styles?: number[] }; answer: string };
/** the box (x, y, w, h in frame px) a camera in a page element draws its view in, as last laid out; null when it draws under the whole frame (3D picking in the box, docs/sdk.feature S3a) */
"page.viewBox": { args: {}; answer: [number, number, number, number] | null };
/** rigid bodies stepped by Rapier, deterministic, made once per request and kept: each body's rigid motion from rest per frame */
diff --git a/sdk/raea/src/page-layout.ts b/sdk/raea/src/page-layout.ts
index 19dd266f..bcd272b2 100644
--- a/sdk/raea/src/page-layout.ts
+++ b/sdk/raea/src/page-layout.ts
@@ -5,6 +5,7 @@
// so a burst of reads costs one layout. A host that lays nothing out says so, and the read throws that.
import { native } from "@raea/app/native";
+import { continueRender } from "./hold";
/** Numbers per element in the snapshot's `n` (raea-sys-page's STRIDE) and in its `o`. */
const STRIDE = 18;
@@ -28,21 +29,26 @@ export type Box = {
inline: boolean;
};
-type Snapshot = { vw: number; vh: number; n: number[]; o?: number[] };
+type Snapshot = { vw: number; vh: number; n: number[]; o?: number[]; s?: Record<string, Record<string, string>> };
let boxes: Map<number, Box> | null = null;
+/** Computed styles asked for since the last commit, by element (LR5). */
+const styles = new Map<number, Record<string, string>>();
let viewport: [number, number] = [0, 0];
const HOST = (globalThis as any).__bevyHost;
/** The layout read last is stale: something committed, or a new frame started. */
export function stale(): void {
boxes = null;
+ styles.clear();
}
function read(): Map<number, Box> {
if (boxes) return boxes;
// the page answers its snapshot as one JSON string (made in Rust as text, not a value to re-encode)
const s = JSON.parse(native("page.layout", {})) as Snapshot;
+ // a pass that draws no page answers a 0 x 0 viewport: its holds can't wait on a measure (hold.ts)
+ if (!s.vw && !s.vh) noPage();
const m = new Map<number, Box>();
for (let i = 0; i + STRIDE <= s.n.length; i += STRIDE) {
const v = s.n;
@@ -73,6 +79,18 @@ export function boxOf(id: number): Box | undefined {
return read().get(id);
}
+/** Element `id`'s computed style as the page has it now ({property: value}, as Chrome serializes it: px lengths,
+ * rgb() colours); undefined when it isn't on the page. One read lays the page out and answers its boxes too. */
+export function computedOf(id: number): Record<string, string> | undefined {
+ const had = styles.get(id);
+ if (had) return had;
+ const s = JSON.parse(native("page.layout", { styles: [id] })) as Snapshot;
+ if (!s.vw && !s.vh) noPage();
+ const got = s.s?.[String(id)];
+ if (got) styles.set(id, got);
+ return got;
+}
+
/** The page's size, as the last read gave it. */
export function viewportSize(): [number, number] {
read();
@@ -87,8 +105,20 @@ export function layoutReads(): void {
const flush = HOST.op_flush;
HOST.op_flush = (json: string, devtools: boolean) => {
boxes = null;
+ styles.clear();
return flush(json, devtools);
};
}
layoutReads();
+
+/** A pass that draws no page (the sound pass, the 3D rows' pre-pass) answers every read with a 0 x 0 page, so a hold
+ * waiting on a measure (a size a ResizeObserver reports, say) could never end there: on that answer its holds are
+ * released, and delayRender holds nothing after it (hold.ts). Its frames are for sound and 3D, which a measure
+ * doesn't change. */
+function noPage(): void {
+ const g = globalThis as { __raeaNoPage?: boolean; __raeaHold?: { open?: Map<number, string> } };
+ if (g.__raeaNoPage) return;
+ g.__raeaNoPage = true;
+ for (const h of [...(g.__raeaHold?.open?.keys() ?? [])]) continueRender(h);
+}
diff --git a/systems/canvas/src/lib.rs b/systems/canvas/src/lib.rs
index 7593e94c..4e72302e 100644
--- a/systems/canvas/src/lib.rs
+++ b/systems/canvas/src/lib.rs
@@ -28,6 +28,8 @@ use tiny_skia as sk;
mod draw;
mod measure;
pub use measure::{advances, metrics};
+mod svgtext;
+pub use svgtext::svg_text;
mod filter;
mod paint;
mod subsets;
diff --git a/systems/canvas/src/svgtext.rs b/systems/canvas/src/svgtext.rs
new file mode 100644
index 00000000..39e39d5f
--- /dev/null
+++ b/systems/canvas/src/svgtext.rs
@@ -0,0 +1,63 @@
+//! An SVG <text>'s measures (docs/layout-reads.feature LR7): getComputedTextLength and getStartPositionOfChar, as usvg
+//! lays its words out in the element's computed font, the engine and fonts the page draws an svg with. A composition
+//! reads them off hidden text (an opacity-0 group) to set its words, which the page's svg never lays out, so the words
+//! are laid out here on their own.
+
+use serde_json::{json, Value};
+
+/// The computed properties that change where an svg text's glyphs fall.
+const FONT: [&str; 9] = ["font-family", "font-size", "font-weight", "font-style", "font-stretch", "letter-spacing", "word-spacing", "font-variation-settings", "font-feature-settings"];
+
+/// `canvas.svgText`: {text, style: {property: computed value}} -> {length, starts}: the text's advance
+/// (getComputedTextLength) and the x where each of its characters starts (getStartPositionOfChar), in user units from
+/// the text's own x. Spaces are kept, as `white-space: pre` keeps them.
+pub fn svg_text(args: &Value) -> Result<Value, String> {
+ Ok(svg_text_in(&crate::page_options(), args))
+}
+
+fn svg_text_in(opt: &usvg::Options, args: &Value) -> Value {
+ let text = args["text"].as_str().unwrap_or("");
+ let style: Vec<String> = FONT
+ .iter()
+ .filter_map(|p| args["style"][p].as_str().filter(|v| !v.is_empty()).map(|v| format!("{p}:{}", v.replace('"', "'").replace('&', "&amp;"))))
+ .collect();
+ let esc = text.replace('&', "&amp;").replace('<', "&lt;");
+ let doc = format!("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"1\" height=\"1\"><text x=\"0\" y=\"0\" xml:space=\"preserve\" style=\"{}\">{esc}</text></svg>", style.join(";"));
+ let t = usvg::Tree::from_str(&doc, opt).ok();
+ let t = t.as_ref().and_then(|t| t.root().children().iter().find_map(|n| if let usvg::Node::Text(t) = n { Some(t.clone()) } else { None }));
+ let Some(t) = t else { return json!({ "length": 0, "starts": vec![0; text.chars().count()] }) };
+ let mut starts = Vec::new();
+ for span in t.layouted() {
+ for g in &span.positioned_glyphs {
+ // a ligature's characters all start where it does
+ let x = g.transform().tx;
+ starts.extend(g.text.chars().map(|_| x));
+ }
+ }
+ // usvg's box ends at the last glyph's advance; Chrome's length tracks every character, the last one too
+ let tracking = args["style"]["letter-spacing"].as_str().and_then(|v| v.strip_suffix("px")?.trim().parse::<f32>().ok()).unwrap_or(0.0);
+ let length = if text.is_empty() { 0.0 } else { t.bounding_box().width() + tracking };
+ json!({ "length": length, "starts": starts })
+}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+
+ #[test]
+ fn a_texts_length_is_its_advance_and_tracking_widens_it() {
+ let mut db = usvg::fontdb::Database::new();
+ db.load_font_data(std::fs::read("/System/Library/Fonts/Supplemental/Arial.ttf").unwrap());
+ let opt = usvg::Options { fontdb: std::sync::Arc::new(db), ..Default::default() };
+ let st = |ls: &str| json!({ "font-family": "Arial", "font-size": "40px", "letter-spacing": ls });
+ let plain = super::svg_text_in(&opt, &json!({ "text": "Hi there", "style": st("normal") }));
+ let wide = super::svg_text_in(&opt, &json!({ "text": "Hi there", "style": st("10px") }));
+ let (a, b) = (plain["length"].as_f64().unwrap(), wide["length"].as_f64().unwrap());
+ assert!(a > 100.0, "{plain}");
+ assert!((b - a - 80.0).abs() < 1.0, "8 characters tracked 10 px each: {a} -> {b}");
+ let s = plain["starts"].as_array().unwrap();
+ assert_eq!(s.len(), 8, "one start per character, the space's too: {plain}");
+ assert_eq!(s[0].as_f64(), Some(0.0));
+ assert!(s.windows(2).all(|w| w[1].as_f64() > w[0].as_f64()), "{plain}");
+ }
+}
diff --git a/systems/fonts/src/google.rs b/systems/fonts/src/google.rs
index 6a0f38d5..a2c7343b 100644
--- a/systems/fonts/src/google.rs
+++ b/systems/fonts/src/google.rs
@@ -73,6 +73,26 @@ pub fn load_missing(doc: &mut BaseDocument) -> bool {
loaded
}
+/// The family's faces for a canvas and SVG text now (document.fonts.load, layout-reads LR7): a family the composition
+/// asked for, fetched as load_missing would and given to usvg's font database at once, where the page would only
+/// fetch it once an element names it. How many faces it has; 0 for one not asked for or not on Google Fonts.
+pub fn load_now(family: &str) -> usize {
+ if !wanted(family) {
+ return 0;
+ }
+ let mut known = FAMILIES.lock().unwrap();
+ let known = known.get_or_insert_default();
+ if let Some(faces) = known.get(family) {
+ return faces.len();
+ }
+ let faces = Arc::new(fetch(family));
+ for (ttf, _, _) in faces.iter() {
+ blitz_dom::util::add_svg_font(ttf.to_vec(), Some(family));
+ }
+ known.insert(family.to_string(), faces.clone());
+ faces.len()
+}
+
/// A family's Latin faces from Google Fonts, or none
fn fetch(family: &str) -> Vec<(Bytes, f32, bool)> {
let url = format!("https://fonts.googleapis.com/css?family={}:{WEIGHTS}", family.replace(' ', "+"));
@@ -99,3 +119,20 @@ fn fetch(family: &str) -> Vec<(Bytes, f32, bool)> {
bevy::log::info!("raea-page: Google Fonts {family:?}, {} faces", faces.len());
faces
}
+
+/// A face a composition loads by URL (`new FontFace(family, "url(…)")`, docs/layout-reads.feature LR7), fetched now
+/// through raea's cache and given to a canvas's and an svg's text as `family`; woff2 is unpacked, TrueType and OpenType
+/// are taken as they are. How many faces that gave (0 when it doesn't load). A URL already loaded is not fetched again.
+pub fn face_now(family: &str, url: &str) -> usize {
+ static LOADED: Mutex<Vec<(String, String)>> = Mutex::new(Vec::new());
+ let key = (family.to_string(), url.to_string());
+ if LOADED.lock().unwrap().contains(&key) {
+ return 1;
+ }
+ let Ok(bytes) = raea_io_net::cache::read(url) else { return 0 };
+ let ttf = if bytes.starts_with(b"wOF2") { wuff::decompress_woff2(&bytes).ok() } else { Some(bytes) };
+ let Some(ttf) = ttf else { return 0 };
+ blitz_dom::util::add_svg_font(ttf, Some(family));
+ LOADED.lock().unwrap().push(key);
+ 1
+}