thing-core: a Cells control declared under 3 rows keeps that height in a compact form, and layout states the form

Ruling cells-control-height-forms. A content-sized Cells control is the 3-row bordered
form; one laid under 3 rows keeps exactly that height as Compact (brackets for
TextInput, Select and Button, the toggle glyph for Toggle; one cell each side, no
vertical inset, content on the first row). Layout finds the form by solving: a bordered
control's padding floors its height at 2 rows, so a control left under 3 rows is built
again compact and solved afresh. LaidNode.inside (None for two things, border inferred
from inner == Some(rect)) is replaced by LaidNode.control: Option<LaidControl { form,
content }>, which render reads and infers nothing from. Pixels controls are Bordered; a
Pixels Button's content box is its border box. No golden moves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-28 15:42:21 +01:00
commit fe19483279
8 changed files with 260 additions and 112 deletions

View file

@ -6,6 +6,7 @@ use taffy::{AvailableSpace, Size};
use thing_contract::NodeId;
use crate::bind::Bound;
use super::ControlForm;
use crate::text::CellText;
/// The room a leaf is offered on one axis.
@ -105,6 +106,9 @@ pub(crate) const MAX_DEVICE: f32 = 2_097_152.0;
/// leaves. A smaller side is below the resolution layout keeps.
pub(super) const MIN_SIDE: f32 = 0.125;
/// The fewest rows a Cells control needs to be `Bordered`: a border row above and below a content row.
pub(super) const BORDERED_ROWS: f32 = 3.0;
/// Device px per cell, `(across, down)`: the metric a terminal cell stands for. In Cells mode a Px
/// length converts at it (8 wide, 16 tall), and an Image's pixel extent is read in cells at it.
pub(crate) const CELL_PX: (f32, f32) = (8.0, 16.0);
@ -166,20 +170,15 @@ impl Device {
}
}
/// The inset of a laid bordered control's content (Button, TextInput, Select, Toggle) from its
/// border box, `(x, y)`, in device units: the one rule, owned here. Layout reserves it as padding
/// in Cells (so a content-sized control's box includes its border rows) and publishes the laid
/// content box; render reads that box and computes no inset. In Pixels: the 2 px
/// of chrome, never more than half a side. In Cells the border stands in the edge cells, so
/// content keeps one cell clear on every side when the box is tall enough (3 rows) to hold the
/// border and a content row; a shorter box paints no border and its content takes the whole box.
pub(super) fn inset(self, w: f32, h: f32) -> (f32, f32) {
let (x, y) = if !self.cells {
(self.px(2.0), self.px(2.0))
} else if h >= 3.0 {
(1.0, 1.0)
} else {
(0.0, 0.0)
/// The inset of a laid control's content from its border box, `(x, y)`, in device units: the one
/// rule, owned here. In Pixels: the 2 px of chrome. In Cells a `Bordered` control keeps one cell
/// clear on every side, a `Compact` one a cell on each side across and none down. Never more than
/// half a side.
pub(super) fn inset(self, form: ControlForm, w: f32, h: f32) -> (f32, f32) {
let (x, y) = match (self.cells, form) {
(false, _) => (self.px(2.0), self.px(2.0)),
(true, ControlForm::Bordered) => (1.0, 1.0),
(true, ControlForm::Compact) => (1.0, 0.0),
};
(x.min(w / 2.0).max(0.0), y.min(h / 2.0).max(0.0))
}

View file

@ -15,7 +15,7 @@ mod style;
mod tree;
use taffy::{AvailableSpace, Size, compute_leaf_layout};
use measure::Device;
use measure::{BORDERED_ROWS, Device};
use thing_contract::{NodeId, OverlayNode};
pub use measure::{Avail, CellStyle, Constraint, FontId, Glyph, Leaf, Measure, Run, TextLayout, TextLine, TextRequest};
@ -69,12 +69,28 @@ pub struct LaidNode {
/// it. Layout never sees a scroll position, so a scroll never re-runs layout.
pub max_scroll: Option<(f32, f32)>,
pub clip: Option<Rect>,
/// The box a bordered control's content (Button, TextInput, Select, Toggle) is laid or drawn
/// in: the border box less the control's inset, in device px (Pixels) or cells. Layout owns
/// the inset; render draws in this box and computes none. A box with no inset (a Cells control
/// under 3 rows tall, which paints no border) has the border box itself. `None` for every other
/// node and for a Button in Pixels, whose content is laid without an inset.
pub inside: Option<Rect>,
/// A control's (Button, TextInput, Select, Toggle) form and content box, stated by layout; render
/// draws what this says and infers nothing from geometry. `None` for every other node.
pub control: Option<LaidControl>,
}
/// The two forms of a control. In Pixels every control is `Bordered` (render draws chrome behind its
/// content). In Cells a control laid 3 rows or taller is `Bordered`: its border stands in the edge
/// cells and its content keeps one cell clear on every side. A control laid shorter keeps exactly
/// that height as `Compact`: its one-row affordance on the first row, one cell each side.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ControlForm {
Bordered,
Compact,
}
/// A laid control: the form layout chose and the box its content is laid or drawn in, in device px
/// (Pixels) or cells: the border box less the form's inset. A Pixels Button's content is laid
/// without an inset, so its content box is its border box.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LaidControl {
pub form: ControlForm,
pub content: Rect,
}
/// Every laid node in paint order (document order, Repeat instances spliced), and the style
@ -127,26 +143,29 @@ pub fn layout(tree: &BoundTree, frame: &LayoutFrame, measure: &mut dyn Measure)
};
let mut nodes = Vec::new();
let mut diagnostics = Vec::new();
let main = tree::build(tree, dev, tree::Top::Document, (vw, vh), measure);
let overlays = solve(tree, main, dev, (vw, vh), (0.0, 0.0), measure, &mut nodes, &mut diagnostics)?;
let overlays = solve(tree, tree::Top::Document, dev, (vw, vh), (0.0, 0.0), measure, &mut nodes, &mut diagnostics)?;
overlay::place_all(tree, dev, (vw, vh), overlays, measure, &mut nodes, &mut diagnostics)?;
Ok(LaidTree { nodes, diagnostics })
}
/// Solve one built Taffy tree in `size` device px, its origin at `origin`, and append its laid
/// nodes (absolute, in entry order) and its diagnostics. Returns the Overlays the tree met in flow.
#[allow(clippy::too_many_arguments)]
fn solve<'a>(
tree: &BoundTree,
mut built: tree::Built<'a>,
dev: Device,
size: (f32, f32),
origin: (f32, f32),
measure: &mut dyn Measure,
nodes: &mut Vec<LaidNode>,
diagnostics: &mut Vec<Diagnostic>,
) -> Result<Vec<&'a OverlayNode>, LayoutError> {
let tree::Built { taffy, root, entries, leaves, diagnostics: own, overlays } = &mut built;
/// Mark every `Bordered` control `built` laid under `BORDERED_ROWS` rows as `Compact`, by entry
/// index. Returns whether any was marked: a marked control is built and solved again.
fn mark_too_short(built: &tree::Built, compact: &mut Vec<bool>) -> bool {
compact.resize(built.entries.len(), false);
let mut marked = false;
for (i, entry) in built.entries.iter().enumerate() {
let rows = built.taffy.layout(entry.node).expect("taffy: node is in the tree").size.height;
if entry.control.is_some() && !compact[i] && rows < BORDERED_ROWS {
compact[i] = true;
marked = true;
}
}
marked
}
/// Run the one solve over a built tree in `size` device px.
fn compute(built: &mut tree::Built, dev: Device, size: (f32, f32), measure: &mut dyn Measure) {
let tree::Built { taffy, root, entries, leaves, .. } = built;
let space = Size { width: AvailableSpace::Definite(size.0), height: AvailableSpace::Definite(size.1) };
// Entries come parent first, so one pass finds the deepest; the viewport and a spare few add.
let mut depth = vec![1usize; entries.len()];
@ -170,6 +189,35 @@ fn solve<'a>(
})
.expect("taffy: the root is in the tree")
});
}
/// Build and solve one Taffy tree in `size` device px, its origin at `origin`, and append its laid
/// nodes (absolute, in entry order) and its diagnostics. Returns the Overlays the tree met in flow.
///
/// In Cells a control is first laid `Bordered`; one the solve leaves under `BORDERED_ROWS` rows
/// cannot hold a border and a content row, so the tree is built again with it `Compact` and solved
/// afresh, until no bordered control is too short. A bordered control's padding floors its height
/// at 2 rows, which is why the form is found by solving and not read off a declared height.
#[allow(clippy::too_many_arguments)]
fn solve<'a>(
tree: &'a BoundTree,
top: tree::Top<'a>,
dev: Device,
size: (f32, f32),
origin: (f32, f32),
measure: &mut dyn Measure,
nodes: &mut Vec<LaidNode>,
diagnostics: &mut Vec<Diagnostic>,
) -> Result<Vec<&'a OverlayNode>, LayoutError> {
let mut compact: Vec<bool> = Vec::new();
let mut built = loop {
let mut built = tree::build(tree, dev, top, size, measure, &compact);
compute(&mut built, dev, size, measure);
if !dev.cells() || !mark_too_short(&built, &mut compact) {
break built;
}
};
let tree::Built { taffy, entries, diagnostics: own, overlays, .. } = &mut built;
let base = nodes.len();
let mut absolute: Vec<(f32, f32)> = Vec::with_capacity(entries.len());
for entry in entries.iter() {
@ -208,9 +256,9 @@ fn solve<'a>(
w: clean(w - laid.border.left - laid.border.right),
h: clean(h - laid.border.top - laid.border.bottom),
});
let inside = entry.control.then(|| {
let (ix, iy) = dev.inset(w, h);
Rect { x: clean(x + ix), y: clean(y + iy), w: clean(w - 2.0 * ix), h: clean(h - 2.0 * iy) }
let control = entry.control.map(|form| {
let (ix, iy) = if entry.inset { dev.inset(form, w, h) } else { (0.0, 0.0) };
LaidControl { form, content: Rect { x: clean(x + ix), y: clean(y + iy), w: clean(w - 2.0 * ix), h: clean(h - 2.0 * iy) } }
});
nodes.push(LaidNode {
id: entry.id.clone(),
@ -219,7 +267,7 @@ fn solve<'a>(
content,
max_scroll,
clip,
inside,
control,
});
}
diagnostics.append(own);

View file

@ -8,7 +8,7 @@ use std::collections::HashMap;
use thing_contract::{Anchor, NodeId, OverlayNode};
use super::measure::Device;
use super::tree::{self, Top};
use super::tree::Top;
use super::{LaidNode, LayoutError, Measure, Rect, solve};
use crate::bind::BoundTree;
use crate::diagnostic::{Code, Diagnostic};
@ -44,9 +44,8 @@ pub(super) fn place_all<'a>(
}
},
};
let built = tree::build(tree, dev, Top::Overlay(overlay), (anchor.w, anchor.h), measure);
let start = nodes.len();
let nested = solve(tree, built, dev, (anchor.w, anchor.h), (anchor.x, anchor.y), measure, nodes, diagnostics)?;
let nested = solve(tree, Top::Overlay(overlay), dev, (anchor.w, anchor.h), (anchor.x, anchor.y), measure, nodes, diagnostics)?;
for node in &nodes[start..] {
rects.entry(node.id.clone()).or_insert(node.rect);
}

View file

@ -3,6 +3,7 @@
use taffy::{Style, TaffyTree};
use thing_contract::{Direction, Node, NodeId, Overflow, OverlayNode};
use super::ControlForm;
use super::measure::{Axis, Device, Leaf, MAX_DEVICE, intrinsic_ratio};
use super::style::{Invalid, box_style, embed_style};
use crate::bind::{Bound, BoundTree, Field};
@ -18,8 +19,10 @@ pub(super) struct Entry<'a> {
pub(super) parent: Option<usize>,
pub(super) clip: bool,
pub(super) scroll: bool,
/// A bordered control (Button, TextInput, Select, Toggle): its content box is published.
pub(super) control: bool,
/// A control (Button, TextInput, Select, Toggle): its form and content box are published.
pub(super) control: Option<ControlForm>,
/// Whether layout reserves the control an inset (every control but a Pixels Button).
pub(super) inset: bool,
}
pub(super) struct Built<'a> {
@ -38,6 +41,8 @@ struct Builder<'a, 'm> {
surface: String,
dev: Device,
measure: &'m mut dyn super::Measure,
/// The entries (by index, in document order) of the controls laid in the compact form.
compact: &'m [bool],
taffy: TaffyTree<usize>,
entries: Vec<Entry<'a>>,
leaves: Vec<Leaf<'a>>,
@ -49,6 +54,7 @@ struct Builder<'a, 'm> {
}
/// What the Taffy tree is rooted at: the viewport holding the document root, or one Overlay.
#[derive(Clone, Copy)]
pub(super) enum Top<'a> {
Document,
Overlay(&'a OverlayNode),
@ -64,6 +70,7 @@ pub(super) fn build<'a>(
top: Top<'a>,
size: (f32, f32),
measure: &mut dyn super::Measure,
compact: &[bool],
) -> Built<'a> {
let document = tree.resolved().document();
let mut builder = Builder {
@ -71,6 +78,7 @@ pub(super) fn build<'a>(
surface: document.record_key(),
dev,
measure,
compact,
taffy: TaffyTree::new(),
entries: Vec::new(),
leaves: Vec::new(),
@ -113,10 +121,17 @@ pub(super) fn build<'a>(
}
impl<'a> Builder<'a, '_> {
/// A bordered control's padding in Cells: one cell on every side, where its border stands.
fn chrome_padding(&self) -> taffy::Rect<taffy::LengthPercentage> {
let one = taffy::LengthPercentage::length(1.0);
taffy::Rect { left: one, right: one, top: one, bottom: one }
/// The form entry `index` takes: compact when the solve found it laid too short to be bordered.
fn form(&self, index: usize) -> ControlForm {
if self.compact.get(index).copied().unwrap_or(false) { ControlForm::Compact } else { ControlForm::Bordered }
}
/// A control's padding in Cells: one cell across where its brackets or border stand, and one down
/// where a border stands (a compact form has none).
fn chrome_padding(&self, index: usize) -> taffy::Rect<taffy::LengthPercentage> {
let (across, down) = self.dev.inset(self.form(index), f32::INFINITY, f32::INFINITY);
let (across, down) = (taffy::LengthPercentage::length(across), taffy::LengthPercentage::length(down));
taffy::Rect { left: across, right: across, top: down, bottom: down }
}
fn hidden(&self, id: &NodeId) -> bool {
@ -141,7 +156,7 @@ impl<'a> Builder<'a, '_> {
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, control: false });
self.entries.push(Entry { id, node: taffy::NodeId::from(0u64), parent, clip, scroll, control: None, inset: true });
self.entries.len() - 1
}
@ -162,11 +177,14 @@ impl<'a> Builder<'a, '_> {
}
}
let control = matches!(leaf, Leaf::TextInput { .. } | Leaf::Toggle { .. } | Leaf::Select { .. });
let form = self.form(self.entries.len());
if control && self.dev.cells() {
style.padding = self.chrome_padding();
style.padding = self.chrome_padding(self.entries.len());
}
let index = self.entry(id, parent, &Overflow::Visible);
self.entries[index].control = control;
if control {
self.entries[index].control = Some(form);
}
let context = self.leaves.len();
self.leaves.push(leaf);
let node = self.taffy.new_leaf_with_context(style, context).expect("taffy: insert");
@ -213,19 +231,22 @@ impl<'a> Builder<'a, '_> {
}
Node::Button(b) => {
if !self.hidden(&b.common.id) {
// In Cells the border stands in the edge cells: the content keeps clear of it on
// every side (the inset rule, `Device::inset`), so a content-sized Button's box
// includes its border rows. The content is a row as in Pixels, its items centred
// between the borders of a tall Button by alignment. Pixels: render draws the
// chrome behind it.
// In Cells the content keeps clear of the brackets or border on every side its
// form has one (the inset rule, `Device::inset`), so a content-sized Button's box
// includes its border rows. The content is a row as in Pixels: its items centred
// between the borders of a tall bordered Button by alignment, on the first row of
// a compact one. Pixels: render draws the chrome behind it and no inset applies.
let index = self.entries.len();
let form = self.form(index);
let style = if self.dev.cells() {
Style { align_items: taffy::AlignItems::CENTER, padding: self.chrome_padding(), ..Style::default() }
let align = if form == ControlForm::Compact { taffy::AlignItems::FLEX_START } else { taffy::AlignItems::CENTER };
Style { align_items: align, padding: self.chrome_padding(index), ..Style::default() }
} else {
Style::default()
};
let index = self.entries.len();
self.container(&b.common.id, parent, (style, Vec::new()), &Overflow::Visible, Axis::X, &b.content, out);
self.entries[index].control = self.dev.cells();
self.entries[index].control = Some(form);
self.entries[index].inset = self.dev.cells();
}
}
// A Repeat has no box: its instances are its parent's children, in instance order.

