T6c: Rune layers in a Blitz page: what's under data-raea-renderer="rune" (sdk/rune's <RuneLayer>) is drawn by Rune on Bevy's device and shown in its slot

raea-runtime-dom's commits pass through a split (set_split), where raea-rune-layer's Router takes each layer's ops out of the batch in the JS's order, the slot standing for the layer page's root; a page that never makes a slot isn't routed. raea-rune-slots keeps each layer as a raea-rune-page Page in a raea-rune-bevy Tree (its new before_frame hook takes the routed ops), sized each frame to its slot's content box at the page's scale and shown there through ElementImages. Pointer input reaches it through the slot twin's picking events, a held press capturing the pointer as setPointerCapture does; its page's events reach the root's JS (deliver_to). raea-page-host adds it (RAEA_RUNE_LAYERS=0: all Blitz). Said, not dropped: a move between the page and a layer, and that a layer's elements aren't in the layout snapshot. vendor/rune-taffy: Rune and Blitz in one build need taffy's flexbox_balance arms in encode_wrap. Tests (engine/rune/slots/tests/slot.rs, through the page host): the slot's subtree is the layer's and not Blitz's, the layer is the slot's size and shown there, a press reaches the page's JS, and a press released off the layer still ends there; mutants without the split, the deliveries or the capture each fail one. The skill says how to use <RuneLayer> and what it doesn't do yet.
This commit is contained in:
shinyobjectz committed 2026-11-07 15:20:38 -08:00
1 parent 461c7491ac
commit ee771c453c
38 files changed
+5409 -37

No files matched your search

Generated
+27 -1
View File
@@ -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",
]
+8
View File
@@ -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" }
@@ -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.
-1
View File
@@ -351,7 +351,6 @@ LICENSES/<crate>-<version>/.
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
+2
View File
@@ -46,6 +46,8 @@ image = { version = "0.25", default-features = false, features = ["png"] }
serde_json = "1"
# the live stage: <img data-raea-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" }
+5
View File
@@ -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| {
+6 -1
View File
@@ -33,6 +33,8 @@ pub struct Tree<S: 'static> {
pub rt: Runtime<S>,
scale: f32,
renderer: Option<Renderer>,
/// run before each frame with the runtime (a host handing it what changed since: a page's ops)
pub before_frame: Option<Box<dyn FnMut(&mut Runtime<S>)>>,
/// run after each frame with the runtime (a host reading the frame's layout, a video's encoder)
pub after_frame: Option<Box<dyn FnMut(&mut Runtime<S>)>>,
}
@@ -42,12 +44,15 @@ impl<S: 'static> Tree<S> {
pub fn new(mut rt: Runtime<S>, scale: f32) -> Tree<S> {
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<S: 'static> AnyTree for Tree<S> {
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);
+11
View File
@@ -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"
+10
View File
@@ -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 `<RuneLayer>`) 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};
+233
View File
@@ -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<Op>,
/// each layer's ops by its slot's id, for its Rune page; a layer's first ops make it
pub layers: BTreeMap<u64, Vec<Op>>,
/// layers whose slot went (removed, or the page cleared)
pub gone: Vec<u64>,
/// what can't be routed, said and not dropped: an element moved between the page and a layer
pub refused: Vec<String>,
}
/// One page's routing, kept across its batches.
#[derive(Default)]
pub struct Router {
/// attached elements' owners
owner: HashMap<u64, Owner>,
/// the slots (marked elements), by id
slots: std::collections::HashSet<u64>,
/// unattached subtrees: each element's top, and each top's ops waiting
top: HashMap<u64, u64>,
waiting: HashMap<u64, Vec<(u64, Op)>>,
/// 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<String, Value>) -> 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<u64> {
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<u64> {
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<Op>) -> 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<Op> = 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<Op>, 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<u64, u64> = 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<u64> = 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;
+98
View File
@@ -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<Op> {
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)]);
}
+8 -1
View File
@@ -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()))
+24
View File
@@ -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"] }
+88
View File
@@ -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<Vec2>)>);
/// `E` on any entity queued as what `read` makes of it.
fn on<E: EntityEvent>(app: &mut App, read: fn(&E) -> (Kind, Option<Vec3>)) {
app.add_observer(move |e: On<E>, mut c: Commands| {
let (twin, (kind, at)) = (e.event_target(), read(&e));
c.queue(move |w: &mut World| w.resource_mut::<Pending>().0.push((twin, kind, at.map(|p| p.truncate()))));
});
}
pub(crate) fn observe(app: &mut App) {
on::<PointerMove>(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::<PointerOut>(app, |_| (Kind::Leave, None));
on::<PointerScroll>(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::<Pending>().0);
for (twin, kind, at) in pending {
let Some(el) = world.get::<PageElement>(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::<Docs>().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::<Trees>().0.get_mut(&slot.entity) {
t.input(ev);
}
}
}
+51
View File
@@ -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<RefCell<Vec<(Entity, String)>>>) -> (Tree<Page>, Rc<RefCell<Vec<Op>>>) {
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<Page>| {
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<Page>| {
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)
}
+171
View File
@@ -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 `<RuneLayer>`) 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 `<img>` 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<Entity, Router>,
ops: Vec<(Entity, u64, Vec<Op>)>,
gone: Vec<(Entity, u64)>,
refused: Vec<String>,
}
/// One layer: its RuneLayer entity, and the ops its tree takes at its next frame.
pub struct Slot {
pub entity: Entity,
ops: Rc<RefCell<Vec<Op>>>,
node: Option<blitz_dom::NodeId>,
}
/// The layers, by page and slot's wire id (a non-send resource).
#[derive(Default)]
pub struct Slots {
inbox: Rc<RefCell<Inbox>>,
pub layers: HashMap<(Entity, u64), Slot>,
/// what the layers' Rune pages queued for the JS, by page
outbox: Rc<RefCell<Vec<(Entity, String)>>>,
/// what couldn't be done as asked, each said once
pub report: Vec<String>,
/// 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::<RuneLayerPlugin>() {
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::<ElementImages>().init_resource::<input::Pending>().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<Inbox>, page: Entity, ops: Vec<Op>) -> Vec<Op> {
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::<Slots>();
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::<Slots>().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::<ElementImages>().0.remove(&(key.0, n));
}
}
}
for (page, slot, ops) in ops {
if !slots.layers.contains_key(&(page, slot)) {
let scale = world.get::<Page>(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::<Roots>().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::<Docs>().0.get(page)?.get_node(n).map(|n| content(n).1));
let scale = world.get::<Page>(*page).map_or(1.0, |p| p.scale);
if let Some(size) = size {
let mut trees = world.non_send_mut::<Trees>();
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::<RuneLayer>(slot.entity).map(|l| l.image.clone()) else { continue };
let mut shows = world.resource_mut::<ElementImages>();
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()))
}
+138
View File
@@ -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::<Docs>()
.init_resource::<PageClock>()
.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::<Slots>().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 <p>
let roots = w.non_send::<Roots>();
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::<Docs>();
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::<Trees>();
let tree = &trees.0[&e];
let p = tree.state().downcast_ref::<Page>().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::<RuneLayer>(e).unwrap().image;
assert_eq!(w.resource::<ElementImages>().0.get(&(page, nodes.by_id[&2])), Some(image));
assert!(w.non_send::<Slots>().report.iter().all(|r| !r.contains("moved")), "{:?}", w.non_send::<Slots>().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::<Trees>().0.get_mut(&e).unwrap().input(ev);
app.update();
}
for _ in 0..3 {
app.update();
}
let asks = &app.world().resource::<PageAsks>().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::<Roots>();
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::<Docs>();
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::<Trees>().0[&e].state().downcast_ref::<Page>().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");
}
+2 -2
View File
@@ -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 };
}
+3 -3
View File
@@ -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;
}
+22 -7
View File
@@ -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<String>) {
/// 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<dyn FnMut(Entity, Vec<wire::Op>) -> Vec<wire::Op>>;
thread_local!(static SPLIT: std::cell::RefCell<Option<Split>> = 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<String>) {
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<Str
/// `batches` committed to `doc`; a focus the commit moved (an autofocus) is told to the root (`queue`), as a focus
/// event its element hears.
pub(crate) fn commit_focus(doc: &mut BaseDocument, nodes: &mut Nodes, batches: Vec<String>, queue: Option<&mut Vec<Value>>) {
pub(crate) fn commit_focus(page: Entity, doc: &mut BaseDocument, nodes: &mut Nodes, batches: Vec<String>, queue: Option<&mut Vec<Value>>) {
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::<Docs>().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::<Roots>().as_mut().and_then(|r| r.get_mut(page)) {
r.queue.push(wire::named(name, value));
r.queue.push(msg);
}
}
+1
View File
@@ -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). */
+17
View File
@@ -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<HTMLDivElement>): ReactElement {
return (
<div {...props} {...RUNE_LAYER}>
{children}
</div>
);
}
+5
View File
@@ -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: `<RuneLayer className="w-80 h-48">...</RuneLayer>` 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" }`,
+2
View File
@@ -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"
+4
View File
@@ -29,6 +29,10 @@ upstream_dir() {
local name=$1 up=$2 ver dir reg
case $up in
crates.io:*) ver=${up#crates.io:} ;;
# git:<repo>@<rev>:<dir>, 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
+16
View File
@@ -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"] }
+378
View File
@@ -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<NodeContext>` 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<NodeId>` allocations.
pub fn baseline_storage_stats<NodeContext>(
tree: &taffy::TaffyTree<NodeContext>,
root: Option<NodeId>,
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::<Style>()
+ core::mem::size_of::<taffy::Cache>()
+ 2 * core::mem::size_of::<Layout>()
+ core::mem::size_of::<Vec<NodeId>>()
+ core::mem::size_of::<DetailedLayoutInfo>()
+ 16;
let children_slot_bytes = core::mem::size_of::<Vec<NodeId>>() + 8;
let parents_slot_bytes = core::mem::size_of::<Option<NodeId>>() + 8;
let context_slot_bytes = core::mem::size_of::<NodeContext>() + 16;
let bytes_per_slot = node_data_bytes + children_slot_bytes + parents_slot_bytes + context_slot_bytes;
let inline_buffer_bytes = slot_cap * bytes_per_slot;
let mut child_heap_bytes = 0usize;
if let Some(root_id) = root {
let mut stack = vec![root_id];
while let Some(id) = stack.pop() {
let count = tree.child_count(id);
if count > 0 {
let cap = count.max(4).next_power_of_two();
child_heap_bytes += cap * core::mem::size_of::<NodeId>();
for i in 0..count {
stack.push(tree.get_child_id(id, i));
}
}
}
}
StorageStats {
live_nodes,
slot_capacity: slot_cap,
sparse_capacity: slot_cap,
bytes_per_slot,
inline_buffer_bytes,
child_heap_bytes,
cold_style_bytes: 0,
cold_cache_bytes: 0,
cold_aux_bytes: 0,
total_retained_bytes: inline_buffer_bytes + child_heap_bytes,
}
}
#[derive(Debug, Clone)]
struct BaselineSlot {
taffy_id: NodeId,
style: CompactStyle,
measure: Option<u64>,
node_idx: u32,
used: bool,
mutated: bool,
}
/// Drop-in `LayoutStore` equivalent backed by upstream `taffy::TaffyTree<usize>`.
#[derive(Debug, Clone)]
pub struct BaselineLayoutStore {
tree: BaselineTaffyTree<usize>,
slots: Vec<Option<BaselineSlot>>,
by_key: HashMap<u64, u32>,
free: Vec<u32>,
child_scratch: Vec<u32>,
last_root: Option<NodeId>,
peak_nodes: usize,
}
impl Default for BaselineLayoutStore {
fn default() -> Self {
Self::new()
}
}
impl BaselineLayoutStore {
#[must_use]
pub fn new() -> Self {
Self::with_capacity(32)
}
#[must_use]
pub fn with_capacity(capacity: usize) -> Self {
let mut tree = BaselineTaffyTree::with_capacity(capacity);
tree.disable_rounding();
Self {
tree,
slots: Vec::with_capacity(capacity),
by_key: HashMap::with_capacity(capacity),
free: Vec::new(),
child_scratch: Vec::with_capacity(64),
last_root: None,
peak_nodes: 0,
}
}
#[inline]
pub fn live_count(&self) -> usize {
self.by_key.len()
}
pub fn begin_commit(&mut self) {
self.child_scratch.clear();
for s in self.slots.iter_mut().flatten() {
s.used = false;
}
}
#[inline(always)]
pub fn begin_children(&self) -> usize {
self.child_scratch.len()
}
#[inline(always)]
pub fn push_child(&mut self, child: SlotId) {
self.child_scratch.push(child.0);
}
#[inline]
pub fn can_reuse(&self, key: u64, slot: SlotId) -> bool {
self.by_key.get(&key) == Some(&slot.0)
&& self
.slots
.get(slot.0 as usize)
.and_then(Option::as_ref)
.is_some_and(|e| !e.used && !e.mutated)
}
#[inline]
pub fn is_used_this_commit(&self, key: u64) -> bool {
self.by_key.get(&key).is_some_and(|&s| {
self.slots
.get(s as usize)
.and_then(Option::as_ref)
.is_some_and(|e| e.used)
})
}
#[inline]
pub fn reuse_slot(&mut self, slot: SlotId, node_idx: u32) {
let entry = self.slots[slot.0 as usize].as_mut().unwrap();
entry.used = true;
entry.node_idx = node_idx;
if entry.measure.is_some() {
*self.tree.get_node_context_mut(entry.taffy_id).unwrap() = node_idx as usize;
}
}
pub fn rekey_and_reuse_batch(
&mut self,
items: impl ExactSizeIterator<Item = (u64, u64, SlotId, u32)> + Clone,
) {
let mut first = true;
for (old_key, _, slot, _) in items.clone() {
if first {
first = false;
let tid = self.slots[slot.0 as usize].as_ref().unwrap().taffy_id;
if let Some(old_p) = self.tree.parent(tid) {
drop(self.tree.remove_child(old_p, tid));
}
}
let removed = self.by_key.remove(&old_key);
debug_assert_eq!(removed, Some(slot.0));
}
for (_, new_key, slot, node_idx) in items {
if let Some(stale) = self.by_key.remove(&new_key) {
if let Some(old) = self.slots[stale as usize].take() {
drop(self.tree.set_children(old.taffy_id, &[]));
self.tree.remove(old.taffy_id).unwrap();
}
self.free.push(stale);
}
self.by_key.insert(new_key, slot.0);
self.reuse_slot(slot, node_idx);
}
}
#[allow(clippy::too_many_arguments)]
pub fn sync_node(
&mut self,
key: u64,
node_idx: u32,
style: CompactStyle,
measure: Option<u64>,
force_measure_dirty: bool,
child_mark: usize,
_children_dirty: bool,
) -> (SlotId, bool) {
let kids: Vec<NodeId> = self.child_scratch[child_mark..]
.iter()
.map(|&s| self.slots[s as usize].as_ref().unwrap().taffy_id)
.collect();
self.child_scratch.truncate(child_mark);
let me = node_idx as usize;
let measured = measure.is_some();
if let Some(&s) = self.by_key.get(&key) {
let slot = self.slots[s as usize].as_mut().unwrap();
let id = slot.taffy_id;
let mut dirty = false;
if slot.style != style {
self.tree.set_style(id, style.to_style()).unwrap();
slot.style = style;
dirty = true;
}
if !self.tree.child_ids(id).eq(kids.iter().copied()) {
self.tree.set_children(id, &kids).unwrap();
dirty = true;
}
if slot.measure.is_some() != measured {
self.tree.set_node_context(id, measured.then_some(me)).unwrap();
dirty = true;
} else if measured {
*self.tree.get_node_context_mut(id).unwrap() = me;
}
if force_measure_dirty || slot.measure != measure {
self.tree.mark_dirty(id).unwrap();
dirty = true;
}
if dirty {
slot.mutated = true;
}
slot.measure = measure;
slot.node_idx = node_idx;
slot.used = true;
(SlotId(s), dirty)
} else {
let full = style.to_style();
let id = if !kids.is_empty() {
self.tree.new_with_children(full, &kids).unwrap()
} else if measured {
self.tree.new_leaf_with_context(full, me).unwrap()
} else {
self.tree.new_leaf(full).unwrap()
};
if measured && self.tree.get_node_context(id).is_none() {
self.tree.set_node_context(id, Some(me)).unwrap();
}
let entry = BaselineSlot {
taffy_id: id,
style,
measure,
node_idx,
used: true,
mutated: true,
};
let s = if let Some(free_s) = self.free.pop() {
self.slots[free_s as usize] = Some(entry);
free_s
} else {
let s = self.slots.len() as u32;
self.slots.push(Some(entry));
s
};
self.by_key.insert(key, s);
(SlotId(s), true)
}
}
pub fn finish_flatten(&mut self) {
self.peak_nodes = self.peak_nodes.max(self.by_key.len());
let Self {
tree,
slots,
by_key,
free,
..
} = self;
by_key.retain(|_, &mut s| {
let keep = slots[s as usize].as_ref().is_some_and(|e| e.used);
if !keep {
if let Some(old) = slots[s as usize].take() {
tree.remove(old.taffy_id).unwrap();
}
free.push(s);
}
keep
});
self.peak_nodes = self.peak_nodes.max(self.by_key.len());
}
pub fn compact_if_sparse(&mut self, _remap: impl FnMut(u32, SlotId)) {
for s in self.slots.iter_mut().flatten() {
s.mutated = false;
}
}
pub fn end_commit(&mut self, _root: &mut SlotId, _remap: impl FnMut(u32, SlotId)) {
self.finish_flatten();
for s in self.slots.iter_mut().flatten() {
s.mutated = false;
}
}
#[inline]
pub fn style(&self, id: SlotId) -> &CompactStyle {
&self.slots[id.0 as usize].as_ref().unwrap().style
}
#[inline]
pub fn box_layout(&self, id: SlotId) -> BoxLayout {
let tid = self.slots[id.0 as usize].as_ref().unwrap().taffy_id;
BoxLayout::from_taffy(self.tree.layout(tid).unwrap())
}
#[inline]
pub fn mounted_node_index(&self, key: u64) -> Option<usize> {
let &s = self.by_key.get(&key)?;
let slot = self.slots.get(s as usize)?.as_ref()?;
slot.used.then_some(slot.node_idx as usize)
}
pub fn measure_hash(&self, key: u64) -> Option<Option<u64>> {
let &s = self.by_key.get(&key)?;
Some(self.slots[s as usize].as_ref()?.measure)
}
pub fn set_style_and_mark_ancestors(
&mut self,
id: SlotId,
style: CompactStyle,
_ancestors: impl IntoIterator<Item = SlotId>,
) {
let slot = self.slots[id.0 as usize].as_mut().unwrap();
self.tree.set_style(slot.taffy_id, style.to_style()).unwrap();
slot.style = style;
slot.mutated = true;
}
pub fn mark_dirty_and_ancestors(&mut self, id: SlotId, _ancestors: impl IntoIterator<Item = SlotId>) {
let tid = self.slots[id.0 as usize].as_ref().unwrap().taffy_id;
drop(self.tree.mark_dirty(tid));
}
pub fn mark_all_dirty(&mut self) {
for s in self.slots.iter().flatten() {
if s.measure.is_some() {
drop(self.tree.mark_dirty(s.taffy_id));
}
}
}
pub fn compute_layout<F>(&mut self, root: SlotId, available_space: Size<AvailableSpace>, mut measure_leaf: F)
where
F: FnMut(LayoutInput, Option<usize>, &CompactStyle) -> LayoutOutput,
{
let root_id = self.slots[root.0 as usize].as_ref().unwrap().taffy_id;
self.last_root = Some(root_id);
self.tree
.compute_layout_with_measure(root_id, available_space, |inputs, _id, ctx, style| {
let cs = CompactStyle::from_style(style.clone());
measure_leaf(inputs, ctx.copied(), &cs)
})
.unwrap();
}
pub fn storage_stats(&self) -> StorageStats {
baseline_storage_stats(&self.tree, self.last_root, self.peak_nodes.max(self.by_key.len()))
}
}
+503
View File
@@ -0,0 +1,503 @@
//! Compact layout cache (96 bytes inline vs 408 bytes in `taffy::Cache`) with the exact 9-slot
//! second-chance clock semantics of `taffy::Cache`.
//!
//! Stores the final-layout entry and the first two `ComputeSize` entries inline (since Flexbox
//! measures a child at most twice per pass), and lazily allocates slots 2..9 or cold final-layout
//! fields (`oof_candidates`, non-zero top/left overflow, `baselines.last`, collapsible margins)
//! only when needed.
use taffy::geometry::{Point, Rect, Size};
use taffy::style::AvailableSpace;
use taffy::tree::{
Baselines, ClearState, CollapsibleMarginSet, LayoutInput, LayoutOutput, OofCandidates, RequestedAxis, RunMode,
SizingMode,
};
const CACHE_SIZE: usize = 9;
const INLINE_MEASURES: usize = 2;
const OVERFLOW_MEASURES: usize = CACHE_SIZE - INLINE_MEASURES;
const MEASURE_MASK_BITS: u32 = (1 << CACHE_SIZE) - 1; // bits 0..9
const FINAL_VALID_BIT: u32 = 1 << 9; // bit 9
const VALID_BITS_MASK: u32 = MEASURE_MASK_BITS | FINAL_VALID_BIT; // bits 0..10
const RECENT_SHIFT: u32 = 10; // bits 10..19
const NEXT_SHIFT: u32 = 19; // bits 19..23 (0..9)
const MODE_SHIFT: u32 = 23; // bits 23..26 (0..8)
const M0_DEF_SHIFT: u32 = 26; // bits 26..28
const M1_DEF_SHIFT: u32 = 28; // bits 28..30
const FINAL_DEF_SHIFT: u32 = 30; // bits 30..32
const INFINITY_BITS: u32 = f32::INFINITY.to_bits();
const NEG_INFINITY_BITS: u32 = f32::NEG_INFINITY.to_bits();
const SIGN_BIT_1: u64 = 1u64 << 63;
const SIGN_BIT_2: u64 = 1u64 << 31;
const BOTH_SIGN_BITS_MASK: u64 = SIGN_BIT_1 | SIGN_BIT_2;
const NON_SIGN_BITS_MASK: u64 = !BOTH_SIGN_BITS_MASK;
const X_AXIS_VALUE_MASK: u64 = (u32::MAX as u64) << 32;
#[inline(always)]
fn option_cache_key(input: Option<f32>) -> u32 {
match input {
Some(value) => value.to_bits(),
None => INFINITY_BITS,
}
}
#[inline(always)]
fn size_option_cache_key(input: Size<Option<f32>>) -> u64 {
(option_cache_key(input.width) as u64) << 32 | option_cache_key(input.height) as u64
}
#[inline(always)]
fn available_space_cache_key(input: AvailableSpace) -> u32 {
match input {
AvailableSpace::Definite(value) => (-value).to_bits(),
AvailableSpace::MinContent => NEG_INFINITY_BITS,
AvailableSpace::MaxContent => INFINITY_BITS,
}
}
#[inline(always)]
fn mixed_cache_key(kd: Option<f32>, avs: AvailableSpace) -> u32 {
kd.map(f32::to_bits).unwrap_or_else(|| available_space_cache_key(avs))
}
#[inline(always)]
fn size_mixed_cache_key(kd: Size<Option<f32>>, avs: Size<AvailableSpace>) -> u64 {
(mixed_cache_key(kd.width, avs.width) as u64) << 32 | mixed_cache_key(kd.height, avs.height) as u64
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct CacheKey {
kd_available_space: u64,
parent_size: u64,
kd_def: u8,
}
impl CacheKey {
#[inline(always)]
fn from_input(input: &LayoutInput) -> Self {
let extra_bits = match input.axis {
RequestedAxis::Horizontal => SIGN_BIT_1,
RequestedAxis::Vertical => SIGN_BIT_2,
RequestedAxis::Both => SIGN_BIT_1 | SIGN_BIT_2,
};
let def_w = input.known_dimensions_are_definite.width || input.known_dimensions.width.is_none();
let def_h = input.known_dimensions_are_definite.height || input.known_dimensions.height.is_none();
Self {
kd_available_space: size_mixed_cache_key(input.known_dimensions, input.available_space),
parent_size: (size_option_cache_key(input.parent_size) & NON_SIGN_BITS_MASK) | extra_bits,
kd_def: (def_w as u8) | ((def_h as u8) << 1),
}
}
#[inline(always)]
fn x_axis_parent_size(parent_size: u64) -> u64 {
parent_size & (X_AXIS_VALUE_MASK & NON_SIGN_BITS_MASK)
}
#[inline(always)]
fn requested_axis_bits(parent_size: u64) -> u64 {
parent_size & BOTH_SIGN_BITS_MASK
}
#[inline(always)]
fn size_is_valid_for(entry_parent_size: u64, query_parent_size: u64) -> bool {
let entry_axis = Self::requested_axis_bits(entry_parent_size);
entry_axis == BOTH_SIGN_BITS_MASK || entry_axis == Self::requested_axis_bits(query_parent_size)
}
}
#[inline(always)]
fn cache_mode(input: &LayoutInput) -> u8 {
let inherent = matches!(input.sizing_mode, SizingMode::InherentSize) as u8;
let c = input.vertical_margins_are_collapsible;
inherent | ((c.start as u8) << 1) | ((c.end as u8) << 2)
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct CompactMeasureEntry {
kd_available_space: u64,
parent_size: u64,
size: Size<f32>,
}
impl CompactMeasureEntry {
const ZERO: Self = Self {
kd_available_space: 0,
parent_size: 0,
size: Size::ZERO,
};
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct CompactFinalEntry {
kd_available_space: u64,
parent_size: u64,
size: Size<f32>,
overflow_br: Size<f32>,
baseline_first: f32,
meta: u32,
}
impl CompactFinalEntry {
const ZERO: Self = Self {
kd_available_space: 0,
parent_size: 0,
size: Size::ZERO,
overflow_br: Size::ZERO,
baseline_first: f32::NAN,
meta: 0,
};
}
#[derive(Debug, Clone, PartialEq)]
struct ColdFinalOutput {
overflow_lt: Point<f32>,
baseline_last: Option<f32>,
top_margin: CollapsibleMarginSet,
bottom_margin: CollapsibleMarginSet,
margins_can_collapse_through: bool,
oof_candidates: OofCandidates,
}
#[derive(Debug, Clone, PartialEq)]
struct CacheOverflow {
measures: [CompactMeasureEntry; OVERFLOW_MEASURES],
/// 2-bit `kd_def` for overflow slots `2..9` (14 bits used).
kd_defs: u16,
cold_final: Option<ColdFinalOutput>,
}
impl Default for CacheOverflow {
fn default() -> Self {
Self {
measures: [CompactMeasureEntry::ZERO; OVERFLOW_MEASURES],
kd_defs: 0,
cold_final: None,
}
}
}
/// Compact per-node layout cache (96 bytes inline).
#[derive(Debug, Clone, PartialEq)]
pub struct CompactCache {
final_entry: CompactFinalEntry,
measures: [CompactMeasureEntry; INLINE_MEASURES],
overflow: Option<Box<CacheOverflow>>,
}
const _: () = assert!(core::mem::size_of::<CompactCache>() <= 96);
#[cfg(target_pointer_width = "64")]
const _: () = assert!(core::mem::size_of::<CompactCache>() == 96);
impl Default for CompactCache {
fn default() -> Self {
Self::new()
}
}
impl CompactCache {
pub const fn new() -> Self {
Self {
final_entry: CompactFinalEntry::ZERO,
measures: [CompactMeasureEntry::ZERO; INLINE_MEASURES],
overflow: None,
}
}
#[inline(always)]
fn kd_def(&self, slot: usize) -> u8 {
match slot {
0 => ((self.final_entry.meta >> M0_DEF_SHIFT) & 0b11) as u8,
1 => ((self.final_entry.meta >> M1_DEF_SHIFT) & 0b11) as u8,
CACHE_SIZE => ((self.final_entry.meta >> FINAL_DEF_SHIFT) & 0b11) as u8,
_ => self
.overflow
.as_ref()
.map_or(0, |ov| ((ov.kd_defs >> ((slot - INLINE_MEASURES) * 2)) & 0b11) as u8),
}
}
#[inline(always)]
fn set_kd_def(&mut self, slot: usize, kd_def: u8) {
let bits = (kd_def & 0b11) as u32;
match slot {
0 => self.final_entry.meta = (self.final_entry.meta & !(0b11 << M0_DEF_SHIFT)) | (bits << M0_DEF_SHIFT),
1 => self.final_entry.meta = (self.final_entry.meta & !(0b11 << M1_DEF_SHIFT)) | (bits << M1_DEF_SHIFT),
CACHE_SIZE => {
self.final_entry.meta = (self.final_entry.meta & !(0b11 << FINAL_DEF_SHIFT)) | (bits << FINAL_DEF_SHIFT);
}
_ => {
let shift = (slot - INLINE_MEASURES) * 2;
let ov = self.overflow.get_or_insert_with(Default::default);
ov.kd_defs = (ov.kd_defs & !(0b11 << shift)) | ((bits as u16) << shift);
}
}
}
#[inline(always)]
fn next_measure_entry(&self) -> u8 {
((self.final_entry.meta >> NEXT_SHIFT) & 0xF) as u8
}
#[inline(always)]
fn set_next_measure_entry(&mut self, next: u8) {
self.final_entry.meta =
(self.final_entry.meta & !(0xF << NEXT_SHIFT)) | (((next & 0xF) as u32) << NEXT_SHIFT);
}
#[inline(always)]
fn mode(&self) -> u8 {
((self.final_entry.meta >> MODE_SHIFT) & 0x7) as u8
}
#[inline(always)]
fn set_mode(&mut self, mode: u8) {
self.final_entry.meta =
(self.final_entry.meta & !(0x7 << MODE_SHIFT)) | (((mode & 0x7) as u32) << MODE_SHIFT);
}
#[inline(always)]
fn measure_slot(&self, index: usize) -> Option<&CompactMeasureEntry> {
if index < INLINE_MEASURES {
Some(&self.measures[index])
} else {
self.overflow.as_ref().map(|ov| &ov.measures[index - INLINE_MEASURES])
}
}
#[inline(always)]
fn measure_slot_mut(&mut self, index: usize) -> &mut CompactMeasureEntry {
if index < INLINE_MEASURES {
&mut self.measures[index]
} else {
&mut self.overflow.get_or_insert_with(Default::default).measures[index - INLINE_MEASURES]
}
}
#[inline]
pub fn get(&mut self, input: &LayoutInput) -> Option<LayoutOutput> {
let meta = self.final_entry.meta;
if (meta & VALID_BITS_MASK) == 0 || self.mode() != cache_mode(input) {
return None;
}
let key = CacheKey::from_input(input);
match input.run_mode {
RunMode::PerformLayout => {
if (meta & FINAL_VALID_BIT) == 0 {
return None;
}
if self.final_entry.kd_available_space != key.kd_available_space
|| self.final_entry.parent_size != key.parent_size
|| self.kd_def(CACHE_SIZE) != key.kd_def
{
return None;
}
let by0 = self.final_entry.baseline_first;
let cold = self.overflow.as_ref().and_then(|ov| ov.cold_final.as_ref());
let (lt, baseline_last) = match cold {
Some(c) => (c.overflow_lt, c.baseline_last),
None => (Point::ZERO, None),
};
let baselines = Baselines {
first: (!by0.is_nan()).then_some(by0),
last: baseline_last,
};
let rect = Rect {
left: lt.x,
top: lt.y,
right: self.final_entry.overflow_br.width,
bottom: self.final_entry.overflow_br.height,
};
let mut out = LayoutOutput::from_sizes_and_baselines(self.final_entry.size, rect, baselines);
if let Some(c) = cold {
out.top_margin = c.top_margin;
out.bottom_margin = c.bottom_margin;
out.margins_can_collapse_through = c.margins_can_collapse_through;
out.oof_candidates = c.oof_candidates.clone();
}
Some(out)
}
RunMode::ComputeSize => {
let measure_mask = meta & MEASURE_MASK_BITS;
if measure_mask == 0 {
return None;
}
if self.overflow.is_none() {
if (measure_mask & 1) != 0 {
let entry = &self.measures[0];
if entry.kd_available_space == key.kd_available_space
&& self.kd_def(0) == key.kd_def
&& CacheKey::x_axis_parent_size(entry.parent_size)
== CacheKey::x_axis_parent_size(key.parent_size)
&& CacheKey::size_is_valid_for(entry.parent_size, key.parent_size)
{
self.final_entry.meta |= 1 << RECENT_SHIFT;
return Some(LayoutOutput::from_outer_size(entry.size));
}
}
if (measure_mask & 2) != 0 {
let entry = &self.measures[1];
if entry.kd_available_space == key.kd_available_space
&& self.kd_def(1) == key.kd_def
&& CacheKey::x_axis_parent_size(entry.parent_size)
== CacheKey::x_axis_parent_size(key.parent_size)
&& CacheKey::size_is_valid_for(entry.parent_size, key.parent_size)
{
self.final_entry.meta |= 2 << RECENT_SHIFT;
return Some(LayoutOutput::from_outer_size(entry.size));
}
}
return None;
}
for index in 0..CACHE_SIZE {
if (measure_mask & (1 << index)) == 0 {
continue;
}
let Some(entry) = self.measure_slot(index) else { continue };
if entry.kd_available_space == key.kd_available_space
&& self.kd_def(index) == key.kd_def
&& CacheKey::x_axis_parent_size(entry.parent_size)
== CacheKey::x_axis_parent_size(key.parent_size)
&& CacheKey::size_is_valid_for(entry.parent_size, key.parent_size)
{
let size = entry.size;
self.final_entry.meta |= 1 << (RECENT_SHIFT + index as u32);
return Some(LayoutOutput::from_outer_size(size));
}
}
None
}
RunMode::PerformHiddenLayout => None,
}
}
pub fn store(&mut self, input: &LayoutInput, layout_output: LayoutOutput) {
if input.run_mode == RunMode::PerformHiddenLayout {
return;
}
let mode = cache_mode(input);
if self.mode() != mode {
self.clear();
self.set_mode(mode);
}
let key = CacheKey::from_input(input);
match input.run_mode {
RunMode::PerformLayout => {
self.final_entry.meta |= FINAL_VALID_BIT;
self.set_kd_def(CACHE_SIZE, key.kd_def);
let meta = self.final_entry.meta;
let r = layout_output.scrollable_overflow_rect;
self.final_entry = CompactFinalEntry {
kd_available_space: key.kd_available_space,
parent_size: key.parent_size,
size: layout_output.size,
overflow_br: Size {
width: r.right,
height: r.bottom,
},
baseline_first: layout_output.baselines.first.unwrap_or(f32::NAN),
meta,
};
let needs_cold = r.left != 0.0
|| r.top != 0.0
|| layout_output.baselines.last.is_some()
|| layout_output.margins_can_collapse_through
|| layout_output.top_margin != CollapsibleMarginSet::ZERO
|| layout_output.bottom_margin != CollapsibleMarginSet::ZERO
|| !layout_output.oof_candidates.is_empty();
if needs_cold {
self.overflow.get_or_insert_with(Default::default).cold_final = Some(ColdFinalOutput {
overflow_lt: Point { x: r.left, y: r.top },
baseline_last: layout_output.baselines.last,
top_margin: layout_output.top_margin,
bottom_margin: layout_output.bottom_margin,
margins_can_collapse_through: layout_output.margins_can_collapse_through,
oof_candidates: layout_output.oof_candidates,
});
} else if let Some(ov) = &mut self.overflow {
ov.cold_final = None;
}
}
RunMode::ComputeSize => {
if layout_output.margins_can_collapse_through
|| layout_output.top_margin != CollapsibleMarginSet::ZERO
|| layout_output.bottom_margin != CollapsibleMarginSet::ZERO
{
return;
}
let measure_mask = self.final_entry.meta & MEASURE_MASK_BITS;
if measure_mask != 0 {
let limit = if self.overflow.is_some() { CACHE_SIZE } else { INLINE_MEASURES };
for index in 0..limit {
if (measure_mask & (1 << index)) == 0 {
continue;
}
if let Some(entry) = self.measure_slot(index)
&& entry.kd_available_space == key.kd_available_space
&& entry.parent_size == key.parent_size
&& self.kd_def(index) == key.kd_def
{
self.measure_slot_mut(index).size = layout_output.size;
self.final_entry.meta |= 1 << (RECENT_SHIFT + index as u32);
return;
}
}
}
let mut next = self.next_measure_entry();
while (self.final_entry.meta & (1 << (RECENT_SHIFT + next as u32))) != 0 {
self.final_entry.meta &= !(1 << (RECENT_SHIFT + next as u32));
next += 1;
if next == CACHE_SIZE as u8 {
next = 0;
}
}
let entry_index = next as usize;
self.final_entry.meta |= (1 << entry_index) | (1 << (RECENT_SHIFT + entry_index as u32));
self.set_kd_def(entry_index, key.kd_def);
*self.measure_slot_mut(entry_index) = CompactMeasureEntry {
kd_available_space: key.kd_available_space,
parent_size: key.parent_size,
size: layout_output.size,
};
next += 1;
if next == CACHE_SIZE as u8 {
next = 0;
}
self.set_next_measure_entry(next);
}
RunMode::PerformHiddenLayout => {}
}
}
#[inline]
pub fn clear(&mut self) -> ClearState {
if (self.final_entry.meta & VALID_BITS_MASK) == 0 {
return ClearState::AlreadyEmpty;
}
// Keep `mode` bits intact (same as upstream `taffy::Cache::clear`), clear valid + recent + next + kd_def.
self.final_entry.meta &= 0x7 << MODE_SHIFT;
if let Some(ov) = &mut self.overflow {
ov.kd_defs = 0;
ov.cold_final = None;
}
ClearState::Cleared
}
#[inline(always)]
pub fn is_empty(&self) -> bool {
(self.final_entry.meta & VALID_BITS_MASK) == 0
}
pub fn heap_bytes(&self) -> usize {
self.overflow.as_ref().map_or(0, |ov| {
let oof_bytes = ov
.cold_final
.as_ref()
.map_or(0, |c| core::mem::size_of_val(c.oof_candidates.as_slice()));
core::mem::size_of::<CacheOverflow>() + oof_bytes
})
}
}
+32
View File
@@ -0,0 +1,32 @@
//! Compact retained layout store (`LayoutStore`) driving Taffy 0.15's solver directly.
//!
//! Keeps Taffy's Flexbox, CSS Grid, Block, out-of-flow positioning, and intrinsic sizing
//! algorithms while replacing `TaffyTree`'s `SlotMap`s, 552-byte inline `Style`, 408-byte
//! inline `Cache`, dual 92-byte `Layout`s, and per-node child `Vec`s with 216-byte dense
//! `RetainedSlot`s, 64-byte `CompactStyle`, 96-byte `CompactCache`, and flat child arenas.
mod baseline_store;
mod cache;
pub mod prelude;
mod store;
mod style;
#[cfg(test)]
mod tests;
mod view;
pub use baseline_store::BaselineLayoutStore;
pub use baseline_store::baseline_storage_stats;
pub use cache::CompactCache;
pub use store::BoxLayout;
pub use store::LayoutStore;
pub use store::SlotChildIter;
pub use store::SlotId;
pub use store::StorageStats;
pub use style::CompactStyle;
pub use taffy::TaffyTree as BaselineTaffyTree;
#[cfg(not(feature = "baseline-taffy"))]
pub type LayoutEngine = LayoutStore;
#[cfg(feature = "baseline-taffy")]
pub type LayoutEngine = BaselineLayoutStore;
+25
View File
@@ -0,0 +1,25 @@
//! Drop-in prelude matching `taffy::prelude`, re-exporting [`crate::LayoutEngine`] and compact types.
pub use crate::{BoxLayout, CompactStyle, LayoutEngine, SlotId};
pub use taffy::{
geometry::{Line, Rect, Size},
style::{
AlignContent, AlignContentKeyword, AlignItems, AlignItemsKeyword, AlignSelf, AlignmentSafety, AvailableSpace,
BoxSizing, CompactLength, Dimension, Display, FlexboxItemStyle, JustifyContent, JustifyItems, JustifySelf,
LengthPercentage, LengthPercentageAuto, Position, Style,
},
style_helpers::{
FromFr, FromLength, FromPercent, TaffyAuto, TaffyFitContent, TaffyMaxContent, TaffyMinContent, TaffyZero, auto,
fit_content, length, max_content, min_content, percent, zero,
},
tree::{Layout, LayoutPartialTree, NodeId, PrintTree, RoundTree, TraversePartialTree, TraverseTree},
};
pub use taffy::style::{FlexDirection, FlexWrap};
pub use taffy::style::{
GridAutoFlow, GridPlacement, GridTemplateComponent, MaxTrackSizingFunction, MinTrackSizingFunction,
RepetitionCount, TrackSizingFunction,
};
pub use taffy::style_helpers::{
TaffyGridLine, TaffyGridSpan, evenly_sized_tracks, flex, fr, line, minmax, repeat, span,
};
+628
View File
@@ -0,0 +1,628 @@
//! Retained no-second-tree layout store (`LayoutStore`) driving Taffy 0.15's solver directly.
//!
//! Instead of maintaining a general-purpose `TaffyTree` (`SlotMap`s / `SparseSet`, parent links,
//! per-node child `Vec`s, dual 92-byte `Layout`s, and `Option<NodeContext>`), `LayoutStore` holds:
//! - Dense 216-byte `RetainedSlot`s indexed directly by `SlotId(u32)` (`NodeId`).
//! - Double-buffered flat `Vec<u32>` child arenas (`prev_children` / `curr_children`) plus a
//! reusable DFS `child_scratch` stack so `flatten` allocates zero child `Vec`s.
//! - Single-pass post-order dirty propagation during `flatten`, with an `O(1)` warm unmount check
//! when the mounted key count is unchanged.
use std::collections::HashMap;
use std::hash::{BuildHasherDefault, Hasher};
use taffy::DetailedGridInfo;
use taffy::compute::compute_root_layout;
use taffy::geometry::Size;
use taffy::style::AvailableSpace;
use taffy::tree::{ClearState, DetailedLayoutInfo, Layout, LayoutInput, LayoutOutput, NodeId};
use crate::cache::CompactCache;
use crate::style::CompactStyle;
use crate::view::LayoutStoreView;
/// Memory breakdown for a layout store instance.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct StorageStats {
pub live_nodes: usize,
pub slot_capacity: usize,
pub sparse_capacity: usize,
pub bytes_per_slot: usize,
pub inline_buffer_bytes: usize,
pub child_heap_bytes: usize,
pub cold_style_bytes: usize,
pub cold_cache_bytes: usize,
pub cold_aux_bytes: usize,
pub total_retained_bytes: usize,
}
const UNMOUNTED: u32 = u32::MAX;
#[derive(Default)]
struct FxU64(u64);
impl Hasher for FxU64 {
#[inline(always)]
fn finish(&self) -> u64 {
self.0
}
#[inline(always)]
fn write(&mut self, bytes: &[u8]) {
let mut h = self.0;
for &b in bytes {
h = (h.rotate_left(5) ^ (b as u64)).wrapping_mul(0x517c_c1b7_2722_0a95);
}
self.0 = h;
}
#[inline(always)]
fn write_u64(&mut self, i: u64) {
self.0 = (self.0.rotate_left(5) ^ i).wrapping_mul(0x517c_c1b7_2722_0a95);
}
}
type KeyMap<V> = HashMap<u64, V, BuildHasherDefault<FxU64>>;
/// Direct index into [`LayoutStore`]'s dense slot array.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct SlotId(pub u32);
impl SlotId {
#[inline(always)]
pub const fn to_taffy(self) -> NodeId {
NodeId::new(self.0 as u64)
}
#[inline(always)]
pub fn from_taffy(id: NodeId) -> Self {
Self(u64::from(id) as u32)
}
}
/// Unrounded box geometry and combined `padding + border` insets (32 bytes vs 92 bytes for `taffy::Layout`).
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct BoxLayout {
pub x: f32,
pub y: f32,
pub w: f32,
pub h: f32,
/// `[left, top, right, bottom]` = `padding + border`.
pub inset: [f32; 4],
}
const _: () = assert!(core::mem::size_of::<BoxLayout>() == 32);
impl BoxLayout {
pub const ZERO: Self = Self {
x: 0.0,
y: 0.0,
w: 0.0,
h: 0.0,
inset: [0.0; 4],
};
#[inline(always)]
pub fn from_taffy(l: &Layout) -> Self {
Self {
x: l.location.x,
y: l.location.y,
w: l.size.width,
h: l.size.height,
inset: [
l.padding.left + l.border.left,
l.padding.top + l.border.top,
l.padding.right + l.border.right,
l.padding.bottom + l.border.bottom,
],
}
}
#[inline(always)]
pub const fn size(&self) -> Size<f32> {
Size {
width: self.w,
height: self.h,
}
}
}
const HAS_CTX_BIT: u32 = 1 << 31;
const MUTATED_BIT: u32 = 1 << 30;
const CHILD_LEN_MASK: u32 = !(HAS_CTX_BIT | MUTATED_BIT);
#[derive(Debug, Clone)]
pub(crate) struct RetainedSlot {
pub(crate) style: CompactStyle,
pub(crate) cache: CompactCache,
pub(crate) box_layout: BoxLayout,
pub(crate) measure: u64,
pub(crate) grid_info: Option<Box<DetailedLayoutInfo>>,
pub(crate) child_start: u32,
pub(crate) child_len_and_flags: u32,
}
const _: () = assert!(core::mem::size_of::<RetainedSlot>() <= 216);
#[cfg(target_pointer_width = "64")]
const _: () = assert!(core::mem::size_of::<RetainedSlot>() == 216);
impl RetainedSlot {
#[inline(always)]
fn empty() -> Self {
Self {
style: CompactStyle::default(),
cache: CompactCache::new(),
box_layout: BoxLayout::ZERO,
measure: 0,
grid_info: None,
child_start: 0,
child_len_and_flags: 0,
}
}
#[inline(always)]
pub(crate) fn child_len(&self) -> u32 {
self.child_len_and_flags & CHILD_LEN_MASK
}
#[inline(always)]
pub(crate) fn has_context(&self) -> bool {
(self.child_len_and_flags & HAS_CTX_BIT) != 0
}
#[inline(always)]
fn has_mutated(&self) -> bool {
(self.child_len_and_flags & MUTATED_BIT) != 0
}
}
/// Contiguous slice iterator over a node's child [`SlotId`]s for the current commit.
#[derive(Debug, Clone)]
pub struct SlotChildIter<'a>(pub(crate) core::slice::Iter<'a, u32>);
impl Iterator for SlotChildIter<'_> {
type Item = NodeId;
#[inline(always)]
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(|&s| NodeId::new(s as u64))
}
#[inline(always)]
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
impl ExactSizeIterator for SlotChildIter<'_> {
#[inline(always)]
fn len(&self) -> usize {
self.0.len()
}
}
/// Retained layout store integrated directly with Rune's commit pass.
#[derive(Debug, Clone, Default)]
pub struct LayoutStore {
pub(crate) slots: Vec<RetainedSlot>,
pub(crate) node_idx: Vec<u32>,
by_key: KeyMap<u32>,
free: Vec<u32>,
prev_children: Vec<u32>,
pub(crate) curr_children: Vec<u32>,
child_scratch: Vec<u32>,
mutated_slots: Vec<u32>,
prev_live: usize,
visited_existing: usize,
}
impl LayoutStore {
#[must_use]
pub fn new() -> Self {
Self::with_capacity(32)
}
#[must_use]
pub fn with_capacity(capacity: usize) -> Self {
Self {
slots: Vec::with_capacity(capacity),
node_idx: Vec::with_capacity(capacity),
by_key: KeyMap::with_capacity_and_hasher(capacity, Default::default()),
free: Vec::new(),
prev_children: Vec::with_capacity(capacity),
curr_children: Vec::with_capacity(capacity),
child_scratch: Vec::with_capacity(64),
mutated_slots: Vec::new(),
prev_live: 0,
visited_existing: 0,
}
}
#[inline]
pub fn live_count(&self) -> usize {
self.by_key.len()
}
/// Starts a new flatten pass, swapping the flat child arena without deallocating.
#[inline]
pub fn begin_commit(&mut self) {
core::mem::swap(&mut self.prev_children, &mut self.curr_children);
self.curr_children.clear();
self.child_scratch.clear();
self.node_idx.fill(UNMOUNTED);
self.prev_live = self.by_key.len();
self.visited_existing = 0;
}
#[inline(always)]
pub fn begin_children(&self) -> usize {
self.child_scratch.len()
}
#[inline(always)]
pub fn push_child(&mut self, child: SlotId) {
self.child_scratch.push(child.0);
}
/// Whether `key` still owns `slot` and has not been claimed or mutated earlier in this commit.
#[inline]
pub fn can_reuse(&self, key: u64, slot: SlotId) -> bool {
let idx = slot.0 as usize;
self.by_key.get(&key) == Some(&slot.0)
&& self.node_idx.get(idx).copied() == Some(UNMOUNTED)
&& self.slots.get(idx).is_some_and(|s| !s.has_mutated())
}
/// Whether `key` has already been claimed earlier in this commit.
#[inline]
pub fn is_used_this_commit(&self, key: u64) -> bool {
self.by_key
.get(&key)
.is_some_and(|&s| self.node_idx.get(s as usize).copied() != Some(UNMOUNTED))
}
/// Reuses an unchanged slot (`memo_reuse`) by copying its previous child slice into
/// `curr_children` and updating its `node_idx` without re-checking style or cache.
#[inline]
pub fn reuse_slot(&mut self, slot: SlotId, node_idx: u32) {
let idx = slot.0 as usize;
debug_assert!(idx < self.slots.len());
if self.node_idx[idx] == UNMOUNTED {
self.visited_existing += 1;
}
self.node_idx[idx] = node_idx;
let old_start = self.slots[idx].child_start as usize;
let len = self.slots[idx].child_len() as usize;
let new_start = self.curr_children.len() as u32;
if len > 0 {
self.curr_children
.extend_from_slice(&self.prev_children[old_start..old_start + len]);
}
self.slots[idx].child_start = new_start;
}
/// Rebases a slice of `(old_key, new_key, slot, node_idx)` entries when a memoized subtree
/// moves to a new parent path, preserving each slot's warm cache and children.
pub fn rekey_and_reuse_batch(
&mut self,
items: impl ExactSizeIterator<Item = (u64, u64, SlotId, u32)> + Clone,
) {
for (old_key, _, slot, _) in items.clone() {
let removed = self.by_key.remove(&old_key);
debug_assert_eq!(removed, Some(slot.0));
}
for (_, new_key, slot, node_idx) in items {
if let Some(stale) = self.by_key.remove(&new_key) {
self.slots[stale as usize] = RetainedSlot::empty();
self.free.push(stale);
self.prev_live = self.prev_live.saturating_sub(1);
}
self.by_key.insert(new_key, slot.0);
self.reuse_slot(slot, node_idx);
}
}
/// Reconciles one node in post-order after its children have pushed onto `child_scratch[child_mark..]`.
/// Returns `(slot_id, subtree_dirty)` and clears this slot's cache immediately if dirty.
#[inline]
#[allow(clippy::too_many_arguments)]
pub fn sync_node(
&mut self,
key: u64,
node_idx: u32,
style: CompactStyle,
measure: Option<u64>,
force_measure_dirty: bool,
child_mark: usize,
children_dirty: bool,
) -> (SlotId, bool) {
let new_kids = &self.child_scratch[child_mark..];
let child_start = self.curr_children.len() as u32;
let child_len = new_kids.len() as u32;
self.curr_children.extend_from_slice(new_kids);
if let Some(&s) = self.by_key.get(&key) {
let idx = s as usize;
debug_assert!(idx < self.slots.len());
// SAFETY: every slot value stored in `by_key` is a valid index into `node_idx` and `slots`.
let prev_idx = unsafe { self.node_idx.get_unchecked_mut(idx) };
let first_visit = *prev_idx == UNMOUNTED;
if first_visit {
self.visited_existing += 1;
}
*prev_idx = node_idx;
// SAFETY: `idx < self.slots.len()` holds for all entries in `by_key`.
let slot = unsafe { self.slots.get_unchecked_mut(idx) };
let old_start = slot.child_start as usize;
let old_end = old_start + slot.child_len() as usize;
let kids_changed = if first_visit {
&self.prev_children[old_start..old_end] != new_kids
} else {
self.curr_children[old_start..old_end] != self.curr_children[child_start as usize..]
};
let style_changed = slot.style != style;
if style_changed {
slot.style = style;
}
slot.child_start = child_start;
let had_measure = slot.has_context();
let has_measure = measure.is_some();
let new_m = measure.unwrap_or(0);
let measure_changed =
had_measure != has_measure || (has_measure && (force_measure_dirty || slot.measure != new_m));
let was_mutated = slot.has_mutated();
let now_mutated = was_mutated || style_changed || kids_changed || measure_changed;
slot.child_len_and_flags = child_len
| if has_measure { HAS_CTX_BIT } else { 0 }
| if now_mutated { MUTATED_BIT } else { 0 };
slot.measure = new_m;
let dirty = style_changed || kids_changed || measure_changed || children_dirty;
if dirty {
slot.cache.clear();
}
if now_mutated && !was_mutated {
self.mutated_slots.push(s);
}
self.child_scratch.truncate(child_mark);
(SlotId(s), dirty)
} else {
self.child_scratch.truncate(child_mark);
let new_slot = RetainedSlot {
style,
cache: CompactCache::new(),
box_layout: BoxLayout::ZERO,
measure: measure.unwrap_or(0),
grid_info: None,
child_start,
child_len_and_flags: child_len
| if measure.is_some() { HAS_CTX_BIT } else { 0 }
| MUTATED_BIT,
};
let s = if let Some(free_s) = self.free.pop() {
let idx = free_s as usize;
self.slots[idx] = new_slot;
self.node_idx[idx] = node_idx;
free_s
} else {
let s = self.slots.len() as u32;
self.slots.push(new_slot);
self.node_idx.push(node_idx);
s
};
self.mutated_slots.push(s);
self.by_key.insert(key, s);
(SlotId(s), true)
}
}
/// Frees any slots not visited during `flatten` without renumbering kept `SlotId`s, so
/// measurement retries still see stable `SlotId`s on `old_nodes`.
#[inline]
pub fn finish_flatten(&mut self) {
if self.visited_existing == self.prev_live {
return;
}
let Self {
slots,
node_idx,
by_key,
free,
..
} = self;
by_key.retain(|_, &mut s| {
let idx = s as usize;
if node_idx[idx] == UNMOUNTED {
slots[idx] = RetainedSlot::empty();
free.push(s);
false
} else {
true
}
});
}
/// Shrinks storage when live occupancy drops below 25% of capacity.
#[inline]
pub fn compact_if_sparse(&mut self, remap: impl FnMut(u32, SlotId)) {
let mut dummy = SlotId(UNMOUNTED);
self.compact_with_root(&mut dummy, remap);
}
fn compact_with_root(&mut self, root: &mut SlotId, mut remap: impl FnMut(u32, SlotId)) {
for idx in self.mutated_slots.drain(..) {
if let Some(s) = self.slots.get_mut(idx as usize) {
s.child_len_and_flags &= !MUTATED_BIT;
}
}
let live = self.by_key.len();
if self.slots.capacity() <= 64 || live.saturating_mul(4) > self.slots.capacity() {
return;
}
let Self {
slots,
node_idx,
by_key,
free,
curr_children,
prev_children,
child_scratch,
..
} = self;
let cap = (live * 2).max(32);
let mut remap_table = vec![UNMOUNTED; slots.len()];
let mut new_slots = Vec::with_capacity(cap);
let mut new_node_idx = Vec::with_capacity(cap);
for s_mut in by_key.values_mut() {
let old_s = *s_mut as usize;
let new_s = new_slots.len() as u32;
remap_table[old_s] = new_s;
let mut slot = core::mem::replace(&mut slots[old_s], RetainedSlot::empty());
slot.cache.clear();
let me = node_idx[old_s];
remap(me, SlotId(new_s));
*s_mut = new_s;
new_slots.push(slot);
new_node_idx.push(me);
}
if let Some(&new_root) = remap_table.get(root.0 as usize)
&& new_root != UNMOUNTED
{
root.0 = new_root;
}
for c in curr_children.iter_mut() {
*c = remap_table[*c as usize];
}
*slots = new_slots;
*node_idx = new_node_idx;
*free = Vec::new();
by_key.shrink_to(cap);
curr_children.shrink_to(cap);
*prev_children = Vec::with_capacity(cap);
child_scratch.shrink_to(64);
}
/// Finishes a flatten pass, recycling unvisited slots and compacting when sparse.
#[inline]
pub fn end_commit(&mut self, root: &mut SlotId, remap: impl FnMut(u32, SlotId)) {
if self.visited_existing != self.prev_live {
self.finish_flatten();
}
self.compact_with_root(root, remap);
}
#[inline(always)]
pub fn style(&self, id: SlotId) -> &CompactStyle {
debug_assert!((id.0 as usize) < self.slots.len());
// SAFETY: `id` is a live `SlotId` index into `slots`.
unsafe { &self.slots.get_unchecked(id.0 as usize).style }
}
#[inline(always)]
pub fn box_layout(&self, id: SlotId) -> BoxLayout {
debug_assert!((id.0 as usize) < self.slots.len());
// SAFETY: `id` is a live `SlotId` index into `slots`.
unsafe { self.slots.get_unchecked(id.0 as usize).box_layout }
}
/// Returns the index in the current commit's `nodes` slice for `key`, if mounted this commit.
#[inline]
pub fn mounted_node_index(&self, key: u64) -> Option<usize> {
let &s = self.by_key.get(&key)?;
let idx = *self.node_idx.get(s as usize)?;
(idx != UNMOUNTED).then_some(idx as usize)
}
pub fn measure_hash(&self, key: u64) -> Option<Option<u64>> {
let &s = self.by_key.get(&key)?;
let slot = &self.slots[s as usize];
Some(slot.has_context().then_some(slot.measure))
}
/// Updates `id`'s style (for intra-commit two-pass refits like `aspect_fit` and `anchored_fit`)
/// and clears `id`'s and its ancestors' layout caches.
#[inline]
pub fn set_style_and_mark_ancestors(
&mut self,
id: SlotId,
style: CompactStyle,
ancestors: impl IntoIterator<Item = SlotId>,
) {
let slot = &mut self.slots[id.0 as usize];
if !slot.has_mutated() {
slot.child_len_and_flags |= MUTATED_BIT;
self.mutated_slots.push(id.0);
}
slot.style = style;
slot.cache.clear();
for anc in ancestors {
if matches!(self.slots[anc.0 as usize].cache.clear(), ClearState::AlreadyEmpty) {
break;
}
}
}
/// Clears `id`'s and its ancestors' layout caches without modifying style.
#[inline]
pub fn mark_dirty_and_ancestors(&mut self, id: SlotId, ancestors: impl IntoIterator<Item = SlotId>) {
self.slots[id.0 as usize].cache.clear();
for anc in ancestors {
if matches!(self.slots[anc.0 as usize].cache.clear(), ClearState::AlreadyEmpty) {
break;
}
}
}
/// Clears every live slot's layout cache (e.g. when switching font families).
pub fn mark_all_dirty(&mut self) {
for &s in self.by_key.values() {
self.slots[s as usize].cache.clear();
}
}
pub fn compute_layout<F>(&mut self, root: SlotId, available_space: Size<AvailableSpace>, measure_leaf: F)
where
F: FnMut(LayoutInput, Option<usize>, &CompactStyle) -> LayoutOutput,
{
let mut view = LayoutStoreView {
store: self,
measure_leaf,
};
compute_root_layout(&mut view, root.to_taffy(), available_space);
}
pub fn storage_stats(&self) -> StorageStats {
let slot_capacity = self.slots.capacity();
let bytes_per_slot = core::mem::size_of::<RetainedSlot>() + core::mem::size_of::<u32>();
let inline_buffer_bytes = slot_capacity * bytes_per_slot
+ (self.prev_children.capacity() + self.curr_children.capacity() + self.child_scratch.capacity())
* core::mem::size_of::<u32>()
+ self.free.capacity() * core::mem::size_of::<u32>();
let mut cold_style_bytes = 0usize;
let mut cold_cache_bytes = 0usize;
let mut cold_aux_bytes = 0usize;
for &s in self.by_key.values() {
let slot = &self.slots[s as usize];
cold_style_bytes += slot.style.heap_bytes();
cold_cache_bytes += slot.cache.heap_bytes();
if slot.grid_info.is_some() {
cold_aux_bytes += core::mem::size_of::<DetailedLayoutInfo>() + core::mem::size_of::<DetailedGridInfo>();
}
}
StorageStats {
live_nodes: self.by_key.len(),
slot_capacity,
sparse_capacity: self.by_key.capacity(),
bytes_per_slot,
inline_buffer_bytes,
child_heap_bytes: 0,
cold_style_bytes,
cold_cache_bytes,
cold_aux_bytes,
total_retained_bytes: inline_buffer_bytes + cold_style_bytes + cold_cache_bytes + cold_aux_bytes,
}
}
}
+255
View File
@@ -0,0 +1,255 @@
//! Conversions and equality between [`CompactStyle`] and [`taffy::Style`].
use super::*;
impl CompactStyle {
pub fn from_style(s: Style) -> Self {
let mut vals = [0u32; HOT_VAL_COUNT];
let mut len_tags: u16 = 0;
let mut needs_extra = has_cold_fields(&s);
let dims = [
s.size.width.into_raw(),
s.size.height.into_raw(),
s.min_size.width.into_raw(),
s.min_size.height.into_raw(),
s.max_size.width.into_raw(),
s.max_size.height.into_raw(),
];
for (i, raw) in dims.into_iter().enumerate() {
let (v, t) = pack_raw_len(raw);
vals[i] = v;
if let Some(code) = encode_dim_tag(t) {
len_tags |= code << (i * 2);
} else {
needs_extra = true;
}
}
let pads = [
s.padding.left.into_raw(),
s.padding.right.into_raw(),
s.padding.top.into_raw(),
s.padding.bottom.into_raw(),
];
for (i, raw) in pads.into_iter().enumerate() {
let (v, t) = pack_raw_len(raw);
vals[IDX_PAD_L + i] = v;
if t as usize == CompactLength::PERCENT_TAG {
len_tags |= 1 << (12 + i);
} else if t as usize != CompactLength::LENGTH_TAG {
needs_extra = true;
}
}
let (gw_bits, gw_tag) = pack_raw_len(s.gap.width.into_raw());
let (gh_bits, gh_tag) = pack_raw_len(s.gap.height.into_raw());
let gap_w_bf16 = if (gw_bits & 0xFFFF) == 0 {
(gw_bits >> 16) as u16
} else {
needs_extra = true;
0
};
let gap_h_bf16 = if (gh_bits & 0xFFFF) == 0 {
(gh_bits >> 16) as u16
} else {
needs_extra = true;
0
};
let flex_grow_bf16 = match pack_bf16_exact(s.flex_grow) {
Some(b) => b,
None => {
needs_extra = true;
0
}
};
let flex_shrink_bf16 = match pack_bf16_exact(s.flex_shrink) {
Some(b) => b,
None => {
needs_extra = true;
0
}
};
let (basis_bits, basis_tag) = pack_raw_len(s.flex_basis.into_raw());
let pos_code = match encode_position(s.position) {
Some(c) => c,
None => {
needs_extra = true;
0b11
}
};
let mut mode_flags = encode_display(s.display) | (pos_code << MODE_POS_SHIFT);
if gw_tag as usize == CompactLength::PERCENT_TAG {
mode_flags |= MODE_GAP_W_PCT;
} else if gw_tag as usize != CompactLength::LENGTH_TAG {
needs_extra = true;
}
if gh_tag as usize == CompactLength::PERCENT_TAG {
mode_flags |= MODE_GAP_H_PCT;
} else if gh_tag as usize != CompactLength::LENGTH_TAG {
needs_extra = true;
}
if basis_tag as usize == CompactLength::LENGTH_TAG && basis_bits == 0 {
mode_flags |= MODE_BASIS_ZERO;
} else if basis_tag as usize != CompactLength::AUTO_TAG {
needs_extra = true;
}
let box_flags = pack_box_flags(s.flex_direction, s.flex_wrap, s.overflow.x, s.overflow.y);
let align_items_u8 = pack_align_items(s.align_items);
let align_self_u8 = pack_align_self(s.align_self);
let justify_content_u8 = pack_align_content(s.justify_content);
let align_content_u8 = pack_align_content(s.align_content);
let extra = needs_extra.then(|| Box::new(s));
Self {
vals,
gap_w_bf16,
gap_h_bf16,
flex_grow_bf16,
flex_shrink_bf16,
len_tags,
box_flags,
mode_flags,
align_items_u8,
align_self_u8,
justify_content_u8,
align_content_u8,
extra,
}
}
pub fn to_style(&self) -> Style {
if let Some(extra) = &self.extra {
return (**extra).clone();
}
Style {
display: self.display(),
position: self.position(),
overflow: CoreStyle::overflow(self),
size: CoreStyle::size(self),
min_size: CoreStyle::min_size(self),
max_size: CoreStyle::max_size(self),
aspect_ratio: None,
padding: CoreStyle::padding(self),
gap: FlexboxContainerStyle::gap(self),
align_items: unpack_align_items(self.align_items_u8),
align_self: unpack_align_self(self.align_self_u8),
justify_content: unpack_align_content(self.justify_content_u8),
align_content: unpack_align_content(self.align_content_u8),
flex_direction: FlexboxContainerStyle::flex_direction(self),
flex_wrap: FlexboxContainerStyle::flex_wrap(self),
flex_grow: FlexboxItemStyle::flex_grow(self),
flex_shrink: FlexboxItemStyle::flex_shrink(self),
flex_basis: FlexboxItemStyle::flex_basis(self),
..Style::DEFAULT
}
}
pub fn heap_bytes(&self) -> usize {
self.extra.as_ref().map_or(0, |s| {
type Ident = <Style as CoreStyle>::CustomIdent;
core::mem::size_of::<Style>()
+ s.grid_template_rows.capacity() * core::mem::size_of::<taffy::GridTemplateComponent<Ident>>()
+ s.grid_template_columns.capacity() * core::mem::size_of::<taffy::GridTemplateComponent<Ident>>()
})
}
#[inline(always)]
pub fn eq_style(&self, other: &Style) -> bool {
if let Some(extra) = &self.extra {
return &**extra == other;
}
self.display() == other.display
&& self.position() == other.position
&& self.box_flags == pack_box_flags(other.flex_direction, other.flex_wrap, other.overflow.x, other.overflow.y)
&& self.align_items_u8 == pack_align_items(other.align_items)
&& self.align_self_u8 == pack_align_self(other.align_self)
&& self.justify_content_u8 == pack_align_content(other.justify_content)
&& self.align_content_u8 == pack_align_content(other.align_content)
&& FlexboxItemStyle::flex_grow(self) == other.flex_grow
&& FlexboxItemStyle::flex_shrink(self) == other.flex_shrink
&& other.aspect_ratio.is_none()
&& CoreStyle::size(self) == other.size
&& CoreStyle::min_size(self) == other.min_size
&& CoreStyle::max_size(self) == other.max_size
&& CoreStyle::padding(self) == other.padding
&& FlexboxContainerStyle::gap(self) == other.gap
&& FlexboxItemStyle::flex_basis(self) == other.flex_basis
&& !has_cold_fields(other)
}
}
impl From<Style> for CompactStyle {
#[inline]
fn from(s: Style) -> Self {
Self::from_style(s)
}
}
impl From<&Style> for CompactStyle {
#[inline]
fn from(s: &Style) -> Self {
Self::from_style(s.clone())
}
}
impl From<CompactStyle> for Style {
#[inline]
fn from(s: CompactStyle) -> Self {
match s.extra {
Some(extra) => *extra,
None => s.to_style(),
}
}
}
impl From<&CompactStyle> for Style {
#[inline]
fn from(s: &CompactStyle) -> Self {
s.to_style()
}
}
impl PartialEq for CompactStyle {
#[inline(always)]
fn eq(&self, other: &Self) -> bool {
if self.extra.is_none() && other.extra.is_none() {
return self.vals == other.vals
&& self.gap_w_bf16 == other.gap_w_bf16
&& self.gap_h_bf16 == other.gap_h_bf16
&& self.flex_grow_bf16 == other.flex_grow_bf16
&& self.flex_shrink_bf16 == other.flex_shrink_bf16
&& self.len_tags == other.len_tags
&& self.box_flags == other.box_flags
&& self.mode_flags == other.mode_flags
&& self.align_items_u8 == other.align_items_u8
&& self.align_self_u8 == other.align_self_u8
&& self.justify_content_u8 == other.justify_content_u8
&& self.align_content_u8 == other.align_content_u8;
}
self.eq_cold(other)
}
}
impl CompactStyle {
#[cold]
#[inline(never)]
fn eq_cold(&self, other: &Self) -> bool {
match (&self.extra, &other.extra) {
(Some(a), Some(b)) => a == b,
(Some(a), None) => other.eq_style(a),
(None, Some(b)) => self.eq_style(b),
(None, None) => unreachable!(),
}
}
}
impl PartialEq<Style> for CompactStyle {
#[inline(always)]
fn eq(&self, other: &Style) -> bool {
self.eq_style(other)
}
}
+624
View File
@@ -0,0 +1,624 @@
//! Compact node style representation (64 bytes inline — one CPU cache line — vs 552 bytes for `taffy::Style`).
//!
//! Stores the hot Flexbox/Block/Core properties inline in 56 bytes plus an 8-byte `Option<Box<Style>>`
//! for cold CSS properties (Grid tracks/placement, non-zero margin/border/inset, `aspect_ratio`,
//! or exotic sizing keywords).
use taffy::geometry::{Line, Point, Rect, Size};
use taffy::style::{
AlignContent, AlignContentKeyword, AlignItems, AlignItemsKeyword, AlignSelf, AlignmentSafety, BlockContainerStyle,
BlockItemStyle, BoxGenerationMode, BoxSizing, CompactLength, Contain, CoreStyle, Dimension, Direction, Display,
FlexDirection, FlexWrap, FlexboxContainerStyle, FlexboxItemStyle, GridAutoFlow, GridContainerStyle, GridItemStyle,
GridPlacement, JustifyContent, LengthPercentage, LengthPercentageAuto, OofItemStyle, Overflow, Position, Style,
TextAlign,
};
use taffy::style_helpers::{TaffyAuto, TaffyZero, fr, line, span};
const IDX_SIZE_W: usize = 0;
const IDX_SIZE_H: usize = 1;
const IDX_MIN_W: usize = 2;
const IDX_MIN_H: usize = 3;
const IDX_MAX_W: usize = 4;
const IDX_MAX_H: usize = 5;
const IDX_PAD_L: usize = 6;
const IDX_PAD_R: usize = 7;
const IDX_PAD_T: usize = 8;
const IDX_PAD_B: usize = 9;
const HOT_VAL_COUNT: usize = 10;
const MODE_DISPLAY_MASK: u8 = 0b0000_0111;
const MODE_POS_SHIFT: u8 = 3;
const MODE_POS_MASK: u8 = 0b0001_1000;
const MODE_GAP_W_PCT: u8 = 1 << 5;
const MODE_GAP_H_PCT: u8 = 1 << 6;
const MODE_BASIS_ZERO: u8 = 1 << 7;
const BASE_LEN_TAGS: u16 = 0b0000_1010_1010_1010;
const ONE_BF16: u16 = 0x3F80;
#[inline(always)]
fn pack_raw_len(len: CompactLength) -> (u32, u8) {
#[cfg(target_pointer_width = "64")]
{
// SAFETY: on 64-bit targets `CompactLength` is a single pointer-sized word (`usize`).
let raw: usize = unsafe { core::mem::transmute(len) };
((raw >> 32) as u32, (raw & 0xFF) as u8)
}
#[cfg(not(target_pointer_width = "64"))]
{
let tag = len.tag() as u8;
let bits = if (tag as usize & CompactLength::KEYWORD_BIT) == 0
|| matches!(
tag as usize,
CompactLength::FR_TAG | CompactLength::FIT_CONTENT_PX_TAG | CompactLength::FIT_CONTENT_PERCENT_TAG
) {
len.value().to_bits()
} else {
0
};
(bits, tag)
}
}
#[inline(always)]
fn encode_dim_tag(raw_tag: u8) -> Option<u16> {
match raw_tag as usize {
CompactLength::LENGTH_TAG => Some(0),
CompactLength::PERCENT_TAG => Some(1),
CompactLength::AUTO_TAG => Some(2),
CompactLength::MAX_CONTENT_TAG => Some(3),
_ => None,
}
}
#[inline(always)]
fn decode_dim_tag(code: u16) -> u8 {
match code & 0b11 {
0 => CompactLength::LENGTH_TAG as u8,
1 => CompactLength::PERCENT_TAG as u8,
2 => CompactLength::AUTO_TAG as u8,
_ => CompactLength::MAX_CONTENT_TAG as u8,
}
}
#[inline(always)]
fn unpack_len(bits: u32, tag: u8) -> CompactLength {
#[cfg(target_pointer_width = "64")]
{
let raw: usize = ((bits as usize) << 32) | (tag as usize);
// SAFETY: `tag` is one of `LENGTH_TAG`, `PERCENT_TAG`, `AUTO_TAG`, or `MAX_CONTENT_TAG`,
// matching `CompactLength`'s 64-bit tagged representation.
unsafe { core::mem::transmute(raw) }
}
#[cfg(not(target_pointer_width = "64"))]
{
let val = f32::from_bits(bits);
match tag as usize {
CompactLength::LENGTH_TAG => CompactLength::length(val),
CompactLength::PERCENT_TAG => CompactLength::percent(val),
CompactLength::AUTO_TAG => CompactLength::auto(),
CompactLength::MAX_CONTENT_TAG => CompactLength::max_content(),
_ => CompactLength::auto(),
}
}
}
#[inline(always)]
fn unpack_dim(bits: u32, code: u16) -> Dimension {
// SAFETY: `decode_dim_tag` produces only valid `Dimension` tags (`LENGTH`, `PERCENT`, `AUTO`, `MAX_CONTENT`).
unsafe { Dimension::from_raw(unpack_len(bits, decode_dim_tag(code))) }
}
#[inline(always)]
fn unpack_lpa(bits: u32, code: u16) -> LengthPercentageAuto {
// SAFETY: `decode_dim_tag` produces only valid `LengthPercentageAuto` tags.
unsafe { LengthPercentageAuto::from_raw(unpack_len(bits, decode_dim_tag(code))) }
}
#[inline(always)]
fn unpack_lp(bits: u32, is_pct: bool) -> LengthPercentage {
let tag = if is_pct {
CompactLength::PERCENT_TAG as u8
} else {
CompactLength::LENGTH_TAG as u8
};
// SAFETY: `tag` is either `LENGTH_TAG` or `PERCENT_TAG`, both valid for `LengthPercentage`.
unsafe { LengthPercentage::from_raw(unpack_len(bits, tag)) }
}
#[inline(always)]
fn pack_bf16_exact(v: f32) -> Option<u16> {
let bits = v.to_bits();
((bits & 0xFFFF) == 0).then_some((bits >> 16) as u16)
}
#[inline(always)]
fn unpack_bf16(b: u16) -> f32 {
f32::from_bits((b as u32) << 16)
}
#[inline(always)]
fn rect_is_zero_lpa(r: &Rect<LengthPercentageAuto>) -> bool {
const ZERO: Rect<LengthPercentageAuto> = Rect {
left: LengthPercentageAuto::ZERO,
right: LengthPercentageAuto::ZERO,
top: LengthPercentageAuto::ZERO,
bottom: LengthPercentageAuto::ZERO,
};
#[cfg(target_pointer_width = "64")]
{
// SAFETY: on 64-bit targets `Rect<LengthPercentageAuto>` is four 8-byte-aligned 64-bit words.
let a: &[u64; 4] = unsafe { &*(r as *const Rect<LengthPercentageAuto> as *const [u64; 4]) };
// SAFETY: `ZERO` has the same `Rect<LengthPercentageAuto>` layout.
let b: &[u64; 4] = unsafe { &*(&ZERO as *const Rect<LengthPercentageAuto> as *const [u64; 4]) };
a == b || *r == ZERO
}
#[cfg(not(target_pointer_width = "64"))]
{
*r == ZERO
}
}
#[inline(always)]
fn rect_is_zero_lp(r: &Rect<LengthPercentage>) -> bool {
const ZERO: Rect<LengthPercentage> = Rect {
left: LengthPercentage::ZERO,
right: LengthPercentage::ZERO,
top: LengthPercentage::ZERO,
bottom: LengthPercentage::ZERO,
};
#[cfg(target_pointer_width = "64")]
{
// SAFETY: on 64-bit targets `Rect<LengthPercentage>` is four 8-byte-aligned 64-bit words.
let a: &[u64; 4] = unsafe { &*(r as *const Rect<LengthPercentage> as *const [u64; 4]) };
// SAFETY: `ZERO` has the same `Rect<LengthPercentage>` layout.
let b: &[u64; 4] = unsafe { &*(&ZERO as *const Rect<LengthPercentage> as *const [u64; 4]) };
a == b || *r == ZERO
}
#[cfg(not(target_pointer_width = "64"))]
{
*r == ZERO
}
}
#[inline(always)]
fn rect_is_auto_lpa(r: &Rect<LengthPercentageAuto>) -> bool {
const AUTO: Rect<LengthPercentageAuto> = Rect {
left: LengthPercentageAuto::AUTO,
right: LengthPercentageAuto::AUTO,
top: LengthPercentageAuto::AUTO,
bottom: LengthPercentageAuto::AUTO,
};
#[cfg(target_pointer_width = "64")]
{
// SAFETY: on 64-bit targets `Rect<LengthPercentageAuto>` is four 8-byte-aligned 64-bit words.
let a: &[u64; 4] = unsafe { &*(r as *const Rect<LengthPercentageAuto> as *const [u64; 4]) };
// SAFETY: `AUTO` has the same `Rect<LengthPercentageAuto>` layout.
let b: &[u64; 4] = unsafe { &*(&AUTO as *const Rect<LengthPercentageAuto> as *const [u64; 4]) };
a == b || *r == AUTO
}
#[cfg(not(target_pointer_width = "64"))]
{
*r == AUTO
}
}
#[inline(always)]
fn has_cold_fields(s: &Style) -> bool {
s.display == Display::Grid
|| s.aspect_ratio.is_some()
|| !rect_is_zero_lpa(&s.margin)
|| !rect_is_auto_lpa(&s.inset)
|| !rect_is_zero_lp(&s.border)
|| s.box_sizing != BoxSizing::BorderBox
|| s.direction != Direction::Ltr
|| s.scrollbar_width != 0.0
|| s.contain != Contain::NONE
|| s.justify_items != AlignItems::NORMAL
|| s.justify_self.is_some()
|| s.text_align != TextAlign::Auto
|| s.item_is_table
|| s.item_is_replaced
|| s.item_is_compressible_replaced
|| s.grid_auto_flow != GridAutoFlow::Row
|| s.grid_row != Line { start: GridPlacement::Auto, end: GridPlacement::Auto }
|| s.grid_column != Line { start: GridPlacement::Auto, end: GridPlacement::Auto }
|| !s.grid_template_rows.is_empty()
|| !s.grid_template_columns.is_empty()
|| !s.grid_auto_rows.is_empty()
|| !s.grid_auto_columns.is_empty()
|| s.grid_template_areas.is_some()
|| !s.grid_template_column_names.is_empty()
|| !s.grid_template_row_names.is_empty()
}
#[inline(always)]
const fn encode_display(d: Display) -> u8 {
match d {
Display::Flex => 0,
Display::Block => 1,
Display::Grid => 2,
Display::FlowRoot => 3,
Display::None => 4,
}
}
#[inline(always)]
const fn decode_display(b: u8) -> Display {
match b & MODE_DISPLAY_MASK {
0 => Display::Flex,
1 => Display::Block,
2 => Display::Grid,
3 => Display::FlowRoot,
_ => Display::None,
}
}
#[inline(always)]
const fn encode_position(p: Position) -> Option<u8> {
match p {
Position::Static => Some(0),
Position::Relative => Some(1),
Position::Absolute => Some(2),
Position::Fixed | Position::Sticky => None,
}
}
#[inline(always)]
fn decode_position(mode_flags: u8, extra: Option<&Style>) -> Position {
match (mode_flags & MODE_POS_MASK) >> MODE_POS_SHIFT {
0 => Position::Static,
1 => Position::Relative,
2 => Position::Absolute,
_ => extra.map_or(Position::Static, |s| s.position),
}
}
const ALIGN_SELF_NONE: u8 = 0xFF;
#[inline(always)]
const fn pack_align_items(a: AlignItems) -> u8 {
((a.safety as u8) << 4) | (a.keyword as u8)
}
#[inline(always)]
const fn unpack_align_items(b: u8) -> AlignItems {
let safety = match (b >> 4) & 0b11 {
0 => AlignmentSafety::Default,
1 => AlignmentSafety::Unsafe,
_ => AlignmentSafety::Safe,
};
let keyword = match b & 0x0F {
0 => AlignItemsKeyword::Normal,
1 => AlignItemsKeyword::Start,
2 => AlignItemsKeyword::End,
3 => AlignItemsKeyword::FlexStart,
4 => AlignItemsKeyword::FlexEnd,
5 => AlignItemsKeyword::SelfStart,
6 => AlignItemsKeyword::SelfEnd,
7 => AlignItemsKeyword::Center,
8 => AlignItemsKeyword::Baseline,
_ => AlignItemsKeyword::Stretch,
};
AlignItems { keyword, safety }
}
#[inline(always)]
const fn pack_align_self(a: Option<AlignSelf>) -> u8 {
match a {
Some(v) => pack_align_items(v),
None => ALIGN_SELF_NONE,
}
}
#[inline(always)]
const fn unpack_align_self(b: u8) -> Option<AlignSelf> {
if b == ALIGN_SELF_NONE {
None
} else {
Some(unpack_align_items(b))
}
}
#[inline(always)]
const fn pack_align_content(a: AlignContent) -> u8 {
((a.safety as u8) << 4) | (a.keyword as u8)
}
#[inline(always)]
const fn unpack_align_content(b: u8) -> AlignContent {
let safety = match (b >> 4) & 0b11 {
0 => AlignmentSafety::Default,
1 => AlignmentSafety::Unsafe,
_ => AlignmentSafety::Safe,
};
let keyword = match b & 0x0F {
0 => AlignContentKeyword::Normal,
1 => AlignContentKeyword::Start,
2 => AlignContentKeyword::End,
3 => AlignContentKeyword::FlexStart,
4 => AlignContentKeyword::FlexEnd,
5 => AlignContentKeyword::Center,
6 => AlignContentKeyword::Stretch,
7 => AlignContentKeyword::SpaceBetween,
8 => AlignContentKeyword::SpaceEvenly,
_ => AlignContentKeyword::SpaceAround,
};
AlignContent { keyword, safety }
}
#[inline(always)]
const fn encode_overflow(o: Overflow) -> u8 {
match o {
Overflow::Visible => 0,
Overflow::Clip => 1,
Overflow::Hidden => 2,
Overflow::Scroll => 3,
}
}
#[inline(always)]
const fn decode_overflow(b: u8) -> Overflow {
match b & 0b11 {
0 => Overflow::Visible,
1 => Overflow::Clip,
2 => Overflow::Hidden,
_ => Overflow::Scroll,
}
}
#[inline(always)]
const fn encode_wrap(w: FlexWrap) -> u8 {
match w {
FlexWrap::NoWrap => 0,
FlexWrap::Wrap => 1,
FlexWrap::WrapReverse => 2,
// raea: taffy's flexbox_balance (on here, and Blitz's) adds two wrap modes; Rune doesn't balance lines, so they
// wrap as their plain counterparts
FlexWrap::Balance => 1,
FlexWrap::BalanceReverse => 2,
}
}
#[inline(always)]
const fn decode_wrap(b: u8) -> FlexWrap {
match b & 0b11 {
0 => FlexWrap::NoWrap,
1 => FlexWrap::Wrap,
_ => FlexWrap::WrapReverse,
}
}
#[inline(always)]
const fn encode_dir(d: FlexDirection) -> u8 {
match d {
FlexDirection::Row => 0,
FlexDirection::Column => 1,
FlexDirection::RowReverse => 2,
FlexDirection::ColumnReverse => 3,
}
}
#[inline(always)]
const fn decode_dir(b: u8) -> FlexDirection {
match b & 0b11 {
0 => FlexDirection::Row,
1 => FlexDirection::Column,
2 => FlexDirection::RowReverse,
_ => FlexDirection::ColumnReverse,
}
}
#[inline(always)]
const fn pack_box_flags(dir: FlexDirection, wrap: FlexWrap, ox: Overflow, oy: Overflow) -> u8 {
encode_dir(dir) | (encode_wrap(wrap) << 2) | (encode_overflow(ox) << 4) | (encode_overflow(oy) << 6)
}
/// Compact representation of `taffy::Style` (64 bytes inline — one cache line).
#[derive(Debug)]
pub struct CompactStyle {
vals: [u32; HOT_VAL_COUNT],
gap_w_bf16: u16,
gap_h_bf16: u16,
flex_grow_bf16: u16,
flex_shrink_bf16: u16,
/// Bits 0..12: 2-bit tags for `size.w/h`, `min_size.w/h`, `max_size.w/h`.
/// Bits 12..16: 1-bit tags (`0 = Length`, `1 = Percent`) for `pad.l/r/t/b`.
len_tags: u16,
box_flags: u8,
/// Bits 0..3: `Display`.
/// Bits 3..5: `Position` (`Static`, `Relative`, `Absolute`).
/// Bit 5: `gap.width` is `Percent`.
/// Bit 6: `gap.height` is `Percent`.
/// Bit 7: `flex_basis` is `Length(0.0)` (otherwise `Auto`).
mode_flags: u8,
align_items_u8: u8,
align_self_u8: u8,
justify_content_u8: u8,
align_content_u8: u8,
extra: Option<Box<Style>>,
}
const _: () = assert!(core::mem::size_of::<CompactStyle>() <= 64);
#[cfg(target_pointer_width = "64")]
const _: () = assert!(core::mem::size_of::<CompactStyle>() == 64);
impl Clone for CompactStyle {
#[inline(always)]
fn clone(&self) -> Self {
if self.extra.is_none() {
Self {
vals: self.vals,
gap_w_bf16: self.gap_w_bf16,
gap_h_bf16: self.gap_h_bf16,
flex_grow_bf16: self.flex_grow_bf16,
flex_shrink_bf16: self.flex_shrink_bf16,
len_tags: self.len_tags,
box_flags: self.box_flags,
mode_flags: self.mode_flags,
align_items_u8: self.align_items_u8,
align_self_u8: self.align_self_u8,
justify_content_u8: self.justify_content_u8,
align_content_u8: self.align_content_u8,
extra: None,
}
} else {
self.clone_cold()
}
}
}
impl Default for CompactStyle {
#[inline(always)]
fn default() -> Self {
Self {
vals: [0; HOT_VAL_COUNT],
gap_w_bf16: 0,
gap_h_bf16: 0,
flex_grow_bf16: 0,
flex_shrink_bf16: ONE_BF16,
len_tags: BASE_LEN_TAGS,
box_flags: 0,
mode_flags: encode_display(Display::Flex),
align_items_u8: pack_align_items(AlignItems::NORMAL),
align_self_u8: ALIGN_SELF_NONE,
justify_content_u8: pack_align_content(JustifyContent::NORMAL),
align_content_u8: pack_align_content(AlignContent::NORMAL),
extra: None,
}
}
}
impl CompactStyle {
/// Base element style used by Rune (`Display::Flex`, `Position::Relative`, `flex_shrink: 0.0`).
#[inline(always)]
pub const fn rune_base(dir: FlexDirection) -> Self {
Self {
vals: [0; HOT_VAL_COUNT],
gap_w_bf16: 0,
gap_h_bf16: 0,
flex_grow_bf16: 0,
flex_shrink_bf16: 0,
len_tags: BASE_LEN_TAGS,
box_flags: encode_dir(dir),
mode_flags: encode_display(Display::Flex) | (1 << MODE_POS_SHIFT),
align_items_u8: pack_align_items(AlignItems::NORMAL),
align_self_u8: ALIGN_SELF_NONE,
justify_content_u8: pack_align_content(JustifyContent::NORMAL),
align_content_u8: pack_align_content(AlignContent::NORMAL),
extra: None,
}
}
#[cold]
#[inline(never)]
fn clone_cold(&self) -> Self {
Self {
vals: self.vals,
gap_w_bf16: self.gap_w_bf16,
gap_h_bf16: self.gap_h_bf16,
flex_grow_bf16: self.flex_grow_bf16,
flex_shrink_bf16: self.flex_shrink_bf16,
len_tags: self.len_tags,
box_flags: self.box_flags,
mode_flags: self.mode_flags,
align_items_u8: self.align_items_u8,
align_self_u8: self.align_self_u8,
justify_content_u8: self.justify_content_u8,
align_content_u8: self.align_content_u8,
extra: self.extra.clone(),
}
}
#[cold]
#[inline(never)]
pub fn modify_cold(&mut self, f: impl FnOnce(&mut Style)) {
let mut s = match self.extra.take() {
Some(b) => *b,
None => self.to_style(),
};
f(&mut s);
*self = Self::from_style(s);
}
#[inline(always)]
pub fn display(&self) -> Display {
decode_display(self.mode_flags)
}
#[inline(always)]
pub fn position(&self) -> Position {
decode_position(self.mode_flags, self.extra.as_deref())
}
#[inline(always)]
pub fn flex_direction(&self) -> FlexDirection {
decode_dir(self.box_flags)
}
#[inline(always)]
pub fn flex_wrap(&self) -> FlexWrap {
decode_wrap(self.box_flags >> 2)
}
#[inline(always)]
pub fn size(&self) -> Size<Dimension> {
CoreStyle::size(self)
}
#[inline(always)]
pub fn min_size(&self) -> Size<LengthPercentageAuto> {
CoreStyle::min_size(self)
}
#[inline(always)]
pub fn max_size(&self) -> Size<LengthPercentageAuto> {
CoreStyle::max_size(self)
}
#[inline(always)]
pub fn padding(&self) -> Rect<LengthPercentage> {
CoreStyle::padding(self)
}
#[inline(always)]
pub fn inset(&self) -> Rect<LengthPercentageAuto> {
CoreStyle::inset(self)
}
#[inline(always)]
pub fn gap(&self) -> Size<LengthPercentage> {
FlexboxContainerStyle::gap(self)
}
#[inline(always)]
pub fn flex_grow(&self) -> f32 {
FlexboxItemStyle::flex_grow(self)
}
#[inline(always)]
pub fn flex_shrink(&self) -> f32 {
FlexboxItemStyle::flex_shrink(self)
}
#[inline(always)]
pub fn flex_basis(&self) -> Dimension {
FlexboxItemStyle::flex_basis(self)
}
#[inline(always)]
pub fn aspect_ratio(&self) -> Option<f32> {
CoreStyle::aspect_ratio(self)
}
#[inline(always)]
pub fn align_self(&self) -> Option<AlignSelf> {
unpack_align_self(self.align_self_u8)
}
}
mod convert;
mod setters;
mod traits;
+402
View File
@@ -0,0 +1,402 @@
//! Builder setters for [`CompactStyle`].
use super::*;
impl CompactStyle {
#[inline(always)]
fn set_dim_slot(&mut self, idx: usize, raw: CompactLength, cold_set: impl FnOnce(&mut Style)) {
if self.extra.is_none() {
let (v, t) = pack_raw_len(raw);
if let Some(code) = encode_dim_tag(t) {
self.vals[idx] = v;
let shift = idx * 2;
self.len_tags = (self.len_tags & !(0b11 << shift)) | (code << shift);
return;
}
}
self.modify_cold(cold_set);
}
#[inline(always)]
pub fn set_width(&mut self, d: Dimension) {
self.set_dim_slot(IDX_SIZE_W, d.into_raw(), |s| s.size.width = d);
}
#[inline(always)]
pub fn set_height(&mut self, d: Dimension) {
self.set_dim_slot(IDX_SIZE_H, d.into_raw(), |s| s.size.height = d);
}
#[inline(always)]
pub fn set_size(&mut self, size: Size<Dimension>) {
self.set_width(size.width);
self.set_height(size.height);
}
#[inline(always)]
pub fn set_min_width(&mut self, d: LengthPercentageAuto) {
self.set_dim_slot(IDX_MIN_W, d.into_raw(), |s| s.min_size.width = d);
}
#[inline(always)]
pub fn set_min_height(&mut self, d: LengthPercentageAuto) {
self.set_dim_slot(IDX_MIN_H, d.into_raw(), |s| s.min_size.height = d);
}
#[inline(always)]
pub fn set_max_width(&mut self, d: LengthPercentageAuto) {
self.set_dim_slot(IDX_MAX_W, d.into_raw(), |s| s.max_size.width = d);
}
#[inline(always)]
pub fn set_max_height(&mut self, d: LengthPercentageAuto) {
self.set_dim_slot(IDX_MAX_H, d.into_raw(), |s| s.max_size.height = d);
}
#[inline(always)]
pub fn set_pad_left(&mut self, p: f32) {
if self.extra.is_none() {
self.vals[IDX_PAD_L] = p.to_bits();
self.len_tags &= !(1 << 12);
} else {
self.modify_cold(|s| s.padding.left = LengthPercentage::length(p));
}
}
#[inline(always)]
pub fn set_pad_right(&mut self, p: f32) {
if self.extra.is_none() {
self.vals[IDX_PAD_R] = p.to_bits();
self.len_tags &= !(1 << 13);
} else {
self.modify_cold(|s| s.padding.right = LengthPercentage::length(p));
}
}
#[inline(always)]
pub fn set_pad_top(&mut self, p: f32) {
if self.extra.is_none() {
self.vals[IDX_PAD_T] = p.to_bits();
self.len_tags &= !(1 << 14);
} else {
self.modify_cold(|s| s.padding.top = LengthPercentage::length(p));
}
}
#[inline(always)]
pub fn set_pad_bottom(&mut self, p: f32) {
if self.extra.is_none() {
self.vals[IDX_PAD_B] = p.to_bits();
self.len_tags &= !(1 << 15);
} else {
self.modify_cold(|s| s.padding.bottom = LengthPercentage::length(p));
}
}
#[inline(always)]
pub fn set_padding_all(&mut self, p: f32) {
if self.extra.is_none() {
let bits = p.to_bits();
self.vals[IDX_PAD_L] = bits;
self.vals[IDX_PAD_R] = bits;
self.vals[IDX_PAD_T] = bits;
self.vals[IDX_PAD_B] = bits;
self.len_tags &= !0xF000;
} else {
let lp = LengthPercentage::length(p);
self.modify_cold(|s| s.padding = Rect { left: lp, right: lp, top: lp, bottom: lp });
}
}
#[inline(always)]
pub fn set_gap(&mut self, column: f32, row: f32) {
if self.extra.is_none()
&& let (Some(cw), Some(rh)) = (pack_bf16_exact(column), pack_bf16_exact(row))
{
self.gap_w_bf16 = cw;
self.gap_h_bf16 = rh;
self.mode_flags &= !(MODE_GAP_W_PCT | MODE_GAP_H_PCT);
return;
}
self.modify_cold(|s| {
s.gap = Size {
width: LengthPercentage::length(column),
height: LengthPercentage::length(row),
};
});
}
#[inline(always)]
pub fn set_grow(&mut self, g: f32) {
if self.extra.is_none()
&& let Some(gb) = pack_bf16_exact(g)
{
self.flex_grow_bf16 = gb;
self.flex_shrink_bf16 = ONE_BF16;
self.mode_flags |= MODE_BASIS_ZERO;
return;
}
self.modify_cold(|s| {
s.flex_grow = g;
s.flex_shrink = 1.0;
s.flex_basis = Dimension::ZERO;
});
}
#[inline(always)]
pub fn set_flex_grow(&mut self, g: f32) {
if self.extra.is_none()
&& let Some(gb) = pack_bf16_exact(g)
{
self.flex_grow_bf16 = gb;
return;
}
self.modify_cold(|s| s.flex_grow = g);
}
#[inline(always)]
pub fn set_flex_shrink(&mut self, sh: f32) {
if self.extra.is_none()
&& let Some(sb) = pack_bf16_exact(sh)
{
self.flex_shrink_bf16 = sb;
return;
}
self.modify_cold(|s| s.flex_shrink = sh);
}
#[inline(always)]
pub fn set_flex_basis(&mut self, basis: Dimension) {
if self.extra.is_none() {
let (bits, tag) = pack_raw_len(basis.into_raw());
if tag as usize == CompactLength::AUTO_TAG {
self.mode_flags &= !MODE_BASIS_ZERO;
return;
}
if tag as usize == CompactLength::LENGTH_TAG && bits == 0 {
self.mode_flags |= MODE_BASIS_ZERO;
return;
}
}
self.modify_cold(|s| s.flex_basis = basis);
}
#[inline(always)]
pub fn set_flex_direction(&mut self, dir: FlexDirection) {
self.box_flags = (self.box_flags & !0b11) | encode_dir(dir);
if let Some(s) = &mut self.extra {
s.flex_direction = dir;
}
}
#[inline(always)]
pub fn set_flex_wrap(&mut self, wrap: FlexWrap) {
self.box_flags = (self.box_flags & !(0b11 << 2)) | (encode_wrap(wrap) << 2);
if let Some(s) = &mut self.extra {
s.flex_wrap = wrap;
}
}
#[inline(always)]
pub fn set_overflow(&mut self, x: Overflow, y: Overflow) {
self.box_flags = (self.box_flags & 0x0F) | (encode_overflow(x) << 4) | (encode_overflow(y) << 6);
if let Some(s) = &mut self.extra {
s.overflow = Point { x, y };
}
}
#[inline(always)]
pub fn set_align_items(&mut self, a: AlignItems) {
self.align_items_u8 = pack_align_items(a);
if let Some(s) = &mut self.extra {
s.align_items = a;
}
}
#[inline(always)]
pub fn set_align_self(&mut self, a: Option<AlignSelf>) {
self.align_self_u8 = pack_align_self(a);
if let Some(s) = &mut self.extra {
s.align_self = a;
}
}
#[inline(always)]
pub fn set_justify_content(&mut self, j: JustifyContent) {
self.justify_content_u8 = pack_align_content(j);
if let Some(s) = &mut self.extra {
s.justify_content = j;
}
}
#[inline(always)]
pub fn set_aspect_ratio(&mut self, ratio: Option<f32>) {
if self.extra.is_none() && ratio.is_none() {
return;
}
self.modify_cold(|s| s.aspect_ratio = ratio);
}
#[inline(always)]
pub fn set_equal_columns(&mut self, n: usize) {
self.modify_cold(|s| {
s.display = Display::Grid;
s.grid_template_columns = vec![fr(1.0); n.max(1)];
});
}
#[inline(always)]
pub fn set_grid_cell(&mut self, column: usize) {
self.modify_cold(|s| {
s.grid_column = Line {
start: line(column as i16 + 1),
end: span(1),
};
s.grid_row = Line {
start: line(1),
end: span(1),
};
});
}
#[inline(always)]
pub fn set_position_absolute(&mut self) {
if let Some(s) = &mut self.extra {
s.position = Position::Absolute;
}
self.mode_flags = (self.mode_flags & !MODE_POS_MASK) | (2 << MODE_POS_SHIFT);
}
#[inline(always)]
pub fn set_absolute_inset(&mut self, inset: Rect<LengthPercentageAuto>) {
if self.extra.is_none() && rect_is_auto_lpa(&inset) {
self.mode_flags = (self.mode_flags & !MODE_POS_MASK) | (2 << MODE_POS_SHIFT);
return;
}
self.modify_cold(|s| {
s.position = Position::Absolute;
s.inset = inset;
});
}
#[inline(always)]
pub fn set_margin_left(&mut self, m: f32) {
if self.extra.is_none() && m == 0.0 { return; }
self.modify_cold(|s| s.margin.left = LengthPercentageAuto::length(m));
}
#[inline(always)]
pub fn set_margin_right(&mut self, m: f32) {
if self.extra.is_none() && m == 0.0 { return; }
self.modify_cold(|s| s.margin.right = LengthPercentageAuto::length(m));
}
#[inline(always)]
pub fn set_margin_top(&mut self, m: f32) {
if self.extra.is_none() && m == 0.0 { return; }
self.modify_cold(|s| s.margin.top = LengthPercentageAuto::length(m));
}
#[inline(always)]
pub fn set_margin_bottom(&mut self, m: f32) {
if self.extra.is_none() && m == 0.0 { return; }
self.modify_cold(|s| s.margin.bottom = LengthPercentageAuto::length(m));
}
#[inline(always)]
pub fn set_margin_x(&mut self, m: f32) {
if self.extra.is_none() && m == 0.0 { return; }
let v = LengthPercentageAuto::length(m);
self.modify_cold(|s| { s.margin.left = v; s.margin.right = v; });
}
#[inline(always)]
pub fn set_margin_y(&mut self, m: f32) {
if self.extra.is_none() && m == 0.0 { return; }
let v = LengthPercentageAuto::length(m);
self.modify_cold(|s| { s.margin.top = v; s.margin.bottom = v; });
}
/// Moves this style's outer box sizing and placement onto a fresh column wrapper style and
/// resets this style's outer box to fill that column (`flex: 1 1 auto`, `min_size: 0`). The
/// wrapper keeps the overflow too, so a scroll viewport's wrapper is a scroll container: its
/// automatic minimum size is zero and its content doesn't size the ancestors around it.
pub fn take_box_placement(&mut self) -> Self {
if self.extra.is_none() {
let hidden = (self.mode_flags & MODE_DISPLAY_MASK) == encode_display(Display::None);
let mut outer = Self::rune_base(FlexDirection::Column);
outer.vals[..6].copy_from_slice(&self.vals[..6]);
outer.len_tags = (outer.len_tags & !0x0FFF) | (self.len_tags & 0x0FFF);
outer.flex_grow_bf16 = self.flex_grow_bf16;
outer.flex_shrink_bf16 = self.flex_shrink_bf16;
outer.mode_flags = (outer.mode_flags & !(MODE_DISPLAY_MASK | MODE_POS_MASK | MODE_BASIS_ZERO))
| (if hidden { encode_display(Display::None) } else { encode_display(Display::Flex) })
| (self.mode_flags & (MODE_POS_MASK | MODE_BASIS_ZERO));
outer.align_self_u8 = self.align_self_u8;
outer.box_flags = (outer.box_flags & 0x0F) | (self.box_flags & 0xF0);
self.vals[..6].fill(0);
self.len_tags = (self.len_tags & 0xF000) | 0b0000_1010_0000_1010;
self.flex_grow_bf16 = ONE_BF16;
self.flex_shrink_bf16 = ONE_BF16;
self.mode_flags = (self.mode_flags & !(MODE_DISPLAY_MASK | MODE_POS_MASK | MODE_BASIS_ZERO))
| encode_display(Display::Flex)
| (1 << MODE_POS_SHIFT);
self.align_self_u8 = ALIGN_SELF_NONE;
return outer;
}
let mut s = match self.extra.take() {
Some(b) => *b,
None => self.to_style(),
};
let outer = Style {
display: if s.display == Display::None { Display::None } else { Display::Flex },
flex_direction: FlexDirection::Column,
overflow: s.overflow,
flex_shrink: s.flex_shrink,
flex_grow: s.flex_grow,
flex_basis: s.flex_basis,
position: s.position,
inset: s.inset,
size: s.size,
min_size: s.min_size,
max_size: s.max_size,
margin: s.margin,
align_self: s.align_self,
justify_self: s.justify_self,
aspect_ratio: s.aspect_ratio,
grid_row: s.grid_row,
grid_column: s.grid_column,
..Style::DEFAULT
};
if s.display == Display::None {
s.display = Display::Flex;
}
s.position = Position::Relative;
s.inset = Rect {
left: LengthPercentageAuto::AUTO,
right: LengthPercentageAuto::AUTO,
top: LengthPercentageAuto::AUTO,
bottom: LengthPercentageAuto::AUTO,
};
s.size = Size { width: Dimension::AUTO, height: Dimension::AUTO };
s.min_size = Size { width: LengthPercentageAuto::ZERO, height: LengthPercentageAuto::ZERO };
s.max_size = Size { width: LengthPercentageAuto::AUTO, height: LengthPercentageAuto::AUTO };
s.margin = Rect {
left: LengthPercentageAuto::ZERO,
right: LengthPercentageAuto::ZERO,
top: LengthPercentageAuto::ZERO,
bottom: LengthPercentageAuto::ZERO,
};
s.flex_grow = 1.0;
s.flex_shrink = 1.0;
s.flex_basis = Dimension::AUTO;
s.align_self = None;
s.justify_self = None;
s.aspect_ratio = None;
s.grid_row = Line { start: GridPlacement::Auto, end: GridPlacement::Auto };
s.grid_column = Line { start: GridPlacement::Auto, end: GridPlacement::Auto };
*self = Self::from_style(s);
Self::from_style(outer)
}
}
+391
View File
@@ -0,0 +1,391 @@
//! Taffy style trait implementations (`CoreStyle`, `Flexbox*`, `Grid*`, `Block*`, `OofItemStyle`) for [`CompactStyle`].
use super::*;
impl CoreStyle for CompactStyle {
type CustomIdent = <Style as CoreStyle>::CustomIdent;
#[inline(always)]
fn box_generation_mode(&self) -> BoxGenerationMode {
match self.display() {
Display::None => BoxGenerationMode::None,
_ => BoxGenerationMode::Normal,
}
}
#[inline(always)]
fn is_block(&self) -> bool {
matches!(self.display(), Display::Block)
}
#[inline(always)]
fn is_compressible_replaced(&self) -> bool {
self.extra.as_ref().is_some_and(|s| s.item_is_replaced || s.item_is_compressible_replaced)
}
#[inline(always)]
fn is_replaced(&self) -> bool {
self.extra.as_ref().is_some_and(|s| s.item_is_replaced)
}
#[inline(always)]
fn box_sizing(&self) -> BoxSizing {
self.extra.as_ref().map_or(BoxSizing::BorderBox, |s| s.box_sizing)
}
#[inline(always)]
fn direction(&self) -> Direction {
self.extra.as_ref().map_or(Direction::Ltr, |s| s.direction)
}
#[inline(always)]
fn overflow(&self) -> Point<Overflow> {
Point {
x: decode_overflow(self.box_flags >> 4),
y: decode_overflow(self.box_flags >> 6),
}
}
#[inline(always)]
fn scrollbar_width(&self) -> f32 {
self.extra.as_ref().map_or(0.0, |s| s.scrollbar_width)
}
#[inline(always)]
fn position(&self) -> Position {
decode_position(self.mode_flags, self.extra.as_deref())
}
#[inline(always)]
fn inset(&self) -> Rect<LengthPercentageAuto> {
self.extra.as_ref().map_or(Rect::auto(), |s| s.inset)
}
#[inline(always)]
fn size(&self) -> Size<Dimension> {
if let Some(s) = &self.extra {
return s.size;
}
Size {
width: unpack_dim(self.vals[IDX_SIZE_W], self.len_tags),
height: unpack_dim(self.vals[IDX_SIZE_H], self.len_tags >> 2),
}
}
#[inline(always)]
fn min_size(&self) -> Size<LengthPercentageAuto> {
if let Some(s) = &self.extra {
return s.min_size;
}
Size {
width: unpack_lpa(self.vals[IDX_MIN_W], self.len_tags >> 4),
height: unpack_lpa(self.vals[IDX_MIN_H], self.len_tags >> 6),
}
}
#[inline(always)]
fn max_size(&self) -> Size<LengthPercentageAuto> {
if let Some(s) = &self.extra {
return s.max_size;
}
Size {
width: unpack_lpa(self.vals[IDX_MAX_W], self.len_tags >> 8),
height: unpack_lpa(self.vals[IDX_MAX_H], self.len_tags >> 10),
}
}
#[inline(always)]
fn aspect_ratio(&self) -> Option<f32> {
self.extra.as_ref().and_then(|s| s.aspect_ratio)
}
#[inline(always)]
fn margin(&self) -> Rect<LengthPercentageAuto> {
self.extra.as_ref().map_or(Rect::zero(), |s| s.margin)
}
#[inline(always)]
fn padding(&self) -> Rect<LengthPercentage> {
if let Some(s) = &self.extra {
return s.padding;
}
Rect {
left: unpack_lp(self.vals[IDX_PAD_L], (self.len_tags & (1 << 12)) != 0),
right: unpack_lp(self.vals[IDX_PAD_R], (self.len_tags & (1 << 13)) != 0),
top: unpack_lp(self.vals[IDX_PAD_T], (self.len_tags & (1 << 14)) != 0),
bottom: unpack_lp(self.vals[IDX_PAD_B], (self.len_tags & (1 << 15)) != 0),
}
}
#[inline(always)]
fn border(&self) -> Rect<LengthPercentage> {
self.extra.as_ref().map_or(Rect::zero(), |s| s.border)
}
#[inline(always)]
fn contain(&self) -> Contain {
self.extra.as_ref().map_or(Contain::NONE, |s| s.contain)
}
}
impl OofItemStyle for CompactStyle {
#[inline(always)]
fn align_self(&self) -> Option<AlignSelf> {
unpack_align_self(self.align_self_u8)
}
#[inline(always)]
fn justify_self(&self) -> Option<AlignSelf> {
self.extra.as_ref().and_then(|s| s.justify_self)
}
#[inline(always)]
fn is_table(&self) -> bool {
self.extra.as_ref().is_some_and(|s| s.item_is_table)
}
#[inline(always)]
fn grid_row(&self) -> Line<GridPlacement<Self::CustomIdent>> {
self.extra
.as_ref()
.map_or(Line { start: GridPlacement::Auto, end: GridPlacement::Auto }, |s| s.grid_row.clone())
}
#[inline(always)]
fn grid_column(&self) -> Line<GridPlacement<Self::CustomIdent>> {
self.extra
.as_ref()
.map_or(Line { start: GridPlacement::Auto, end: GridPlacement::Auto }, |s| s.grid_column.clone())
}
}
impl FlexboxContainerStyle for CompactStyle {
#[inline(always)]
fn flex_direction(&self) -> FlexDirection {
decode_dir(self.box_flags)
}
#[inline(always)]
fn flex_wrap(&self) -> FlexWrap {
decode_wrap(self.box_flags >> 2)
}
#[inline(always)]
fn gap(&self) -> Size<LengthPercentage> {
if let Some(s) = &self.extra {
return s.gap;
}
Size {
width: unpack_lp((self.gap_w_bf16 as u32) << 16, (self.mode_flags & MODE_GAP_W_PCT) != 0),
height: unpack_lp((self.gap_h_bf16 as u32) << 16, (self.mode_flags & MODE_GAP_H_PCT) != 0),
}
}
#[inline(always)]
fn align_content(&self) -> AlignContent {
unpack_align_content(self.align_content_u8)
}
#[inline(always)]
fn align_items(&self) -> AlignItems {
unpack_align_items(self.align_items_u8)
}
#[inline(always)]
fn justify_content(&self) -> JustifyContent {
unpack_align_content(self.justify_content_u8)
}
}
impl FlexboxItemStyle for CompactStyle {
#[inline(always)]
fn flex_basis(&self) -> Dimension {
if let Some(s) = &self.extra {
return s.flex_basis;
}
if (self.mode_flags & MODE_BASIS_ZERO) != 0 {
Dimension::ZERO
} else {
Dimension::AUTO
}
}
#[inline(always)]
fn flex_grow(&self) -> f32 {
if let Some(s) = &self.extra {
return s.flex_grow;
}
unpack_bf16(self.flex_grow_bf16)
}
#[inline(always)]
fn flex_shrink(&self) -> f32 {
if let Some(s) = &self.extra {
return s.flex_shrink;
}
unpack_bf16(self.flex_shrink_bf16)
}
#[inline(always)]
fn align_self(&self) -> Option<AlignSelf> {
unpack_align_self(self.align_self_u8)
}
}
impl GridContainerStyle for CompactStyle {
type Repetition<'a>
= <Style as GridContainerStyle>::Repetition<'a>
where
Self: 'a;
type TemplateTrackList<'a>
= <Style as GridContainerStyle>::TemplateTrackList<'a>
where
Self: 'a;
type AutoTrackList<'a>
= <Style as GridContainerStyle>::AutoTrackList<'a>
where
Self: 'a;
type TemplateLineNames<'a>
= <Style as GridContainerStyle>::TemplateLineNames<'a>
where
Self: 'a;
type GridTemplateAreas<'a>
= <Style as GridContainerStyle>::GridTemplateAreas<'a>
where
Self: 'a;
#[inline(always)]
fn grid_template_rows(&self) -> Option<Self::TemplateTrackList<'_>> {
self.extra.as_ref().and_then(|s| GridContainerStyle::grid_template_rows(&**s))
}
#[inline(always)]
fn grid_template_columns(&self) -> Option<Self::TemplateTrackList<'_>> {
self.extra.as_ref().and_then(|s| GridContainerStyle::grid_template_columns(&**s))
}
#[inline(always)]
fn grid_auto_rows(&self) -> Self::AutoTrackList<'_> {
self.extra.as_ref().map_or_else(|| [].iter().copied(), |s| GridContainerStyle::grid_auto_rows(&**s))
}
#[inline(always)]
fn grid_auto_columns(&self) -> Self::AutoTrackList<'_> {
self.extra.as_ref().map_or_else(|| [].iter().copied(), |s| GridContainerStyle::grid_auto_columns(&**s))
}
#[inline(always)]
fn grid_auto_flow(&self) -> GridAutoFlow {
self.extra.as_ref().map_or(GridAutoFlow::Row, |s| s.grid_auto_flow)
}
#[inline(always)]
fn gap(&self) -> Size<LengthPercentage> {
FlexboxContainerStyle::gap(self)
}
#[inline(always)]
fn align_content(&self) -> AlignContent {
unpack_align_content(self.align_content_u8)
}
#[inline(always)]
fn justify_content(&self) -> JustifyContent {
unpack_align_content(self.justify_content_u8)
}
#[inline(always)]
fn align_items(&self) -> AlignItems {
unpack_align_items(self.align_items_u8)
}
#[inline(always)]
fn justify_items(&self) -> AlignItems {
self.extra.as_ref().map_or(AlignItems::NORMAL, |s| s.justify_items)
}
#[inline(always)]
fn grid_template_areas(&self) -> Option<Self::GridTemplateAreas<'_>> {
self.extra.as_ref().and_then(|s| GridContainerStyle::grid_template_areas(&**s))
}
#[inline(always)]
fn grid_template_area_row_count(&self) -> u16 {
self.extra.as_ref().map_or(0, |s| GridContainerStyle::grid_template_area_row_count(&**s))
}
#[inline(always)]
fn grid_template_area_column_count(&self) -> u16 {
self.extra.as_ref().map_or(0, |s| GridContainerStyle::grid_template_area_column_count(&**s))
}
#[inline(always)]
fn grid_template_column_names(&self) -> Option<Self::TemplateLineNames<'_>> {
self.extra.as_ref().and_then(|s| GridContainerStyle::grid_template_column_names(&**s))
}
#[inline(always)]
fn grid_template_row_names(&self) -> Option<Self::TemplateLineNames<'_>> {
self.extra.as_ref().and_then(|s| GridContainerStyle::grid_template_row_names(&**s))
}
}
impl GridItemStyle for CompactStyle {
#[inline(always)]
fn grid_row(&self) -> Line<GridPlacement<Self::CustomIdent>> {
OofItemStyle::grid_row(self)
}
#[inline(always)]
fn grid_column(&self) -> Line<GridPlacement<Self::CustomIdent>> {
OofItemStyle::grid_column(self)
}
#[inline(always)]
fn align_self(&self) -> Option<AlignSelf> {
unpack_align_self(self.align_self_u8)
}
#[inline(always)]
fn justify_self(&self) -> Option<AlignSelf> {
self.extra.as_ref().and_then(|s| s.justify_self)
}
}
impl BlockContainerStyle for CompactStyle {
#[inline(always)]
fn text_align(&self) -> TextAlign {
self.extra.as_ref().map_or(TextAlign::Auto, |s| s.text_align)
}
#[inline(always)]
fn align_content(&self) -> AlignContent {
unpack_align_content(self.align_content_u8)
}
#[inline(always)]
fn justify_items(&self) -> AlignItems {
self.extra.as_ref().map_or(AlignItems::NORMAL, |s| s.justify_items)
}
}
impl BlockItemStyle for CompactStyle {
#[inline(always)]
fn is_table(&self) -> bool {
self.extra.as_ref().is_some_and(|s| s.item_is_table)
}
#[inline(always)]
fn align_self(&self) -> Option<AlignSelf> {
unpack_align_self(self.align_self_u8)
}
#[inline(always)]
fn justify_self(&self) -> Option<AlignSelf> {
self.extra.as_ref().and_then(|s| s.justify_self)
}
}
+915
View File
@@ -0,0 +1,915 @@
use crate::prelude::*;
use crate::{
BaselineLayoutStore, BaselineTaffyTree, BoxLayout, CompactCache, CompactStyle, LayoutStore, SlotId,
baseline_storage_stats,
};
use core::mem::size_of;
use taffy::geometry::{Line, Point, Rect, Size};
use taffy::style::{AvailableSpace, CoreStyle, FlexboxContainerStyle, FlexboxItemStyle, Overflow};
use taffy::tree::{Baselines, CollapsibleMarginSet, LayoutInput, LayoutOutput, RequestedAxis, RunMode, SizingMode};
#[test]
fn compact_types_stay_within_size_budgets() {
assert_eq!(size_of::<CompactStyle>(), 64);
assert_eq!(size_of::<CompactCache>(), 96);
assert_eq!(size_of::<BoxLayout>(), 32);
}
#[test]
fn compact_style_round_trips_all_length_variants() {
let hot_dims = [
Dimension::auto(),
Dimension::ZERO,
Dimension::length(42.5),
Dimension::percent(0.375),
Dimension::max_content(),
];
for &w in &hot_dims {
for &h in &hot_dims {
let s = Style {
display: Display::Flex,
position: Position::Relative,
flex_direction: FlexDirection::ColumnReverse,
flex_wrap: FlexWrap::Wrap,
overflow: Point { x: Overflow::Hidden, y: Overflow::Scroll },
size: Size { width: w, height: h },
min_size: Size { width: length(10.0), height: percent(0.25) },
max_size: Size { width: auto(), height: length(500.0) },
padding: Rect {
left: length(4.0),
right: percent(0.125),
top: length(8.0),
bottom: length(12.0),
},
gap: Size { width: length(6.0), height: percent(0.25) },
flex_basis: Dimension::ZERO,
flex_grow: 1.5,
flex_shrink: 0.25,
align_items: AlignItems::CENTER,
align_self: Some(AlignSelf::FLEX_END),
justify_content: JustifyContent::SPACE_BETWEEN,
align_content: AlignContent::STRETCH,
..Style::DEFAULT
};
let compact = CompactStyle::from_style(s.clone());
assert_eq!(compact.heap_bytes(), 0, "hot Rune style should stay 100% inline in 64 bytes");
assert!(compact == s);
assert_eq!(compact.to_style(), s);
}
}
let all_dims = [
Dimension::auto(),
Dimension::ZERO,
Dimension::length(42.5),
Dimension::percent(0.375),
Dimension::min_content(),
Dimension::max_content(),
Dimension::fit_content_px(120.0),
Dimension::fit_content_percent(0.8),
];
for &w in &all_dims {
for &h in &all_dims {
let s = Style {
display: Display::Flex,
position: Position::Relative,
flex_direction: FlexDirection::ColumnReverse,
flex_wrap: FlexWrap::Wrap,
overflow: Point { x: Overflow::Hidden, y: Overflow::Scroll },
size: Size { width: w, height: h },
min_size: Size { width: length(10.0), height: percent(0.25) },
max_size: Size { width: auto(), height: length(500.0) },
padding: Rect {
left: length(4.0),
right: percent(0.1),
top: length(8.0),
bottom: length(12.0),
},
gap: Size { width: length(6.0), height: percent(0.05) },
flex_basis: w,
flex_grow: 1.5,
flex_shrink: 0.25,
aspect_ratio: Some(1.75),
align_items: AlignItems::CENTER,
align_self: Some(AlignSelf::FLEX_END),
justify_content: JustifyContent::SPACE_BETWEEN,
align_content: AlignContent::STRETCH,
..Style::DEFAULT
};
let compact = CompactStyle::from_style(s.clone());
assert!(compact == s);
assert_eq!(compact.to_style(), s);
assert_eq!(CoreStyle::size(&compact), s.size);
assert_eq!(CoreStyle::min_size(&compact), s.min_size);
assert_eq!(CoreStyle::max_size(&compact), s.max_size);
assert_eq!(CoreStyle::padding(&compact), s.padding);
assert_eq!(FlexboxContainerStyle::gap(&compact), s.gap);
assert_eq!(FlexboxItemStyle::flex_basis(&compact), s.flex_basis);
}
}
}
#[test]
fn compact_cache_preserves_second_chance_and_overflow_semantics() {
let make_input = |w: f32| LayoutInput {
run_mode: RunMode::ComputeSize,
sizing_mode: SizingMode::InherentSize,
axis: RequestedAxis::Both,
known_dimensions: Size { width: Some(w), height: None },
known_dimensions_are_definite: Size { width: true, height: true },
parent_size: Size::NONE,
available_space: Size { width: AvailableSpace::MaxContent, height: AvailableSpace::MaxContent },
vertical_margins_are_collapsible: Line::FALSE,
};
let make_out = |w: f32| LayoutOutput::from_outer_size(Size { width: w, height: w * 2.0 });
let mut cache = CompactCache::new();
cache.store(&make_input(0.0), make_out(0.0));
cache.store(&make_input(1.0), make_out(1.0));
assert_eq!(cache.heap_bytes(), 0);
for w in 2..9 {
cache.store(&make_input(w as f32), make_out(w as f32));
}
assert!(cache.heap_bytes() > 0);
cache.store(&make_input(9.0), make_out(9.0));
assert_eq!(cache.get(&make_input(1.0)), Some(make_out(1.0)));
cache.store(&make_input(10.0), make_out(10.0));
assert_eq!(cache.get(&make_input(1.0)), Some(make_out(1.0)));
assert_eq!(cache.get(&make_input(2.0)), None);
let mut collapse = make_out(99.0);
collapse.top_margin = CollapsibleMarginSet::from_margin(8.0);
cache.store(&make_input(99.0), collapse);
assert_eq!(cache.get(&make_input(99.0)), None);
}
#[test]
fn compact_style_setters_match_taffy_style() {
for dir in [
FlexDirection::Row,
FlexDirection::Column,
FlexDirection::RowReverse,
FlexDirection::ColumnReverse,
] {
let mut cs = CompactStyle::rune_base(dir);
let mut ts = Style {
display: Display::Flex,
flex_direction: dir,
flex_shrink: 0.0,
position: Position::Relative,
..Style::DEFAULT
};
assert_eq!(cs.to_style(), ts);
assert_eq!(cs, CompactStyle::from_style(ts.clone()));
cs.set_width(percent(1.0));
ts.size.width = percent(1.0);
cs.set_height(length(48.5));
ts.size.height = length(48.5);
cs.set_min_width(length(0.0));
ts.min_size.width = length(0.0);
cs.set_max_height(length(240.0));
ts.max_size.height = length(240.0);
cs.set_padding_all(12.0);
ts.padding = Rect { left: length(12.0), right: length(12.0), top: length(12.0), bottom: length(12.0) };
cs.set_pad_left(6.0);
ts.padding.left = length(6.0);
cs.set_gap(8.0, 4.0);
ts.gap = Size { width: length(8.0), height: length(4.0) };
cs.set_grow(1.5);
ts.flex_grow = 1.5;
ts.flex_shrink = 1.0;
ts.flex_basis = length(0.0);
cs.set_flex_wrap(FlexWrap::Wrap);
ts.flex_wrap = FlexWrap::Wrap;
cs.set_overflow(Overflow::Hidden, Overflow::Scroll);
ts.overflow = Point { x: Overflow::Hidden, y: Overflow::Scroll };
cs.set_align_items(AlignItems::CENTER);
ts.align_items = AlignItems::CENTER;
cs.set_align_self(Some(AlignSelf::STRETCH));
ts.align_self = Some(AlignSelf::STRETCH);
cs.set_justify_content(JustifyContent::SPACE_BETWEEN);
ts.justify_content = JustifyContent::SPACE_BETWEEN;
assert_eq!(cs.heap_bytes(), 0, "hot setters should stay inline");
assert_eq!(cs.to_style(), ts);
assert_eq!(cs, CompactStyle::from_style(ts.clone()));
cs.set_aspect_ratio(Some(1.75));
ts.aspect_ratio = Some(1.75);
assert_eq!(cs.to_style(), ts);
cs.set_aspect_ratio(None);
ts.aspect_ratio = None;
assert_eq!(cs.heap_bytes(), 0, "clearing last cold field drops extra Box");
assert_eq!(cs.to_style(), ts);
}
for pos in [Position::Static, Position::Relative, Position::Absolute] {
let s = Style { position: pos, ..Style::DEFAULT };
let c = CompactStyle::from_style(s.clone());
assert_eq!(c.position(), pos);
assert_eq!(c.to_style(), s);
}
}
#[test]
fn a_taken_box_placement_keeps_the_overflow_on_the_wrapper() {
for cold in [false, true] {
let mut cs = CompactStyle::rune_base(FlexDirection::Column);
cs.set_overflow(Overflow::Hidden, Overflow::Scroll);
if cold {
cs.set_aspect_ratio(Some(2.0));
}
let outer = cs.take_box_placement();
assert_eq!(outer.overflow(), Point { x: Overflow::Hidden, y: Overflow::Scroll }, "cold {cold}");
assert_eq!(cs.overflow(), Point { x: Overflow::Hidden, y: Overflow::Scroll }, "cold {cold}");
}
}
#[derive(Clone)]
struct SpecNode {
key: u64,
style: Style,
leaf: Option<(u64, f32, f32, f32)>, // (measure_hash, intrinsic_w, line_h, baseline)
children: Vec<SpecNode>,
}
struct CommitEntry {
key: u64,
parent: Option<usize>,
comp_slot: SlotId,
base_slot: SlotId,
leaf: Option<(f32, f32, f32)>,
}
fn sync_pair(
spec: &SpecNode,
parent: Option<usize>,
comp: &mut LayoutStore,
base: &mut BaselineLayoutStore,
out: &mut Vec<CommitEntry>,
) -> (SlotId, bool, SlotId) {
let me = out.len();
out.push(CommitEntry {
key: spec.key,
parent,
comp_slot: SlotId(0),
base_slot: SlotId(0),
leaf: spec.leaf.map(|(_, w, h, b)| (w, h, b)),
});
let c_mark = comp.begin_children();
let b_mark = base.begin_children();
let mut kids_dirty = false;
let mut c_kids = Vec::with_capacity(spec.children.len());
let mut b_kids = Vec::with_capacity(spec.children.len());
for child in &spec.children {
let (cs, cd, bs) = sync_pair(child, Some(me), comp, base, out);
kids_dirty |= cd;
c_kids.push(cs);
b_kids.push(bs);
}
for cs in c_kids {
comp.push_child(cs);
}
for bs in b_kids {
base.push_child(bs);
}
let measure = spec.leaf.map(|(h, ..)| h);
let cs_style = CompactStyle::from_style(spec.style.clone());
let (c_slot, dirty) = comp.sync_node(spec.key, me as u32, cs_style.clone(), measure, false, c_mark, kids_dirty);
let (b_slot, _) = base.sync_node(spec.key, me as u32, cs_style, measure, false, b_mark, kids_dirty);
out[me].comp_slot = c_slot;
out[me].base_slot = b_slot;
(c_slot, dirty, b_slot)
}
fn commit_and_assert_parity(
root: &SpecNode,
room: Size<AvailableSpace>,
comp: &mut LayoutStore,
base: &mut BaselineLayoutStore,
) -> (Vec<CommitEntry>, Vec<u64>, Vec<u64>) {
comp.begin_commit();
base.begin_commit();
let mut entries = Vec::new();
let (mut c_root, _, mut b_root) = sync_pair(root, None, comp, base, &mut entries);
comp.end_commit(&mut c_root, |me, slot| entries[me as usize].comp_slot = slot);
base.end_commit(&mut b_root, |me, slot| entries[me as usize].base_slot = slot);
assert_eq!(comp.live_count(), entries.len());
assert_eq!(base.live_count(), entries.len());
let eval_leaf = |inputs: LayoutInput, ctx: Option<usize>, style: &CompactStyle, log: &mut Vec<u64>| {
let mut baselines = Baselines::NONE;
let mut out = taffy::compute_leaf_layout(inputs, style, |_, _| 0.0, |known, avail| {
let Some(i) = ctx else { return Size::ZERO };
log.push(entries[i].key);
let (full_w, line_h, baseline) = entries[i].leaf.expect("ctx must point to measured leaf");
let max_w = known.width.or(match avail.width {
AvailableSpace::Definite(w) => Some(w),
AvailableSpace::MinContent => Some((full_w * 0.25).max(20.0)),
AvailableSpace::MaxContent => None,
});
let (w, lines) = match max_w {
Some(limit) if full_w > limit && limit > 0.0 => (limit, (full_w / limit).ceil().max(1.0)),
_ => (full_w, 1.0),
};
if baseline > 0.0 {
baselines = Baselines { first: Some(baseline), last: Some((lines - 1.0) * line_h + baseline) };
}
Size {
width: known.width.unwrap_or(w),
height: known.height.unwrap_or(lines * line_h),
}
});
out.baselines = baselines;
out
};
let mut c_log = Vec::new();
let mut b_log = Vec::new();
comp.compute_layout(c_root, room, |inputs, ctx, style| eval_leaf(inputs, ctx, style, &mut c_log));
base.compute_layout(b_root, room, |inputs, ctx, style| eval_leaf(inputs, ctx, style, &mut b_log));
for (i, e) in entries.iter().enumerate() {
assert_eq!(
comp.box_layout(e.comp_slot),
base.box_layout(e.base_slot),
"BoxLayout mismatch at entry {i} (key={})",
e.key
);
}
(entries, c_log, b_log)
}
#[test]
fn differential_flex_grid_oof_scroll_text_baselines_reorder_and_removal() {
let mut comp = LayoutStore::new();
let mut base = BaselineLayoutStore::new();
let text_style = Style {
flex_shrink: 1.0,
min_size: Size { width: length(0.0), height: auto() },
max_size: Size { width: length(180.0), height: length(100.0) },
..Style::DEFAULT
};
let build_scene = |reordered: bool, scaled: bool, removed: bool| {
let t1 = SpecNode {
key: 11,
style: text_style.clone(),
leaf: Some(if scaled { (2, 310.0, 20.0, 15.5) } else { (1, 240.0, 18.0, 14.0) }),
children: vec![],
};
let t2 = SpecNode {
key: 12,
style: text_style.clone(),
leaf: Some((3, 95.5, 22.0, 17.0)),
children: vec![],
};
let flex_row = SpecNode {
key: 10,
style: Style {
display: Display::Flex,
flex_direction: FlexDirection::Row,
flex_wrap: FlexWrap::Wrap,
align_items: AlignItems::BASELINE,
gap: Size { width: length(8.25), height: length(4.5) },
padding: Rect { left: length(10.5), right: length(10.5), top: length(6.25), bottom: length(6.25) },
..Style::DEFAULT
},
leaf: None,
children: if reordered { vec![t2, t1] } else { vec![t1, t2] },
};
let mut grid_kids = vec![SpecNode {
key: 21,
style: Style {
grid_column: Line { start: line(1), end: span(2) },
grid_row: Line { start: line(1), end: span(1) },
size: Size { width: auto(), height: length(28.5) },
..Style::DEFAULT
},
leaf: None,
children: vec![],
}];
if !removed {
grid_kids.push(SpecNode {
key: 22,
style: Style {
grid_column: Line { start: line(3), end: span(1) },
grid_row: Line { start: line(1), end: span(1) },
aspect_ratio: Some(1.5),
..Style::DEFAULT
},
leaf: None,
children: vec![],
});
}
let grid = SpecNode {
key: 20,
style: Style {
display: Display::Grid,
grid_template_columns: vec![fr(1.0), fr(2.0), minmax(length(40.0), fr(1.0))],
gap: Size { width: length(6.0), height: length(6.0) },
size: Size { width: percent(1.0), height: auto() },
..Style::DEFAULT
},
leaf: None,
children: grid_kids,
};
let scroll = SpecNode {
key: 30,
style: Style {
display: Display::Flex,
flex_direction: FlexDirection::Column,
position: Position::Relative,
overflow: Point { x: Overflow::Hidden, y: Overflow::Scroll },
flex_grow: 1.0,
flex_shrink: 1.0,
flex_basis: length(0.0),
min_size: Size { width: length(0.0), height: length(0.0) },
..Style::DEFAULT
},
leaf: None,
children: vec![
SpecNode {
key: 31,
style: Style { size: Size { width: percent(1.0), height: length(420.0) }, flex_shrink: 0.0, ..Style::DEFAULT },
leaf: None,
children: vec![],
},
SpecNode {
key: 32,
style: Style {
position: Position::Absolute,
inset: Rect { left: length(12.25), top: length(8.75), right: auto(), bottom: auto() },
size: Size { width: length(64.0), height: length(24.0) },
..Style::DEFAULT
},
leaf: None,
children: vec![],
},
],
};
SpecNode {
key: 1,
style: Style {
display: Display::Flex,
flex_direction: FlexDirection::Column,
position: Position::Relative,
size: Size { width: length(360.0), height: length(240.0) },
gap: Size { width: length(0.0), height: length(8.0) },
..Style::DEFAULT
},
leaf: None,
children: vec![flex_row, grid, scroll],
}
};
let room = Size {
width: AvailableSpace::Definite(360.0),
height: AvailableSpace::Definite(240.0),
};
let (_, c1, b1) = commit_and_assert_parity(&build_scene(false, false, false), room, &mut comp, &mut base);
assert_eq!(c1, b1);
let (_, c2, b2) = commit_and_assert_parity(&build_scene(true, true, true), room, &mut comp, &mut base);
assert_eq!(c2, b2);
}
#[test]
fn large_to_small_swap_shrinks_retained_memory_and_matches_baseline() {
let mut comp = LayoutStore::new();
let mut base = BaselineLayoutStore::new();
let make_list = |rows: usize| {
let mut children = Vec::with_capacity(rows);
for i in 0..rows {
let base_key = 100 + (i as u64) * 10;
children.push(SpecNode {
key: base_key,
style: Style {
display: Display::Flex,
flex_direction: FlexDirection::Row,
size: Size { width: percent(1.0), height: length(32.0) },
..Style::DEFAULT
},
leaf: None,
children: vec![
SpecNode {
key: base_key + 1,
style: Style { size: Size { width: length(120.0), height: length(18.0) }, ..Style::DEFAULT },
leaf: Some((i as u64 + 1, 120.0, 18.0, 14.0)),
children: vec![],
},
SpecNode {
key: base_key + 2,
style: Style { size: Size { width: length(20.0), height: length(20.0) }, ..Style::DEFAULT },
leaf: None,
children: vec![],
},
],
});
}
SpecNode {
key: 1,
style: Style {
display: Display::Flex,
flex_direction: FlexDirection::Column,
size: Size { width: length(1000.0), height: length(900.0) },
..Style::DEFAULT
},
leaf: None,
children,
}
};
let room = Size {
width: AvailableSpace::Definite(1000.0),
height: AvailableSpace::Definite(900.0),
};
commit_and_assert_parity(&make_list(500), room, &mut comp, &mut base);
let b_stats_500 = base.storage_stats();
let c_stats_500 = comp.storage_stats();
assert!(
c_stats_500.total_retained_bytes * 2 < b_stats_500.total_retained_bytes,
"expected >50% reduction at 500 rows: compact={} vs baseline={}",
c_stats_500.total_retained_bytes,
b_stats_500.total_retained_bytes
);
commit_and_assert_parity(&make_list(10), room, &mut comp, &mut base);
let b_stats_10 = base.storage_stats();
let c_stats_10 = comp.storage_stats();
assert!(
c_stats_10.slot_capacity <= 64,
"LayoutStore slot capacity should shrink after 500->10 swap, got {}",
c_stats_10.slot_capacity
);
assert!(
c_stats_10.total_retained_bytes * 10 < b_stats_10.total_retained_bytes,
"expected >90% reduction after 500->10 swap: compact={} vs baseline={}",
c_stats_10.total_retained_bytes,
b_stats_10.total_retained_bytes
);
}
#[test]
fn differential_hoisted_oof_aspect_fit_anchored_fit_and_cache_hits() {
let mut comp = LayoutStore::new();
let mut base = BaselineLayoutStore::new();
let scene = SpecNode {
key: 1,
style: Style {
display: Display::Flex,
flex_direction: FlexDirection::Column,
position: Position::Relative,
size: Size { width: length(400.0), height: length(300.0) },
..Style::DEFAULT
},
leaf: None,
children: vec![
SpecNode {
key: 10,
style: Style {
display: Display::Flex,
position: Position::Static,
padding: Rect { left: length(7.25), right: length(7.25), top: length(5.5), bottom: length(5.5) },
..Style::DEFAULT
},
leaf: None,
children: vec![SpecNode {
key: 11,
style: Style {
position: Position::Absolute,
inset: Rect { left: auto(), right: length(14.5), top: length(9.25), bottom: auto() },
size: Size { width: length(88.0), height: length(36.0) },
..Style::DEFAULT
},
leaf: None,
children: vec![],
}],
},
SpecNode {
key: 20,
style: Style {
flex_grow: 1.0,
size: Size { width: percent(1.0), height: auto() },
..Style::DEFAULT
},
leaf: None,
children: vec![],
},
SpecNode {
key: 30,
style: Style {
position: Position::Absolute,
inset: Rect { left: length(0.0), top: length(0.0), right: auto(), bottom: auto() },
size: Size { width: length(160.0), height: auto() },
..Style::DEFAULT
},
leaf: None,
children: vec![SpecNode {
key: 31,
style: Style { size: Size { width: percent(1.0), height: auto() }, ..Style::DEFAULT },
leaf: Some((99, 160.0, 320.0, 0.0)),
children: vec![],
}],
},
],
};
let room = Size {
width: AvailableSpace::Definite(400.0),
height: AvailableSpace::Definite(300.0),
};
let (_, c_cold, b_cold) = commit_and_assert_parity(&scene, room, &mut comp, &mut base);
assert!(!c_cold.is_empty());
assert_eq!(c_cold, b_cold, "measure call count mismatch on cold pass");
// Warm commit with zero changes hits root cache (0 leaf measurements).
let (entries, c_warm, b_warm) = commit_and_assert_parity(&scene, room, &mut comp, &mut base);
assert!(c_warm.is_empty());
assert!(b_warm.is_empty());
// Pass 2 intra-commit refit: clamp `aspect_fit` (key 20) to 16:9 and `anchored_fit` (key 30) max_size.height.
let aspect_idx = entries.iter().position(|e| e.key == 20).unwrap();
let ov_idx = entries.iter().position(|e| e.key == 30).unwrap();
let room_sz = comp.box_layout(entries[aspect_idx].comp_slot).size();
let fit_w = room_sz.width.min(room_sz.height * (16.0 / 9.0));
let fit_h = fit_w / (16.0 / 9.0);
let fitted = CompactStyle::from_style(Style {
size: Size { width: length(fit_w), height: length(fit_h) },
flex_shrink: 0.0,
..Style::DEFAULT
});
comp.set_style_and_mark_ancestors(
entries[aspect_idx].comp_slot,
fitted.clone(),
core::iter::successors(entries[aspect_idx].parent, |&p| entries[p].parent).map(|p| entries[p].comp_slot),
);
base.set_style_and_mark_ancestors(
entries[aspect_idx].base_slot,
fitted,
core::iter::successors(entries[aspect_idx].parent, |&p| entries[p].parent).map(|p| entries[p].base_slot),
);
let mut ov_style = comp.style(entries[ov_idx].comp_slot).clone();
ov_style.set_max_height(length(180.0));
comp.set_style_and_mark_ancestors(
entries[ov_idx].comp_slot,
ov_style.clone(),
core::iter::successors(entries[ov_idx].parent, |&p| entries[p].parent).map(|p| entries[p].comp_slot),
);
base.set_style_and_mark_ancestors(
entries[ov_idx].base_slot,
ov_style,
core::iter::successors(entries[ov_idx].parent, |&p| entries[p].parent).map(|p| entries[p].base_slot),
);
let mut c_pass2 = 0usize;
let mut b_pass2 = 0usize;
comp.compute_layout(entries[0].comp_slot, room, |inputs, _ctx, style| {
taffy::compute_leaf_layout(inputs, style, |_, _| 0.0, |known, _| {
c_pass2 += 1;
Size { width: known.width.unwrap_or(160.0), height: known.height.unwrap_or(320.0) }
})
});
base.compute_layout(entries[0].base_slot, room, |inputs, _ctx, style| {
taffy::compute_leaf_layout(inputs, style, |_, _| 0.0, |known, _| {
b_pass2 += 1;
Size { width: known.width.unwrap_or(160.0), height: known.height.unwrap_or(320.0) }
})
});
assert_eq!(c_pass2, b_pass2, "measure call count mismatch after aspect_fit + anchored_fit refit");
for (i, e) in entries.iter().enumerate() {
assert_eq!(comp.box_layout(e.comp_slot), base.box_layout(e.base_slot), "refit mismatch at {i}");
}
}
#[test]
fn layout_store_carries_cache_across_commits_and_matches_upstream_bit_for_bit() {
let make_row = |id_base: u64, text_w: f32, hash: u64| SpecNode {
key: id_base,
style: Style {
display: Display::Flex,
flex_direction: FlexDirection::Row,
flex_shrink: 0.0,
position: Position::Relative,
size: Size { width: percent(1.0), height: auto() },
padding: Rect { left: length(8.0), right: length(8.0), top: length(4.0), bottom: length(4.0) },
gap: Size { width: length(6.0), height: length(0.0) },
align_items: AlignItems::CENTER,
..Style::DEFAULT
},
leaf: None,
children: vec![
SpecNode {
key: id_base + 1,
style: Style { size: Size { width: length(16.0), height: length(16.0) }, flex_shrink: 0.0, ..Style::DEFAULT },
leaf: None,
children: vec![],
},
SpecNode {
key: id_base + 2,
style: Style {
flex_grow: 1.0,
flex_shrink: 1.0,
flex_basis: length(0.0),
min_size: Size { width: length(0.0), height: auto() },
..Style::DEFAULT
},
leaf: Some((hash, text_w, 16.0, 0.0)),
children: vec![],
},
],
};
let make_tree = |rows: Vec<SpecNode>, vp_w: f32| {
let grid_header = SpecNode {
key: 10,
style: Style {
display: Display::Grid,
position: Position::Relative,
size: Size { width: percent(1.0), height: auto() },
gap: Size { width: length(8.0), height: length(4.0) },
grid_template_columns: vec![fr(1.0), fr(2.0)],
..Style::DEFAULT
},
leaf: None,
children: vec![
SpecNode {
key: 11,
style: Style { size: Size { width: auto(), height: length(24.0) }, ..Style::DEFAULT },
leaf: None,
children: vec![],
},
SpecNode {
key: 12,
style: Style { size: Size { width: auto(), height: length(24.0) }, ..Style::DEFAULT },
leaf: Some((999, 180.0, 18.0, 0.0)),
children: vec![],
},
SpecNode {
key: 13,
style: Style {
position: Position::Absolute,
inset: Rect { left: auto(), top: length(2.0), right: length(4.0), bottom: auto() },
size: Size { width: length(20.0), height: length(12.0) },
..Style::DEFAULT
},
leaf: None,
children: vec![],
},
],
};
let static_oof = SpecNode {
key: 20,
style: Style { position: Position::Static, size: Size { width: percent(1.0), height: length(10.0) }, ..Style::DEFAULT },
leaf: None,
children: vec![SpecNode {
key: 21,
style: Style {
position: Position::Absolute,
inset: Rect { left: length(12.0), top: auto(), right: length(12.0), bottom: length(6.0) },
size: Size { width: auto(), height: length(18.0) },
..Style::DEFAULT
},
leaf: None,
children: vec![],
}],
};
let hidden = SpecNode {
key: 30,
style: Style { display: Display::None, size: Size { width: length(90.0), height: length(90.0) }, ..Style::DEFAULT },
leaf: None,
children: vec![make_row(31, 100.0, 31)],
};
let mut children = vec![grid_header, static_oof, hidden];
children.extend(rows);
SpecNode {
key: 1,
style: Style {
display: Display::Flex,
flex_direction: FlexDirection::Column,
position: Position::Relative,
size: Size { width: length(vp_w), height: length(500.0) },
padding: Rect { left: length(10.0), right: length(10.0), top: length(8.0), bottom: length(8.0) },
gap: Size { width: length(0.0), height: length(4.0) },
..Style::DEFAULT
},
leaf: None,
children,
}
};
let mut comp = LayoutStore::new();
let mut base = BaselineLayoutStore::new();
let room = |vp_w: f32| Size {
width: AvailableSpace::Definite(vp_w),
height: AvailableSpace::Definite(500.0),
};
let rows_1: Vec<SpecNode> = (0..8).map(|i| make_row(100 + i * 10, 220.0 + (i as f32) * 35.0, 1000 + i)).collect();
// Commit 1 (Cold): measures leaves and matches BaselineLayoutStore bit-for-bit.
let (entries_1, keys_1, _) = commit_and_assert_parity(&make_tree(rows_1.clone(), 360.0), room(360.0), &mut comp, &mut base);
assert!(keys_1.len() >= 9);
let mut raw_base = BaselineTaffyTree::<usize>::new();
let raw_leaf = raw_base.new_leaf(Style::DEFAULT).unwrap();
let base_bytes = baseline_storage_stats(&raw_base, Some(raw_leaf), entries_1.len()).total_retained_bytes;
assert!(comp.storage_stats().total_retained_bytes * 2 < base_bytes);
// Commit 2 (Warm identical): hits root cache — 0 leaf measurements!
let (_, keys_2, _) = commit_and_assert_parity(&make_tree(rows_1.clone(), 360.0), room(360.0), &mut comp, &mut base);
assert!(keys_2.is_empty(), "warm commit with no changes must invoke measure 0 times");
// Commit 3 (Insert row 90 at front — shifts every existing row's `me` index by +3!):
let mut rows_3 = vec![make_row(90, 310.0, 9999)];
rows_3.extend(rows_1);
let (_, keys_3, _) = commit_and_assert_parity(&make_tree(rows_3.clone(), 360.0), room(360.0), &mut comp, &mut base);
assert!(!keys_3.is_empty());
assert!(keys_3.iter().all(|&k| k == 92), "only newly inserted row leaf (key=92) may measure; got {keys_3:?}");
// Commit 4 (Narrow viewport width from 360 -> 280 after index shift):
let (_, keys_4, _) = commit_and_assert_parity(&make_tree(rows_3.clone(), 280.0), room(280.0), &mut comp, &mut base);
assert!(keys_4.len() >= 9, "narrowed viewport must re-measure shifted leaves");
// Commit 5 (Remove 3 rows, reorder remaining rows, insert 2 new rows recycling freed slots, mutate 1 leaf hash):
let mut rows_5 = vec![
rows_3[5].clone(),
make_row(500, 410.0, 5001),
rows_3[2].clone(),
make_row(510, 145.0, 5002),
rows_3[0].clone(),
];
rows_5[2].children[1].leaf = Some((77777, 480.0, 16.0, 0.0));
let (_, keys_5, _) = commit_and_assert_parity(&make_tree(rows_5, 280.0), room(280.0), &mut comp, &mut base);
assert!(keys_5.contains(&502) && keys_5.contains(&512) && keys_5.contains(&112));
assert!(!keys_5.contains(&92) && !keys_5.contains(&142), "unchanged reordered rows must hit cache");
}
#[test]
fn memo_reuse_and_retry_mutation_guard_match_baseline() {
let mut comp = LayoutStore::new();
let mut base = BaselineLayoutStore::new();
// Commit 1 (applied): create slot for key 10 with width 120.
comp.begin_commit();
base.begin_commit();
let mut s1 = CompactStyle::rune_base(FlexDirection::Row);
s1.set_width(length(120.0));
s1.set_height(length(40.0));
let m_c = comp.begin_children();
let (slot_c, _) = comp.sync_node(10, 0, s1.clone(), None, false, m_c, false);
comp.finish_flatten();
comp.compact_if_sparse(|_, _| {});
let m_b = base.begin_children();
let (slot_b, _) = base.sync_node(10, 0, s1.clone(), None, false, m_b, false);
base.finish_flatten();
base.compact_if_sparse(|_, _| {});
// Commit 2, Pass 1 (discarded before apply): key 10 temporarily mutates to width 300.
comp.begin_commit();
base.begin_commit();
assert!(comp.can_reuse(10, slot_c));
assert!(base.can_reuse(10, slot_b));
let mut s_tmp = CompactStyle::rune_base(FlexDirection::Row);
s_tmp.set_width(length(300.0));
s_tmp.set_height(length(40.0));
let m_c = comp.begin_children();
comp.sync_node(10, 0, s_tmp.clone(), None, false, m_c, false);
comp.finish_flatten();
let m_b = base.begin_children();
base.sync_node(10, 0, s_tmp, None, false, m_b, false);
base.finish_flatten();
// Commit 2, Pass 2 (retry without apply): `can_reuse` must reject `slot` because Pass 1 mutated it!
comp.begin_commit();
base.begin_commit();
assert!(!comp.can_reuse(10, slot_c), "mutated slot must not be reused across intra-commit retry");
assert!(!base.can_reuse(10, slot_b), "baseline store must match retry mutation guard");
// Normal flatten restores `s1` and applies.
let m_c = comp.begin_children();
comp.sync_node(10, 0, s1.clone(), None, false, m_c, false);
comp.finish_flatten();
comp.compact_if_sparse(|_, _| {});
let m_b = base.begin_children();
base.sync_node(10, 0, s1, None, false, m_b, false);
base.finish_flatten();
base.compact_if_sparse(|_, _| {});
// Commit 3: clean slot is reusable again and can rekey cleanly to key 20.
comp.begin_commit();
base.begin_commit();
assert!(comp.can_reuse(10, slot_c));
assert!(base.can_reuse(10, slot_b));
comp.rekey_and_reuse_batch(core::iter::once((10, 20, slot_c, 3)));
base.rekey_and_reuse_batch(core::iter::once((10, 20, slot_b, 3)));
assert_eq!(comp.mounted_node_index(20), Some(3));
assert_eq!(base.mounted_node_index(20), Some(3));
assert_eq!(comp.mounted_node_index(10), None);
assert_eq!(base.mounted_node_index(10), None);
}
+297
View File
@@ -0,0 +1,297 @@
//! Low-level Taffy 0.15 solver trait implementations over [`LayoutStore`].
use taffy::compute::{
compute_block_layout, compute_cached_layout, compute_flexbox_layout, compute_grid_layout, compute_hidden_layout,
compute_oof_layout,
};
use taffy::style::{CoreStyle, Display, Style};
use taffy::tree::{
DetailedLayoutInfo, Layout, LayoutBlockContainer, LayoutContainingBlock, LayoutFlexboxContainer,
LayoutGridContainer, LayoutInput, LayoutOutput, LayoutPartialTree, NodeId, RunMode, TraversePartialTree,
TraverseTree,
};
use taffy::{BlockContext, CacheTree, DetailedGridInfo};
use crate::store::{BoxLayout, LayoutStore, RetainedSlot, SlotChildIter};
use crate::style::CompactStyle;
const NONE_DETAIL: DetailedLayoutInfo = DetailedLayoutInfo::None;
pub(crate) struct LayoutStoreView<'s, F>
where
F: FnMut(LayoutInput, Option<usize>, &CompactStyle) -> LayoutOutput,
{
pub(crate) store: &'s mut LayoutStore,
pub(crate) measure_leaf: F,
}
impl<F> LayoutStoreView<'_, F>
where
F: FnMut(LayoutInput, Option<usize>, &CompactStyle) -> LayoutOutput,
{
#[inline(always)]
fn slot(&self, node_id: NodeId) -> &RetainedSlot {
let idx = u64::from(node_id) as usize;
debug_assert!(idx < self.store.slots.len());
// SAFETY: all `NodeId`s in `curr_children` and `root` are allocated indices into `slots`.
unsafe { self.store.slots.get_unchecked(idx) }
}
#[inline(always)]
fn slot_mut(&mut self, node_id: NodeId) -> &mut RetainedSlot {
let idx = u64::from(node_id) as usize;
debug_assert!(idx < self.store.slots.len());
// SAFETY: all `NodeId`s in `curr_children` and `root` are allocated indices into `slots`.
unsafe { self.store.slots.get_unchecked_mut(idx) }
}
#[inline(always)]
fn compute_child_layout_inner(
&mut self,
node_id: NodeId,
inputs: LayoutInput,
block_ctx: Option<&mut BlockContext<'_>>,
) -> LayoutOutput {
if inputs.run_mode == RunMode::PerformHiddenLayout {
self.slot_mut(node_id).box_layout = BoxLayout::ZERO;
return compute_hidden_layout(self, node_id);
}
compute_cached_layout(self, node_id, inputs, |view, node_id, inputs| {
let idx = u64::from(node_id) as usize;
// SAFETY: `node_id` is a live `SlotId` index into `slots`.
let (display_mode, has_children) = unsafe {
let s = view.store.slots.get_unchecked(idx);
(s.style.display(), s.child_len() != 0)
};
let mut output = match (display_mode, has_children) {
(Display::None, _) => compute_hidden_layout(view, node_id),
(Display::Block, true) => compute_block_layout(view, node_id, inputs, block_ctx),
(Display::FlowRoot, true) => compute_block_layout(view, node_id, inputs, None),
(Display::Flex, true) => compute_flexbox_layout(view, node_id, inputs),
(Display::Grid, true) => compute_grid_layout(view, node_id, inputs),
(_, false) => {
// SAFETY: `idx` is in bounds of both `slots` and `node_idx`.
let (ctx, style) = unsafe {
let s = view.store.slots.get_unchecked(idx);
let ctx = s
.has_context()
.then(|| *view.store.node_idx.get_unchecked(idx) as usize);
(ctx, &s.style)
};
(view.measure_leaf)(inputs, ctx, style)
}
};
if inputs.run_mode == RunMode::PerformLayout {
compute_oof_layout(view, node_id, &mut output);
}
output
})
}
}
impl<F> TraversePartialTree for LayoutStoreView<'_, F>
where
F: FnMut(LayoutInput, Option<usize>, &CompactStyle) -> LayoutOutput,
{
type ChildIter<'a>
= SlotChildIter<'a>
where
Self: 'a;
#[inline(always)]
fn child_ids(&self, parent_node_id: NodeId) -> Self::ChildIter<'_> {
let s = self.slot(parent_node_id);
let start = s.child_start as usize;
let end = start + s.child_len() as usize;
// SAFETY: `child_start..child_start + child_len` was appended to `curr_children` this commit.
SlotChildIter(unsafe { self.store.curr_children.get_unchecked(start..end) }.iter())
}
#[inline(always)]
fn child_count(&self, parent_node_id: NodeId) -> usize {
self.slot(parent_node_id).child_len() as usize
}
#[inline(always)]
fn get_child_id(&self, parent_node_id: NodeId, child_index: usize) -> NodeId {
let s = self.slot(parent_node_id);
debug_assert!(child_index < s.child_len() as usize);
// SAFETY: Taffy calls `get_child_id` with `child_index < child_count(parent_node_id)`.
let child_slot = unsafe { *self.store.curr_children.get_unchecked(s.child_start as usize + child_index) };
NodeId::new(child_slot as u64)
}
}
impl<F> TraverseTree for LayoutStoreView<'_, F> where
F: FnMut(LayoutInput, Option<usize>, &CompactStyle) -> LayoutOutput
{
}
impl<F> LayoutPartialTree for LayoutStoreView<'_, F>
where
F: FnMut(LayoutInput, Option<usize>, &CompactStyle) -> LayoutOutput,
{
type CoreContainerStyle<'a>
= &'a CompactStyle
where
Self: 'a;
type CustomIdent = <Style as CoreStyle>::CustomIdent;
#[inline(always)]
fn get_core_container_style(&self, node_id: NodeId) -> Self::CoreContainerStyle<'_> {
&self.slot(node_id).style
}
#[inline(always)]
fn set_unrounded_layout(&mut self, node_id: NodeId, layout: &Layout) {
self.slot_mut(node_id).box_layout = BoxLayout::from_taffy(layout);
}
#[inline(always)]
fn resolve_calc_value(&self, _val: *const (), _basis: f32) -> f32 {
0.0
}
#[inline(always)]
fn compute_child_layout(&mut self, node_id: NodeId, inputs: LayoutInput) -> LayoutOutput {
self.compute_child_layout_inner(node_id, inputs, None)
}
}
impl<F> LayoutContainingBlock for LayoutStoreView<'_, F>
where
F: FnMut(LayoutInput, Option<usize>, &CompactStyle) -> LayoutOutput,
{
type OofItemStyle<'a>
= &'a CompactStyle
where
Self: 'a;
#[inline(always)]
fn get_oof_item_style(&self, node_id: NodeId) -> Self::OofItemStyle<'_> {
&self.slot(node_id).style
}
#[inline(always)]
fn clear_hoisted_children(&mut self, _node_id: NodeId) {}
#[inline(always)]
fn add_hoisted_children(&mut self, _node_id: NodeId, _hoisted: &[NodeId]) {}
#[inline(always)]
fn get_detailed_layout_info(&self, node_id: NodeId) -> &DetailedLayoutInfo {
self.slot(node_id).grid_info.as_deref().unwrap_or(&NONE_DETAIL)
}
}
impl<F> CacheTree for LayoutStoreView<'_, F>
where
F: FnMut(LayoutInput, Option<usize>, &CompactStyle) -> LayoutOutput,
{
#[inline(always)]
fn cache_get(&mut self, node_id: NodeId, input: &LayoutInput) -> Option<LayoutOutput> {
self.slot_mut(node_id).cache.get(input)
}
#[inline(always)]
fn cache_store(&mut self, node_id: NodeId, input: &LayoutInput, layout_output: LayoutOutput) {
self.slot_mut(node_id).cache.store(input, layout_output);
}
#[inline(always)]
fn cache_clear(&mut self, node_id: NodeId) {
self.slot_mut(node_id).cache.clear();
}
}
impl<F> LayoutBlockContainer for LayoutStoreView<'_, F>
where
F: FnMut(LayoutInput, Option<usize>, &CompactStyle) -> LayoutOutput,
{
type BlockContainerStyle<'a>
= &'a CompactStyle
where
Self: 'a;
type BlockItemStyle<'a>
= &'a CompactStyle
where
Self: 'a;
#[inline(always)]
fn get_block_container_style(&self, node_id: NodeId) -> Self::BlockContainerStyle<'_> {
&self.slot(node_id).style
}
#[inline(always)]
fn get_block_child_style(&self, child_node_id: NodeId) -> Self::BlockItemStyle<'_> {
&self.slot(child_node_id).style
}
#[inline(always)]
fn compute_block_child_layout(
&mut self,
node_id: NodeId,
inputs: LayoutInput,
block_ctx: Option<&mut BlockContext<'_>>,
) -> LayoutOutput {
self.compute_child_layout_inner(node_id, inputs, block_ctx)
}
}
impl<F> LayoutFlexboxContainer for LayoutStoreView<'_, F>
where
F: FnMut(LayoutInput, Option<usize>, &CompactStyle) -> LayoutOutput,
{
type FlexboxContainerStyle<'a>
= &'a CompactStyle
where
Self: 'a;
type FlexboxItemStyle<'a>
= &'a CompactStyle
where
Self: 'a;
#[inline(always)]
fn get_flexbox_container_style(&self, node_id: NodeId) -> Self::FlexboxContainerStyle<'_> {
&self.slot(node_id).style
}
#[inline(always)]
fn get_flexbox_child_style(&self, child_node_id: NodeId) -> Self::FlexboxItemStyle<'_> {
&self.slot(child_node_id).style
}
}
impl<F> LayoutGridContainer for LayoutStoreView<'_, F>
where
F: FnMut(LayoutInput, Option<usize>, &CompactStyle) -> LayoutOutput,
{
type GridContainerStyle<'a>
= &'a CompactStyle
where
Self: 'a;
type GridItemStyle<'a>
= &'a CompactStyle
where
Self: 'a;
#[inline(always)]
fn get_grid_container_style(&self, node_id: NodeId) -> Self::GridContainerStyle<'_> {
&self.slot(node_id).style
}
#[inline(always)]
fn get_grid_child_style(&self, child_node_id: NodeId) -> Self::GridItemStyle<'_> {
&self.slot(child_node_id).style
}
#[inline(always)]
fn set_detailed_grid_info(&mut self, node_id: NodeId, detailed_grid_info: DetailedGridInfo) {
self.slot_mut(node_id).grid_info = Some(Box::new(DetailedLayoutInfo::Grid(Box::new(detailed_grid_info))));
}
}
+7
View File
@@ -150,3 +150,10 @@ upstream = "crates.io:0.11.0"
kind = "patch"
reason = "linear-light blending in fine.wgsl (Config.blend_linear, set by vello_encoding's set_blend_linear): every colour, ramp and texel decoded from sRGB, blended, and encoded once, the blend stack kept sRGB-encoded, so raea-page blends a bevy_ui page as Bevy's UI does on an sRGB target"
exit = "a Vello release that blends in linear light on request"
[rune-taffy]
path = "vendor/rune-taffy"
upstream = "git:github.com/anomalyco/rune@7ead7d63fcf6f9dd9669385a8b90e2ae80015d7b:crates/rune-taffy"
kind = "patch"
reason = "taffy's flexbox_balance is on (Blitz turns it on and features unify in one build), so encode_wrap maps FlexWrap::Balance and BalanceReverse; upstream's match isn't exhaustive with that feature"
exit = "a Rune release whose rune-taffy handles taffy's flexbox_balance"