diff --git a/crates/thing-core/src/diagnostic.rs b/crates/thing-core/src/diagnostic.rs index c475973..4ed8b32 100644 --- a/crates/thing-core/src/diagnostic.rs +++ b/crates/thing-core/src/diagnostic.rs @@ -39,6 +39,8 @@ pub enum Code { StyleValueInvalid, /// A laid node reaches past the precision bound: the layout is refused, never rounded. LayoutOutOfRange, + /// An Overlay anchored to a node that is not laid (hidden or absent); it was placed against the viewport. + OverlayAnchorMissing, } impl Code { diff --git a/crates/thing-core/src/layout/mod.rs b/crates/thing-core/src/layout/mod.rs index 65e8a14..001a96f 100644 --- a/crates/thing-core/src/layout/mod.rs +++ b/crates/thing-core/src/layout/mod.rs @@ -6,14 +6,17 @@ //! 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. +//! Overlays are out of flow: after the main pass each is laid out as its own root against its anchor +//! and appended after every main-tree node. mod measure; +mod overlay; mod style; mod tree; use taffy::{AvailableSpace, Size, compute_leaf_layout}; use measure::{Device, MAX_DEVICE}; -use thing_contract::NodeId; +use thing_contract::{NodeId, OverlayNode}; pub use measure::{Avail, Constraint, Leaf, Measure}; @@ -57,6 +60,10 @@ pub struct LaidNode { pub id: NodeId, pub rect: Rect, pub content: Option<(f32, f32)>, + /// How far `content` reaches past the padding box, never negative: the most an offset may + /// scroll. Input owns the offset and clamps it here; render and hit-test translate the + /// children by it. Layout never sees an offset, so a scroll never re-runs layout. + pub max_scroll: Option<(f32, f32)>, pub clip: bool, } @@ -108,9 +115,29 @@ pub fn layout(tree: &BoundTree, frame: &LayoutFrame, measure: &mut dyn Measure) let (Some(vw), Some(vh)) = (side(frame.viewport.0), side(frame.viewport.1)) else { return Err(FrameError::Viewport.into()); }; - let mut built = tree::build(tree, dev, (vw, vh), measure); - let tree::Built { taffy, root, entries, leaves, diagnostics } = &mut built; - let space = Size { width: AvailableSpace::Definite(vw), height: AvailableSpace::Definite(vh) }; + 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)?; + 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, + diagnostics: &mut Vec, +) -> Result, LayoutError> { + let tree::Built { taffy, root, entries, leaves, diagnostics: own, overlays } = &mut 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()]; for (i, entry) in entries.iter().enumerate() { @@ -134,10 +161,9 @@ pub fn layout(tree: &BoundTree, frame: &LayoutFrame, measure: &mut dyn Measure) .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 (px, py) = entry.parent.map_or(origin, |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); @@ -146,6 +172,12 @@ pub fn layout(tree: &BoundTree, frame: &LayoutFrame, measure: &mut dyn Measure) let round = |v: f32| (v + 0.5).floor(); (clean(round(overflow.right).max(w)), clean(round(overflow.bottom).max(h))) }); + // What the content reaches past the padding box, which is what an offset may scroll. + let max_scroll = content.map(|(cw, ch)| { + let inner_w = w - laid.border.left - laid.border.right; + let inner_h = h - laid.border.top - laid.border.bottom; + (clean((cw - inner_w).max(0.0)), clean((ch - inner_h).max(0.0))) + }); // Precision is a property of the whole layout: a position or an extent past the bound // (a sum along an axis included) refuses it, so no value is silently rounded. let reach = [x, y, x + w, y + h, content.map_or(0.0, |c| c.0), content.map_or(0.0, |c| c.1)]; @@ -161,8 +193,10 @@ pub fn layout(tree: &BoundTree, frame: &LayoutFrame, measure: &mut dyn Measure) id: entry.id.clone(), rect: Rect { x: clean(x), y: clean(y), w: clean(w), h: clean(h) }, content, + max_scroll, clip: entry.clip, }); } - Ok(LaidTree { nodes, diagnostics: std::mem::take(diagnostics) }) + diagnostics.append(own); + Ok(std::mem::take(overlays)) } diff --git a/crates/thing-core/src/layout/overlay.rs b/crates/thing-core/src/layout/overlay.rs new file mode 100644 index 0000000..9a594d3 --- /dev/null +++ b/crates/thing-core/src/layout/overlay.rs @@ -0,0 +1,56 @@ +//! The overlay pass: each Overlay is its own Taffy root, laid out against its anchor after the +//! main pass and appended after every main-tree node, which is the paint order (overlays last). +//! The viewport and a node anchor share one placement: the anchor's rect is the overlay's origin +//! and size. + +use std::collections::HashMap; + +use thing_contract::{Anchor, NodeId, OverlayNode}; + +use super::measure::Device; +use super::tree::{self, Top}; +use super::{LaidNode, LayoutError, Measure, Rect, solve}; +use crate::bind::BoundTree; +use crate::diagnostic::{Code, Diagnostic}; + +/// Lay out `first` and every Overlay nested in them: each Overlay before the Overlays inside it, +/// in document order, so an anchor inside an earlier Overlay resolves. An anchor that is not laid +/// (hidden, absent) places the overlay against the viewport and is named once. +pub(super) fn place_all<'a>( + tree: &'a BoundTree, + dev: Device, + viewport: (f32, f32), + first: Vec<&'a OverlayNode>, + measure: &mut dyn Measure, + nodes: &mut Vec, + diagnostics: &mut Vec, +) -> Result<(), LayoutError> { + let mut rects: HashMap = nodes.iter().map(|n| (n.id.clone(), n.rect)).collect(); + let mut pending: Vec<&OverlayNode> = first; + pending.reverse(); + while let Some(overlay) = pending.pop() { + let anchor = match &overlay.anchor { + Anchor::Viewport => Rect { x: 0.0, y: 0.0, w: viewport.0, h: viewport.1 }, + Anchor::Node(anchor) => match rects.get(&anchor.node) { + Some(rect) => *rect, + None => { + diagnostics.push(Diagnostic { + code: Code::OverlayAnchorMissing, + surface: tree.resolved().document().record_key(), + node: Some(overlay.common.id.clone()), + detail: anchor.node.as_str().to_string(), + }); + Rect { x: 0.0, y: 0.0, w: viewport.0, h: viewport.1 } + } + }, + }; + 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)?; + for node in &nodes[start..] { + rects.entry(node.id.clone()).or_insert(node.rect); + } + pending.extend(nested.into_iter().rev()); + } + Ok(()) +} diff --git a/crates/thing-core/src/layout/tree.rs b/crates/thing-core/src/layout/tree.rs index dc365da..7481bd4 100644 --- a/crates/thing-core/src/layout/tree.rs +++ b/crates/thing-core/src/layout/tree.rs @@ -1,7 +1,7 @@ //! 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 thing_contract::{Node, NodeId, Overflow, OverlayNode}; use super::measure::{Device, Leaf, MAX_DEVICE, intrinsic_ratio}; use super::style::{Invalid, box_style, embed_style}; @@ -27,6 +27,8 @@ pub(super) struct Built<'a> { /// The Taffy context of a measured leaf is its index here. pub(super) leaves: Vec>, pub(super) diagnostics: Vec, + /// The visible Overlays met in flow, in document order, for the overlay pass. + pub(super) overlays: Vec<&'a OverlayNode>, } struct Builder<'a, 'm> { @@ -38,12 +40,24 @@ struct Builder<'a, 'm> { entries: Vec>, leaves: Vec>, diagnostics: Vec, + overlays: Vec<&'a OverlayNode>, } +/// What the Taffy tree is rooted at: the viewport holding the document root, or one Overlay. +pub(super) enum Top<'a> { + Document, + Overlay(&'a OverlayNode), +} + +/// Build one Taffy tree of `size` device px. The document's tree is a block container (the +/// viewport) the root flows in, so a root with an auto width fills it and a Repeat at the root has +/// a parent to splice into. An Overlay's tree is the Overlay itself, the first entry: a container +/// of Taffy's default style the anchor's size, so its children are laid against the anchor. pub(super) fn build<'a>( tree: &'a BoundTree, dev: Device, - viewport: (f32, f32), + top: Top<'a>, + size: (f32, f32), measure: &mut dyn super::Measure, ) -> Built<'a> { let document = tree.resolved().document(); @@ -56,19 +70,40 @@ pub(super) fn build<'a>( entries: Vec::new(), leaves: Vec::new(), diagnostics: Vec::new(), + overlays: 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), height: taffy::Dimension::length(viewport.1) }, + let mut style = Style { + size: taffy::Size { width: taffy::Dimension::length(size.0), height: taffy::Dimension::length(size.1) }, ..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 } + let overlay = match top { + Top::Document => { + builder.visit(&document.root, None, &mut kids); + style.display = taffy::Display::Block; + style.position = taffy::Position::Relative; + None + } + Top::Overlay(overlay) => { + let index = builder.entry(&overlay.common.id, None, &Overflow::Visible); + for child in &overlay.children { + builder.visit(child, Some(index), &mut kids); + } + Some(index) + } + }; + let root = builder.taffy.new_with_children(style, &kids).expect("taffy: insert"); + if let Some(index) = overlay { + builder.entries[index].node = root; + } + Built { + taffy: builder.taffy, + root, + entries: builder.entries, + leaves: builder.leaves, + diagnostics: builder.diagnostics, + overlays: builder.overlays, + } } impl<'a> Builder<'a, '_> { @@ -165,8 +200,12 @@ impl<'a> Builder<'a, '_> { } } } - // Overlays are placed by their own cut; in flow they are nothing. - Node::Overlay(_) => {} + // An Overlay is out of flow: nothing here; the overlay pass lays it out against its anchor. + Node::Overlay(o) => { + if !self.hidden(&o.common.id) { + self.overlays.push(o); + } + } // A Use that stayed is resolve's placeholder (beside its diagnostic): a childless leaf // that keeps its place so render can draw the error. A Slot never survives resolve. Node::Use(u) => { diff --git a/crates/thing-core/tests/layout.rs b/crates/thing-core/tests/layout.rs index b779577..dd9f719 100644 --- a/crates/thing-core/tests/layout.rs +++ b/crates/thing-core/tests/layout.rs @@ -44,9 +44,29 @@ fn bind_with(state: &mut MemState, document: &SurfaceDocument, limits: Limits) - Ok(binder.tree(&document.record_key()).expect("bound").clone()) } -fn render(laid: &LaidTree) -> String { +/// Each Overlay of the document with its anchor, as the golden names it. +fn overlay_anchors(node: &Node, out: &mut std::collections::HashMap) { + match node { + Node::Box(b) => b.children.iter().for_each(|c| overlay_anchors(c, out)), + Node::Button(b) => b.content.iter().for_each(|c| overlay_anchors(c, out)), + Node::Overlay(o) => { + let anchor = match &o.anchor { + Anchor::Viewport => "viewport".to_string(), + Anchor::Node(a) => a.node.as_str().to_string(), + }; + out.insert(o.common.id.as_str().to_string(), anchor); + o.children.iter().for_each(|c| overlay_anchors(c, out)); + } + _ => {} + } +} + +fn render(laid: &LaidTree, anchors: &std::collections::HashMap) -> String { let mut out = String::new(); - for LaidNode { id, rect, content, clip } in &laid.nodes { + for LaidNode { id, rect, content, max_scroll, clip } in &laid.nodes { + if let Some(anchor) = anchors.get(id.as_str()) { + out += &format!("overlay {} anchor {anchor}\n", id.as_str()); + } out += &format!("{}\t{}\t{}\t{}\t{}", id.as_str(), rect.x, rect.y, rect.w, rect.h); if *clip { out += "\tclip"; @@ -54,6 +74,9 @@ fn render(laid: &LaidTree) -> String { if let Some((w, h)) = content { out += &format!("\tcontent {w}x{h}"); } + if let Some((x, y)) = max_scroll { + out += &format!("\tmax_scroll {x}x{y}"); + } out += "\n"; } out @@ -81,12 +104,17 @@ fn laid_fixture(fixture: Fixture, frame: &LayoutFrame) -> Vec<(String, Result String { let mut out = String::new(); + let set = fixture.load(); for (key, laid) in laid_fixture(fixture, frame) { match laid { Ok(laid) => { let mode = if frame.metrics == Metrics::Cells { "cells" } else { "pixels" }; out += &format!("surface {key} viewport {}x{} scale {} {mode}\n", frame.viewport.0, frame.viewport.1, frame.scale); - out += &render(&laid); + let mut anchors = std::collections::HashMap::new(); + for document in set.surfaces.iter().filter(|d| d.record_key() == key) { + overlay_anchors(&document.root, &mut anchors); + } + out += &render(&laid, &anchors); } Err(code) => out += &format!("surface {key} refused {code:?}\n"), } @@ -104,23 +132,25 @@ fn check(fixture: Fixture, suffix: &str, frame: &LayoutFrame) -> String { text } -const NOT_HERE: [Fixture; 2] = [Fixture::F05ModalOverlay, Fixture::F06ScrollList]; + #[test] fn goldens() { - for fixture in Fixture::ALL.into_iter().filter(|f| !NOT_HERE.contains(f)) { + for fixture in Fixture::ALL { check(fixture, "", &pixels(800.0, 600.0, 1.0)); } check(Fixture::F01SwarmDashboard, "-scale2", &pixels(800.0, 600.0, 2.0)); check(Fixture::F01SwarmDashboard, "-scale1.5", &pixels(800.0, 600.0, 1.5)); check(Fixture::F08EmbedViewport, "-scale1.5", &pixels(800.0, 600.0, 1.5)); check(Fixture::F12TextEdge, "-scale1.5", &pixels(800.0, 600.0, 1.5)); + check(Fixture::F05ModalOverlay, "-scale1.5", &pixels(800.0, 600.0, 1.5)); + check(Fixture::F06ScrollList, "-scale1.5", &pixels(800.0, 600.0, 1.5)); check(Fixture::F01SwarmDashboard, "-cells", &cells(100.0, 37.0)); } #[test] fn determinism() { - for fixture in Fixture::ALL.into_iter().filter(|f| !NOT_HERE.contains(f)) { + for fixture in Fixture::ALL { for frame in [pixels(800.0, 600.0, 1.0), pixels(800.0, 600.0, 1.5)] { let first = laid_fixture(fixture, &frame); let second = laid_fixture(fixture, &frame); @@ -971,3 +1001,191 @@ fn each_edge_of_the_precision_bound_refuses() { // Whole layouts at the bound are fine. assert!(!refused(bx("root", column, vec![embed("a", 10.0, 2_097_152.0)]))); } + +// ---- overlays and scroll ----------------------------------------------------------------- + +fn overlay(id: &str, anchor: Anchor, children: Vec) -> Node { + Node::Overlay(OverlayNode { common: common(id), anchor, modal: false, dismiss: command("dismiss"), children }) +} + +fn at(node: &str) -> Anchor { + Anchor::Node(AnchorNode { node: nid(node) }) +} + +fn hide(mut node: Node) -> Node { + if let Node::Box(b) = &mut node { + b.common.visible = lit_bool(false); + } + node +} + +fn code_count(laid: &LaidTree, code: Code) -> usize { + laid.diagnostics.iter().filter(|d| d.code == code).count() +} + +#[test] +fn anchor() { + let target = BoxStyle { margin: Edges { left: px(30.0), top: px(20.0), ..edges(px(0.0)) }, ..sized(100.0, 50.0) }; + let tree = |anchor: Anchor, hidden: bool| { + let target = bx("target", target.clone(), vec![]); + bx("root", plain(), vec![ + if hidden { hide(target) } else { target }, + overlay("pop", anchor, vec![bx("pop-box", sized(20.0, 10.0), vec![])]), + ]) + }; + // A node anchor: the overlay is the target's border box and its child sits at the target origin. + let laid = lay(tree(at("target"), false), 400.0, 300.0); + assert_eq!(rect(&laid, "target"), (30.0, 20.0, 100.0, 50.0)); + assert_eq!(rect(&laid, "pop"), (30.0, 20.0, 100.0, 50.0)); + assert_eq!(rect(&laid, "pop-box"), (30.0, 20.0, 20.0, 10.0)); + assert!(laid.diagnostics.is_empty()); + // Scale 1.5: the anchor rect is in device px and so is the placement. + let scaled = lay_with(&mut MemState::new(), tree(at("target"), false), &pixels(400.0, 300.0, 1.5)); + assert_eq!(rect(&scaled, "pop"), rect(&scaled, "target")); + assert_eq!(rect(&scaled, "pop-box"), (45.0, 30.0, 30.0, 15.0)); + // The viewport anchor. + let laid = lay(tree(Anchor::Viewport, false), 400.0, 300.0); + assert_eq!(rect(&laid, "pop"), (0.0, 0.0, 400.0, 300.0)); + assert_eq!(rect(&laid, "pop-box"), (0.0, 0.0, 20.0, 10.0)); + // A hidden anchor and an absent one: the viewport, and one diagnostic each. + for (anchor, hidden) in [(at("target"), true), (at("nowhere"), false)] { + let laid = lay(tree(anchor, hidden), 400.0, 300.0); + assert_eq!(rect(&laid, "pop"), (0.0, 0.0, 400.0, 300.0)); + assert_eq!(code_count(&laid, Code::OverlayAnchorMissing), 1); + let d = &laid.diagnostics[0]; + assert_eq!((d.node.as_ref().map(|n| n.as_str()), d.detail.as_str()), (Some("pop"), if hidden { "target" } else { "nowhere" })); + assert!(!d.code.refuses_document()); + } + // A hidden overlay is not laid at all. + let mut gone = overlay("pop", Anchor::Viewport, vec![]); + if let Node::Overlay(o) = &mut gone { + o.common.visible = lit_bool(false); + } + assert_eq!(ids(&lay(bx("root", plain(), vec![gone]), 400.0, 300.0)), ["root"]); +} + +#[test] +fn nested_overlays_resolve_their_anchors_in_document_order() { + let root = bx("root", plain(), vec![ + bx("target", sized(100.0, 50.0), vec![]), + overlay("outer", at("target"), vec![ + bx("pad", BoxStyle { margin: Edges { left: px(7.0), top: px(9.0), ..edges(px(0.0)) }, ..sized(40.0, 20.0) }, vec![]), + overlay("inner", at("pad"), vec![bx("deep", sized(5.0, 5.0), vec![])]), + ]), + overlay("sibling", Anchor::Viewport, vec![]), + ]); + let laid = lay(root, 400.0, 300.0); + // Each overlay is followed by the overlays inside it, then the next sibling. + assert_eq!(ids(&laid), ["root", "target", "outer", "pad", "inner", "deep", "sibling"]); + // The overlay root is a row flex container at the anchor origin: its child starts at its margin. + assert_eq!(rect(&laid, "pad"), (7.0, 9.0, 40.0, 20.0)); + assert_eq!(rect(&laid, "inner"), (7.0, 9.0, 40.0, 20.0)); + assert_eq!(rect(&laid, "deep"), (7.0, 9.0, 5.0, 5.0)); + assert!(laid.diagnostics.is_empty()); + // An anchor in a later overlay is not resolved yet: the viewport and a diagnostic. + let root = bx("root", plain(), vec![ + overlay("first", at("late"), vec![]), + overlay("second", Anchor::Viewport, vec![bx("late", sized(5.0, 5.0), vec![])]), + ]); + assert_eq!(code_count(&lay(root, 400.0, 300.0), Code::OverlayAnchorMissing), 1); +} + +#[test] +fn overlays_paint_after_the_main_tree() { + let root = bx("root", plain(), vec![ + overlay("o1", Anchor::Viewport, vec![bx("o1-child", sized(5.0, 5.0), vec![])]), + bx("after", sized(10.0, 10.0), vec![bx("after-child", sized(1.0, 1.0), vec![])]), + overlay("o2", Anchor::Viewport, vec![]), + bx("last", sized(10.0, 10.0), vec![]), + ]); + assert_eq!(ids(&lay(root, 400.0, 300.0)), ["root", "after", "after-child", "last", "o1", "o1-child", "o2"]); +} + +#[test] +fn a_node_anchor_places_through_the_same_rect_as_the_viewport() { + // An anchor that fills the viewport places the overlay exactly as the viewport anchor does. + let page = |anchor: Anchor| { + bx("root", BoxStyle { direction: Direction::Column, ..plain() }, vec![ + bx("full", sized(400.0, 300.0), vec![]), + overlay("pop", anchor, vec![bx("c", sized(20.0, 10.0), vec![])]), + ]) + }; + let by_node = lay(page(at("full")), 400.0, 300.0); + let by_viewport = lay(page(Anchor::Viewport), 400.0, 300.0); + let tail = |laid: &LaidTree| laid.nodes[2..].to_vec(); + assert_eq!(tail(&by_node), tail(&by_viewport)); +} + +fn scroll_box(id: &str, w: f64, h: f64, children: Vec) -> Node { + bx(id, BoxStyle { overflow: Overflow::Scroll, direction: Direction::Column, ..sized(w, h) }, children) +} + +fn scroll_of(laid: &LaidTree, id: &str) -> Option<(f32, f32)> { + laid.nodes.iter().find(|n| n.id.as_str() == id).unwrap_or_else(|| panic!("no node {id}")).max_scroll +} + +#[test] +fn scroll() { + let rows = |n: usize| -> Vec { + (0..n).map(|i| bx(&format!("row{i}"), BoxStyle { shrink: 0.0, ..sized(60.0, 25.0) }, vec![])).collect() + }; + let laid = lay(bx("root", plain(), vec![scroll_box("list", 100.0, 100.0, rows(10))]), 400.0, 300.0); + // 10 rows of 25 in a 100 box: 250 of content, 150 to scroll; the width fits. + let list = laid.nodes.iter().find(|n| n.id.as_str() == "list").unwrap(); + assert_eq!(list.content, Some((100.0, 250.0))); + assert_eq!(list.max_scroll, Some((0.0, 150.0))); + // A node that is not a scroll box has neither. + for id in ["root", "row0"] { + assert_eq!(scroll_of(&laid, id), None, "{id}"); + } + // Content smaller than the box scrolls nowhere. + let laid = lay(bx("root", plain(), vec![scroll_box("list", 100.0, 100.0, rows(2))]), 400.0, 300.0); + assert_eq!(scroll_of(&laid, "list"), Some((0.0, 0.0))); + // Overflow on the cross axis: a wide row. + let wide = bx("wide", BoxStyle { shrink: 0.0, ..sized(160.0, 10.0) }, vec![]); + let laid = lay(bx("root", plain(), vec![scroll_box("list", 100.0, 100.0, vec![wide])]), 400.0, 300.0); + assert_eq!(scroll_of(&laid, "list"), Some((60.0, 0.0))); +} + +#[test] +fn scroll_extent_is_measured_from_the_padding_box() { + // A 4 px border on a 100x100 box: the padding box is 92x92, so the same content + // scrolls further than it would in the border box. + let paint = Paint { background: None, border: Some(Border { color: ColorRef::Rgba(Rgba { r: 0, g: 0, b: 0, a: 255 }), width: 4.0 }), radius: 0.0 }; + let rows: Vec = (0..10).map(|i| bx(&format!("row{i}"), BoxStyle { shrink: 0.0, ..sized(10.0, 25.0) }, vec![])).collect(); + let style = BoxStyle { overflow: Overflow::Scroll, direction: Direction::Column, ..sized(100.0, 100.0) }; + let laid = lay(bx("root", plain(), vec![bx_paint("list", style, paint, rows)]), 400.0, 300.0); + let list = laid.nodes.iter().find(|n| n.id.as_str() == "list").unwrap(); + println!("PROBE border: content {:?} max_scroll {:?}", list.content, list.max_scroll); + let (_, content_h) = list.content.unwrap(); + let (_, scroll_y) = list.max_scroll.unwrap(); + assert_eq!(scroll_y, content_h - 92.0); +} + +#[test] +fn a_scroll_extent_past_the_bound_refuses_though_every_rect_is_in_range() { + // The scroll box sits far left, so the child absolute right edge is in range while its + // extent from the box origin is past 2^21: only the content extent is out of range. + let tree = |overflow: Overflow| { + let list = BoxStyle { overflow, shrink: 0.0, margin: Edges { left: px(-1_500_000.0), ..edges(px(0.0)) }, ..sized(100.0, 100.0) }; + let child = BoxStyle { shrink: 0.0, margin: Edges { left: px(1_000_000.0), ..edges(px(0.0)) }, ..sized(2_000_000.0, 10.0) }; + bx("root", plain(), vec![bx("list", list, vec![bx("child", child, vec![])])]) + }; + let run = |overflow: Overflow| { + let tree = bind(&mut MemState::new(), &surface_of(tree(overflow))).unwrap(); + layout(&tree, &pixels(800.0, 600.0, 1.0), &mut FixedMeasure::pixels(&[])) + }; + assert!(run(Overflow::Visible).is_ok(), "the same boxes without a scroll lay out"); + match run(Overflow::Scroll) { + Err(LayoutError::OutOfRange(d)) => assert_eq!(d.node.as_ref().map(|n| n.as_str()), Some("list")), + other => panic!("{other:?}"), + } +} + +#[test] +fn overlays_hold_the_bound() { + // An overlay's content past the bound refuses like the main tree's. + let root = bx("root", plain(), vec![overlay("pop", Anchor::Viewport, vec![embed("big", 10.0, 2_097_153.0)])]); + let tree = bind(&mut MemState::new(), &surface_of(root)).unwrap(); + assert!(matches!(layout(&tree, &pixels(800.0, 600.0, 1.0), &mut FixedMeasure::pixels(&[])), Err(LayoutError::OutOfRange(_)))); +}