diff --git a/Cargo.lock b/Cargo.lock index facc8a8a..598dc6c4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -14386,6 +14386,7 @@ dependencies = [ "raea-page", "raea-page-stage", "raea-page-window", + "raea-rune-slots", "raea-runtime-dom", "raea-runtime-input", "raea-runtime-js", @@ -14546,6 +14547,14 @@ dependencies = [ "serde_json", ] +[[package]] +name = "raea-rune-layer" +version = "0.1.0" +dependencies = [ + "raea-core-wire", + "serde_json", +] + [[package]] name = "raea-rune-look" version = "0.1.0" @@ -14579,6 +14588,24 @@ dependencies = [ "serde_json", ] +[[package]] +name = "raea-rune-slots" +version = "0.1.0" +dependencies = [ + "bevy", + "blitz-dom", + "raea-core-wire", + "raea-rune-bevy", + "raea-rune-layer", + "raea-rune-media", + "raea-rune-page", + "raea-runtime-dom", + "raea-runtime-twins", + "raea-sys-page", + "rune", + "serde_json", +] + [[package]] name = "raea-rune-style" version = "0.1.0" @@ -17059,7 +17086,6 @@ dependencies = [ [[package]] name = "rune-taffy" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=7ead7d63fcf6f9dd9669385a8b90e2ae80015d7b#7ead7d63fcf6f9dd9669385a8b90e2ae80015d7b" dependencies = [ "taffy", ] diff --git a/Cargo.toml b/Cargo.toml index 91d09b1c..6bba783a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -48,6 +48,8 @@ members = [ "engine/rune/style", "engine/rune/bevy", "engine/rune/js", + "engine/rune/layer", + "engine/rune/slots", "engine/page/stage", "engine/page/window", "io/trace", @@ -308,3 +310,9 @@ firewheel-core = { path = "vendor/firewheel-core" } firewheel-graph = { path = "vendor/firewheel-graph" } firewheel-macros = { path = "vendor/firewheel-macros" } firewheel-nodes = { path = "vendor/firewheel-nodes" } + +[patch."https://github.com/anomalyco/rune"] +# rune-taffy at the rev above with encode_wrap covering taffy's flexbox_balance modes, which Blitz turns on: a crate +# with Rune and Blitz in one build (raea-rune-slots) doesn't compile without it (changes marked "raea:"). Back to +# upstream once Rune has it. +rune-taffy = { path = "vendor/rune-taffy" } diff --git a/LICENSES/rune-taffy-0.0.1/repository-LICENSE b/LICENSES/rune-taffy-0.0.1/repository-LICENSE deleted file mode 100644 index 66aed126..00000000 --- a/LICENSES/rune-taffy-0.0.1/repository-LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 Anomaly - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/NOTICE b/NOTICE index e0aa77ab..7f1276fb 100644 --- a/NOTICE +++ b/NOTICE @@ -351,7 +351,6 @@ LICENSES/-/. rune-kit 0.0.1: MIT rune-motion 0.1.0: MIT rune-staging 0.0.1: MIT - rune-taffy 0.0.1: MIT rune 0.0.1: MIT rusticata-macros 4.1.0: MIT/Apache-2.0 rustls-native-certs 0.8.5: Apache-2.0 OR ISC OR MIT diff --git a/engine/page/host/Cargo.toml b/engine/page/host/Cargo.toml index acd5fcd4..2c747cdc 100644 --- a/engine/page/host/Cargo.toml +++ b/engine/page/host/Cargo.toml @@ -46,6 +46,8 @@ image = { version = "0.25", default-features = false, features = ["png"] } serde_json = "1" # the live stage: (raea-page-stage) raea-page-stage = { path = "../stage" } +# Rune layers in the page: what's under a data-raea-renderer="rune" element drawn by Rune on this device (T6c) +raea-rune-slots = { path = "../../rune/slots" } # the window build turns bevy_winit on for every Bevy app in the process; the stage's engine is told to leave it out (main.rs) raea-runtime-plugins = { path = "../../../runtime/plugins", optional = true } raea-runtime-view = { path = "../../../runtime/view" } diff --git a/engine/page/host/src/main.rs b/engine/page/host/src/main.rs index 6feeea91..a33bfcca 100644 --- a/engine/page/host/src/main.rs +++ b/engine/page/host/src/main.rs @@ -104,6 +104,11 @@ fn main() { // the clipboard, links, notifications, the dock badge, raea:// links and the chrome (raea-page-window) .add_plugins(raea_page_window::DesktopPlugin { chrome: a.chrome, live: a.window }); raea_page_host::page_plugins(&mut app, picking); + // Rune layers (docs/targets.feature T6c): what's under a data-raea-renderer="rune" element is drawn by Rune on this + // device and shown in it; a page without one isn't touched. RAEA_RUNE_LAYERS=0: Blitz draws it all + if std::env::var("RAEA_RUNE_LAYERS").as_deref() != Ok("0") { + app.add_plugins(raea_rune_slots::RuneSlotsPlugin); + } let (css, size) = (a.css, a.size); let preamble = vec![a.chrome.preamble()]; let mount = move |world: &mut World| { diff --git a/engine/rune/bevy/src/tree.rs b/engine/rune/bevy/src/tree.rs index 7659f459..f6bd41ed 100644 --- a/engine/rune/bevy/src/tree.rs +++ b/engine/rune/bevy/src/tree.rs @@ -33,6 +33,8 @@ pub struct Tree { pub rt: Runtime, scale: f32, renderer: Option, + /// run before each frame with the runtime (a host handing it what changed since: a page's ops) + pub before_frame: Option)>>, /// run after each frame with the runtime (a host reading the frame's layout, a video's encoder) pub after_frame: Option)>>, } @@ -42,12 +44,15 @@ impl Tree { pub fn new(mut rt: Runtime, scale: f32) -> Tree { let viewport = rt.viewport; rt.set_viewport(viewport, scale); - Tree { rt, scale, renderer: None, after_frame: None } + Tree { rt, scale, renderer: None, before_frame: None, after_frame: None } } } impl AnyTree for Tree { fn step(&mut self, dt: f64) { + if let Some(f) = self.before_frame.as_mut() { + f(&mut self.rt); + } self.rt.frame(dt); if let Some(f) = self.after_frame.as_mut() { f(&mut self.rt); diff --git a/engine/rune/layer/Cargo.toml b/engine/rune/layer/Cargo.toml new file mode 100644 index 00000000..43892dfd --- /dev/null +++ b/engine/rune/layer/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "raea-rune-layer" +version = "0.1.0" +edition = "2024" +license = "FSL-1.1-ALv2" +publish = false +description = "Rune layers in a Blitz page (docs/targets.feature T6, per layer): an element marked data-raea-renderer=\"rune\" has its subtree drawn by Rune, the page's op wire split between Blitz and each layer" + +[dependencies] +raea-core-wire = { path = "../../../core/wire" } +serde_json = "1" diff --git a/engine/rune/layer/src/lib.rs b/engine/rune/layer/src/lib.rs new file mode 100644 index 00000000..c96467c0 --- /dev/null +++ b/engine/rune/layer/src/lib.rs @@ -0,0 +1,10 @@ +//! Rune layers in a page (docs/targets.feature T6c, per layer): any element marked +//! `data-raea-renderer="rune"` (sdk/rune's ``) keeps its place in the page, drawn by Blitz as a slot, and +//! everything under it is drawn by Rune instead, a tree of its own on Bevy's device (raea-rune-bevy) shown in the slot. +//! The wire doesn't change: the app's JS sends one op stream, and [`Router`] splits it here, so the page applies only +//! what is Blitz's and each layer's Rune page (raea-rune-page) applies its own, its children under its root. A page +//! that doesn't route (or a host without Rune) draws the marked element as a plain element: the layer degrades to Blitz. + +pub mod route; + +pub use route::{MARK, Routed, Router, creates_slot}; diff --git a/engine/rune/layer/src/route.rs b/engine/rune/layer/src/route.rs new file mode 100644 index 00000000..b5b69073 --- /dev/null +++ b/engine/rune/layer/src/route.rs @@ -0,0 +1,233 @@ +//! The op stream split between the page (Blitz) and its Rune layers. An element is Blitz's or a layer's, by where it's +//! attached: under a marked element (the layer's slot, itself Blitz's) or under one of the layer's own. React builds a +//! subtree before it attaches it (creates, appends inside it, then one append of its top), so ops for an element not yet +//! attached wait with its subtree's until it is; then each goes to its element's owner, in the order the JS sent them. +//! A layer's ops have the slot as their parent rewritten to the layer page's root (raea-rune-page's ROOT). + +use std::collections::{BTreeMap, HashMap}; + +use raea_core_wire::Op; +use serde_json::Value; + +/// The prop that marks an element whose subtree Rune draws, and its value. +pub const MARK: (&str, &str) = ("data-raea-renderer", "rune"); + +/// The root's id in a layer's page (raea-rune-page's tree::ROOT, sdk/ui wire.ts ROOT). +const ROOT: u64 = 0; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Owner { + Page, + /// the layer whose slot is this element id + Layer(u64), +} + +/// What one batch becomes. +#[derive(Default, Debug)] +pub struct Routed { + /// the page's own ops, for Blitz + pub page: Vec, + /// each layer's ops by its slot's id, for its Rune page; a layer's first ops make it + pub layers: BTreeMap>, + /// layers whose slot went (removed, or the page cleared) + pub gone: Vec, + /// what can't be routed, said and not dropped: an element moved between the page and a layer + pub refused: Vec, +} + +/// One page's routing, kept across its batches. +#[derive(Default)] +pub struct Router { + /// attached elements' owners + owner: HashMap, + /// the slots (marked elements), by id + slots: std::collections::HashSet, + /// unattached subtrees: each element's top, and each top's ops waiting + top: HashMap, + waiting: HashMap>, + /// each op's place in the stream, so a subtree's ops leave in the order the JS sent them + seq: u64, +} + +fn marked(props: &serde_json::Map) -> bool { + props.get(MARK.0).and_then(Value::as_str) == Some(MARK.1) +} + +/// Whether `op` makes a slot: a page whose batches never have one needn't be routed. +pub fn creates_slot(op: &Op) -> bool { + matches!(op, Op::Create { props, .. } if marked(props)) +} + +/// The element an op is about (its child, for a move). +fn subject(op: &Op) -> Option { + match op { + Op::Clear => None, + Op::Create { id, .. } | Op::Remove { id } | Op::Update { id, .. } | Op::Listen { id, .. } | Op::Unlisten { id, .. } => Some(*id), + Op::Append { child, .. } | Op::Insert { child, .. } => Some(*child), + } +} + +fn parent_of(op: &Op) -> Option { + match op { + Op::Append { parent, .. } | Op::Insert { parent, .. } => Some(*parent), + _ => None, + } +} + +impl Router { + /// Whether any layer has been seen: a page without one routes nothing (all of it is Blitz's). + pub fn has_layers(&self) -> bool { + !self.slots.is_empty() + } + + /// `ops` split. + pub fn route(&mut self, ops: Vec) -> Routed { + let mut out = Routed::default(); + for op in ops { + self.one(op, &mut out); + } + out + } + + /// Whom an attached element's children belong to: one the router never saw is the page's (made before its + /// first slot, when its batches went to Blitz unrouted). + fn under(&self, parent: u64) -> Owner { + if self.slots.contains(&parent) && self.owner.get(&parent) == Some(&Owner::Page) { + return Owner::Layer(parent); + } + self.owner.get(&parent).copied().unwrap_or(Owner::Page) + } + + fn one(&mut self, op: Op, out: &mut Routed) { + self.seq += 1; + let n = self.seq; + if let Op::Clear = op { + out.gone.extend(self.slots.iter().copied().filter(|s| self.owner.get(s) == Some(&Owner::Page))); + out.gone.sort_unstable(); + *self = Router { seq: n, ..Router::default() }; + out.page.push(Op::Clear); + return; + } + let Some(id) = subject(&op) else { return }; + if let Op::Create { props, .. } = &op + && marked(props) + { + self.slots.insert(id); + } + if let Some(parent) = parent_of(&op) { + return self.attach(n, op, id, parent, out); + } + if let Op::Create { .. } = op { + self.top.insert(id, id); + self.waiting.insert(id, vec![(n, op)]); + return; + } + // an op on an element: its owner's, or waiting with its subtree + if let Some(t) = self.top.get(&id) { + self.waiting.get_mut(t).expect("a waiting subtree").push((n, op)); + return; + } + let owner = self.owner.get(&id).copied().unwrap_or(Owner::Page); + if let Op::Remove { .. } = op { + if self.slots.remove(&id) && owner == Owner::Page { + out.gone.push(id); + } + self.owner.remove(&id); + } + send(owner, op, out); + } + + /// An append or insert of `child` under `parent`. + fn attach(&mut self, n: u64, op: Op, child: u64, parent: u64, out: &mut Routed) { + // into a subtree that isn't attached yet: it waits with it + if let Some(&t) = self.top.get(&parent) { + let mut ops = self.waiting.remove(&child).unwrap_or_default(); + for v in self.top.values_mut().filter(|v| **v == child) { + *v = t; + } + let w = self.waiting.get_mut(&t).expect("a waiting subtree"); + w.append(&mut ops); + w.push((n, op)); + self.top.insert(child, t); + return; + } + let to = self.under(parent); + match self.waiting.remove(&child) { + // a subtree attached: each of its ops to its element's owner, in order + Some(mut ops) => { + ops.push((n, op)); + ops.sort_by_key(|(n, _)| *n); + let ops: Vec = ops.into_iter().map(|(_, op)| op).collect(); + self.top.retain(|_, t| *t != child); + self.flush(ops, child, to, out); + } + // an attached element moved + None => { + let from = self.owner.get(&child).copied().unwrap_or(Owner::Page); + if from != to { + out.refused.push(format!("element {child} moved between the page and a Rune layer (it stays where it was drawn)")); + return; + } + send(to, op, out); + } + } + } + + /// A subtree's waiting ops, now that its top `top` is attached under `to`'s. + fn flush(&mut self, ops: Vec, top: u64, to: Owner, out: &mut Routed) { + // the subtree's shape from its appends, then each element's owner from its top down + let mut parent: HashMap = HashMap::new(); + for op in &ops { + if let (Some(c), Some(p)) = (subject(op), parent_of(op)) + && c != top + { + parent.insert(c, p); + } + } + self.owner.insert(top, to); + let mut members: Vec = ops.iter().filter_map(subject).collect(); + members.dedup(); + for m in members { + let mut chain = vec![m]; + while let Some(&p) = parent.get(chain.last().unwrap()) { + if self.owner.contains_key(&p) || p == top { + chain.push(p); + break; + } + chain.push(p); + } + // owners down the chain from the first one known + for w in chain.windows(2).rev() { + let (c, p) = (w[0], w[1]); + if !self.owner.contains_key(&c) { + let o = self.under(p); + self.owner.insert(c, o); + } + } + } + for op in ops { + let id = subject(&op).expect("a subtree's op names its element"); + let owner = self.owner.get(&id).copied().unwrap_or(to); + send(owner, op, out); + } + } +} + +/// `op` to `owner`, a layer's with its slot as parent made its root. +fn send(owner: Owner, op: Op, out: &mut Routed) { + match owner { + Owner::Page => out.page.push(op), + Owner::Layer(slot) => { + let op = match op { + Op::Append { parent, child } if parent == slot => Op::Append { parent: ROOT, child }, + Op::Insert { parent, child, before } if parent == slot => Op::Insert { parent: ROOT, child, before }, + op => op, + }; + out.layers.entry(slot).or_default().push(op); + } + } +} + +#[cfg(test)] +#[path = "route_tests.rs"] +mod tests; diff --git a/engine/rune/layer/src/route_tests.rs b/engine/rune/layer/src/route_tests.rs new file mode 100644 index 00000000..8035bd4d --- /dev/null +++ b/engine/rune/layer/src/route_tests.rs @@ -0,0 +1,98 @@ +use raea_core_wire::{Ev, Op}; +use serde_json::{Map, json}; + +use super::*; + +fn create(id: u64, kind: &str) -> Op { + Op::Create { id, kind: kind.into(), props: Map::new(), text: None } +} + +fn slot(id: u64) -> Op { + let props = json!({"data-raea-renderer": "rune", "className": "w-40 h-20"}).as_object().unwrap().clone(); + Op::Create { id, kind: "div".into(), props, text: None } +} + +fn text(id: u64, s: &str) -> Op { + Op::Create { id, kind: "#text".into(), props: Map::new(), text: Some(s.into()) } +} + +fn append(parent: u64, child: u64) -> Op { + Op::Append { parent, child } +} + +/// The page's first mount, as React sends it: built from the leaves up, then its top attached to the root. +fn mount() -> Vec { + vec![create(1, "div"), slot(2), create(3, "span"), text(4, "Lights"), append(3, 4), append(2, 3), create(5, "p"), append(1, 5), append(1, 2), append(0, 1)] +} + +#[test] +fn a_page_without_a_layer_is_all_blitz_in_order() { + let mut r = Router::default(); + let ops = vec![create(1, "div"), text(2, "hi"), append(1, 2), append(0, 1)]; + let out = r.route(ops); + assert_eq!(out.page, vec![create(1, "div"), text(2, "hi"), append(1, 2), append(0, 1)]); + assert!(out.layers.is_empty() && out.gone.is_empty() && out.refused.is_empty()); + assert!(!r.has_layers()); +} + +#[test] +fn a_slots_subtree_goes_to_its_layer_under_the_layers_root() { + let mut r = Router::default(); + let out = r.route(mount()); + assert_eq!(out.page, vec![create(1, "div"), slot(2), create(5, "p"), append(1, 5), append(1, 2), append(0, 1)]); + assert_eq!(out.layers.len(), 1); + assert_eq!(out.layers[&2], vec![create(3, "span"), text(4, "Lights"), append(3, 4), append(0, 3)]); + assert!(out.refused.is_empty(), "{:?}", out.refused); +} + +#[test] +fn later_ops_follow_their_elements_owner() { + let mut r = Router::default(); + r.route(mount()); + let set = json!({"className": "text-red-500"}).as_object().unwrap().clone(); + let out = r.route(vec![ + Op::Update { id: 3, set: Some(set.clone()), unset: None, text: None }, + Op::Listen { id: 3, events: vec![Ev::PointerDown] }, + Op::Update { id: 5, set: Some(set.clone()), unset: None, text: None }, + // a new element straight into the layer's slot, and one into the layer's span + text(6, "on"), + append(2, 6), + create(7, "b"), + Op::Insert { parent: 3, child: 7, before: 4 }, + ]); + assert_eq!(out.page, vec![Op::Update { id: 5, set: Some(set.clone()), unset: None, text: None }]); + assert_eq!( + out.layers[&2], + vec![Op::Update { id: 3, set: Some(set), unset: None, text: None }, Op::Listen { id: 3, events: vec![Ev::PointerDown] }, text(6, "on"), append(0, 6), create(7, "b"), Op::Insert { parent: 3, child: 7, before: 4 }] + ); +} + +#[test] +fn a_slot_removed_or_cleared_is_gone() { + let mut r = Router::default(); + r.route(mount()); + let out = r.route(vec![Op::Remove { id: 2 }]); + assert_eq!((out.page, out.gone), (vec![Op::Remove { id: 2 }], vec![2])); + let mut r = Router::default(); + r.route(mount()); + let out = r.route(vec![Op::Clear]); + assert_eq!((out.page, out.gone), (vec![Op::Clear], vec![2])); + assert!(!r.has_layers()); +} + +#[test] +fn a_move_between_the_page_and_a_layer_is_refused_not_dropped() { + let mut r = Router::default(); + r.route(mount()); + let out = r.route(vec![append(2, 5)]); + assert!(out.page.is_empty() && out.layers.is_empty()); + assert_eq!(out.refused.len(), 1, "{:?}", out.refused); +} + +#[test] +fn a_layer_inside_a_layer_is_the_outer_layers_element() { + let mut r = Router::default(); + let out = r.route(vec![slot(1), slot(2), text(3, "x"), append(2, 3), append(1, 2), append(0, 1)]); + assert_eq!(out.page, vec![slot(1), append(0, 1)]); + assert_eq!(out.layers[&1], vec![slot(2), text(3, "x"), append(2, 3), append(0, 2)]); +} diff --git a/engine/rune/page/src/page.rs b/engine/rune/page/src/page.rs index 532b2ee6..1f80cb16 100644 --- a/engine/rune/page/src/page.rs +++ b/engine/rune/page/src/page.rs @@ -68,7 +68,14 @@ impl Page { /// A batch from the JS, applied to the tree; each text field's edit follows its `value` (a controlled input: what /// React decides the value is wins over what was typed). pub fn apply(&mut self, json: &str) -> Result<(), String> { - self.tree.apply_json(json)?; + self.apply_ops(&raea_core_wire::decode(json)?) + } + + /// Ops already decoded (a Rune layer's, which raea-rune-slots routed out of a Blitz page's batch), as `apply`. + pub fn apply_ops(&mut self, ops: &[raea_core_wire::Op]) -> Result<(), String> { + for op in ops { + self.tree.apply(op)?; + } let fields: Vec<(u64, String)> = self.tree.ids().filter_map(|id| { let n = self.tree.get(id)?; (n.kind == "editableText").then(|| (id, n.props.get("value").and_then(Value::as_str).unwrap_or("").to_string())) diff --git a/engine/rune/slots/Cargo.toml b/engine/rune/slots/Cargo.toml new file mode 100644 index 00000000..6058a55f --- /dev/null +++ b/engine/rune/slots/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "raea-rune-slots" +version = "0.1.0" +edition = "2024" +license = "FSL-1.1-ALv2" +publish = false +description = "Rune layers in a Blitz page: what's under a data-raea-renderer=\"rune\" element drawn by Rune on Bevy's device and shown in it" + +[dependencies] +raea-rune-layer = { path = "../layer" } +raea-rune-bevy = { path = "../bevy" } +raea-rune-page = { path = "../page" } +raea-rune-media = { path = "../media" } +raea-runtime-dom = { path = "../../../runtime/dom" } +raea-runtime-twins = { path = "../../../runtime/twins" } +raea-sys-page = { path = "../../../systems/page" } +raea-core-wire = { path = "../../../core/wire" } +rune.workspace = true +bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "bevy_render", "bevy_asset", "bevy_image", "bevy_log", "bevy_window", "bevy_picking"] } +blitz-dom = { version = "=0.3.0-beta.4", default-features = false } +serde_json = "1" + +[dev-dependencies] +bevy = { version = "=0.20.0", default-features = false, features = ["std", "async_executor", "bevy_window", "bevy_asset", "bevy_image", "bevy_render", "bevy_core_pipeline", "bevy_picking"] } diff --git a/engine/rune/slots/src/input.rs b/engine/rune/slots/src/input.rs new file mode 100644 index 00000000..2ec18d0b --- /dev/null +++ b/engine/rune/slots/src/input.rs @@ -0,0 +1,88 @@ +//! Pointer input into a layer: the picking events on its slot's twin (raea-runtime-twins: every element's entity), +//! queued as they're triggered and given to the layer's tree at the sync, at the same point in the slot's content box +//! (its CSS px are the layer's points). A wheel's lines are 40 points each, as raea-rune-bevy's overlay takes them. + +use bevy::input::mouse::MouseScrollUnit; +use bevy::picking::events::{PointerMove, PointerOut, PointerPress, PointerRelease, PointerScroll}; +use bevy::picking::pointer::PointerButton; +use bevy::prelude::*; +use raea_rune_bevy::{Input, Trees}; +use raea_runtime_twins::bridge::PageElement; +use raea_sys_page::Docs; + +use crate::Slots; + +#[derive(Clone, Copy)] +pub(crate) enum Kind { + Move, + Down(PointerButton), + Up(PointerButton), + Leave, + /// a wheel's vertical points, positive moving the content down + Wheel(f32), +} + +/// Picking events on twins since the last sync: the twin, what happened, and where in its page (CSS px). +#[derive(Resource, Default)] +pub(crate) struct Pending(Vec<(Entity, Kind, Option)>); + +/// `E` on any entity queued as what `read` makes of it. +fn on(app: &mut App, read: fn(&E) -> (Kind, Option)) { + app.add_observer(move |e: On, mut c: Commands| { + let (twin, (kind, at)) = (e.event_target(), read(&e)); + c.queue(move |w: &mut World| w.resource_mut::().0.push((twin, kind, at.map(|p| p.truncate())))); + }); +} + +pub(crate) fn observe(app: &mut App) { + on::(app, |e| (Kind::Move, e.hit.position)); + // a press and a release are alike but for what they are + macro_rules! button { + ($e:ty, $kind:path) => { + on::<$e>(app, |e| ($kind(e.button), e.hit.position)) + }; + } + button!(PointerPress, Kind::Down); + button!(PointerRelease, Kind::Up); + on::(app, |_| (Kind::Leave, None)); + on::(app, |e| { + let lines = matches!(e.unit, MouseScrollUnit::Line); + (Kind::Wheel(if lines { e.y * 40.0 } else { e.y }), e.hit.position) + }); +} + +/// The pending events on slots' twins, each to its layer's tree. A press on a layer captures the pointer, as +/// setPointerCapture does on the page: until its release, that page's moves and the release go to the layer wherever +/// they land, at their points in the slot's box, so a press dragged off the layer still ends there. +pub(crate) fn apply(world: &mut World, slots: &mut Slots) { + let pending = std::mem::take(&mut world.resource_mut::().0); + for (twin, kind, at) in pending { + let Some(el) = world.get::(twin).copied() else { continue }; + let held = slots.held.filter(|(page, _)| *page == el.page && matches!(kind, Kind::Move | Kind::Up(_) | Kind::Leave)); + // picking's events bubble: otherwise only the slot's own twin is the layer's (its parents' are the page's) + let Some(key) = held.or_else(|| el.op.map(|id| (el.page, id)).filter(|k| slots.layers.contains_key(k))) else { continue }; + let Some(slot) = slots.layers.get(&key) else { continue }; + let min = slot.node.and_then(|n| world.non_send::().0.get(&key.0)?.get_node(n).map(|n| crate::content(n).0)); + let p = at.zip(min).map(|(at, min)| at - min); + let ev = match (kind, p) { + // a held press keeps the pointer: leaving the slot isn't leaving the layer + (Kind::Leave, _) if held.is_some() => continue, + (Kind::Leave, _) => Input::Leave, + (Kind::Move, Some(p)) => Input::Move(p.x, p.y), + (Kind::Down(PointerButton::Secondary), Some(p)) => Input::SecondaryDown(p.x, p.y), + (Kind::Up(PointerButton::Secondary), Some(p)) => Input::SecondaryUp(p.x, p.y), + (Kind::Down(PointerButton::Primary), Some(p)) => Input::Down(p.x, p.y), + (Kind::Up(PointerButton::Primary), Some(p)) => Input::Up(p.x, p.y), + (Kind::Wheel(dy), Some(p)) => Input::Wheel(p.x, p.y, dy), + _ => continue, + }; + match kind { + Kind::Down(_) => slots.held = Some(key), + Kind::Up(_) => slots.held = None, + _ => {} + } + if let Some(t) = world.non_send_mut::().0.get_mut(&slot.entity) { + t.input(ev); + } + } +} diff --git a/engine/rune/slots/src/layer.rs b/engine/rune/slots/src/layer.rs new file mode 100644 index 00000000..5b1e37f7 --- /dev/null +++ b/engine/rune/slots/src/layer.rs @@ -0,0 +1,51 @@ +//! A layer's tree: a Rune page (raea-rune-page) in a raea-rune-bevy Tree, taking its routed ops (and its slot's size +//! as its breakpoints' width) before each frame and handing what its handlers queued for the JS to the plugin after it. + +use std::cell::RefCell; +use std::rc::Rc; + +use bevy::prelude::Entity; +use raea_core_wire::Op; +use raea_rune_bevy::Tree; +use raea_rune_page::page::{Out, Page, view}; +use rune::{Env, Runtime}; + +/// A layer of page `page` at `scale` (sized to its slot by the next sync), its messages for the JS into `outbox`; and +/// the ops it takes at its next frame. +pub(crate) fn make(page: Entity, scale: f32, outbox: Rc>>) -> (Tree, Rc>>) { + let viewport = (1.0, 1.0); + let text = rune::text::TextSystem::new(raea_rune_media::fonts::registered(), ("Inter", "Inter")); + let mut state = Page::default(); + state.viewport = viewport; + let mut tree = Tree::new(Runtime::with_text(state, view, viewport, Env::new(false, scale), text), scale); + let pending = Rc::new(RefCell::new(Vec::new())); + let ops = pending.clone(); + tree.before_frame = Some(Box::new(move |rt: &mut Runtime| { + let ops = std::mem::take(&mut *ops.borrow_mut()); + // the slot's size, the page's breakpoints' width (Page::resized would tell the root's JS the window resized) + let resized = rt.state.viewport != rt.viewport; + if ops.is_empty() && !resized { + return; + } + let (mut r, viewport) = (Ok(()), rt.viewport); + rt.update(|p, _| { + p.viewport = viewport; + r = p.apply_ops(&ops); + }); + if let Err(e) = r { + eprintln!("raea-rune-slots: a layer's ops: {e}"); + } + })); + tree.after_frame = Some(Box::new(move |rt: &mut Runtime| { + let m = raea_rune_page::layout::measure(&rt.elements(), &rt.state.boxes.borrow(), rt.viewport); + rt.state.measured(m); + rt.state.media_news(); + // its element events and host messages for `__ui_deliver`; a layout snapshot is the page's (Blitz's) alone + let mut out = outbox.borrow_mut(); + out.extend(rt.state.take_out().into_iter().filter_map(|o| match o { + Out::Deliver(m) => Some((page, m)), + Out::Layout(_) => None, + })); + })); + (tree, pending) +} diff --git a/engine/rune/slots/src/lib.rs b/engine/rune/slots/src/lib.rs new file mode 100644 index 00000000..1d06b51a --- /dev/null +++ b/engine/rune/slots/src/lib.rs @@ -0,0 +1,171 @@ +//! raea-rune-slots: Rune layers in a Blitz page (docs/targets.feature T6c, per layer). An element marked +//! `data-raea-renderer="rune"` (sdk/rune's ``) stays Blitz's, a slot; what's under it is a Rune page's +//! (raea-rune-page), drawn by Rune on Bevy's device into an Image (raea-rune-bevy) that the slot shows (raea-page's +//! ElementImages, as the stage's `` shows its picture). +//! +//! - Ops: the page host's commits pass through raea-runtime-dom's split, where raea-rune-layer's Router takes each +//! layer's ops out of the batch; a page whose batches never make a slot isn't routed at all. +//! - Size: each frame a layer's viewport is its slot's content box in CSS px (its points), at the page's scale. +//! - Input: a pointer over a slot is a pointer over its layer, at the same point in the slot's content box (the +//! twin's picking events, [`input`]); the events the Rune page's handlers queue go to the root's JS as Blitz's do. +//! - Said, not dropped ([`Slots::report`]): a move between the page and a layer, and that a layer's elements have no +//! geometry in the page's layout snapshot (getBoundingClientRect on one is zero). + +mod input; +mod layer; + +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; + +use bevy::prelude::*; +use raea_core_wire::Op; +use raea_rune_bevy::{RuneLayer, RuneLayerPlugin, SpawnRune, Trees}; +use raea_rune_layer::{Router, creates_slot}; +use raea_runtime_dom::host::Roots; +use raea_sys_page::view3d::ElementImages; +use raea_sys_page::{Docs, Page}; + +/// What the page host's commits routed since the last sync. +#[derive(Default)] +struct Inbox { + routers: HashMap, + ops: Vec<(Entity, u64, Vec)>, + gone: Vec<(Entity, u64)>, + refused: Vec, +} + +/// One layer: its RuneLayer entity, and the ops its tree takes at its next frame. +pub struct Slot { + pub entity: Entity, + ops: Rc>>, + node: Option, +} + +/// The layers, by page and slot's wire id (a non-send resource). +#[derive(Default)] +pub struct Slots { + inbox: Rc>, + pub layers: HashMap<(Entity, u64), Slot>, + /// what the layers' Rune pages queued for the JS, by page + outbox: Rc>>, + /// what couldn't be done as asked, each said once + pub report: Vec, + /// the layer a held press captured the pointer to (input.rs) + held: Option<(Entity, u64)>, +} + +/// Rune layers in the App's Blitz pages. +pub struct RuneSlotsPlugin; + +impl Plugin for RuneSlotsPlugin { + fn build(&self, app: &mut App) { + if !app.is_plugin_added::() { + app.add_plugins(RuneLayerPlugin); + } + let slots = Slots::default(); + let inbox = slots.inbox.clone(); + raea_runtime_dom::host::set_split(Box::new(move |page, ops| split(&inbox, page, ops))); + app.init_resource::().init_resource::().insert_non_send(slots).add_systems(Update, sync); + input::observe(app); + } +} + +/// A batch of `page`'s ops: the page's back, each layer's kept for the next sync. +fn split(inbox: &RefCell, page: Entity, ops: Vec) -> Vec { + let mut i = inbox.borrow_mut(); + if !i.routers.get(&page).is_some_and(Router::has_layers) && !ops.iter().any(creates_slot) { + return ops; + } + let out = i.routers.entry(page).or_default().route(ops); + i.ops.extend(out.layers.into_iter().map(|(slot, ops)| (page, slot, ops))); + i.gone.extend(out.gone.into_iter().map(|s| (page, s))); + i.refused.extend(out.refused); + out.page +} + +fn say(slots: &mut Slots, what: String) { + if !slots.report.contains(&what) { + eprintln!("raea-rune-slots: {what}"); + slots.report.push(what); + } +} + +/// Update: routed ops to their layers (a layer made by its first), gone slots' layers dropped, each layer sized to +/// its slot and shown there, pointer input in, and what the layers' pages queued out to the JS. +fn sync(world: &mut World) { + let (ops, gone, refused) = { + let s = world.non_send::(); + let mut i = s.inbox.borrow_mut(); + (std::mem::take(&mut i.ops), std::mem::take(&mut i.gone), std::mem::take(&mut i.refused)) + }; + let mut slots = world.remove_non_send::().expect("Slots"); + for r in refused { + say(&mut slots, r); + } + for key in gone { + if slots.held == Some(key) { + slots.held = None; + } + if let Some(s) = slots.layers.remove(&key) { + world.despawn(s.entity); + if let Some(n) = s.node { + world.resource_mut::().0.remove(&(key.0, n)); + } + } + } + for (page, slot, ops) in ops { + if !slots.layers.contains_key(&(page, slot)) { + let scale = world.get::(page).map_or(1.0, |p| p.scale); + let (tree, pending) = layer::make(page, scale, slots.outbox.clone()); + let entity = world.spawn_rune(tree, [0.0; 4]); + slots.layers.insert((page, slot), Slot { entity, ops: pending, node: None }); + say(&mut slots, "a Rune layer's elements aren't in the page's layout snapshot (their getBoundingClientRect is zero)".into()); + } + slots.layers[&(page, slot)].ops.borrow_mut().extend(ops); + } + place(world, &mut slots); + input::apply(world, &mut slots); + let out = std::mem::take(&mut *slots.outbox.borrow_mut()); + world.insert_non_send(slots); + for (page, msg) in out { + match serde_json::from_str(&msg) { + Ok(v) => raea_runtime_dom::host::deliver_to(world, page, v), + Err(e) => eprintln!("raea-rune-slots: a layer's message that isn't JSON: {e}"), + } + } +} + +/// Each layer at its slot: the slot's node found, the tree's viewport its content box, its Image shown there. +fn place(world: &mut World, slots: &mut Slots) { + for ((page, id), slot) in slots.layers.iter_mut() { + let node = world.get_non_send::().and_then(|r| r.0.iter().find(|r| r.page == *page).and_then(|r| r.nodes.by_id.get(id).copied())); + let size = node.and_then(|n| world.non_send::().0.get(page)?.get_node(n).map(|n| content(n).1)); + let scale = world.get::(*page).map_or(1.0, |p| p.scale); + if let Some(size) = size { + let mut trees = world.non_send_mut::(); + if let Some(t) = trees.0.get_mut(&slot.entity) + && t.viewport() != ((size.x, size.y), scale) + { + t.resize((size.x.max(1.0), size.y.max(1.0)), scale); + } + } + let Some(image) = world.get::(slot.entity).map(|l| l.image.clone()) else { continue }; + let mut shows = world.resource_mut::(); + if let Some(old) = slot.node.filter(|o| Some(*o) != node) { + shows.0.remove(&(*page, old)); + } + if let Some(n) = node { + shows.0.insert((*page, n), image); + } + slot.node = node; + } +} + +/// A node's content box: its top left in page CSS px, and its size. +pub(crate) fn content(node: &blitz_dom::Node) -> (Vec2, Vec2) { + let l = node.final_layout(); + let abs = node.absolute_position(0.0, 0.0); + let min = Vec2::new(abs.x + l.border.left + l.padding.left, abs.y + l.border.top + l.padding.top); + (min, Vec2::new(l.content_box_width(), l.content_box_height())) +} diff --git a/engine/rune/slots/tests/slot.rs b/engine/rune/slots/tests/slot.rs new file mode 100644 index 00000000..dbdfa080 --- /dev/null +++ b/engine/rune/slots/tests/slot.rs @@ -0,0 +1,138 @@ +//! A Blitz page with a Rune layer, through the page host (raea-runtime-dom) in a headless Bevy app: what's under the +//! marked element is the layer's Rune page's and not the document's, the layer is its slot's size and shown there, +//! and a press on the layer's button reaches the page's JS as an event of that button. + +use bevy::prelude::*; +use bevy::window::ExitCondition; +use raea_rune_bevy::{Input, RuneLayer, Trees}; +use raea_rune_page::page::Page; +use raea_rune_slots::{RuneSlotsPlugin, Slots}; +use raea_runtime_dom::host::{self, HostStepPlugin, PageAsks, Roots}; +use raea_sys_page::view3d::ElementImages; +use raea_sys_page::{Docs, PageClock, PageSystems}; +use serde_json::Value; + +const CODE: &str = r#" + globalThis.__ui_deliver = (json) => { const m = JSON.parse(json); if (m.t === "event") __ui_emit("heard", JSON.stringify(m)); }; + __ui_flush(JSON.stringify({ v: 1, ops: [ + { op: "create", id: 1, kind: "div", props: {} }, + { op: "create", id: 2, kind: "div", props: { "data-raea-renderer": "rune", style: { width: "200px", height: "100px" } } }, + { op: "create", id: 3, kind: "button", props: { style: { width: "200px", height: "100px" } } }, + { op: "create", id: 4, kind: "text", props: {}, text: "Press" }, + { op: "append", parent: 3, child: 4 }, + { op: "listen", id: 3, events: ["pointerdown"] }, + { op: "append", parent: 2, child: 3 }, + { op: "create", id: 5, kind: "p", props: {} }, + { op: "append", parent: 1, child: 2 }, + { op: "append", parent: 1, child: 5 }, + { op: "append", parent: 0, child: 1 }, + ] })); +"#; + +fn app() -> (App, Entity) { + let mut app = App::new(); + app.add_plugins( + DefaultPlugins + .build() + .set(WindowPlugin { primary_window: None, exit_condition: ExitCondition::DontExit, close_when_requested: false, ..default() }) + .set(bevy::render::RenderPlugin { synchronous_pipeline_compilation: true, ..default() }), + ); + app.add_plugins((HostStepPlugin, RuneSlotsPlugin)) + .init_non_send::() + .init_resource::() + .add_systems(PostUpdate, raea_sys_page::resolve.in_set(PageSystems::Restyle)); + app.finish(); + app.cleanup(); + let page = host::mount(app.world_mut(), 400, 300, CODE, &[], None).unwrap(); + for _ in 0..6 { + app.update(); + } + (app, page) +} + +fn layer(app: &App, page: Entity) -> Entity { + app.world().non_send::().layers.get(&(page, 2)).expect("a layer for the marked element").entity +} + +#[test] +fn whats_under_the_slot_is_the_layers() { + let (app, page) = app(); + let w = app.world(); + // the document: the slot, empty, beside the page's own

+ let roots = w.non_send::(); + let nodes = &roots.0.iter().find(|r| r.page == page).unwrap().nodes; + assert!(nodes.by_id.contains_key(&2) && nodes.by_id.contains_key(&5)); + assert!(!nodes.by_id.contains_key(&3) && !nodes.by_id.contains_key(&4), "the layer's elements reached Blitz"); + let doc = w.non_send::(); + let slot = doc.0[&page].get_node(nodes.by_id[&2]).unwrap(); + assert!(slot.children.is_empty(), "the slot has Blitz children"); + // the layer's page: the button under its root + let e = layer(&app, page); + let trees = w.non_send::(); + let tree = &trees.0[&e]; + let p = tree.state().downcast_ref::().unwrap(); + assert_eq!(p.tree.get(0).unwrap().children, vec![3]); + assert_eq!(p.tree.get(3).unwrap().children, vec![4]); + // sized to the slot's content box, its Image shown in the slot + assert_eq!(tree.viewport(), ((200.0, 100.0), 1.0)); + let image = &w.get::(e).unwrap().image; + assert_eq!(w.resource::().0.get(&(page, nodes.by_id[&2])), Some(image)); + assert!(w.non_send::().report.iter().all(|r| !r.contains("moved")), "{:?}", w.non_send::().report); +} + +#[test] +fn a_press_on_the_layer_reaches_the_pages_js() { + let (mut app, page) = app(); + let e = layer(&app, page); + for ev in [Input::Move(40.0, 30.0), Input::Down(40.0, 30.0), Input::Up(40.0, 30.0)] { + app.world_mut().non_send_mut::().0.get_mut(&e).unwrap().input(ev); + app.update(); + } + for _ in 0..3 { + app.update(); + } + let asks = &app.world().resource::().0; + let heard: Vec<&Value> = asks.iter().filter(|(p, n, _)| *p == page && n == "heard").map(|(_, _, v)| v).collect(); + assert!(heard.iter().any(|m| m["id"] == 3 && m["event"] == "pointerdown"), "the JS heard {heard:?}"); +} + +/// Picking's press on the slot's twin, and its release on another element's: the layer has the press, and the release +/// still ends it there (the pointer captured, as setPointerCapture does), so its button isn't left held. +#[test] +fn a_press_held_off_the_layer_still_ends_there() { + use bevy::camera::NormalizedRenderTarget; + use bevy::picking::backend::HitData; + use bevy::picking::events::{Pointer, PointerPress, PointerRelease}; + use bevy::picking::pointer::{Location, PointerButton, PointerId}; + use raea_runtime_twins::bridge::PageElement; + + let (mut app, page) = app(); + let w = app.world_mut(); + let (slot, p) = { + let roots = w.non_send::(); + let nodes = &roots.0.iter().find(|r| r.page == page).unwrap().nodes; + (nodes.by_id[&2], nodes.by_id[&5]) + }; + let at = { + let docs = w.non_send::(); + let n = docs.0[&page].get_node(slot).unwrap(); + let (abs, l) = (n.absolute_position(0.0, 0.0), n.final_layout()); + Vec2::new(abs.x + l.border.left + l.padding.left, abs.y + l.border.top + l.padding.top) + Vec2::new(40.0, 30.0) + }; + let slot_twin = w.spawn(PageElement { page, node: slot, op: Some(2) }).id(); + let p_twin = w.spawn(PageElement { page, node: p, op: Some(5) }).id(); + let pointer = Pointer::new(PointerId::Mouse, Location { target: NormalizedRenderTarget::None { width: 400, height: 300 }, position: Vec2::ZERO }); + let hit = |p: Vec2| HitData::new(Entity::PLACEHOLDER, 0.0, Some(p.extend(0.0)), None); + w.trigger(PointerPress { entity: slot_twin, pointer: pointer.clone(), button: PointerButton::Primary, hit: hit(at), count: 1 }); + app.update(); + app.update(); + let e = layer(&app, page); + let pressed = |app: &App| app.world().non_send::().0[&e].state().downcast_ref::().unwrap().pressed.clone(); + // (the press holds the button and each element up to the layer's root, as :active does) + assert!(pressed(&app).contains(&3), "the press didn't reach the layer's button: {:?}", pressed(&app)); + app.world_mut().trigger(PointerRelease { entity: p_twin, pointer, button: PointerButton::Primary, hit: hit(at + Vec2::new(0.0, 200.0)) }); + for _ in 0..3 { + app.update(); + } + assert!(pressed(&app).is_empty(), "the release off the layer left its button held"); +} diff --git a/runtime/dom/src/host.rs b/runtime/dom/src/host.rs index 248f2e4a..eca0e792 100644 --- a/runtime/dom/src/host.rs +++ b/runtime/dom/src/host.rs @@ -115,9 +115,9 @@ impl PageSync { if batches.is_empty() { return; } - let (nodes, queue) = (self.nodes, self.queue); + let (nodes, queue, page) = (self.nodes, self.queue, self.page); let Some(doc) = self.doc() else { return }; - commit_focus(doc, unsafe { &mut *nodes }, batches, queue.map(|q| unsafe { &mut *q })); + commit_focus(page, doc, unsafe { &mut *nodes }, batches, queue.map(|q| unsafe { &mut *q })); if let Some(c) = self.synced { unsafe { *c = true }; } diff --git a/runtime/dom/src/host/bridge.rs b/runtime/dom/src/host/bridge.rs index d1409fef..93d50fd7 100644 --- a/runtime/dom/src/host/bridge.rs +++ b/runtime/dom/src/host/bridge.rs @@ -65,7 +65,7 @@ impl Bridge<'_> { eprintln!("raea-page: js: an event threw: {e}"); } let batches = std::mem::take(&mut self.out.borrow_mut().flushed); - commit(d, self.nodes, batches); + commit(self.page, d, self.nodes, batches); true } @@ -261,7 +261,7 @@ impl EventHandler for Bridge<'_> { o.emits.retain(|(n, _)| n != "prevented"); (std::mem::take(&mut o.flushed), prevented) }; - commit(&mut d, self.nodes, batches); + commit(self.page, &mut d, self.nodes, batches); // a right press: its contextmenu, to the nearest element up that hears it (before the press's focus default: a // menu it opens has the focus) if let DomEventData::PointerDown(p) = &event.data @@ -274,7 +274,7 @@ impl EventHandler for Bridge<'_> { eprintln!("raea-page: js: an event threw: {e}"); } let batches = std::mem::take(&mut self.out.borrow_mut().flushed); - commit(&mut d, self.nodes, batches); + commit(self.page, &mut d, self.nodes, batches); // (Chrome's contextmenu comes after the press's focus: a focus it moves stays, on any page) prevented |= d.get_focussed_node_id() != before; } diff --git a/runtime/dom/src/host/commit.rs b/runtime/dom/src/host/commit.rs index 95271746..cca3ef78 100644 --- a/runtime/dom/src/host/commit.rs +++ b/runtime/dom/src/host/commit.rs @@ -17,11 +17,21 @@ pub(crate) fn timers(js: &mut dyn JsEngine) { } } -/// A root's op batches applied to its document. -pub(crate) fn commit(doc: &mut BaseDocument, nodes: &mut Nodes, batches: Vec) { +/// What takes a page's ops before its document does, and hands back the document's: raea-rune-slots', whose Rune +/// layers draw what's under their slots (T6c). None: every op is the document's. +pub type Split = Box) -> Vec>; +thread_local!(static SPLIT: std::cell::RefCell> = const { std::cell::RefCell::new(None) }); + +/// `f` as every root's [`Split`] on this thread (the page host's). +pub fn set_split(f: Split) { + SPLIT.with_borrow_mut(|s| *s = Some(f)); +} + +/// Page `page`'s op batches applied to its document. +pub(crate) fn commit(page: Entity, doc: &mut BaseDocument, nodes: &mut Nodes, batches: Vec) { for b in batches { match wire::decode(&b) { - Ok(o) => ops::apply(doc, nodes, o), + Ok(o) => ops::apply(doc, nodes, SPLIT.with_borrow_mut(|s| match s.as_mut() { Some(f) => f(page, o), None => o })), Err(e) => eprintln!("raea-page: {e}"), } } @@ -29,9 +39,9 @@ pub(crate) fn commit(doc: &mut BaseDocument, nodes: &mut Nodes, batches: Vec, queue: Option<&mut Vec>) { +pub(crate) fn commit_focus(page: Entity, doc: &mut BaseDocument, nodes: &mut Nodes, batches: Vec, queue: Option<&mut Vec>) { let before = doc.get_focussed_node_id(); - commit(doc, nodes, batches); + commit(page, doc, nodes, batches); if let Some(q) = queue && let Some(n) = doc.get_focussed_node_id().filter(|n| Some(*n) != before) && let Some(id) = nodes.id_of(n).filter(|id| nodes.hears(*id, Ev::Focus)) @@ -51,7 +61,7 @@ pub(crate) fn drain(world: &mut World, r: &mut Root) -> bool { if !batches.is_empty() && let Some(doc) = world.non_send_mut::().0.get_mut(&r.page) { - commit_focus(doc, &mut r.nodes, batches, Some(&mut r.queue)); + commit_focus(r.page, doc, &mut r.nodes, batches, Some(&mut r.queue)); } // a scroller a commit moved (its scrollTop set, here or in an event's delivery): its scroll event, as Chrome // sends one after @@ -215,7 +225,12 @@ pub fn post(world: &mut World, name: &str, value: Value) { /// A host event for one root at its next step. pub fn post_to(world: &mut World, page: Entity, name: &str, value: Value) { + deliver_to(world, page, wire::named(name, value)); +} + +/// A message for one root's `__ui_deliver` at its next step (an element's event a Rune layer heard). +pub fn deliver_to(world: &mut World, page: Entity, msg: Value) { if let Some(r) = world.get_non_send_mut::().as_mut().and_then(|r| r.get_mut(page)) { - r.queue.push(wire::named(name, value)); + r.queue.push(msg); } } diff --git a/sdk/rune/src/index.ts b/sdk/rune/src/index.ts index 2f8035ff..d63b04bc 100644 --- a/sdk/rune/src/index.ts +++ b/sdk/rune/src/index.ts @@ -12,6 +12,7 @@ import "./web.css"; import { web } from "./web.ts"; export * from "./kit.tsx"; +export * from "./layer.tsx"; export { web } from "./web.ts"; /** A spring as Rune has it: how long it takes to settle, in seconds, and how much it overshoots (0 none, 1 a lot). */ diff --git a/sdk/rune/src/layer.tsx b/sdk/rune/src/layer.tsx new file mode 100644 index 00000000..594c3c82 --- /dev/null +++ b/sdk/rune/src/layer.tsx @@ -0,0 +1,17 @@ +// A Rune layer in a page (docs/targets.feature T6c, per layer): what's inside is drawn by Rune on Bevy's device, in this +// element's box, and the rest of the page stays Blitz's. The page host splits the op stream there +// (engine/rune/layer, engine/rune/slots); a browser or a host without Rune layers draws it as a plain div. +import type { HTMLAttributes, ReactElement } from "react"; + +/** The prop that marks a layer, and its value (engine/rune/layer's MARK). */ +export const RUNE_LAYER = { "data-raea-renderer": "rune" } as const; + +/** Its children drawn by Rune. Give it a size (className or style): the layer is its content box. Their events reach + * React as Blitz's do; their boxes aren't in the page's layout snapshot (a getBoundingClientRect inside is zero). */ +export function RuneLayer({ children, ...props }: HTMLAttributes): ReactElement { + return ( +

+ {children} +
+ ); +} diff --git a/sdk/skills/raea/SKILL.md b/sdk/skills/raea/SKILL.md index 496ce835..3aed456b 100644 --- a/sdk/skills/raea/SKILL.md +++ b/sdk/skills/raea/SKILL.md @@ -184,6 +184,11 @@ game stays a composition; an app is an application's interface. `instant`, `blur`, `backdropBlur` and `glass`, and its `Badge`, `Spinner`, `Progress`, `RollingText` and `Switch`. On web, a preset motion becomes a CSS transition and an entrance a keyframe, blur and glass become filters, and the rest is ignored and listed by the check. Without these props an element lands at once, as in a browser. +- Part of a web page can be Rune's: `...` from `@raea/rune` draws its + children with Rune, on the GPU, in its box, and the rest of the page stays Blitz's. Give it a size: the layer is + its content box. Clicks and wheel reach its elements, and their handlers run as anywhere else. A + `getBoundingClientRect` inside one is zero, and keys don't reach a field in one yet. In a browser it's a plain + div. `RAEA_RUNE_LAYERS=0` draws it with Blitz. - Host calls (`call` and `callSync` from `@raea/ui/wire`), answered on both targets: `net.fetch`, `net.ws.*`, `net.storage.*`, `net.clipboard.*`, `os.open` (http, https, mailto), `fs.pick`, `fs.save`, `fs.read`, `fs.write` and `dialog.message`. Headless, a step answers a dialog: `{ pick: ["a.txt"] }`, `{ save: "out.txt" }`, diff --git a/tools/layers.toml b/tools/layers.toml index d5783f77..531f8781 100644 --- a/tools/layers.toml +++ b/tools/layers.toml @@ -146,6 +146,8 @@ raea-rune-look = "runtime" raea-rune-style = "runtime" raea-rune-js = "runtime" raea-rune-bevy = "runtime" +raea-rune-layer = "runtime" +raea-rune-slots = "runtime" raea-page-stage = "runtime" raea-page-window = "runtime" raea-runtime-react = "runtime" diff --git a/tools/vendor b/tools/vendor index 2472dfc2..443881de 100755 --- a/tools/vendor +++ b/tools/vendor @@ -29,6 +29,10 @@ upstream_dir() { local name=$1 up=$2 ver dir reg case $up in crates.io:*) ver=${up#crates.io:} ;; + # git:@:, from cargo's checkout of that rev (the lock pins it, so cargo has fetched it) + git:*) local rev=${up#*@}; local sub=${rev#*:}; rev=${rev%%:*} + for reg in "$HOME"/.cargo/git/checkouts/*/"${rev:0:7}"/"$sub"; do [ -d "$reg" ] && { echo "$reg"; return; }; done + echo "vendor: $name: no cargo checkout of $up" >&2; return 1 ;; *) echo "vendor: $name: only crates.io upstreams are fetched ($up)" >&2; return 1 ;; esac for reg in "$HOME"/.cargo/registry/src/index.crates.io-*/"$name-$ver"; do [ -d "$reg" ] && { echo "$reg"; return; }; done diff --git a/vendor/rune-taffy/Cargo.toml b/vendor/rune-taffy/Cargo.toml new file mode 100644 index 00000000..d88604c3 --- /dev/null +++ b/vendor/rune-taffy/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "rune-taffy" +version = "0.0.1" +edition = "2024" +license = "MIT" +# raea: vendored from anomalyco/rune 7ead7d6 (crates/rune-taffy) with taffy's flexbox_balance on, so its +# two wrap modes always exist and encode_wrap names them (src/style/mod.rs) + +[features] +default = [] +# Use upstream `taffy::TaffyTree` instead of `LayoutStore` for A/B benchmarks and parity checks. +baseline-taffy = [] + +[dependencies] +taffy = { version = "0.15", default-features = false, features = ["std", "taffy_tree", "flexbox", "grid", "block_layout", "content_size", "flexbox_balance"] } + diff --git a/vendor/rune-taffy/src/baseline_store.rs b/vendor/rune-taffy/src/baseline_store.rs new file mode 100644 index 00000000..109208b3 --- /dev/null +++ b/vendor/rune-taffy/src/baseline_store.rs @@ -0,0 +1,378 @@ +//! Upstream `taffy::TaffyTree` wrapper implementing the [`crate::LayoutStore`] commit interface +//! for `--features baseline-taffy` parity checks and A/B benchmarks. +#![allow(clippy::unwrap_used)] + +use std::collections::HashMap; + +use taffy::geometry::Size; +use taffy::style::{AvailableSpace, Style}; +use taffy::tree::{DetailedLayoutInfo, Layout, LayoutInput, LayoutOutput, NodeId, TraversePartialTree}; + +use crate::BaselineTaffyTree; +use crate::store::{BoxLayout, SlotId, StorageStats}; +use crate::style::CompactStyle; + +/// Estimates retained heap bytes for a baseline `taffy::TaffyTree` with `live_nodes` +/// and `peak_nodes`, accounting for `SlotMap`'s power-of-two slot buffers (`nodes`, `children`, +/// `parents`, `node_context_data`) and per-container `Vec` allocations. +pub fn baseline_storage_stats( + tree: &taffy::TaffyTree, + root: Option, + peak_nodes: usize, +) -> StorageStats { + let live_nodes = tree.total_node_count(); + let slot_cap = peak_nodes.max(live_nodes).max(16).next_power_of_two(); + let node_data_bytes = core::mem::size_of::