View file

@ -8,7 +8,7 @@ use super::Painter;
use super::command::RenderCommand;
use crate::bind::{Bound, Field};
use crate::diagnostic::{Code, Diagnostic};
use crate::layout::{Measure, Metrics, Rect, TextRequest};
use crate::layout::{ControlForm, LaidControl, Measure, Metrics, Rect, TextRequest};
/// Where an Image lands inside `rect` for an extent of `(w, h)` asset px (1 asset px = 1 logical
/// px), and whether it must be clipped to `rect`.
@ -70,25 +70,33 @@ impl<'a> Painter<'a> {
self.out.commands.push(RenderCommand::StrokeRect { rect, radius: 0.0, width: 1.0, color });
}
/// A control's border: stroked unless layout left it no inset (its content box is its whole
/// box), which is a control too short to hold a border and a row. `inner` is the laid content
/// box; a Button laid without one (Pixels) always has its border.
fn control_border(&mut self, id: &NodeId, rect: Rect, inner: Option<Rect>) {
if inner != Some(rect) {
self.stroke(id, rect);
/// A control's chrome as layout chose its form: `Bordered` is the box stroke; `Compact` is the
/// one-row affordance on the first row, whose stroke is the brackets of a one-row stroke.
fn chrome(&mut self, id: &NodeId, rect: Rect, form: ControlForm) {
match form {
ControlForm::Bordered => self.stroke(id, rect),
ControlForm::Compact => self.stroke(id, Rect { h: rect.h.min(1.0), ..rect }),
}
}
pub(super) fn button(&mut self, n: &ButtonNode, rect: Rect, inner: Option<Rect>) {
pub(super) fn button(&mut self, n: &ButtonNode, rect: Rect, control: LaidControl) {
let id = &n.common.id;
let enabled = self.flag(id, Field::Enabled) != Some(false);
self.fill(id, rect, if enabled { "thing.control.fill" } else { "thing.control.disabled" });
self.control_border(id, rect, inner);
self.chrome(id, rect, control.form);
}
pub(super) fn toggle(&mut self, n: &ToggleNode, rect: Rect, inner: Rect) {
pub(super) fn toggle(&mut self, n: &ToggleNode, rect: Rect, control: LaidControl) {
let id = &n.common.id;
self.control_border(id, rect, Some(inner));
let LaidControl { form, content } = control;
// A compact toggle is its glyph alone, on the one row its form keeps.
let inner = match form {
ControlForm::Bordered => content,
ControlForm::Compact => Rect { h: content.h.min(1.0), ..content },
};
if form == ControlForm::Bordered {
self.chrome(id, rect, form);
}
let side = inner.h.min(inner.w / 2.0).max(0.0);
let checked = self.flag(id, Field::Checked) == Some(true);
let x = if checked { inner.x + inner.w - side } else { inner.x };
@ -118,9 +126,10 @@ impl<'a> Painter<'a> {
self.fill(id, Rect { x, y: rect.y, w: side, h: side }, "thing.control.accent");
}
pub(super) fn select(&mut self, n: &SelectNode, rect: Rect, inner: Rect, text: &mut dyn Measure) {
pub(super) fn select(&mut self, n: &SelectNode, rect: Rect, control: LaidControl, text: &mut dyn Measure) {
let id = &n.common.id;
self.control_border(id, rect, Some(inner));
let inner = control.content;
self.chrome(id, rect, control.form);
let Some(value) = self.bound_text(id, Field::Selected) else { return };
let tree = self.tree;
let label = match tree.value(id, Field::Options) {
@ -130,9 +139,10 @@ impl<'a> Painter<'a> {
self.draw_text(id, label, "thing.text", false, Some(1), inner, inner.h, text);
}
pub(super) fn text_input(&mut self, n: &TextInputNode, rect: Rect, inner: Rect, text: &mut dyn Measure) {
pub(super) fn text_input(&mut self, n: &TextInputNode, rect: Rect, control: LaidControl, text: &mut dyn Measure) {
let id = &n.common.id;
self.control_border(id, rect, Some(inner));
let inner = control.content;
self.chrome(id, rect, control.form);
let (content, token) = match self.bound_text(id, Field::Initial).filter(|t| !t.is_empty()) {
Some(initial) => (initial, "thing.text"),
None => match self.bound_text(id, Field::Placeholder) {

View file

@ -19,7 +19,7 @@ pub use scroll::{ScrollOffsets, clamp};
use crate::bind::{Bound, BoundTree, Field};
use crate::diagnostic::{Code, Diagnostic};
use crate::layout::{LaidTree, MAX_DEVICE, Measure, Metrics, Rect};
use crate::layout::{ControlForm, LaidControl, LaidTree, MAX_DEVICE, Measure, Metrics, Rect};
use crate::resolve::grow;
use crate::theme::{Theme, fallback};
@ -221,8 +221,8 @@ impl<'a> Painter<'a> {
self.out.placed.push(Placed { id: laid.id.clone(), rect, visible });
self.stack.push(i);
let Some(node) = node else { return };
let inner = laid.inside.map(|inside| self.logical(inside, shift));
self.paint(node, rect, inner, text);
let control = laid.control.map(|c| LaidControl { content: self.logical(c.content, shift), ..c });
self.paint(node, rect, control, text);
if let (Some(padding), Node::Box(b)) = (laid.clip, node) {
let clip = self.logical(padding, shift);
let border = self.border(b).map_or(0.0, |(_, width)| width);
@ -231,7 +231,8 @@ impl<'a> Painter<'a> {
}
}
fn paint(&mut self, node: &'a Node, rect: Rect, inner: Option<Rect>, text: &mut dyn Measure) {
fn paint(&mut self, node: &'a Node, rect: Rect, control: Option<LaidControl>, text: &mut dyn Measure) {
let whole = LaidControl { form: ControlForm::Bordered, content: rect };
match node {
Node::Box(b) => {
let id = &b.common.id;
@ -268,11 +269,11 @@ impl<'a> Painter<'a> {
_ => {}
}
}
Node::Button(n) => self.button(n, rect, inner),
Node::Toggle(n) => self.toggle(n, rect, inner.unwrap_or(rect)),
Node::Button(n) => self.button(n, rect, control.unwrap_or(whole)),
Node::Toggle(n) => self.toggle(n, rect, control.unwrap_or(whole)),
Node::Slider(n) => self.slider(n, rect),
Node::Select(n) => self.select(n, rect, inner.unwrap_or(rect), text),
Node::TextInput(n) => self.text_input(n, rect, inner.unwrap_or(rect), text),
Node::Select(n) => self.select(n, rect, control.unwrap_or(whole), text),
Node::TextInput(n) => self.text_input(n, rect, control.unwrap_or(whole), text),
Node::Image(n) => self.image(n, rect, text),
Node::Plot(n) => self.plot(n, rect),
Node::Overlay(_) | Node::Repeat(_) | Node::Slot(_) => {}

View file

@ -8,7 +8,7 @@ use taffy::{AlignContent, AlignItems, AvailableSpace, FlexDirection, Style, Taff
use thing_contract::*;
use thing_core::bind::{Binder, BoundTree};
use thing_core::diagnostic::Code;
use thing_core::layout::{Constraint, FrameError, LaidNode, LayoutError, LaidTree, LayoutFrame, Leaf, Measure, Metrics, TextLayout, TextRequest, layout};
use thing_core::layout::{Constraint, ControlForm, FrameError, LaidNode, LayoutError, LaidTree, LayoutFrame, Leaf, Measure, Metrics, TextLayout, TextRequest, layout};
use thing_core::port::Ledger;
use thing_core::resolve::{Limits, resolve};
use thing_testkit::build::*;
@ -1329,34 +1329,49 @@ fn lay_control(kind: &str, size: Option<(f64, f64)>, frame: &LayoutFrame) -> Lai
layout(&tree, frame, &mut *measure).unwrap()
}
fn inside(laid: &LaidTree, id: &str) -> Option<(f32, f32, f32, f32)> {
/// A control's stated form and content box.
fn control(laid: &LaidTree, id: &str) -> (ControlForm, (f32, f32, f32, f32)) {
let node = laid.nodes.iter().find(|n| n.id.as_str() == id).unwrap_or_else(|| panic!("no node {id}"));
node.inside.map(|r| (r.x, r.y, r.w, r.h))
let c = node.control.unwrap_or_else(|| panic!("{id} is no control"));
(c.form, (c.content.x, c.content.y, c.content.w, c.content.h))
}
/// A cell row in Px.
const ROW: f64 = 16.0;
#[test]
fn the_cells_inset_is_one_rule_for_every_bordered_control_with_its_edges_at_2_and_3_rows() {
// The border stands in the edge cells and the content box is one cell in on every side, once
// the box is 3 rows tall: a border and a content row. At 2 rows there is no room for both, so
// the control paints no border and its content box is its whole box.
fn a_control_declared_under_three_rows_keeps_that_height_in_the_compact_form() {
// The author asked for 1 or 2 rows: exactly that, never floored by chrome. One cell each side
// (the brackets, the toggle glyph), no vertical inset: content on the first row.
for kind in BORDERED {
for (rows, border) in [(2.0_f32, false), (3.0, true), (4.0, true), (7.0, true)] {
let laid = lay_control(kind, Some((20.0 * 8.0, f64::from(rows) * 16.0)), &cells(40.0, 10.0));
for rows in [1.0_f32, 2.0] {
let laid = lay_control(kind, Some((20.0 * 8.0, f64::from(rows) * ROW)), &cells(40.0, 10.0));
let (x, y, w, h) = rect(&laid, kind);
assert_eq!(h, rows, "{kind}: stretched to the root's {rows} rows");
let want = if border { (x + 1.0, y + 1.0, w - 2.0, h - 2.0) } else { (x, y, w, h) };
assert_eq!(inside(&laid, kind), Some(want), "{kind} at {rows} rows");
assert_eq!(h, rows, "{kind}: declared {rows} rows is {rows} rows");
assert_eq!(control(&laid, kind), (ControlForm::Compact, (x + 1.0, y, w - 2.0, h)), "{kind} at {rows} rows");
}
}
}
#[test]
fn a_content_sized_cells_control_includes_its_border_rows() {
fn a_control_of_three_rows_or_more_is_bordered_with_its_content_one_cell_in() {
for kind in BORDERED {
for rows in [3.0_f32, 4.0, 7.0] {
let laid = lay_control(kind, Some((20.0 * 8.0, f64::from(rows) * ROW)), &cells(40.0, 10.0));
let (x, y, w, h) = rect(&laid, kind);
assert_eq!(h, rows, "{kind}: stretched to the root's {rows} rows");
assert_eq!(control(&laid, kind), (ControlForm::Bordered, (x + 1.0, y + 1.0, w - 2.0, h - 2.0)), "{kind} at {rows} rows");
}
}
}
#[test]
fn a_content_sized_cells_control_is_bordered_and_includes_its_border_rows() {
for kind in BORDERED {
let laid = lay_control(kind, None, &cells(40.0, 10.0));
let (x, y, w, h) = rect(&laid, kind);
assert!(h >= 3.0, "{kind}: a border row above and below at least one content row");
assert_eq!(inside(&laid, kind), Some((x + 1.0, y + 1.0, w - 2.0, h - 2.0)), "{kind}");
assert_eq!(control(&laid, kind), (ControlForm::Bordered, (x + 1.0, y + 1.0, w - 2.0, h - 2.0)), "{kind}");
}
// A label that wraps to three lines in a Button 8 cells wide: 3 rows of label between 2 of border.
let hugging = laid_button(&[("label", "abcd efgh ijkl")], None, &cells(8.0, 10.0));
@ -1366,13 +1381,32 @@ fn a_content_sized_cells_control_includes_its_border_rows() {
}
#[test]
fn a_pixels_control_inset_is_two_logical_px_and_a_pixels_button_has_none() {
let laid = lay_control("input", Some((200.0, 100.0)), &pixels(800.0, 600.0, 2.0));
let (x, y, w, h) = rect(&laid, "input");
assert_eq!(inside(&laid, "input"), Some((x + 4.0, y + 4.0, w - 8.0, h - 8.0)), "2 logical px is 4 device px at scale 2");
fn a_compact_buttons_label_stands_on_its_first_row_inside_the_brackets() {
for rows in [1.0_f64, 2.0] {
let laid = laid_button(&[("go", "Go")], Some((160.0, rows * ROW)), &cells(40.0, 10.0));
let (button, label) = (rect(&laid, "btn"), rect(&laid, "go"));
assert_eq!(button.3, rows as f32);
assert_eq!((label.0, label.1), (button.0 + 1.0, button.1), "{rows} rows: one cell in, on the first row");
}
}
#[test]
fn a_pixels_control_is_always_bordered_with_a_two_px_inset_and_a_pixels_button_has_none() {
// The compact form is a Cells form: a short Pixels control keeps its chrome.
for px_height in [16.0, 32.0, 100.0] {
let laid = lay_control("input", Some((200.0, px_height)), &pixels(800.0, 600.0, 2.0));
let (x, y, w, h) = rect(&laid, "input");
let inset = 4.0_f32.min(h / 2.0);
assert_eq!(control(&laid, "input"), (ControlForm::Bordered, (x + 4.0, y + inset, w - 8.0, h - 2.0 * inset)), "2 logical px is 4 device px at scale 2, never more than half a side");
}
let button = lay_control("button", None, &pixels(800.0, 600.0, 2.0));
assert_eq!(inside(&button, "button"), None, "Pixels lays a Button's content without an inset");
assert_eq!(inside(&button, "label"), None, "and a node that is no control has no content box");
let (x, y, w, h) = rect(&button, "button");
assert_eq!(control(&button, "button"), (ControlForm::Bordered, (x, y, w, h)), "Pixels lays a Button's content without an inset");
assert!(laid_node(&button, "label").control.is_none(), "a node that is no control states none");
}
fn laid_node<'a>(laid: &'a LaidTree, id: &str) -> &'a LaidNode {
laid.nodes.iter().find(|n| n.id.as_str() == id).unwrap_or_else(|| panic!("no node {id}"))
}
#[test]
@ -1383,5 +1417,5 @@ fn a_control_smaller_than_its_inset_gives_up_half_of_each_side_at_most() {
let tree = bind(&mut MemState::new(), &surface_of(bx("root", grid, vec![bordered("input")]))).expect("resolves");
let laid = layout(&tree, &pixels(100.0, 100.0, 1.0), &mut FixedMeasure::pixels()).unwrap();
assert_eq!(rect(&laid, "input"), (0.0, 0.0, 2.0, 2.0));
assert_eq!(inside(&laid, "input"), Some((1.0, 1.0, 0.0, 0.0)));
assert_eq!(control(&laid, "input"), (ControlForm::Bordered, (1.0, 1.0, 0.0, 0.0)));
}

View file

@ -1243,9 +1243,9 @@ fn an_image_extent_and_a_px_box_of_the_same_size_are_the_same_cells() {
}
#[test]
fn a_cells_control_too_short_for_a_border_and_a_row_paints_no_border() {
// Layout publishes the content box; a box that is the whole border box has no border to paint.
// 3 rows is the least that holds the border and a content row.
fn render_paints_the_form_layout_stated_for_a_cells_control() {
// Bordered (3 rows or more): the box stroke. Compact (under 3): the brackets, a one-row stroke
// on the first row; a toggle is its glyph alone, no stroke. Layout chose; render drew that.
let strokes = |kind: &str, rows: f64| {
let mut style = plain();
style.size = size2(px(20.0 * 8.0), px(rows * 16.0));
@ -1258,15 +1258,51 @@ fn a_cells_control_too_short_for_a_border_and_a_row_paints_no_border() {
initial: lit_text("hi"),
submit: command("dismiss"),
}),
"select" => {
let options = OptionList::Literal(LiteralOptions { options: vec![SelectOption { value: "a".into(), label: "Alpha".into() }] });
let value = Bind { source: StateSource::Record(StateRef { provider: Some(ProviderId::new(PROVIDER)), schema: SchemaId::new("gamecult.thing.test.series.v1"), key: RecordKey::new("row") }), member: path(&["Name"]), format: None };
Node::Select(SelectNode { common: common("c"), options, value, on_change: command("dismiss") })
}
"toggle" => Node::Toggle(ToggleNode { common: common("c"), checked: lit_bool(true), on_change: command("dismiss") }),
_ => Node::Button(ButtonNode { common: common("c"), content: vec![text("label", "Go")], on_activate: command("dismiss"), enabled: lit_bool(true) }),
};
let (_, rendered) = inline(flat("root", style, vec![node]), &frame(30.0, 12.0, 1.0, Metrics::Cells), &ScrollOffsets::default());
rendered.commands.iter().filter(|c| matches!(c, RenderCommand::StrokeRect { .. })).count()
let rects: Vec<(f32, f32)> = rendered
.commands
.iter()
.filter_map(|c| match c {
RenderCommand::StrokeRect { rect, .. } => Some((rect.y, rect.h)),
_ => None,
})
.collect();
rects
};
for kind in ["input", "toggle", "button"] {
assert_eq!(strokes(kind, 2.0), 0, "{kind} at 2 rows");
assert_eq!(strokes(kind, 3.0), 1, "{kind} at 3 rows");
assert_eq!(strokes(kind, 6.0), 1, "{kind} at 6 rows");
for kind in ["input", "select", "button"] {
assert_eq!(strokes(kind, 1.0), [(0.0, 1.0)], "{kind} at 1 row: brackets");
assert_eq!(strokes(kind, 2.0), [(0.0, 1.0)], "{kind} at 2 rows: brackets on the first row");
assert_eq!(strokes(kind, 3.0), [(0.0, 3.0)], "{kind} at 3 rows: the box");
assert_eq!(strokes(kind, 6.0), [(0.0, 6.0)], "{kind} at 6 rows: the box");
}
assert!(strokes("toggle", 1.0).is_empty() && strokes("toggle", 2.0).is_empty(), "a compact toggle is its glyph");
assert_eq!(strokes("toggle", 3.0), [(0.0, 3.0)]);
}
#[test]
fn a_compact_controls_text_stands_one_cell_in_on_its_first_row() {
let input = |rows: f64| {
let mut style = plain();
style.size = size2(px(20.0 * 8.0), px(rows * 16.0));
let node = Node::TextInput(TextInputNode {
common: common("i"),
multiline: false,
input_kind: InputKind::Text,
placeholder: lit_text("type"),
initial: lit_text("hi"),
submit: command("dismiss"),
});
cells_text_origins(flat("root", style, vec![node]))
};
assert_eq!(input(1.0), [(1.0, 0.0)]);
assert_eq!(input(2.0), [(1.0, 0.0)]);
assert_eq!(input(3.0), [(1.0, 1.0)]);
}