thing-core: layout (Taffy over a BoundTree, one style map, the Measure seam); FixedMeasure
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
ea0edb7bdf
commit
3f3d50bc8b
8 changed files with 794 additions and 0 deletions
|
|
@ -35,6 +35,8 @@ pub enum Code {
|
|||
RepeatKeyDuplicate,
|
||||
/// A surface offered at a version at or below one already offered; the held tree stays.
|
||||
StaleVersionIgnored,
|
||||
/// A style slot holding a value its CSS counterpart forbids; the slot took its initial value.
|
||||
StyleValueInvalid,
|
||||
}
|
||||
|
||||
impl Code {
|
||||
|
|
|
|||
76
crates/thing-core/src/layout/measure.rs
Normal file
76
crates/thing-core/src/layout/measure.rs
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
//! The Measure seam: what a leaf's intrinsic size is. Text, controls and images are sized by a
|
||||
//! `Measure` the frame owner composes (cut 9a ships Pixels and Cells); layout never estimates
|
||||
//! them. Taffy's own types stop at this file: `Leaf` and `Constraint` are plain data.
|
||||
|
||||
use taffy::{AvailableSpace, Size};
|
||||
use thing_contract::NodeId;
|
||||
|
||||
use crate::bind::Bound;
|
||||
|
||||
/// The room a leaf is offered on one axis.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Avail {
|
||||
Definite(f32),
|
||||
MinContent,
|
||||
MaxContent,
|
||||
}
|
||||
|
||||
/// What a leaf is asked, in logical px (Pixels) or cells (Cells). `known` is a size the parent
|
||||
/// already fixed on an axis; `available` is the room on each axis, `[width, height]`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Constraint {
|
||||
pub known: [Option<f32>; 2],
|
||||
pub available: [Avail; 2],
|
||||
}
|
||||
|
||||
/// A leaf node with the values it shows, borrowed from the bound tree.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum Leaf<'a> {
|
||||
Text { node: &'a NodeId, content: &'a Bound, style_token: &'a str, wrap: bool, max_lines: Option<u32> },
|
||||
TextInput { node: &'a NodeId, multiline: bool, placeholder: &'a Bound, value: &'a Bound },
|
||||
Toggle { node: &'a NodeId },
|
||||
Slider { node: &'a NodeId },
|
||||
Select { node: &'a NodeId, selected: &'a Bound },
|
||||
Image { node: &'a NodeId, catalog: &'a str, asset: &'a str },
|
||||
Plot { node: &'a NodeId },
|
||||
}
|
||||
|
||||
/// The intrinsic size `(width, height)` of a leaf under a constraint. A non-finite or negative
|
||||
/// answer is taken as zero.
|
||||
pub trait Measure {
|
||||
fn measure(&mut self, leaf: &Leaf, constraint: Constraint) -> (f32, f32);
|
||||
}
|
||||
|
||||
fn avail(space: AvailableSpace, k: f32) -> Avail {
|
||||
match space {
|
||||
AvailableSpace::Definite(v) => Avail::Definite(v / k),
|
||||
AvailableSpace::MinContent => Avail::MinContent,
|
||||
AvailableSpace::MaxContent => Avail::MaxContent,
|
||||
}
|
||||
}
|
||||
|
||||
/// The one adapter between Taffy's leaf callback and `Measure`: device px in, logical out, and
|
||||
/// back. `k` is the scale factor (1 in Cells).
|
||||
pub(super) fn measure_leaf(
|
||||
measure: &mut dyn Measure,
|
||||
leaf: &Leaf,
|
||||
k: f32,
|
||||
known: Size<Option<f32>>,
|
||||
space: Size<AvailableSpace>,
|
||||
) -> Size<f32> {
|
||||
let constraint = Constraint {
|
||||
known: [known.width.map(|v| v / k), known.height.map(|v| v / k)],
|
||||
available: [avail(space.width, k), avail(space.height, k)],
|
||||
};
|
||||
let (w, h) = measure.measure(leaf, constraint);
|
||||
let device = |v: f32| if v.is_finite() && v > 0.0 { v * k } else { 0.0 };
|
||||
Size { width: device(w), height: device(h) }
|
||||
}
|
||||
|
||||
/// The logical size a leaf has when nothing constrains it; an Image's aspect ratio comes from it.
|
||||
pub(super) fn intrinsic(measure: &mut dyn Measure, leaf: &Leaf) -> (f32, f32) {
|
||||
let constraint = Constraint { known: [None, None], available: [Avail::MaxContent, Avail::MaxContent] };
|
||||
let (w, h) = measure.measure(leaf, constraint);
|
||||
let clean = |v: f32| if v.is_finite() && v > 0.0 { v } else { 0.0 };
|
||||
(clean(w), clean(h))
|
||||
}
|
||||
121
crates/thing-core/src/layout/mod.rs
Normal file
121
crates/thing-core/src/layout/mod.rs
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
//! Layout: a `BoundTree` and a `LayoutFrame` become the geometry of every node, solved by Taffy
|
||||
//! (the one solver) and handed back as plain rectangles. A pure function: it reads no port, no
|
||||
//! clock and no state, builds a fresh Taffy tree per call and keeps none.
|
||||
//!
|
||||
//! Pixels mode runs the solver in device pixels (every Px length and every measured size is
|
||||
//! multiplied by the scale factor at the one adapter) with Taffy's cumulative rounding, so every
|
||||
//! edge lands on a device pixel and adjacent boxes share it. Cells mode ignores the scale. The
|
||||
//! viewport is a block container the document root flows in, and is not itself in the output.
|
||||
|
||||
mod measure;
|
||||
mod style;
|
||||
mod tree;
|
||||
|
||||
use taffy::{AvailableSpace, Size, compute_leaf_layout};
|
||||
use thing_contract::NodeId;
|
||||
|
||||
pub use measure::{Avail, Constraint, Leaf, Measure};
|
||||
|
||||
use crate::bind::BoundTree;
|
||||
use crate::diagnostic::Diagnostic;
|
||||
|
||||
/// The stack Taffy's recursion runs on, sized for a tree as deep as `Limits::max_tree_depth`:
|
||||
/// twice the per-level use measured in a debug build, times the 256 levels and 8 for the entry,
|
||||
/// rounded up to MiB.
|
||||
const LAYOUT_STACK: usize = 64 * 1024 * 1024;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Metrics {
|
||||
Pixels,
|
||||
Cells,
|
||||
}
|
||||
|
||||
/// The room one layout fills. `viewport` is logical px (Pixels) or cells (Cells); `scale` is the
|
||||
/// device pixels per logical px and is ignored in Cells.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct LayoutFrame {
|
||||
pub viewport: (f32, f32),
|
||||
pub scale: f32,
|
||||
pub metrics: Metrics,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Rect {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub w: f32,
|
||||
pub h: f32,
|
||||
}
|
||||
|
||||
/// One node's geometry. `rect` is the absolute border box in device px (Pixels) or cells, and is
|
||||
/// unscrolled. `content` is the scrollable content size of an `Overflow::Scroll` node; `clip` is
|
||||
/// set for Clip and Scroll.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct LaidNode {
|
||||
pub id: NodeId,
|
||||
pub rect: Rect,
|
||||
pub content: Option<(f32, f32)>,
|
||||
pub clip: bool,
|
||||
}
|
||||
|
||||
/// Every laid node in paint order (document order, Repeat instances spliced), and the style
|
||||
/// values that were not legal.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct LaidTree {
|
||||
pub nodes: Vec<LaidNode>,
|
||||
pub diagnostics: Vec<Diagnostic>,
|
||||
}
|
||||
|
||||
/// Whole numbers stay whole, and negative zero is written as zero.
|
||||
fn clean(v: f32) -> f32 {
|
||||
if v == 0.0 || !v.is_finite() { 0.0 } else { v }
|
||||
}
|
||||
|
||||
pub fn layout(tree: &BoundTree, frame: &LayoutFrame, measure: &mut dyn Measure) -> LaidTree {
|
||||
let k = match frame.metrics {
|
||||
Metrics::Pixels if frame.scale.is_finite() && frame.scale > 0.0 => frame.scale,
|
||||
_ => 1.0,
|
||||
};
|
||||
let viewport = |v: f32| if v.is_finite() && v > 0.0 { v } else { 0.0 };
|
||||
let (vw, vh) = (viewport(frame.viewport.0), viewport(frame.viewport.1));
|
||||
let mut built = tree::build(tree, k, (vw, vh), measure);
|
||||
let tree::Built { taffy, root, entries, leaves, diagnostics } = &mut built;
|
||||
let space = Size { width: AvailableSpace::Definite(vw * k), height: AvailableSpace::Definite(vh * k) };
|
||||
stacker::grow(LAYOUT_STACK, || {
|
||||
taffy
|
||||
.compute_layout_with_measure(*root, space, |inputs, _, context, style| {
|
||||
let leaf = context.and_then(|index| leaves.get(*index));
|
||||
compute_leaf_layout(
|
||||
inputs,
|
||||
style,
|
||||
|_, _| 0.0,
|
||||
|known, space| match leaf {
|
||||
Some(leaf) => measure::measure_leaf(measure, leaf, k, known, space),
|
||||
None => Size::ZERO,
|
||||
},
|
||||
)
|
||||
})
|
||||
.expect("taffy: the root is in the tree")
|
||||
});
|
||||
let mut absolute: Vec<(f32, f32)> = Vec::with_capacity(entries.len());
|
||||
let mut nodes = Vec::with_capacity(entries.len());
|
||||
for entry in entries.iter() {
|
||||
let laid = taffy.layout(entry.node).expect("taffy: node is in the tree");
|
||||
let (px, py) = entry.parent.map_or((0.0, 0.0), |parent| absolute[parent]);
|
||||
let (x, y) = (px + laid.location.x, py + laid.location.y);
|
||||
absolute.push((x, y));
|
||||
let (w, h) = (laid.size.width, laid.size.height);
|
||||
let content = entry.scroll.then(|| {
|
||||
let overflow = laid.scrollable_overflow_rect.rect();
|
||||
let round = |v: f32| (v + 0.5).floor();
|
||||
(clean(round(overflow.right).max(w)), clean(round(overflow.bottom).max(h)))
|
||||
});
|
||||
nodes.push(LaidNode {
|
||||
id: entry.id.clone(),
|
||||
rect: Rect { x: clean(x), y: clean(y), w: clean(w), h: clean(h) },
|
||||
content,
|
||||
clip: entry.clip,
|
||||
});
|
||||
}
|
||||
LaidTree { nodes, diagnostics: std::mem::take(diagnostics) }
|
||||
}
|
||||
288
crates/thing-core/src/layout/style.rs
Normal file
288
crates/thing-core/src/layout/style.rs
Normal file
|
|
@ -0,0 +1,288 @@
|
|||
//! The one style map: `BoxStyle` and `Paint` onto Taffy's `Style`. The destructure names every
|
||||
//! contract field, so a new field fails to compile until it is mapped.
|
||||
//!
|
||||
//! A slot holding a value its CSS counterpart forbids (a non-finite or oversized number, a
|
||||
//! negative where none is allowed, a Dimension arm the slot cannot take) takes its initial value
|
||||
//! and is reported once by field name. `Percent` is authored in percent points (50 is half).
|
||||
|
||||
use taffy::style_helpers::TaffyZero;
|
||||
use taffy::{
|
||||
AlignContent, AlignItems, Dimension, Display as TDisplay, FlexDirection, FlexWrap, GridTemplateComponent,
|
||||
LengthPercentage, LengthPercentageAuto, MaxTrackSizingFunction, MinTrackSizingFunction, Overflow as TOverflow,
|
||||
Point, Position as TPosition, Rect, Size, Style, TrackSizingFunction,
|
||||
};
|
||||
use thing_contract as c;
|
||||
|
||||
/// Field names of the slots that took their initial value.
|
||||
pub(super) type Invalid = Vec<&'static str>;
|
||||
|
||||
fn number(value: f64, negative: bool) -> Option<f32> {
|
||||
let fits = value.is_finite() && value.abs() <= f64::from(f32::MAX) && (negative || value >= 0.0);
|
||||
fits.then_some(value as f32)
|
||||
}
|
||||
|
||||
fn length(scalar: &c::Scalar, k: f32, negative: bool) -> Option<f32> {
|
||||
number(scalar.value, negative).map(|v| v * k).filter(|v| v.is_finite())
|
||||
}
|
||||
|
||||
fn percent(scalar: &c::Scalar, negative: bool) -> Option<f32> {
|
||||
number(scalar.value, negative).map(|v| v / 100.0)
|
||||
}
|
||||
|
||||
fn lp(d: &c::Dimension, k: f32) -> Option<LengthPercentage> {
|
||||
match d {
|
||||
c::Dimension::Px(s) => length(s, k, false).map(LengthPercentage::length),
|
||||
c::Dimension::Percent(s) => percent(s, false).map(LengthPercentage::percent),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn lpa(d: &c::Dimension, k: f32, negative: bool) -> Option<LengthPercentageAuto> {
|
||||
match d {
|
||||
c::Dimension::Px(s) => length(s, k, negative).map(LengthPercentageAuto::length),
|
||||
c::Dimension::Percent(s) => percent(s, negative).map(LengthPercentageAuto::percent),
|
||||
c::Dimension::Auto => Some(LengthPercentageAuto::auto()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn size_dim(d: &c::Dimension, k: f32) -> Option<Dimension> {
|
||||
match d {
|
||||
c::Dimension::Px(s) => length(s, k, false).map(Dimension::length),
|
||||
c::Dimension::Percent(s) => percent(s, false).map(Dimension::percent),
|
||||
c::Dimension::Auto => Some(Dimension::auto()),
|
||||
c::Dimension::Content => Some(Dimension::fit_content()),
|
||||
c::Dimension::Fr(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn basis_dim(d: &c::Dimension, k: f32) -> Option<Dimension> {
|
||||
match d {
|
||||
c::Dimension::Content => Some(Dimension::content()),
|
||||
c::Dimension::Fr(_) => None,
|
||||
other => size_dim(other, k),
|
||||
}
|
||||
}
|
||||
|
||||
fn track(d: &c::Dimension, k: f32) -> Option<GridTemplateComponent<String>> {
|
||||
use MaxTrackSizingFunction as Max;
|
||||
use MinTrackSizingFunction as Min;
|
||||
let (min, max) = match d {
|
||||
c::Dimension::Px(s) => {
|
||||
let v = length(s, k, false)?;
|
||||
(Min::length(v), Max::length(v))
|
||||
}
|
||||
c::Dimension::Percent(s) => {
|
||||
let v = percent(s, false)?;
|
||||
(Min::percent(v), Max::percent(v))
|
||||
}
|
||||
c::Dimension::Fr(s) => (Min::auto(), Max::fr(number(s.value, false)?)),
|
||||
c::Dimension::Auto => (Min::auto(), Max::auto()),
|
||||
c::Dimension::Content => (Min::max_content(), Max::max_content()),
|
||||
};
|
||||
Some(GridTemplateComponent::Single(TrackSizingFunction { min, max }))
|
||||
}
|
||||
|
||||
struct Slots {
|
||||
k: f32,
|
||||
invalid: Invalid,
|
||||
}
|
||||
|
||||
impl Slots {
|
||||
fn take<T>(&mut self, field: &'static str, value: Option<T>, initial: T) -> T {
|
||||
value.unwrap_or_else(|| {
|
||||
if !self.invalid.contains(&field) {
|
||||
self.invalid.push(field);
|
||||
}
|
||||
initial
|
||||
})
|
||||
}
|
||||
|
||||
fn size2(&mut self, field: &'static str, s: &c::Size2) -> Size<Dimension> {
|
||||
let k = self.k;
|
||||
Size {
|
||||
width: self.take(field, size_dim(&s.width, k), Dimension::auto()),
|
||||
height: self.take(field, size_dim(&s.height, k), Dimension::auto()),
|
||||
}
|
||||
}
|
||||
|
||||
fn size2_lpa(&mut self, field: &'static str, s: &c::Size2) -> Size<LengthPercentageAuto> {
|
||||
let k = self.k;
|
||||
Size {
|
||||
width: self.take(field, lpa(&s.width, k, false), LengthPercentageAuto::auto()),
|
||||
height: self.take(field, lpa(&s.height, k, false), LengthPercentageAuto::auto()),
|
||||
}
|
||||
}
|
||||
|
||||
fn edges_lpa(
|
||||
&mut self,
|
||||
field: &'static str,
|
||||
e: &c::Edges,
|
||||
negative: bool,
|
||||
initial: LengthPercentageAuto,
|
||||
) -> Rect<LengthPercentageAuto> {
|
||||
let k = self.k;
|
||||
Rect {
|
||||
left: self.take(field, lpa(&e.left, k, negative), initial),
|
||||
right: self.take(field, lpa(&e.right, k, negative), initial),
|
||||
top: self.take(field, lpa(&e.top, k, negative), initial),
|
||||
bottom: self.take(field, lpa(&e.bottom, k, negative), initial),
|
||||
}
|
||||
}
|
||||
|
||||
fn edges_lp(&mut self, field: &'static str, e: &c::Edges) -> Rect<LengthPercentage> {
|
||||
let k = self.k;
|
||||
let zero = LengthPercentage::ZERO;
|
||||
Rect {
|
||||
left: self.take(field, lp(&e.left, k), zero),
|
||||
right: self.take(field, lp(&e.right, k), zero),
|
||||
top: self.take(field, lp(&e.top, k), zero),
|
||||
bottom: self.take(field, lp(&e.bottom, k), zero),
|
||||
}
|
||||
}
|
||||
|
||||
fn tracks(&mut self, field: &'static str, dims: &[c::Dimension]) -> Vec<GridTemplateComponent<String>> {
|
||||
let k = self.k;
|
||||
let tracks: Option<Vec<_>> = dims.iter().map(|d| track(d, k)).collect();
|
||||
self.take(field, tracks, Vec::new())
|
||||
}
|
||||
|
||||
fn weight(&mut self, field: &'static str, value: f64, initial: f32) -> f32 {
|
||||
self.take(field, number(value, false), initial)
|
||||
}
|
||||
}
|
||||
|
||||
fn item(align: &c::ItemAlign) -> Option<AlignItems> {
|
||||
Some(match align {
|
||||
c::ItemAlign::Auto => return None,
|
||||
c::ItemAlign::Start => AlignItems::FLEX_START,
|
||||
c::ItemAlign::End => AlignItems::FLEX_END,
|
||||
c::ItemAlign::Center => AlignItems::CENTER,
|
||||
c::ItemAlign::Stretch => AlignItems::STRETCH,
|
||||
c::ItemAlign::Baseline => AlignItems::BASELINE,
|
||||
})
|
||||
}
|
||||
|
||||
fn content(align: &c::ContentAlign, auto: AlignContent) -> AlignContent {
|
||||
match align {
|
||||
c::ContentAlign::Auto => auto,
|
||||
c::ContentAlign::Start => AlignContent::FLEX_START,
|
||||
c::ContentAlign::End => AlignContent::FLEX_END,
|
||||
c::ContentAlign::Center => AlignContent::CENTER,
|
||||
c::ContentAlign::Stretch => AlignContent::STRETCH,
|
||||
c::ContentAlign::SpaceBetween => AlignContent::SPACE_BETWEEN,
|
||||
c::ContentAlign::SpaceAround => AlignContent::SPACE_AROUND,
|
||||
c::ContentAlign::SpaceEvenly => AlignContent::SPACE_EVENLY,
|
||||
}
|
||||
}
|
||||
|
||||
/// The Taffy style of a Box. `k` converts Px lengths to the solver's unit (the scale factor in
|
||||
/// Pixels, 1 in Cells); the slots that were not legal are named in the second value.
|
||||
pub(super) fn box_style(s: &c::BoxStyle, paint: &c::Paint, k: f32) -> (Style, Invalid) {
|
||||
let c::BoxStyle {
|
||||
display,
|
||||
direction,
|
||||
wrap,
|
||||
gap,
|
||||
padding,
|
||||
margin,
|
||||
size,
|
||||
min_size,
|
||||
max_size,
|
||||
position,
|
||||
inset,
|
||||
overflow,
|
||||
align_items,
|
||||
align_self,
|
||||
align_content,
|
||||
justify_content,
|
||||
grow,
|
||||
shrink,
|
||||
basis,
|
||||
grid_columns,
|
||||
grid_rows,
|
||||
} = s;
|
||||
let mut slots = Slots { k, invalid: Vec::new() };
|
||||
let border = match &paint.border {
|
||||
None => LengthPercentage::ZERO,
|
||||
Some(b) => {
|
||||
let width = slots.take("border", number(b.width, false).map(|w| w * k).filter(|w| w.is_finite()), 0.0);
|
||||
LengthPercentage::length(width)
|
||||
}
|
||||
};
|
||||
let overflow = match overflow {
|
||||
c::Overflow::Visible => TOverflow::Visible,
|
||||
c::Overflow::Clip => TOverflow::Clip,
|
||||
c::Overflow::Scroll => TOverflow::Scroll,
|
||||
};
|
||||
let gap = {
|
||||
let width = slots.take("gap", lp(&gap.width, k), LengthPercentage::ZERO);
|
||||
let height = slots.take("gap", lp(&gap.height, k), LengthPercentage::ZERO);
|
||||
Size { width, height }
|
||||
};
|
||||
let style = Style {
|
||||
display: match display {
|
||||
c::Display::Flex => TDisplay::Flex,
|
||||
c::Display::Grid => TDisplay::Grid,
|
||||
c::Display::Block => TDisplay::Block,
|
||||
},
|
||||
flex_direction: match direction {
|
||||
c::Direction::Row => FlexDirection::Row,
|
||||
c::Direction::Column => FlexDirection::Column,
|
||||
c::Direction::RowReverse => FlexDirection::RowReverse,
|
||||
c::Direction::ColumnReverse => FlexDirection::ColumnReverse,
|
||||
},
|
||||
flex_wrap: match wrap {
|
||||
c::Wrap::NoWrap => FlexWrap::NoWrap,
|
||||
c::Wrap::Wrap => FlexWrap::Wrap,
|
||||
c::Wrap::WrapReverse => FlexWrap::WrapReverse,
|
||||
},
|
||||
gap,
|
||||
padding: slots.edges_lp("padding", padding),
|
||||
border: Rect { left: border, right: border, top: border, bottom: border },
|
||||
margin: slots.edges_lpa("margin", margin, true, LengthPercentageAuto::ZERO),
|
||||
size: slots.size2("size", size),
|
||||
min_size: slots.size2_lpa("min_size", min_size),
|
||||
max_size: slots.size2_lpa("max_size", max_size),
|
||||
position: match position {
|
||||
c::Position::Relative => TPosition::Relative,
|
||||
c::Position::Absolute => TPosition::Absolute,
|
||||
},
|
||||
inset: slots.edges_lpa("inset", inset, true, LengthPercentageAuto::auto()),
|
||||
overflow: Point { x: overflow, y: overflow },
|
||||
scrollbar_width: 0.0,
|
||||
align_items: item(align_items).unwrap_or(AlignItems::STRETCH),
|
||||
align_self: item(align_self),
|
||||
align_content: content(align_content, AlignContent::STRETCH),
|
||||
justify_content: content(justify_content, AlignContent::FLEX_START),
|
||||
flex_grow: slots.weight("grow", *grow, 0.0),
|
||||
flex_shrink: slots.weight("shrink", *shrink, 1.0),
|
||||
flex_basis: {
|
||||
let basis = basis_dim(basis, k);
|
||||
slots.take("basis", basis, Dimension::auto())
|
||||
},
|
||||
grid_template_columns: slots.tracks("grid_columns", grid_columns).into_iter().collect(),
|
||||
grid_template_rows: slots.tracks("grid_rows", grid_rows).into_iter().collect(),
|
||||
..Style::default()
|
||||
};
|
||||
(style, slots.invalid)
|
||||
}
|
||||
|
||||
/// An Embed's style: exactly its declared size, never shrunk.
|
||||
pub(super) fn embed_style(width: f64, height: f64, k: f32) -> (Style, Invalid) {
|
||||
let mut slots = Slots { k, invalid: Vec::new() };
|
||||
let side = |slots: &mut Slots, value: f64| {
|
||||
let v = slots.take("size", number(value, false).map(|v| v * k).filter(|v| v.is_finite()), 0.0);
|
||||
(Dimension::length(v), LengthPercentageAuto::length(v))
|
||||
};
|
||||
let (w, wa) = side(&mut slots, width);
|
||||
let (h, ha) = side(&mut slots, height);
|
||||
let style = Style {
|
||||
size: Size { width: w, height: h },
|
||||
min_size: Size { width: wa, height: ha },
|
||||
max_size: Size { width: wa, height: ha },
|
||||
flex_shrink: 0.0,
|
||||
..Style::default()
|
||||
};
|
||||
(style, slots.invalid)
|
||||
}
|
||||
227
crates/thing-core/src/layout/tree.rs
Normal file
227
crates/thing-core/src/layout/tree.rs
Normal file
|
|
@ -0,0 +1,227 @@
|
|||
//! The walk: a `BoundTree` becomes a Taffy tree, one Taffy node per laid node, Repeats spliced.
|
||||
|
||||
use taffy::{Style, TaffyTree};
|
||||
use thing_contract::{Node, NodeId, Overflow};
|
||||
|
||||
use super::measure::{Leaf, intrinsic};
|
||||
use super::style::{Invalid, box_style, embed_style};
|
||||
use crate::bind::{Bound, BoundTree, Field};
|
||||
use crate::diagnostic::{Code, Diagnostic};
|
||||
use crate::resolve::grow;
|
||||
|
||||
static ABSENT: Bound = Bound::Absent;
|
||||
|
||||
/// One laid node, in document order. `parent` is the entry of the nearest laid ancestor.
|
||||
pub(super) struct Entry<'a> {
|
||||
pub id: &'a NodeId,
|
||||
pub node: taffy::NodeId,
|
||||
pub parent: Option<usize>,
|
||||
pub clip: bool,
|
||||
pub scroll: bool,
|
||||
}
|
||||
|
||||
pub(super) struct Built<'a> {
|
||||
pub taffy: TaffyTree<usize>,
|
||||
pub root: taffy::NodeId,
|
||||
pub entries: Vec<Entry<'a>>,
|
||||
/// The Taffy context of a measured leaf is its index here.
|
||||
pub leaves: Vec<Leaf<'a>>,
|
||||
pub diagnostics: Vec<Diagnostic>,
|
||||
}
|
||||
|
||||
struct Builder<'a, 'm> {
|
||||
tree: &'a BoundTree,
|
||||
surface: String,
|
||||
k: f32,
|
||||
measure: &'m mut dyn super::Measure,
|
||||
taffy: TaffyTree<usize>,
|
||||
entries: Vec<Entry<'a>>,
|
||||
leaves: Vec<Leaf<'a>>,
|
||||
diagnostics: Vec<Diagnostic>,
|
||||
}
|
||||
|
||||
pub(super) fn build<'a>(
|
||||
tree: &'a BoundTree,
|
||||
k: f32,
|
||||
viewport: (f32, f32),
|
||||
measure: &mut dyn super::Measure,
|
||||
) -> Built<'a> {
|
||||
let document = tree.resolved().document();
|
||||
let mut builder = Builder {
|
||||
tree,
|
||||
surface: document.record_key(),
|
||||
k,
|
||||
measure,
|
||||
taffy: TaffyTree::new(),
|
||||
entries: Vec::new(),
|
||||
leaves: Vec::new(),
|
||||
diagnostics: Vec::new(),
|
||||
};
|
||||
let mut kids = Vec::new();
|
||||
builder.visit(&document.root, None, &mut kids);
|
||||
// The viewport is a block container; the document root is its flow child, so a root with an
|
||||
// auto width fills the viewport and a Repeat at the root has a parent to splice into.
|
||||
let root = Style {
|
||||
display: taffy::Display::Block,
|
||||
position: taffy::Position::Relative,
|
||||
size: taffy::Size { width: taffy::Dimension::length(viewport.0 * k), height: taffy::Dimension::length(viewport.1 * k) },
|
||||
..Style::default()
|
||||
};
|
||||
let root = builder.taffy.new_with_children(root, &kids).expect("taffy: insert");
|
||||
Built { taffy: builder.taffy, root, entries: builder.entries, leaves: builder.leaves, diagnostics: builder.diagnostics }
|
||||
}
|
||||
|
||||
impl<'a> Builder<'a, '_> {
|
||||
fn hidden(&self, id: &NodeId) -> bool {
|
||||
matches!(self.tree.value(id, Field::Visible), Some(Bound::Bool(false)))
|
||||
}
|
||||
|
||||
fn value(&self, id: &NodeId, field: Field) -> &'a Bound {
|
||||
self.tree.value(id, field).unwrap_or(&ABSENT)
|
||||
}
|
||||
|
||||
fn report(&mut self, id: &NodeId, invalid: Invalid) {
|
||||
for field in invalid {
|
||||
self.diagnostics.push(Diagnostic {
|
||||
code: Code::StyleValueInvalid,
|
||||
surface: self.surface.clone(),
|
||||
node: Some(id.clone()),
|
||||
detail: field.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn entry(&mut self, id: &'a NodeId, parent: Option<usize>, overflow: &Overflow) -> usize {
|
||||
let clip = !matches!(overflow, Overflow::Visible);
|
||||
let scroll = matches!(overflow, Overflow::Scroll);
|
||||
self.entries.push(Entry { id, node: taffy::NodeId::from(0u64), parent, clip, scroll });
|
||||
self.entries.len() - 1
|
||||
}
|
||||
|
||||
fn leaf(&mut self, id: &'a NodeId, parent: Option<usize>, leaf: Leaf<'a>, out: &mut Vec<taffy::NodeId>) {
|
||||
let mut style = Style::default();
|
||||
if matches!(leaf, Leaf::Image { .. }) {
|
||||
// A stretched image keeps its shape: the ratio is what the measure says it is unconstrained.
|
||||
let (w, h) = intrinsic(self.measure, &leaf);
|
||||
style.item_is_replaced = true;
|
||||
style.aspect_ratio = (w > 0.0 && h > 0.0).then(|| w / h);
|
||||
}
|
||||
let index = self.entry(id, parent, &Overflow::Visible);
|
||||
let context = self.leaves.len();
|
||||
self.leaves.push(leaf);
|
||||
let node = self.taffy.new_leaf_with_context(style, context).expect("taffy: insert");
|
||||
self.entries[index].node = node;
|
||||
out.push(node);
|
||||
}
|
||||
|
||||
fn container(
|
||||
&mut self,
|
||||
id: &'a NodeId,
|
||||
parent: Option<usize>,
|
||||
(style, invalid): (Style, Invalid),
|
||||
overflow: &Overflow,
|
||||
children: &'a [Node],
|
||||
out: &mut Vec<taffy::NodeId>,
|
||||
) {
|
||||
self.report(id, invalid);
|
||||
let index = self.entry(id, parent, overflow);
|
||||
let mut kids = Vec::new();
|
||||
for child in children {
|
||||
self.visit(child, Some(index), &mut kids);
|
||||
}
|
||||
let node = self.taffy.new_with_children(style, &kids).expect("taffy: insert");
|
||||
self.entries[index].node = node;
|
||||
out.push(node);
|
||||
}
|
||||
|
||||
/// Append the Taffy nodes `node` contributes to its parent's children: one, none (hidden,
|
||||
/// Overlay, a Repeat with no instances) or one per Repeat instance.
|
||||
fn visit(&mut self, node: &'a Node, parent: Option<usize>, out: &mut Vec<taffy::NodeId>) {
|
||||
grow(|| match node {
|
||||
Node::Box(b) => {
|
||||
if !self.hidden(&b.common.id) {
|
||||
let style = box_style(&b.style, &b.paint, self.k);
|
||||
self.container(&b.common.id, parent, style, &b.style.overflow, &b.children, out);
|
||||
}
|
||||
}
|
||||
Node::Button(b) => {
|
||||
if !self.hidden(&b.common.id) {
|
||||
self.container(&b.common.id, parent, (Style::default(), Vec::new()), &Overflow::Visible, &b.content, out);
|
||||
}
|
||||
}
|
||||
// A Repeat has no box: its instances are its parent's children, in instance order.
|
||||
Node::Repeat(r) => {
|
||||
if !self.hidden(&r.common.id) {
|
||||
for instance in self.tree.instances(&r.common.id) {
|
||||
self.visit(&instance.root, parent, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Overlays are placed by their own cut; in flow they are nothing.
|
||||
Node::Overlay(_) => {}
|
||||
Node::Use(_) | Node::Slot(_) => debug_assert!(false, "resolve expands Use and Slot"),
|
||||
Node::Embed(e) => {
|
||||
if !self.hidden(&e.common.id) {
|
||||
let (style, invalid) = embed_style(e.width, e.height, self.k);
|
||||
self.report(&e.common.id, invalid);
|
||||
let index = self.entry(&e.common.id, parent, &Overflow::Visible);
|
||||
let id = self.taffy.new_leaf(style).expect("taffy: insert");
|
||||
self.entries[index].node = id;
|
||||
out.push(id);
|
||||
}
|
||||
}
|
||||
Node::Text(n) => {
|
||||
let id = &n.common.id;
|
||||
if !self.hidden(id) {
|
||||
let leaf = Leaf::Text {
|
||||
node: id,
|
||||
content: self.value(id, Field::Content),
|
||||
style_token: &n.style_token,
|
||||
wrap: n.wrap,
|
||||
max_lines: n.max_lines.map(|lines| lines.get().max(0) as u32),
|
||||
};
|
||||
self.leaf(id, parent, leaf, out);
|
||||
}
|
||||
}
|
||||
Node::TextInput(n) => {
|
||||
let id = &n.common.id;
|
||||
if !self.hidden(id) {
|
||||
let leaf = Leaf::TextInput {
|
||||
node: id,
|
||||
multiline: n.multiline,
|
||||
placeholder: self.value(id, Field::Placeholder),
|
||||
value: self.value(id, Field::Initial),
|
||||
};
|
||||
self.leaf(id, parent, leaf, out);
|
||||
}
|
||||
}
|
||||
Node::Toggle(n) => {
|
||||
if !self.hidden(&n.common.id) {
|
||||
self.leaf(&n.common.id, parent, Leaf::Toggle { node: &n.common.id }, out);
|
||||
}
|
||||
}
|
||||
Node::Slider(n) => {
|
||||
if !self.hidden(&n.common.id) {
|
||||
self.leaf(&n.common.id, parent, Leaf::Slider { node: &n.common.id }, out);
|
||||
}
|
||||
}
|
||||
Node::Select(n) => {
|
||||
let id = &n.common.id;
|
||||
if !self.hidden(id) {
|
||||
self.leaf(id, parent, Leaf::Select { node: id, selected: self.value(id, Field::Selected) }, out);
|
||||
}
|
||||
}
|
||||
Node::Image(n) => {
|
||||
if !self.hidden(&n.common.id) {
|
||||
let leaf = Leaf::Image { node: &n.common.id, catalog: &n.catalog, asset: &n.asset };
|
||||
self.leaf(&n.common.id, parent, leaf, out);
|
||||
}
|
||||
}
|
||||
Node::Plot(n) => {
|
||||
if !self.hidden(&n.common.id) {
|
||||
self.leaf(&n.common.id, parent, Leaf::Plot { node: &n.common.id }, out);
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -3,5 +3,6 @@
|
|||
|
||||
pub mod bind;
|
||||
pub mod diagnostic;
|
||||
pub mod layout;
|
||||
pub mod port;
|
||||
pub mod resolve;
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@
|
|||
pub mod build;
|
||||
pub mod fixture;
|
||||
pub mod golden;
|
||||
pub mod measure;
|
||||
pub mod mem_state;
|
||||
pub mod state;
|
||||
pub mod store;
|
||||
|
|
|
|||
78
crates/thing-testkit/src/measure.rs
Normal file
78
crates/thing-testkit/src/measure.rs
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
//! A layout oracle, not a text engine: every size is a fixed function of the leaf, so layout
|
||||
//! goldens never move when a real text measure changes.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use thing_contract::AssetCatalog;
|
||||
use thing_core::bind::Bound;
|
||||
use thing_core::layout::{Avail, Constraint, Leaf, Measure};
|
||||
|
||||
/// Text is 8 px wide per character and 16 px tall per line (one cell each in Cells); controls
|
||||
/// have fixed sizes; an Image is its catalog entry's extent (0x0 when missing); a Plot is 0x0.
|
||||
pub struct FixedMeasure {
|
||||
cells: bool,
|
||||
extents: HashMap<(String, String), (f32, f32)>,
|
||||
}
|
||||
|
||||
impl FixedMeasure {
|
||||
pub fn pixels(catalogs: &[AssetCatalog]) -> Self {
|
||||
Self::new(false, catalogs)
|
||||
}
|
||||
|
||||
pub fn cells(catalogs: &[AssetCatalog]) -> Self {
|
||||
Self::new(true, catalogs)
|
||||
}
|
||||
|
||||
fn new(cells: bool, catalogs: &[AssetCatalog]) -> Self {
|
||||
let mut extents = HashMap::new();
|
||||
for catalog in catalogs {
|
||||
for asset in &catalog.assets {
|
||||
let key = (catalog.catalog_id.as_str().to_string(), asset.id.clone());
|
||||
extents.insert(key, (asset.width.get() as f32, asset.height.get() as f32));
|
||||
}
|
||||
}
|
||||
Self { cells, extents }
|
||||
}
|
||||
|
||||
fn text(&self, content: &Bound, wrap: bool, max_lines: Option<u32>, c: &Constraint) -> (f32, f32) {
|
||||
let (cw, ch) = if self.cells { (1.0, 1.0) } else { (8.0, 16.0) };
|
||||
let text = match content {
|
||||
Bound::Text(text) => text.as_str(),
|
||||
_ => "",
|
||||
};
|
||||
let chars = text.chars().count() as f32;
|
||||
let room = c.known[0].map(Avail::Definite).unwrap_or(c.available[0]);
|
||||
let (width, lines) = match (wrap, room) {
|
||||
(true, Avail::Definite(w)) => {
|
||||
let capacity = (w / cw).floor().max(1.0);
|
||||
(chars.min(capacity), (chars / capacity).ceil().max(1.0))
|
||||
}
|
||||
(true, Avail::MinContent) => {
|
||||
let word = text.split_whitespace().map(|w| w.chars().count()).max().unwrap_or(0) as f32;
|
||||
(word, (chars / word.max(1.0)).ceil().max(1.0))
|
||||
}
|
||||
_ => (chars, 1.0),
|
||||
};
|
||||
let lines = max_lines.map_or(lines, |cap| lines.min(cap as f32));
|
||||
(width * cw, lines * ch)
|
||||
}
|
||||
}
|
||||
|
||||
impl Measure for FixedMeasure {
|
||||
fn measure(&mut self, leaf: &Leaf, c: Constraint) -> (f32, f32) {
|
||||
// Pixels sizes, then the same control in cells: width / 8 and one row.
|
||||
let control = |w: f32, h: f32| if self.cells { (w / 8.0, 1.0) } else { (w, h) };
|
||||
match leaf {
|
||||
Leaf::Text { content, wrap, max_lines, .. } => self.text(content, *wrap, *max_lines, &c),
|
||||
Leaf::TextInput { multiline, .. } => control(200.0, if *multiline { 72.0 } else { 24.0 }),
|
||||
Leaf::Toggle { .. } => control(40.0, 20.0),
|
||||
Leaf::Slider { .. } => control(160.0, 20.0),
|
||||
Leaf::Select { .. } => control(160.0, 24.0),
|
||||
Leaf::Image { catalog, asset, .. } => {
|
||||
let (w, h) = self.extents.get(&(catalog.to_string(), asset.to_string())).copied().unwrap_or((0.0, 0.0));
|
||||
if self.cells { (w / 8.0, (h / 16.0).ceil()) } else { (w, h) }
|
||||
}
|
||||
Leaf::Plot { .. } => (0.0, 0.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue