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.

LR4: a composition's refs have the tree a web component walks and queries: children and childNodes, the first, last and sibling nodes, parentElement, tagName, nodeName and nodeType, id, className, classList, dataset, getAttribute, textContent, contains, matches, closest, querySelector and querySelectorAll, answered in JS from bevy-react's committed instances (sdk/raea's dom-tree, installed from the entry with dom-reads). Selectors cover tag, *, #id, .class, attributes, descendant and child, comma lists, :first-child, :last-child, :only-child, :nth-child and :not; anything else throws a SyntaxError, as Chrome's does. el.id is the id attribute as on the web: the bevy-react patch renames its reconciler id to nodeId, and canvas2d, dom-reads and useEntity read that. probes/tree.tsx prints every answer and matches Chrome's words

shinyobjectz8a2f9c78ab4c
diff --git a/bench/layout-reads/probes/tree.tsx b/bench/layout-reads/probes/tree.tsx
new file mode 100644
index 00000000..fb2a9ef9
--- /dev/null
+++ b/bench/layout-reads/probes/tree.tsx
@@ -0,0 +1,55 @@
+// LR4's reads as a probe (docs/layout-reads.feature): a ref walked and queried as a web component does, each answer
+// printed as words, so the harness's pairing by words fails on any answer that differs from Chrome's.
+import { AbsoluteFill } from "raea";
+import { loadFont } from "raea/text";
+import { useLayoutEffect, useRef, useState } from "react";
+
+const { fontFamily } = loadFont("Inter");
+
+export const conf = { width: 640, height: 360, fps: 30, durationInFrames: 3 };
+export const props = {};
+
+export function Comp() {
+ const list = useRef<HTMLUListElement>(null);
+ const [lines, setLines] = useState<string[]>([]);
+ useLayoutEffect(() => {
+ const l = list.current!;
+ const items = l.querySelectorAll("li");
+ const second = l.querySelector("li:nth-child(2)") as HTMLElement;
+ const word = l.querySelector(".word[data-w='b']") as HTMLElement;
+ let bad = "no throw";
+ try {
+ l.querySelector("li[");
+ } catch (e) {
+ bad = (e as Error).name;
+ }
+ setLines([
+ `tag ${l.tagName} kids ${l.children.length} items ${items.length} first ${l.firstElementChild?.textContent} last ${l.lastElementChild?.textContent}`,
+ `second ${second.textContent} next ${second.nextElementSibling?.textContent} prev ${second.previousElementSibling?.textContent}`,
+ `word ${word.textContent} closest ${word.closest("li")?.id} parent ${word.parentElement?.tagName} data ${word.dataset.w}`,
+ `matches ${second.matches("ul > li.item:not(.off)")} odd ${l.querySelectorAll("li:nth-child(odd)").length} last ${l.querySelectorAll("li:last-child").length}`,
+ `class ${word.className} list ${word.classList.length} has ${word.classList.contains("word")} attr ${word.getAttribute("data-w")} ${word.hasAttribute("title")}`,
+ `contains ${l.contains(word)} ${word.contains(l)} text ${l.textContent?.replace(/\s+/g, "-")} bad ${bad}`,
+ ]);
+ }, []);
+ return (
+ <AbsoluteFill style={{ background: "#fff", color: "#111", fontFamily, fontSize: 16 }}>
+ <ul ref={list} style={{ position: "absolute", left: 24, top: 10, margin: 0 }}>
+ <li id="one" className="item">
+ one
+ </li>
+ <li id="two" className="item">
+ two <span className="word" data-w="b">bee</span>
+ </li>
+ <li id="three" className="item off">
+ three
+ </li>
+ </ul>
+ <div style={{ position: "absolute", left: 24, top: 140 }}>
+ {lines.map((t) => (
+ <div key={t}>{t}</div>
+ ))}
+ </div>
+ </AbsoluteFill>
+ );
+}
diff --git a/docs/layout-reads.feature b/docs/layout-reads.feature
index 22107ba7..e6383753 100644
--- a/docs/layout-reads.feature
+++ b/docs/layout-reads.feature
@@ -151,6 +151,7 @@ Feature: Layout reads: a composition measures its text and layout as Chrome does
inside it; a span's offsets with client 0; and a scroller's scroll sizes.
- The bundle crate was at its 2000-line limit: the stylesheet url() rewriter moved to raea-runtime-cssurls.
+ @done
Scenario: LR4. The tree on refs
Then a ref's element has children, childNodes, firstChild, lastChild, firstElementChild, lastElementChild,
nextSibling, previousSibling, nextElementSibling, previousElementSibling, parentNode and parentElement,
@@ -160,6 +161,20 @@ Feature: Layout reads: a composition measures its text and layout as Chrome does
with no call to Rust
And the selectors cover tag, #id, .class, [attr], [attr=v], descendant, child, :first-child, :last-child,
:nth-child() and :not(), and an unsupported selector throws a SyntaxError, as Chrome's does
+ And 11-12, built:
+ - sdk/raea/src/dom-tree.ts installs these from the entry, with dom-reads. Text nodes also get nodeType,
+ nodeName, textContent, the siblings and parentElement. Elements also get localName, childElementCount,
+ innerText, hasChildNodes, getElementsByTagName and getElementsByClassName. The selectors also cover *,
+ :only-child and [attr~= ^= $= *=], and comma lists.
+ - An attribute is read from the committed props: class from className, for from htmlFor, style as text.
+ A <text> holding a single string keeps it in its props, and textContent reads it there.
+ - `el.id` is the element's id attribute, as on the web. bevy-react kept its reconciler id in `id`, which
+ hid that, so the patch renames it `nodeId`. raea's own readers of it (canvas2d, dom-reads, useEntity)
+ read nodeId, and fall back to id on an unpatched bridge.
+ - classList reads only: add, remove and toggle change the class, which is LR5's writing to an element.
+ - bench/layout-reads/probes/tree.tsx walks and queries a list and prints each answer, and the words match
+ Chrome's: children and querySelectorAll counts, siblings, closest's id, matches with a child combinator
+ and :not, nth-child(odd), classList, dataset, getAttribute, contains, textContent, and the SyntaxError.
@needs:LR1
Scenario: LR5. style and getComputedStyle
diff --git a/runtime/bundle/src/entry.rs b/runtime/bundle/src/entry.rs
index 74013124..b1414c42 100644
--- a/runtime/bundle/src/entry.rs
+++ b/runtime/bundle/src/entry.rs
@@ -16,10 +16,10 @@ import {{ canvas2d }} from "./motion/canvas2d";
import * as BevyReact from "bevy-react";
import {{ mount, addEventListener, BevyCanvasElement }} from "bevy-react";
canvas2d(BevyCanvasElement); // a <canvas> ref's getContext("2d") is the web's (motion canvas2d.ts, #55)
-// a ref has the DOM a web component reads (getBoundingClientRect, offsetWidth ...), from the frame's page (page.layout):
-// on bevy-react's BevyElement, which raea's patch adds (a bridge without it keeps plain handles; layout-reads LR1, LR3)
+// a ref has the DOM a web component reads (getBoundingClientRect, offsetWidth, children, querySelector ...):
+// on bevy-react's BevyElement, which raea's patch adds (a bridge without it keeps plain handles; layout-reads LR1, LR3, LR4)
import {{ domReads }} from "./motion/dom-reads";
-domReads((BevyReact as any).BevyElement);
+domReads(BevyReact as any);
import {{ Component, useEffect, useMemo, useState }} from "react";
import * as M from "./src/{file}";
import {{ Clock, getCompositions, tickClocks }} from "./motion";
diff --git a/sdk/app/src/hooks.ts b/sdk/app/src/hooks.ts
index c1e601e6..9a970ba9 100644
--- a/sdk/app/src/hooks.ts
+++ b/sdk/app/src/hooks.ts
@@ -268,10 +268,11 @@ const nothing = () => () => {};
/** The entity of an element's twin (docs/blitz-bevy.feature B3 H1): every element on the page has one, which Bevy code
* queries like any entity (PageElement, ElementBox). `ref` is the element's React ref; undefined until it's
* committed and its twin made (the frame after). Use it with useComponent, setComponent or BRP calls. */
-export function useEntity(ref: { readonly current: { readonly id: number } | null }): Entity | undefined {
+export function useEntity(ref: { readonly current: { readonly nodeId?: number; readonly id: number | string } | null }): Entity | undefined {
const [op, setOp] = useState<number | undefined>(undefined);
// the ref is set as React commits: read it after each commit (the same id changes nothing)
- useEffect(() => setOp(ref.current?.id));
+ // (a composition's ref names its node by nodeId: its `id` is the element's id attribute, as on the web)
+ useEffect(() => setOp(ref.current ? (ref.current.nodeId ?? Number(ref.current.id)) : undefined));
const k = op === undefined ? undefined : JSON.stringify(["raea/twin", { op }]);
const get = () => (k === undefined ? undefined : ((store.values.get(`?${k}`) as Entity | null | undefined) ?? undefined));
return useSyncExternalStore(k === undefined ? nothing : readSubscriber(k, "raea/twin", { op }), get, get);
diff --git a/sdk/raea/src/canvas2d.ts b/sdk/raea/src/canvas2d.ts
index 9475ed42..030b7fdf 100644
--- a/sdk/raea/src/canvas2d.ts
+++ b/sdk/raea/src/canvas2d.ts
@@ -12,7 +12,9 @@ import { CanvasRenderingContext2D_ } from "@raea/ui/canvas";
/** bevy-react's canvas handle, as the entry passes it (this module can't import bevy-react: the SDK's checks load it
* where only the bundle's runtime has it) */
-type Handle = { readonly id: number };
+// a handle's node id: nodeId on raea's patched bevy-react (its `id` is the element's id attribute there), id before it
+type Handle = { readonly nodeId?: number; readonly id: number };
+const idOf = (h: Handle) => h.nodeId ?? h.id;
type HandleClass = { prototype: Handle };
type Size = { width: number; height: number };
@@ -61,12 +63,12 @@ export function canvas2d(El: HandleClass): void {
contexts.get(id)?._reset();
};
Object.defineProperties(El.prototype, {
- width: { configurable: true, get(this: Handle) { return size(this.id).width; }, set(this: Handle, v: number) { resize(this.id, "width", v); } },
- height: { configurable: true, get(this: Handle) { return size(this.id).height; }, set(this: Handle, v: number) { resize(this.id, "height", v); } },
+ width: { configurable: true, get(this: Handle) { return size(idOf(this)).width; }, set(this: Handle, v: number) { resize(idOf(this), "width", v); } },
+ height: { configurable: true, get(this: Handle) { return size(idOf(this)).height; }, set(this: Handle, v: number) { resize(idOf(this), "height", v); } },
});
(El.prototype as any).getContext = function (this: Handle, kind = "2d") {
if (kind !== "2d") return null;
- const id = this.id;
+ const id = idOf(this);
let ctx = contexts.get(id);
if (!ctx) {
const canvas = { get width() { return size(id).width; }, get height() { return size(id).height; }, getAttribute: (k: string) => (k === "width" || k === "height" ? String(size(id)[k]) : null), _send: (list: unknown) => send(id, { __canvas2d: list }) };
diff --git a/sdk/raea/src/dom-reads.ts b/sdk/raea/src/dom-reads.ts
index 6e94183f..98977ef7 100644
--- a/sdk/raea/src/dom-reads.ts
+++ b/sdk/raea/src/dom-reads.ts
@@ -5,6 +5,7 @@
// offset* doesn't (and is whole px, from the offsetParent's padding edge), client* is the padding box, scroll* the
// scrolled content.
+import { domTree } from "./dom-tree";
import { boxOf, type Box } from "./page-layout";
/** The web's DOMRect, as getBoundingClientRect answers it. */
@@ -36,27 +37,34 @@ export class DOMRect {
}
}
-type El = { id: number; parentNode: El | null; childNodes?: El[] };
+type El = { nodeId: number; parentNode: El | null; childNodes?: El[] };
/** Chrome's integer offset*, client* and scroll*: rounded, as Chrome snaps its layout units. */
const px = (v: number) => Math.round(v);
-const box = (el: El): Box | undefined => boxOf(el.id);
+const box = (el: El): Box | undefined => boxOf(el.nodeId);
/** An element with no box: the zero rect Chrome answers for one that isn't displayed. */
const ZERO: Box = { rect: [0, 0, 0, 0], scroll: [0, 0, 0, 0], padding: [0, 0, 0, 0], border: [0, 0, 0, 0], layout: [0, 0, 0, 0], offsetParent: -2, inline: false };
/** The ancestor with React id `id` (offsetParent's element), or null. */
function ancestor(el: El, id: number): El | null {
- for (let p = el.parentNode; p; p = p.parentNode) if (p.id === id) return p;
+ for (let p = el.parentNode; p; p = p.parentNode) if (p.nodeId === id) return p;
return 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;
-/** LR3's reads, on `Element`'s prototype (bevy-react's BevyElement). */
-export function domReads(Element: { prototype: object } | undefined): void {
+/** 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 {
+ geometry(bevy.BevyElement);
+ domTree(bevy.BevyElement, bevy.BevyTextNode);
+}
+
+/** LR3's reads, on `Element`'s prototype. */
+function geometry(Element: { prototype: object } | undefined): void {
if (!Element || (Element.prototype as any).__domReads) return;
const define = (name: string, get: (this: El) => unknown) => Object.defineProperty(Element.prototype, name, { get, configurable: true });
Object.defineProperty(Element.prototype, "__domReads", { value: true });
diff --git a/sdk/raea/src/dom-tree.ts b/sdk/raea/src/dom-tree.ts
new file mode 100644
index 00000000..002e39ec
--- /dev/null
+++ b/sdk/raea/src/dom-tree.ts
@@ -0,0 +1,322 @@
+// The tree on a composition's refs (docs/layout-reads.feature LR4): what a web component reads off an element to walk
+// and query what it rendered. Answered in JS from bevy-react's instances (raea's patch keeps the tree React last
+// committed on them), with no call to Rust. Installed from the entry with dom-reads.ts.
+// Selectors: tag, *, #id, .class, [attr], [attr=v] (also ~= ^= $= *=), descendant and child combinators, comma lists,
+// :first-child, :last-child, :only-child, :nth-child(an+b | odd | even) and :not(simple). Anything else throws a
+// SyntaxError, as Chrome's does.
+
+type Props = Record<string, unknown>;
+export type Node = { nodeId: number; parentNode: El | null };
+export type El = Node & { type: string; kind?: string; props: Props; childNodes: Node[] };
+type Text = Node & { data: string };
+
+const isEl = (n: unknown): n is El => !!n && Array.isArray((n as El).childNodes);
+/** The root a tree is mounted in (bevy-react's container): not an element a component sees. */
+const isRoot = (n: Node | null): boolean => !n || (isEl(n) && n.type === "root" && n.kind === "root");
+
+/** Chrome's NodeList and HTMLCollection: an array with item(). */
+function list<T>(a: T[]): T[] & { item(i: number): T | null } {
+ return Object.assign(a, { item: (i: number) => a[i] ?? null });
+}
+
+const kids = (n: El) => n.childNodes.filter(isEl);
+const siblings = (n: Node) => (n.parentNode ? n.parentNode.childNodes : [n]);
+
+/** An attribute's value as the DOM has it from React's props (class from className, for from htmlFor). */
+export function attr(el: El, name: string): string | null {
+ const p = el.props;
+ const key = name === "class" ? "className" : name === "for" ? "htmlFor" : name;
+ let v = p[key] ?? (key !== name ? p[name] : undefined);
+ if (name === "style" && v && typeof v === "object") v = Object.entries(v as Props).map(([k, x]) => `${k.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase())}: ${x}`).join("; ");
+ if (v === undefined || v === null || v === false || typeof v === "function" || name === "children" || name === "key" || name === "ref") return null;
+ return v === true ? "" : String(v);
+}
+
+function textOf(n: Node): string {
+ if (!isEl(n)) return (n as Text).data ?? "";
+ if (n.childNodes.length === 0 && (typeof n.props.children === "string" || typeof n.props.children === "number")) return String(n.props.children);
+ return n.childNodes.map(textOf).join("");
+}
+
+// ---- selectors
+
+type Simple = { tag?: string; id?: string; classes: string[]; attrs: [string, string | null, string?][]; pseudos: ((e: El) => boolean)[] };
+type Step = { simple: Simple; comb: " " | ">" | null };
+
+function syntax(sel: string): never {
+ const e = new Error(`Failed to execute 'querySelector' on 'Element': '${sel}' is not a valid selector.`);
+ e.name = "SyntaxError";
+ throw e;
+}
+
+/** an+b's test on a 1-based index */
+function nth(arg: string, sel: string): (i: number) => boolean {
+ const a = arg.replace(/\s+/g, "");
+ if (a === "odd") return (i) => i % 2 === 1;
+ if (a === "even") return (i) => i % 2 === 0;
+ const m = /^([+-]?\d*)n([+-]\d+)?$/.exec(a);
+ if (m) {
+ const k = m[1] === "" || m[1] === "+" ? 1 : m[1] === "-" ? -1 : Number(m[1]);
+ const b = Number(m[2] ?? 0);
+ return (i) => (k === 0 ? i === b : (i - b) / k >= 0 && (i - b) % k === 0);
+ }
+ if (/^[+-]?\d+$/.test(a)) return (i) => i === Number(a);
+ return syntax(sel);
+}
+
+const index = (e: El) => (e.parentNode ? kids(e.parentNode).indexOf(e) + 1 : 1);
+const count = (e: El) => (e.parentNode ? kids(e.parentNode).length : 1);
+
+/** One compound selector from `s` at `at`: its parts, and where it ended. */
+function simple(s: string, at: number, sel: string): [Simple, number] {
+ const out: Simple = { classes: [], attrs: [], pseudos: [] };
+ const ident = /^-?[_a-zA-Z -￿][-_a-zA-Z0-9 -￿]*/;
+ let i = at;
+ const take = (re: RegExp) => {
+ const m = re.exec(s.slice(i));
+ if (!m) syntax(sel);
+ i += m[0].length;
+ return m;
+ };
+ if (s[i] === "*") i++;
+ else if (ident.test(s.slice(i))) out.tag = take(ident)[0].toLowerCase();
+ for (;;) {
+ const c = s[i];
+ if (c === "#") {
+ i++;
+ out.id = take(ident)[0];
+ } else if (c === ".") {
+ i++;
+ out.classes.push(take(ident)[0]);
+ } else if (c === "[") {
+ const m = take(/^\[\s*([-_a-zA-Z0-9:]+)\s*(?:([~^$*]?=)\s*(?:"([^"]*)"|'([^']*)'|([^\]\s]+))\s*)?\]/);
+ out.attrs.push([m[1], m[2] ? (m[3] ?? m[4] ?? m[5]) : null, m[2]]);
+ } else if (c === ":") {
+ const m = take(/^:([-a-z]+)(\(([^()]*(?:\([^()]*\))?[^()]*)\))?/);
+ const [name, arg] = [m[1], m[3]];
+ if (name === "first-child" && arg === undefined) out.pseudos.push((e) => index(e) === 1);
+ else if (name === "last-child" && arg === undefined) out.pseudos.push((e) => index(e) === count(e));
+ else if (name === "only-child" && arg === undefined) out.pseudos.push((e) => count(e) === 1);
+ else if (name === "nth-child" && arg !== undefined) {
+ const t = nth(arg, sel);
+ out.pseudos.push((e) => t(index(e)));
+ } else if (name === "not" && arg !== undefined) {
+ const [inner, end] = simple(arg.trim(), 0, sel);
+ if (end !== arg.trim().length) syntax(sel);
+ out.pseudos.push((e) => !matchSimple(e, inner));
+ } else syntax(sel);
+ } else break;
+ }
+ if (i === at) syntax(sel);
+ return [out, i];
+}
+
+/** A selector list: each selector's steps, right to left. */
+function parse(sel: string): Step[][] {
+ const lists: Step[][] = [];
+ const s = sel.trim();
+ if (!s) syntax(sel);
+ let i = 0;
+ let steps: Step[] = [];
+ let comb: Step["comb"] = null;
+ for (;;) {
+ const [one, end] = simple(s, i, sel);
+ steps.push({ simple: one, comb });
+ i = end;
+ const ws = /^\s*/.exec(s.slice(i))![0].length;
+ const next = s[i + ws];
+ if (next === undefined) break;
+ if (next === ",") {
+ lists.push(steps.reverse());
+ steps = [];
+ comb = null;
+ i += ws + 1;
+ i += /^\s*/.exec(s.slice(i))![0].length;
+ continue;
+ }
+ if (next === ">") {
+ comb = ">";
+ i += ws + 1;
+ i += /^\s*/.exec(s.slice(i))![0].length;
+ } else if (ws > 0) {
+ comb = " ";
+ i += ws;
+ } else syntax(sel);
+ }
+ lists.push(steps.reverse());
+ return lists;
+}
+
+function matchSimple(e: El, s: Simple): boolean {
+ if (s.tag && e.type.toLowerCase() !== s.tag) return false;
+ if (s.id !== undefined && attr(e, "id") !== s.id) return false;
+ if (s.classes.length) {
+ const cls = (attr(e, "class") ?? "").split(/\s+/);
+ if (!s.classes.every((c) => cls.includes(c))) return false;
+ }
+ for (const [name, want, op] of s.attrs) {
+ const v = attr(e, name);
+ if (v === null) return false;
+ if (want === null || want === undefined) continue;
+ const ok = op === "=" ? v === want : op === "~=" ? v.split(/\s+/).includes(want) : op === "^=" ? !!want && v.startsWith(want) : op === "$=" ? !!want && v.endsWith(want) : !!want && v.includes(want);
+ if (!ok) return false;
+ }
+ return s.pseudos.every((p) => p(e));
+}
+
+/** Whether `e` matches a selector's steps (right to left), with ancestors no higher than `scope`'s root. */
+function matchSteps(e: El, steps: Step[], k = 0): boolean {
+ if (!matchSimple(e, steps[k].simple)) return false;
+ if (k === steps.length - 1) return true;
+ const comb = steps[k].comb;
+ for (let p = e.parentNode; p && !isRoot(p); p = p.parentNode) {
+ if (matchSteps(p, steps, k + 1)) return true;
+ if (comb === ">") return false;
+ }
+ return false;
+}
+
+const cache = new Map<string, Step[][]>();
+function compiled(sel: string): Step[][] {
+ let c = cache.get(sel);
+ if (!c) cache.set(sel, (c = parse(sel)));
+ return c;
+}
+
+export function matches(e: El, sel: string): boolean {
+ return compiled(sel).some((steps) => matchSteps(e, steps));
+}
+
+function descendants(e: El, out: El[] = []): El[] {
+ for (const c of e.childNodes) if (isEl(c)) out.push(c), descendants(c, out);
+ return out;
+}
+
+export function querySelectorAll(e: El, sel: string): El[] {
+ const c = compiled(sel);
+ return list(descendants(e).filter((d) => c.some((steps) => matchSteps(d, steps))));
+}
+
+/** LR4's tree on the element and text classes (bevy-react's BevyElement and BevyTextNode). */
+export function domTree(Element: { prototype: object } | undefined, Text: { prototype: object } | undefined): void {
+ if (!Element || (Element.prototype as any).__domTree) return;
+ Object.defineProperty(Element.prototype, "__domTree", { value: true });
+ const nodes = [Element.prototype, Text?.prototype].filter(Boolean) as object[];
+ const get = (protos: object[], name: string, f: (this: any) => unknown) => protos.forEach((p) => Object.defineProperty(p, name, { get: f, configurable: true }));
+ const method = (name: string, f: (this: any, ...a: any[]) => unknown) => Object.defineProperty(Element.prototype, name, { value: f, writable: true, configurable: true });
+ const at = (n: Node, d: number, elements: boolean) => {
+ const s = elements ? siblings(n).filter(isEl) : siblings(n);
+ return s[s.indexOf(n as El) + d] ?? null;
+ };
+ // every node
+ get(nodes, "parentElement", function () {
+ return isRoot(this.parentNode) ? null : this.parentNode;
+ });
+ get(nodes, "nextSibling", function () {
+ return at(this, 1, false);
+ });
+ get(nodes, "previousSibling", function () {
+ return at(this, -1, false);
+ });
+ get(nodes, "nextElementSibling", function () {
+ return at(this, 1, true);
+ });
+ get(nodes, "previousElementSibling", function () {
+ return at(this, -1, true);
+ });
+ get(nodes, "ownerDocument", () => (globalThis as any).document ?? null);
+ if (Text) {
+ get([Text.prototype], "nodeType", () => 3);
+ get([Text.prototype], "nodeName", () => "#text");
+ get([Text.prototype], "textContent", function () {
+ return this.data;
+ });
+ get([Text.prototype], "nodeValue", function () {
+ return this.data;
+ });
+ }
+ // elements
+ const E = [Element.prototype];
+ get(E, "nodeType", () => 1);
+ get(E, "tagName", function () {
+ return String(this.type).toUpperCase();
+ });
+ get(E, "nodeName", function () {
+ return String(this.type).toUpperCase();
+ });
+ get(E, "localName", function () {
+ return String(this.type);
+ });
+ get(E, "children", function () {
+ return list(kids(this));
+ });
+ get(E, "childElementCount", function () {
+ return kids(this).length;
+ });
+ get(E, "firstChild", function () {
+ return this.childNodes[0] ?? null;
+ });
+ get(E, "lastChild", function () {
+ return this.childNodes[this.childNodes.length - 1] ?? null;
+ });
+ get(E, "firstElementChild", function () {
+ return kids(this)[0] ?? null;
+ });
+ get(E, "lastElementChild", function () {
+ const k = kids(this);
+ return k[k.length - 1] ?? null;
+ });
+ get(E, "id", function () {
+ return attr(this, "id") ?? "";
+ });
+ get(E, "className", function () {
+ return attr(this, "class") ?? "";
+ });
+ get(E, "classList", function () {
+ const all = (attr(this, "class") ?? "").split(/\s+/).filter(Boolean);
+ return Object.assign(list([...all]), { value: all.join(" "), contains: (c: string) => all.includes(c), toString: () => all.join(" ") });
+ });
+ get(E, "dataset", function () {
+ const out: Record<string, string> = {};
+ for (const k of Object.keys(this.props)) if (k.startsWith("data-")) out[k.slice(5).replace(/-([a-z])/g, (_, c: string) => c.toUpperCase())] = attr(this, k) ?? "";
+ return out;
+ });
+ get(E, "textContent", function () {
+ return textOf(this);
+ });
+ get(E, "innerText", function () {
+ return textOf(this);
+ });
+ method("getAttribute", function (name: string) {
+ return attr(this, name);
+ });
+ method("hasAttribute", function (name: string) {
+ return attr(this, name) !== null;
+ });
+ method("hasChildNodes", function () {
+ return this.childNodes.length > 0;
+ });
+ method("contains", function (other: Node | null) {
+ for (let n = other; n; n = n.parentNode) if (n === this) return true;
+ return false;
+ });
+ method("matches", function (sel: string) {
+ return matches(this, sel);
+ });
+ method("closest", function (sel: string) {
+ for (let n: El | null = this; n && !isRoot(n); n = n.parentNode) if (matches(n, sel)) return n;
+ return null;
+ });
+ method("querySelector", function (sel: string) {
+ return querySelectorAll(this, sel)[0] ?? null;
+ });
+ method("querySelectorAll", function (sel: string) {
+ return querySelectorAll(this, sel);
+ });
+ method("getElementsByTagName", function (tag: string) {
+ return querySelectorAll(this, tag === "*" ? "*" : tag);
+ });
+ method("getElementsByClassName", function (names: string) {
+ return querySelectorAll(this, names.trim().split(/\s+/).map((c) => "." + c).join(""));
+ });
+}
diff --git a/sdk/react/js/patches/[email protected] b/sdk/react/js/patches/[email protected]
index d1eadec0..71294ada 100644
--- a/sdk/react/js/patches/[email protected]
+++ b/sdk/react/js/patches/[email protected]
@@ -1,3 +1,6 @@
+diff --git a/node_modules/bevy-react/.bun-tag-86152a57801ddfd7 b/.bun-tag-86152a57801ddfd7
+new file mode 100644
+index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/src/canvas.ts b/src/canvas.ts
index 0bd05fcb2730a53ad4893f7d3cf0adad12a510db..5357f3fe7607697a81c88c807777bf9fa31a3a31 100644
--- a/src/canvas.ts
@@ -48,10 +51,10 @@ index 329c833ef3cb6c8f938e7ebdf66862e87507c946..e36f26028eb19555608cefe12020570c
CanvasContext,
diff --git a/node_modules/bevy-react/src/nodes.ts b/src/nodes.ts
new file mode 100644
-index 0000000000000000000000000000000000000000..3fb86d0779c0b2d9767097c460658443dc73cca7
+index 0000000000000000000000000000000000000000..b3a99f314d527d9a3c9530e809afbd6dcfb25f02
--- /dev/null
+++ b/src/nodes.ts
-@@ -0,0 +1,64 @@
+@@ -0,0 +1,65 @@
+// The tree as React last committed it, kept on the instances themselves (raea's patch, docs/layout-reads.feature
+// LR4): each element and text instance knows its parent, its children in order, and its latest props or text. A host
+// can then answer DOM-shaped reads (children, querySelector, textContent) from the instances a ref already holds,
@@ -61,8 +64,9 @@ index 0000000000000000000000000000000000000000..3fb86d0779c0b2d9767097c460658443
+export class BevyNode {
+ parentNode: BevyElement | null = null;
+ constructor(
-+ /** The node's reconciler id (what its ops name). */
-+ readonly id: number,
++ /** The node's reconciler id (what its ops name). Not `id`, which a ref's DOM answers as the web does: the
++ * element's id attribute (raea's dom-tree). */
++ readonly nodeId: number,
+ ) {}
+}
+
@@ -117,7 +121,7 @@ index 0000000000000000000000000000000000000000..3fb86d0779c0b2d9767097c460658443
+ if (child.parentNode === parent) child.parentNode = null;
+}
diff --git a/src/renderer.ts b/src/renderer.ts
-index 84aefa67ab2c6b886dce6445d305dd328a89c0a3..d97b868fd151c8c3bbd12e0e716c42859fb03a19 100644
+index 84aefa67ab2c6b886dce6445d305dd328a89c0a3..23c8a81e1e4423832f7462103360ac5635e096be 100644
--- a/src/renderer.ts
+++ b/src/renderer.ts
@@ -23,6 +23,13 @@ import {
@@ -151,7 +155,7 @@ index 84aefa67ab2c6b886dce6445d305dd328a89c0a3..d97b868fd151c8c3bbd12e0e716c4285
-interface TextInstance {
- id: number;
-}
-+// An instance is a BevyElement (nodes.ts): its id, type and wire kind (`type`,
++// An instance is a BevyElement (nodes.ts): its nodeId, type and wire kind (`type`,
+// except inside a `<text>`: a nested `<text>` is a `textSpan`, an `<image>` an
+// `inlineImage`; every update op names it, since Rust decodes the props against
+// that element; absent on a `<canvas>` handle, whose kind is its type), with
@@ -184,75 +188,102 @@ index 84aefa67ab2c6b886dce6445d305dd328a89c0a3..d97b868fd151c8c3bbd12e0e716c4285
},
appendInitialChild(parent: Instance, child: Instance | TextInstance) {
- push({ op: "append", parent: parent.id, child: child.id });
+- push({ op: "append", parent: parent.id, child: child.id });
++ push({ op: "append", parent: parent.nodeId, child: child.nodeId });
+ link(parent, child);
},
finalizeInitialChildren: () => false,
appendChild(parent: Instance, child: Instance | TextInstance) {
- push({ op: "append", parent: parent.id, child: child.id });
+- push({ op: "append", parent: parent.id, child: child.id });
++ push({ op: "append", parent: parent.nodeId, child: child.nodeId });
+ link(parent, child);
},
appendChildToContainer(container: Container, child: Instance | TextInstance) {
- push({ op: "append", parent: container.id, child: child.id });
+- push({ op: "append", parent: container.id, child: child.id });
++ push({ op: "append", parent: container.id, child: child.nodeId });
+ link(containerNode(container.id), child);
},
insertBefore(
-@@ -239,6 +246,7 @@ const hostConfig: Reconciler.HostConfig<
- child: child.id,
- before: before.id,
+@@ -235,10 +242,11 @@ const hostConfig: Reconciler.HostConfig<
+ ) {
+ push({
+ op: "insert",
+- parent: parent.id,
+- child: child.id,
+- before: before.id,
++ parent: parent.nodeId,
++ child: child.nodeId,
++ before: before.nodeId,
});
+ link(parent, child, before);
},
insertInContainerBefore(
container: Container,
-@@ -251,11 +259,13 @@ const hostConfig: Reconciler.HostConfig<
- child: child.id,
- before: before.id,
+@@ -248,21 +256,24 @@ const hostConfig: Reconciler.HostConfig<
+ push({
+ op: "insert",
+ parent: container.id,
+- child: child.id,
+- before: before.id,
++ child: child.nodeId,
++ before: before.nodeId,
});
+ link(containerNode(container.id), child, before);
},
removeChild(parent: Instance, child: Instance | TextInstance) {
- push({ op: "remove", parent: parent.id, child: child.id });
- dropHandlers(child.id);
+- push({ op: "remove", parent: parent.id, child: child.id });
+- dropHandlers(child.id);
++ push({ op: "remove", parent: parent.nodeId, child: child.nodeId });
++ dropHandlers(child.nodeId);
+ unlink(parent, child);
},
removeChildFromContainer(
container: Container,
-@@ -263,6 +273,7 @@ const hostConfig: Reconciler.HostConfig<
+ child: Instance | TextInstance,
) {
- push({ op: "remove", parent: container.id, child: child.id });
- dropHandlers(child.id);
+- push({ op: "remove", parent: container.id, child: child.id });
+- dropHandlers(child.id);
++ push({ op: "remove", parent: container.id, child: child.nodeId });
++ dropHandlers(child.nodeId);
+ unlink(containerNode(container.id), child);
},
// react-reconciler 0.33 removed `prepareUpdate`; `commitUpdate` now receives both
-@@ -278,6 +289,7 @@ const hostConfig: Reconciler.HostConfig<
+@@ -277,7 +288,8 @@ const hostConfig: Reconciler.HostConfig<
+ newProps: Record<string, unknown>,
_internalHandle: unknown,
) {
- const id = instance.id;
+- const id = instance.id;
++ const id = instance.nodeId;
+ instance.props = newProps;
const op = buildUpdateOp(
id,
oldProps,
-@@ -302,6 +314,7 @@ const hostConfig: Reconciler.HostConfig<
+@@ -301,17 +313,20 @@ const hostConfig: Reconciler.HostConfig<
+ },
commitTextUpdate(textInstance: TextInstance, _old: string, next: string) {
- push({ op: "updateText", id: textInstance.id, text: next });
+- push({ op: "updateText", id: textInstance.id, text: next });
++ push({ op: "updateText", id: textInstance.nodeId, text: next });
+ textInstance.data = next;
},
// Clear an inline-text element's content (React calls this when a `<text>`
-@@ -310,7 +323,9 @@ const hostConfig: Reconciler.HostConfig<
- push({ op: "updateText", id: instance.id, text: "" });
+ // switches from a string child to element children, before the spans mount).
+ resetTextContent(instance: Instance) {
+- push({ op: "updateText", id: instance.id, text: "" });
++ push({ op: "updateText", id: instance.nodeId, text: "" });
},
- clearContainer: () => {},
+- detachDeletedInstance: (instance: Instance) => dropHandlers(instance.id),
+ clearContainer: (container: Container) => {
+ containerNode(container.id).childNodes = [];
+ },
- detachDeletedInstance: (instance: Instance) => dropHandlers(instance.id),
++ detachDeletedInstance: (instance: Instance) => dropHandlers(instance.nodeId),
// No-op scope/blur hooks the reconciler still expects.
+ getInstanceFromNode: () => null,
diff --git a/tools/manual-ref/sdk.ts b/tools/manual-ref/sdk.ts
index 85c32f37..1319aaed 100644
--- a/tools/manual-ref/sdk.ts
+++ b/tools/manual-ref/sdk.ts
@@ -14,7 +14,7 @@ const ROOT = path.resolve(import.meta.dir, "../..")
const ts = createRequire(path.join(ROOT, "sdk/shell/package.json"))("typescript") as typeof import("typescript")
const SRC = path.join(ROOT, "sdk/raea/src")
const REPO = "https://github.com/shinyobjectz/raea/blob/main"
-const SKIP = /(\.gen\.ts|^test\.tsx|^native-calls\.ts|^prelude\.ts|^pure\.ts|^frame-globals\.ts|^canvas2d\.ts|^page-layout\.ts|^dom-reads\.ts)$/
+const SKIP = /(\.gen\.ts|^test\.tsx|^native-calls\.ts|^prelude\.ts|^pure\.ts|^frame-globals\.ts|^canvas2d\.ts|^page-layout\.ts|^dom-[a-z-]+\.ts)$/
const [mode = "check", dirArg] = process.argv.slice(2)
if (mode !== "gen" && mode !== "check") throw new Error("usage: sdk.ts gen|check [DIR]")
const out = path.resolve(dirArg ?? path.join(ROOT, "docs/manual/reference/sdk"))
diff --git a/tools/skills.sh b/tools/skills.sh
index 9d4e7209..0b38495f 100755
--- a/tools/skills.sh
+++ b/tools/skills.sh
@@ -225,7 +225,7 @@ gen_sdk() {
bun -e '
const root = process.argv[1], dir = root + "/sdk/raea/src"
const t = new Bun.Transpiler({ loader: "tsx" })
- const skip = /(\.gen\.ts|^test\.tsx|^native-calls\.ts|^prelude\.ts|^pure\.ts|^frame-globals\.ts|^canvas2d\.ts|^page-layout\.ts|^dom-reads\.ts)$/
+ const skip = /(\.gen\.ts|^test\.tsx|^native-calls\.ts|^prelude\.ts|^pure\.ts|^frame-globals\.ts|^canvas2d\.ts|^page-layout\.ts|^dom-[a-z-]+\.ts)$/
const files = [...new Bun.Glob("*.{ts,tsx}").scanSync(dir)].filter((f) => !skip.test(f)).sort()
const rows = files.map((f) => ({ entry: f.startsWith("index.") ? "raea" : "raea/" + f.replace(/\.tsx?$/, ""), file: "sdk/raea/src/" + f, names: t.scan(require("fs").readFileSync(dir + "/" + f, "utf8")).exports.filter((n) => n !== "default").sort() }))
console.log(JSON.stringify(rows.sort((a, b) => (a.entry === "raea" ? -1 : b.entry === "raea" ? 1 : a.entry.localeCompare(b.entry)))))
@@ -265,7 +265,8 @@ verb:traces (raea's own session logs, for whoever debugs raea)
module:dev_tools (raea's own debugging overlays)
module:test (raea's test harness, for raea's own tests)
module:page-layout (installed by the entry: a composition reads its layout through the DOM on its refs, docs/layout-reads.feature)
-module:dom-reads (installed by the entry on every ref; what it adds is the web's own API)"
+module:dom-reads (installed by the entry on every ref; what it adds is the web's own API)
+module:dom-tree (installed by the entry on every ref; what it adds is the web's own API)"
coverage() {
local corpus v m t f; corpus=$(mktemp "${TMPDIR:-/tmp}/skills-cov.XXXXXX")
texts | while read -r f; do cat "$f"; echo; done > "$corpus"