Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
raea's window is light, dark or the system's; a page's elements can be replaced by outerHTML
shinyobjectzfb19fa48a6b0
diff --git a/engine/page/host/src/lib.rs b/engine/page/host/src/lib.rsindex 408f1b11..cfc6728b 100644--- a/engine/page/host/src/lib.rs+++ b/engine/page/host/src/lib.rs@@ -16,6 +16,7 @@ pub mod idle;pub mod inject;pub mod mcp;pub mod page;+pub mod scheme;pub mod shell;pub mod tree;diff --git a/engine/page/host/src/main.rs b/engine/page/host/src/main.rsindex 3e32b217..fa91c9c4 100644--- a/engine/page/host/src/main.rs+++ b/engine/page/host/src/main.rs@@ -155,6 +155,7 @@ fn main() {let mut code = Some(code);let mount = move |world: &mut World| {chrome::install(world);+ raea_page_host::scheme::install(world);let m = page::Mount { code: code.take().unwrap_or_default(), preamble: preamble.clone(), css: css.clone(), styles: None, picking, size };if let Err(e) = page::mount(world, m) {eprintln!("raea-page-host: {e}");@@ -172,6 +173,7 @@ fn main() {} else {app.add_systems(Update, (page::read_input, page::input, page::size, page::step_dropping_asks, page::show).chain());}+ app.add_systems(PreUpdate, raea_page_host::scheme::follow.run_if(resource_exists::<raea_page_host::scheme::Scheme>));app.add_systems(Last, page::tree.before(tree::answer));app.run();}diff --git a/engine/page/host/src/scheme.rs b/engine/page/host/src/scheme.rsnew file mode 100644index 00000000..627195dd--- /dev/null+++ b/engine/page/host/src/scheme.rs@@ -0,0 +1,108 @@+//! Light or dark: the window's colour scheme, as `@media (prefers-color-scheme)` and matchMedia give it to the page. It+//! follows the system's until the page picks one, with the host call `window.scheme {pick: "system" | "light" | "dark"}`+//! -> {scheme, pick}; a pick also sets the window's own theme, so its title bar and menus match. Headless, light until+//! the page picks.++use bevy::prelude::*;+use bevy::window::{PrimaryWindow, WindowTheme, WindowThemeChanged};+use blitz_traits::shell::ColorScheme;+use raea_runtime_js::HostCalls;+use raea_sys_page::PageScheme;+use serde_json::json;++/// The page's pick (None: the system's), and the system's scheme as the window last said it.+#[derive(Resource, Default)]+pub struct Scheme {+ pick: Option<WindowTheme>,+ system: Option<WindowTheme>,+}++impl Scheme {+ fn now(&self) -> WindowTheme {+ self.pick.or(self.system).unwrap_or(WindowTheme::Light)+ }+}++fn name(t: WindowTheme) -> &'static str {+ match t {+ WindowTheme::Light => "light",+ WindowTheme::Dark => "dark",+ }+}++/// `window.scheme`, on the primary window.+pub fn install(world: &mut World) {+ world.init_resource::<HostCalls>();+ world.init_resource::<Scheme>();+ world.init_resource::<PageScheme>();+ world.resource_mut::<HostCalls>().on("window.scheme", |w, args, answer| {+ let pick = match args.get("pick").and_then(|p| p.as_str()) {+ Some("system") => Some(None),+ Some("light") => Some(Some(WindowTheme::Light)),+ Some("dark") => Some(Some(WindowTheme::Dark)),+ Some(_) => return answer.err("pick system, light or dark"),+ None => None,+ };+ if let Some(pick) = pick+ && w.resource::<Scheme>().pick != pick+ {+ w.resource_mut::<Scheme>().pick = pick;+ let mut q = w.query_filtered::<&mut Window, With<PrimaryWindow>>();+ if let Ok(mut win) = q.single_mut(w) {+ win.window_theme = pick;+ }+ }+ let s = w.resource::<Scheme>();+ let (now, pick) = (name(s.now()), s.pick.map_or("system", name));+ answer.ok(json!({"scheme": now, "pick": pick}))+ });+}++/// The window's theme, first and each time it changes, as the page's scheme.+pub fn follow(mut scheme: ResMut<Scheme>, mut page: ResMut<PageScheme>, win: Query<&Window, With<PrimaryWindow>>, mut evs: MessageReader<WindowThemeChanged>) {+ // the window made: bevy_winit writes the theme it opened in+ if scheme.system.is_none()+ && scheme.pick.is_none()+ && let Some(t) = win.iter().next().and_then(|w| w.window_theme)+ {+ scheme.system = Some(t);+ }+ for e in evs.read() {+ // what a pick makes the window say isn't the system's+ if scheme.pick.is_none() {+ scheme.system = Some(e.theme);+ }+ }+ let now = match scheme.now() {+ WindowTheme::Light => ColorScheme::Light,+ WindowTheme::Dark => ColorScheme::Dark,+ };+ page.set_if_neq(PageScheme(now));+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_page_follows_the_windows_theme_until_it_picks_one() {+ let mut app = App::new();+ app.add_message::<WindowThemeChanged>().add_systems(Update, follow);+ install(app.world_mut());+ let win = app.world_mut().spawn((Window { window_theme: Some(WindowTheme::Dark), ..default() }, PrimaryWindow)).id();+ app.update();+ let scheme = |app: &App| app.world().resource::<PageScheme>().0;+ assert_eq!(scheme(&app), ColorScheme::Dark);+ app.world_mut().write_message(WindowThemeChanged { window: win, theme: WindowTheme::Light });+ app.update();+ assert_eq!(scheme(&app), ColorScheme::Light);+ // picked: the system's changes don't reach the page, and what the pick makes the window say isn't the system's+ app.world_mut().resource_mut::<Scheme>().pick = Some(WindowTheme::Dark);+ app.world_mut().write_message(WindowThemeChanged { window: win, theme: WindowTheme::Dark });+ app.update();+ assert_eq!(scheme(&app), ColorScheme::Dark);+ app.world_mut().resource_mut::<Scheme>().pick = None;+ app.update();+ assert_eq!(scheme(&app), ColorScheme::Light);+ }+}diff --git a/sdk/ui/src/dom/core.ts b/sdk/ui/src/dom/core.tsindex 6bd39b25..720a5d8a 100644--- a/sdk/ui/src/dom/core.ts+++ b/sdk/ui/src/dom/core.ts@@ -16,7 +16,7 @@ export const STRIDE = 18;// innerWidth and media queries read in a first render are the page'sconst vp0 = (globalThis as { __ui_viewport?: { w: number; h: number; dpr: number } }).__ui_viewport;-/** the module's state its files assign (each field was a top-level let) */ export const S: { vw: number; vh: number; dpr: number; frameNo: number; pointerCapture: Element_ | null; active: Element_ | null; wantFocus: Element_ | null | undefined; downTarget: Element_ | null; spaceDown: { t: Element_; ok: boolean } | null; focusVisible: boolean } = { vw: vp0?.w ?? 0, vh: vp0?.h ?? 0, dpr: vp0?.dpr ?? 1, frameNo: 0, pointerCapture: null, active: null, wantFocus: undefined, downTarget: null, spaceDown: null, focusVisible: false };+/** the module's state its files assign (each field was a top-level let) */ export const S: { vw: number; vh: number; dpr: number; dark: boolean; frameNo: number; pointerCapture: Element_ | null; active: Element_ | null; wantFocus: Element_ | null | undefined; downTarget: Element_ | null; spaceDown: { t: Element_; ok: boolean } | null; focusVisible: boolean } = { vw: vp0?.w ?? 0, vh: vp0?.h ?? 0, dpr: vp0?.dpr ?? 1, dark: false, frameNo: 0, pointerCapture: null, active: null, wantFocus: undefined, downTarget: null, spaceDown: null, focusVisible: false };// ---------------------------------------------------------------- the runner (the mounted driver's batch)diff --git a/sdk/ui/src/dom/element.ts b/sdk/ui/src/dom/element.tsindex dcee7cb7..658ad395 100644--- a/sdk/ui/src/dom/element.ts+++ b/sdk/ui/src/dom/element.ts@@ -255,6 +255,13 @@ export class Element_ extends Node_ {const attrs = [...this._attrs].map(([k, v]) => ` ${k}="${escapeHtml(v)}"`).join("");return `<${this.localName}${attrs}>${this.innerHTML}</${this.localName}>`;}+ /** the element replaced by what the markup makes (nothing, for one that isn't in a tree) */+ set outerHTML(v: string) {+ if (!this.parentNode) return;+ const box = this.ownerDocument.createElement("div") as unknown as Element_;+ box.innerHTML = String(v ?? "");+ this.replaceWith(...([...box.childNodes] as any[]));+ }querySelector(s: string): Element_ | null {return query(this, s, true)[0] ?? null;}diff --git a/sdk/ui/src/dom/frame.ts b/sdk/ui/src/dom/frame.tsindex d971e80e..bdef30b1 100644--- a/sdk/ui/src/dom/frame.ts+++ b/sdk/ui/src/dom/frame.ts@@ -232,7 +232,7 @@ function evalMedia(q: string): boolean {case "orientation":return v.trim() === (S.vw >= S.vh ? "landscape" : "portrait");case "prefers-color-scheme":- return v.trim() === "light";+ return v.trim() === (S.dark ? "dark" : "light");case "prefers-reduced-motion":case "prefers-reduced-transparency":case "prefers-reduced-data":@@ -337,17 +337,20 @@ export function onLayout(json: string) {S.frameNo++;S.wantFocus = undefined;let resized = false;+ let rescheme = false;if (json) {- const s = JSON.parse(json) as { vw: number; vh: number; dpr: number; n: number[] };+ const s = JSON.parse(json) as { vw: number; vh: number; dpr: number; dark?: boolean; n: number[] };resized = s.vw !== S.vw || s.vh !== S.vh;+ rescheme = !!s.dark !== S.dark;+ S.dark = !!s.dark;S.vw = s.vw;S.vh = s.vh;S.dpr = s.dpr;geo.clear();for (let i = 0; i + STRIDE <= s.n.length; i += STRIDE) geo.set(s.n[i], s.n.slice(i + 1, i + STRIDE));}- if (resized) {- run(() => dispatch(g, new UIEvent_("resize", { view: g }), true));+ if (resized) run(() => dispatch(g, new UIEvent_("resize", { view: g }), true));+ if (resized || rescheme) {for (const m of mqls) {const now = evalMedia(m.media);if (now !== m._was) {diff --git a/sdk/ui/test/dom.test.tsx b/sdk/ui/test/dom.test.tsxindex 6bf0d89e..27f7a539 100644--- a/sdk/ui/test/dom.test.tsx+++ b/sdk/ui/test/dom.test.tsx@@ -546,3 +546,19 @@ describe("P18 DOM surface: computed style", () => {expect(getComputedStyle(el).color).toBe("red");});});++describe("outerHTML", () => {+ test("set, the element is replaced by its markup in its place; out of a tree, nothing happens", () => {+ fresh();+ let box: any;+ mount(<div ref={(e: any) => (box = e)} />, 0, { dom: true });+ box.innerHTML = "<header class='a'><b>one</b></header><p>after</p>";+ box.firstChild.outerHTML = "<header class='b'><i>two</i></header>";+ expect(box.innerHTML).toBe('<header class="b"><i>two</i></header><p>after</p>');+ box.lastChild.outerHTML = "";+ expect(box.innerHTML).toBe('<header class="b"><i>two</i></header>');+ const off: any = document.createElement("u");+ off.outerHTML = "<s></s>";+ expect(off.outerHTML).toBe("<u></u>");+ });+});diff --git a/systems/page/src/lib.rs b/systems/page/src/lib.rsindex 5c331188..dcd75fea 100644--- a/systems/page/src/lib.rs+++ b/systems/page/src/lib.rs@@ -81,6 +81,11 @@ impl Page {#[derive(Resource, Default)]pub struct PageClock(pub Option<f64>);+/// The colour scheme pages are drawn in, `@media (prefers-color-scheme)` and matchMedia's: light (a render's, always),+/// or what the window says (raea-page-host scheme.rs).+#[derive(Resource, Default, Clone, Copy, PartialEq, Debug)]+pub struct PageScheme(pub blitz_traits::shell::ColorScheme);+/// A page whose image is straight alpha, not premultiplied: one Bevy's UI or sprites draw (they blend straight), as/// an overlay over a scene (docs/blitz-bevy.feature B3 H5).#[derive(Component, Clone, Copy, Debug, Default)]@@ -171,16 +176,18 @@ pub struct Painted(pub Arc<Mutex<Vec<Drawn>>>);pub type Drawn = (Handle<Image>, UVec2, vello::Scene, Vec<raea_sys_filters::Filtered>, u64, bool, bool);/// Each page restyled and laid out (what changed).-pub fn resolve(mut docs: NonSendMut<Docs>, pages: Query<(Entity, &Page)>, time: Res<Time>, clock: Res<PageClock>, mut scanned: Local<HashMap<Entity, usize>>) {+pub fn resolve(mut docs: NonSendMut<Docs>, pages: Query<(Entity, &Page)>, time: Res<Time>, clock: Res<PageClock>, scheme: Option<Res<PageScheme>>, mut scanned: Local<HashMap<Entity, usize>>) {+ let scheme = scheme.map(|s| s.0).unwrap_or_default();for (e, page) in &pages {let Some(doc) = docs.0.get_mut(&e) else { continue };let at = clock.0.unwrap_or_else(|| time.elapsed_secs_f64());// a page resized or rescaled (the iPad sets its scale late): its viewport follows, or text lays out off its boxlet px = page.px();- if doc.viewport().window_size != (px.x, px.y) || doc.viewport().hidpi_scale != page.scale {+ if doc.viewport().window_size != (px.x, px.y) || doc.viewport().hidpi_scale != page.scale || doc.viewport().color_scheme != scheme {let mut v = doc.viewport().clone();v.window_size = (px.x, px.y);v.hidpi_scale = page.scale;+ v.color_scheme = scheme;doc.set_viewport(v);}let t0 = std::time::Instant::now();diff --git a/systems/page/src/snapshot.rs b/systems/page/src/snapshot.rsindex fd537ce9..0f69f5c5 100644--- a/systems/page/src/snapshot.rs+++ b/systems/page/src/snapshot.rs@@ -85,10 +85,12 @@ pub fn snapshot_by(doc: &BaseDocument, nodes: &Nodes, id: impl Fn(u64) -> Option}n.pop();o.pop();+ // the dark scheme, said only when it's on (matchMedia reads it)+ let dark = if doc.viewport().color_scheme == blitz_traits::shell::ColorScheme::Dark { ",\"dark\":true" } else { "" };if offsets {- format!("{{\"vw\":{},\"vh\":{},\"dpr\":{dpr},\"n\":[{n}],\"o\":[{o}]}}", vp.0, vp.1)+ format!("{{\"vw\":{},\"vh\":{},\"dpr\":{dpr}{dark},\"n\":[{n}],\"o\":[{o}]}}", vp.0, vp.1)} else {- format!("{{\"vw\":{},\"vh\":{},\"dpr\":{dpr},\"n\":[{n}]}}", vp.0, vp.1)+ format!("{{\"vw\":{},\"vh\":{},\"dpr\":{dpr}{dark},\"n\":[{n}]}}", vp.0, vp.1)}}