Skip to main content

day_core/
layout.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! The layout engine (DESIGN.md §7): parent-proposes/child-chooses with a proposal-keyed
5//! measure cache. Layout impls are ours or user-provided; they never run reactive user code,
6//! so the engine holds the single tree borrow for the whole pass.
7
8use std::rc::Rc;
9
10day_reactive::tls_slots! {
11    layout;
12    /// Nodes already warned about (see the report site below): once per node, not per
13    /// frame. A rebuilt page gets a fresh node and may report again, which is fine.
14    static REPORTED: std::cell::RefCell<std::collections::HashSet<RNode>> =
15        std::cell::RefCell::new(std::collections::HashSet::new());
16}
17
18use day_spec::*;
19
20use crate::tree::{Flex, RNode, Tree, TreeOps};
21
22/// Open layout protocol (§7.2). `children` are the node's direct children; group nodes
23/// (`when`/`each` anchors) are layout-transparent: stacks expand them inline.
24pub trait Layout: 'static {
25    fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size;
26    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect);
27    /// Where this node's own first text baseline falls, measured from the top of a box of
28    /// `size` (docs/baseline.md). `None` (the default) means the node has no baseline to
29    /// offer, so a baseline-aligned parent falls back to box alignment for it.
30    ///
31    /// A container answers on behalf of its content: a column reports its first
32    /// baseline-bearing child's, shifted by where that child sits. Leaves never reach here;
33    /// [`LayoutOps::baseline_of`] asks the toolkit for those.
34    fn baseline(&self, _cx: &mut dyn LayoutOps, _children: &[RNode], _size: Size) -> Option<f64> {
35        None
36    }
37}
38
39/// The engine surface visible to `Layout` implementations.
40pub trait LayoutOps {
41    fn measure_child(&mut self, child: RNode, p: Proposal) -> Size;
42    fn place_child(&mut self, child: RNode, rect: Rect);
43    /// Place a child whose on-screen frame is native-owned (nav pages in splitter panes /
44    /// nav-controller views): never direction-mirrored, because the toolkit positions it.
45    fn place_child_native(&mut self, child: RNode, rect: Rect) {
46        self.place_child(child, rect);
47    }
48    fn flex_of(&self, child: RNode) -> Flex;
49    fn children_of(&self, node: RNode) -> Vec<RNode>;
50    /// Native intrinsic measurement of the current node (leaves).
51    fn measure_leaf(&mut self, p: Proposal) -> Size;
52    /// A child's first text baseline at `size`, from the top of its box (docs/baseline.md):
53    /// the toolkit answers for a native leaf, the child's own [`Layout::baseline`] for a
54    /// container. `None` ⇒ no baseline to align to.
55    fn baseline_of(&mut self, child: RNode, size: Size) -> Option<f64>;
56    /// Report scroll content size for the current node (§7.6).
57    fn set_scroll_content(&mut self, content: Size);
58    /// The room the current scroll node's scroll bar takes from its content area while the
59    /// content overflows (`Toolkit::scroll_bar_inset`); 0 where bars overlay the content.
60    fn scroll_bar_inset(&mut self, _vertical: bool) -> f64 {
61        0.0
62    }
63    /// Report that the current node's children outgrew the bounds its `place()` was given
64    /// (`needed` vs `available` main-axis points). A diagnostic hook, not a layout input:
65    /// the engine logs it once per node in debug builds and ignores it in release, and
66    /// placement proceeds unchanged either way. Scroll containers never report, since
67    /// content larger than the viewport is their normal state.
68    fn report_overflow(&mut self, _needed: f64, _available: f64) {}
69}
70
71pub struct EngineCx<'a, B: Toolkit> {
72    pub(crate) tree: &'a mut Tree<B>,
73    pub(crate) offset: Point,
74    pub(crate) current: RNode,
75    /// The bounds the current node's `place()` was given: the mirroring axis for RTL.
76    pub(crate) parent_size: Size,
77}
78
79impl<B: Toolkit> LayoutOps for EngineCx<'_, B> {
80    fn measure_child(&mut self, child: RNode, p: Proposal) -> Size {
81        measure_node(self.tree, child, p)
82    }
83    fn place_child(&mut self, child: RNode, rect: Rect) {
84        // RTL (docs/localization): layouts compute LTR ("leading" = left); under a
85        // right-to-left locale every horizontal placement mirrors around the parent's
86        // width, so leading means right everywhere (rows reverse, padding swaps sides,
87        // alignment flips) without any layout impl knowing about direction. Leaf content
88        // (canvas drawing, text runs) is not mirrored; native text handles RTL itself.
89        let rect = if crate::layout_direction() == day_geometry::LayoutDirection::Rtl {
90            Rect::new(
91                self.parent_size.width - rect.origin.x - rect.size.width,
92                rect.origin.y,
93                rect.size.width,
94                rect.size.height,
95            )
96        } else {
97            rect
98        };
99        place_node(self.tree, child, rect, self.offset, false);
100    }
101    fn place_child_native(&mut self, child: RNode, rect: Rect) {
102        place_node(self.tree, child, rect, self.offset, false);
103    }
104    fn flex_of(&self, child: RNode) -> Flex {
105        self.tree.node(child).map_or_default(|n| n.flex)
106    }
107    fn children_of(&self, node: RNode) -> Vec<RNode> {
108        self.tree.node(node).map_or_default(|n| n.children.clone())
109    }
110    fn measure_leaf(&mut self, p: Proposal) -> Size {
111        let Some(n) = self.tree.node(self.current) else {
112            return Size::ZERO;
113        };
114        let kind = n.kind;
115        let Some(h) = n.handle.clone() else {
116            return Size::ZERO;
117        };
118        self.tree.toolkit.measure(&h, kind, p)
119    }
120    fn baseline_of(&mut self, child: RNode, size: Size) -> Option<f64> {
121        baseline_node(self.tree, child, size)
122    }
123    fn set_scroll_content(&mut self, content: Size) {
124        let current = self.current;
125        let Some(n) = self.tree.node_mut(current) else {
126            return;
127        };
128        // Cache for scroll_to_target (§7.6): edge targets need content-minus-viewport math.
129        n.scroll_content = Some(content);
130        let Some(h) = n.handle.clone() else { return };
131        self.tree.toolkit.set_scroll_content(&h, content);
132    }
133    fn scroll_bar_inset(&mut self, vertical: bool) -> f64 {
134        let Some(h) = self.tree.node(self.current).and_then(|n| n.handle.clone()) else {
135            return 0.0;
136        };
137        self.tree.toolkit.scroll_bar_inset(&h, vertical).max(0.0)
138    }
139
140    #[cfg(debug_assertions)]
141    fn report_overflow(&mut self, needed: f64, available: f64) {
142        // Once per node, not per frame: layout re-runs constantly, and this is meant as a
143        // greppable hint, not a firehose. A rebuilt page gets a fresh node and may report
144        // again, which is fine.
145        if REPORTED.with(|r| !r.borrow_mut().insert(self.current)) {
146            return;
147        }
148        // Name the container by the dayscript ids in reach, because an id is the one thing a
149        // developer can grep straight to the source. Ids usually sit a wrapper or two below
150        // the overflowing stack (`.id` tags the piece, decorators wrap it), so this walks the
151        // subtree depth-first and keeps the first few it meets.
152        let mut ids: Vec<String> = Vec::new();
153        let mut stack = vec![self.current];
154        while let Some(node) = stack.pop() {
155            if ids.len() >= 6 {
156                break;
157            }
158            if let Some(n) = self.tree.node(node) {
159                ids.extend(n.id.clone());
160                stack.extend(n.children.iter().rev());
161            }
162        }
163        let who = if ids.is_empty() {
164            String::from("no .id in reach")
165        } else {
166            ids.join(", ")
167        };
168        log::warn!(
169            "day layout: children overflow their container by {:.0}pt ({needed:.0} needed, \
170             {available:.0} available; {who}) — give the row a fit policy: \
171             .fit(RowFit::Wrap/Scroll) or adaptive(..) (docs/size-classes.md)",
172            needed - available,
173        );
174    }
175}
176
177pub(crate) fn measure_node<B: Toolkit>(tree: &mut Tree<B>, node: RNode, p: Proposal) -> Size {
178    let key = p.cache_key();
179    let (layout, children) = {
180        let Some(n) = tree.node(node) else {
181            return Size::ZERO;
182        };
183        if !n.needs_measure
184            && let Some(&(_, s)) = n.cache.iter().find(|(k, _)| *k == key)
185        {
186            return s;
187        }
188        (n.layout.clone(), n.children.clone())
189    };
190    let mut cx = EngineCx {
191        tree,
192        offset: Point::ZERO,
193        current: node,
194        parent_size: Size::ZERO, // placement never happens during measure
195    };
196    let size = layout.measure(&mut cx, &children, p);
197    if let Some(n) = tree.node_mut(node) {
198        n.needs_measure = false;
199        if n.cache.len() >= 4 {
200            n.cache.clear();
201        }
202        n.cache.push((key, size));
203    }
204    size
205}
206
207/// A node's first text baseline at `size`, from the top of its box (docs/baseline.md). A native
208/// leaf asks the toolkit; anything else asks its own `Layout`, which answers for its content.
209///
210/// Cached per size and invalidated with the measure cache, so a baseline-aligned row costs one
211/// toolkit call per child per measure generation rather than one per layout pass.
212pub(crate) fn baseline_node<B: Toolkit>(
213    tree: &mut Tree<B>,
214    node: RNode,
215    size: Size,
216) -> Option<f64> {
217    let key = Proposal::exact(size).cache_key();
218    let (layout, children, handle, kind) = {
219        let n = tree.node(node)?;
220        if !n.needs_measure
221            && let Some((k, b)) = n.baseline_cache
222            && k == key
223        {
224            return b;
225        }
226        (
227            n.layout.clone(),
228            n.children.clone(),
229            n.handle.clone(),
230            n.kind,
231        )
232    };
233    // A realized leaf's baseline is the toolkit's to report; a container's is its layout's.
234    let baseline = match handle {
235        Some(h) if children.is_empty() => tree.toolkit.first_baseline(&h, kind, size),
236        _ => {
237            let mut cx = EngineCx {
238                tree,
239                offset: Point::ZERO,
240                current: node,
241                parent_size: Size::ZERO,
242            };
243            layout.baseline(&mut cx, &children, size)
244        }
245    };
246    if let Some(n) = tree.node_mut(node) {
247        n.baseline_cache = Some((key, baseline));
248    }
249    baseline
250}
251
252/// `rect` is in the parent node's coordinates; `offset` is the parent's origin in the nearest
253/// native ancestor's coordinates (§7.1, accumulated through layout-only nodes).
254pub(crate) fn place_node<B: Toolkit>(
255    tree: &mut Tree<B>,
256    node: RNode,
257    rect: Rect,
258    offset: Point,
259    is_root: bool,
260) {
261    let abs = Rect {
262        origin: rect.origin.offset(offset.x, offset.y),
263        size: rect.size,
264    };
265    let (layout, children, has_handle) = {
266        let Some(n) = tree.node(node) else { return };
267        (n.layout.clone(), n.children.clone(), n.handle.is_some())
268    };
269    // A cover's frame is the backend's (docs/cover.md): presented, it is re-homed over the
270    // window and follows the window's resizing; parked, it is hidden. Where it sits in
271    // the tree it measures zero (`CoverLayout`), so applying the parent's placement (a
272    // zero-size rect at the parent's center) would collapse a presented cover to a line
273    // the moment anything re-lays the parent out. A window resize did exactly that on
274    // macOS (Games Fair, 2026-09-11): the game vanished into a one-pixel strip over the home
275    // page. Its content is still placed below, at the size the backend reported.
276    let native_frame = tree
277        .node(node)
278        .is_some_and(|n| n.kind == day_spec::kinds::COVER);
279    let child_offset = if has_handle {
280        if !is_root && !native_frame {
281            let changed = tree
282                .node(node)
283                .is_some_and(|n| n.last_native_frame.is_none_or(|f| !f.approx_eq(&abs, 0.25)));
284            if changed {
285                let h = tree.node(node).and_then(|n| n.handle.clone());
286                if let Some(h) = h {
287                    let anim = tree.resolve_anim(node);
288                    tree.toolkit.set_frame(&h, abs, anim.as_ref());
289                }
290                if tree
291                    .node(node)
292                    .is_some_and(|n| n.kind == day_spec::kinds::CANVAS)
293                {
294                    // Queue-only (§8.3): canvases re-record against the new size after layout.
295                    crate::tree::enqueue_event(
296                        crate::tree::rnode_to_id(node),
297                        day_spec::Event::FrameChanged(abs.size),
298                    );
299                }
300            }
301        }
302        Point::ZERO
303    } else {
304        abs.origin
305    };
306    // A list whose width changes re-lays its active cells in this pass: the native table
307    // resizes the physical cell views, but each cell's day content keeps the old width's
308    // placement until laid out again (a trailing control would sit clipped after a
309    // narrowing). It runs synchronously because interactive live-resize runs inside a
310    // native tracking loop where deferred main-thread work may not drain until the drag
311    // ends.
312    let relayout_cells = tree.node(node).is_some_and(|n| {
313        n.kind == day_spec::kinds::LIST
314            && n.last_native_frame
315                .is_some_and(|f| (f.size.width - abs.size.width).abs() > 0.25)
316    });
317    if let Some(n) = tree.node_mut(node) {
318        n.last_native_frame = Some(abs);
319        n.needs_layout = false;
320    }
321    if relayout_cells {
322        for key in tree.list_cell_keys(node) {
323            tree.list_layout_cell(node, key);
324        }
325    }
326    let mut cx = EngineCx {
327        tree,
328        offset: child_offset,
329        current: node,
330        parent_size: rect.size,
331    };
332    layout.place(&mut cx, &children, Rect::from_size(rect.size));
333}
334
335// ---------------------------------------------------------------------------
336// Built-in layouts
337// ---------------------------------------------------------------------------
338
339/// A single-child wrapper's baseline is its child's, moved by where the child sits inside it
340/// (docs/baseline.md).
341///
342/// Padding and alignment add vertical offsets; the other wrappers forward the child’s baseline
343/// at the size they assign during placement. Without this a decorated piece reports no baseline, and since decorators are
344/// invisible in the source (`.width(90)` on a label is still "a label" to the reader), a row
345/// would silently center the very children the author asked to align. That is exactly what
346/// happened to the showcase's first baseline demo.
347fn wrapper_baseline(
348    cx: &mut dyn LayoutOps,
349    children: &[RNode],
350    child_size: Size,
351    dy: f64,
352) -> Option<f64> {
353    let &c = children.first()?;
354    Some(cx.baseline_of(c, child_size)? + dy)
355}
356
357/// Single-child pass-through (root, wrappers, group fallback): top-leading.
358pub struct PassThrough;
359
360impl Layout for PassThrough {
361    fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
362        match children.first() {
363            Some(&c) => cx.measure_child(c, p),
364            None => Size::ZERO,
365        }
366    }
367    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
368        if let Some(&c) = children.first() {
369            let s = cx.measure_child(c, Proposal::exact(bounds.size));
370            cx.place_child(c, Rect::from_size(s));
371        }
372    }
373}
374
375/// A recycled tree cell's anchor layout (docs/tree.md): row content hugs its own height, so
376/// center it in the cell's fixed row height; [`PassThrough`] pins it to the top, which
377/// reads as a misaligned row whenever the content is shorter than the row (a 16pt label in
378/// a 28pt row sat 6pt high). Width still fills; a content taller than the row clamps to it.
379pub struct CellCenter;
380
381impl Layout for CellCenter {
382    fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
383        match children.first() {
384            Some(&c) => cx.measure_child(c, p),
385            None => Size::ZERO,
386        }
387    }
388    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
389        if let Some(&c) = children.first() {
390            let s = cx.measure_child(c, Proposal::exact(bounds.size));
391            let y = ((bounds.size.height - s.height) / 2.0).max(0.0);
392            cx.place_child(
393                c,
394                Rect::new(0.0, y, s.width, s.height.min(bounds.size.height)),
395            );
396        }
397    }
398    fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
399        PassThrough::forward(cx, children, size)
400    }
401}
402
403/// A list cell's anchor layout (docs/list.md "Row metrics"): the row sits inside the platform's
404/// row margins and the cell is at least the platform's row height, content centered in it.
405/// With zero metrics it is [`PassThrough`].
406pub struct CellMetrics(pub day_spec::RowMetrics);
407
408impl CellMetrics {
409    /// The metrics for `child`. The platform's own whole row keeps the list's side margins
410    /// (they line up with the separators) and sizes its height itself.
411    fn for_child(&self, cx: &dyn LayoutOps, child: RNode) -> day_spec::RowMetrics {
412        // Through the single-child wrappers a row's decorators and builder add around it.
413        let mut node = child;
414        for _ in 0..8 {
415            if cx.flex_of(node).whole_row {
416                let i = self.0.insets;
417                return day_spec::RowMetrics {
418                    insets: day_spec::Insets {
419                        top: 0.0,
420                        leading: i.leading,
421                        bottom: 0.0,
422                        trailing: i.trailing,
423                    },
424                    min_height: 0.0,
425                };
426            }
427            match cx.children_of(node)[..] {
428                [only] => node = only,
429                _ => break,
430            }
431        }
432        self.0
433    }
434}
435
436impl Layout for CellMetrics {
437    fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
438        let Some(&c) = children.first() else {
439            return Size::ZERO;
440        };
441        let m = self.for_child(cx, c);
442        let i = m.insets;
443        let (dx, dy) = (i.leading + i.trailing, i.top + i.bottom);
444        let s = cx.measure_child(
445            c,
446            Proposal::new(
447                p.width.map(|w| (w - dx).max(0.0)),
448                p.height.map(|h| (h - dy).max(0.0)),
449            ),
450        );
451        Size::new(s.width + dx, (s.height + dy).max(m.min_height))
452    }
453    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
454        let Some(&c) = children.first() else {
455            return;
456        };
457        let i = self.for_child(cx, c).insets;
458        let inner = Size::new(
459            (bounds.size.width - i.leading - i.trailing).max(0.0),
460            (bounds.size.height - i.top - i.bottom).max(0.0),
461        );
462        let s = cx.measure_child(c, Proposal::new(Some(inner.width), None));
463        // Inside the margins where the row has room for them; a fixed-height row too short for
464        // them (`RowHeight::Uniform`) centers its content in the whole row instead of clipping.
465        let (y, h) = if s.height <= inner.height {
466            (i.top + (inner.height - s.height) / 2.0, s.height)
467        } else {
468            let h = s.height.min(bounds.size.height);
469            (((bounds.size.height - h) / 2.0).max(0.0), h)
470        };
471        cx.place_child(c, Rect::new(i.leading, y, inner.width, h));
472    }
473    fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
474        PassThrough::forward(cx, children, size)
475    }
476}
477
478impl PassThrough {
479    /// Shared by every wrapper whose child measures at the wrapper's own size.
480    fn forward(cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
481        let &c = children.first()?;
482        let cs = cx.measure_child(c, Proposal::exact(size));
483        wrapper_baseline(cx, children, cs, 0.0)
484    }
485}
486
487/// Paint/clip wrapper (`.background`, `.corner_radius`, the animatable layers): like
488/// [`PassThrough`] for measurement, but the granted rect flows to the child verbatim at place
489/// time. These containers exist to paint or clip the area the parent granted, so a grow
490/// stretch above them must reach the painted surface (the grid-cell card case) instead of
491/// being re-hugged at every wrapper. Under a parent that places at measured size (every
492/// stack, grid rigid cell, and overlay) bounds equal the measure and nothing changes.
493pub struct FillThrough;
494
495impl Layout for FillThrough {
496    fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
497        match children.first() {
498            Some(&c) => cx.measure_child(c, p),
499            None => Size::ZERO,
500        }
501    }
502    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
503        if let Some(&c) = children.first() {
504            cx.place_child(c, Rect::from_size(bounds.size));
505        }
506    }
507    fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
508        wrapper_baseline(cx, children, size, 0.0)
509    }
510}
511
512/// Native leaf: measurement delegates to the toolkit.
513pub struct LeafLayout;
514
515impl Layout for LeafLayout {
516    fn measure(&self, cx: &mut dyn LayoutOps, _children: &[RNode], p: Proposal) -> Size {
517        cx.measure_leaf(p)
518    }
519    fn place(&self, _cx: &mut dyn LayoutOps, _children: &[RNode], _bounds: Rect) {}
520}
521
522#[derive(Clone, Copy, PartialEq, Eq)]
523pub enum Axis {
524    Vertical,
525    Horizontal,
526}
527
528#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
529pub enum CrossAlign {
530    Leading,
531    #[default]
532    Center,
533    Trailing,
534    /// Align children on their first text baseline rather than on their boxes
535    /// (docs/baseline.md). Horizontal rows only: a column's children are stacked along the
536    /// axis a baseline lives on, so there is nothing to align. A child whose toolkit reports no
537    /// baseline is centered, so a row of text and an image still looks right.
538    FirstBaseline,
539}
540
541impl CrossAlign {
542    /// Placement fraction of the free space: 0 = leading, 0.5 = center, 1 = trailing.
543    fn fraction(self) -> f64 {
544        match self {
545            CrossAlign::Leading => 0.0,
546            // No baseline to align to at this level (a column, or every child reported None):
547            // centering is the fallback the variant promises.
548            CrossAlign::Center | CrossAlign::FirstBaseline => 0.5,
549            CrossAlign::Trailing => 1.0,
550        }
551    }
552}
553
554/// Column/row negotiation (§7.2): rigid children first, remaining main-axis space divided
555/// among flexible children; `spacer()` is maximally flexible; group anchors expand inline.
556pub struct StackLayout {
557    pub axis: Axis,
558    pub spacing: f64,
559    pub align: CrossAlign,
560}
561
562impl StackLayout {
563    fn main(&self, s: Size) -> f64 {
564        match self.axis {
565            Axis::Vertical => s.height,
566            Axis::Horizontal => s.width,
567        }
568    }
569    fn cross(&self, s: Size) -> f64 {
570        match self.axis {
571            Axis::Vertical => s.width,
572            Axis::Horizontal => s.height,
573        }
574    }
575    fn mk(&self, main: f64, cross: f64) -> Size {
576        match self.axis {
577            Axis::Vertical => Size::new(cross, main),
578            Axis::Horizontal => Size::new(main, cross),
579        }
580    }
581    fn split(&self, p: Proposal) -> (Option<f64>, Option<f64>) {
582        match self.axis {
583            Axis::Vertical => (p.height, p.width),
584            Axis::Horizontal => (p.width, p.height),
585        }
586    }
587    fn proposal(&self, main: Option<f64>, cross: Option<f64>) -> Proposal {
588        match self.axis {
589            Axis::Vertical => Proposal::new(cross, main),
590            Axis::Horizontal => Proposal::new(main, cross),
591        }
592    }
593    fn grows_main(&self, f: Flex) -> bool {
594        f.is_spacer
595            || match self.axis {
596                Axis::Vertical => f.grow_h,
597                Axis::Horizontal => f.grow_w,
598            }
599    }
600    /// Sized after the rigid children, against what they leave, without growing the stack
601    /// (`Flex::yields_h`, a column only).
602    fn yields_main(&self, f: Flex) -> bool {
603        self.axis == Axis::Vertical && f.yields_h && !self.grows_main(f)
604    }
605    fn grows_cross(&self, f: Flex) -> bool {
606        match self.axis {
607            Axis::Vertical => f.grow_w,
608            Axis::Horizontal => f.grow_h,
609        }
610    }
611
612    fn flatten(cx: &mut dyn LayoutOps, children: &[RNode], out: &mut Vec<RNode>) {
613        for &c in children {
614            if cx.flex_of(c).is_group {
615                let inner = cx.children_of(c);
616                Self::flatten(cx, &inner, out);
617            } else {
618                out.push(c);
619            }
620        }
621    }
622
623    fn negotiate(&self, cx: &mut dyn LayoutOps, kids: &[RNode], p: Proposal) -> Vec<Size> {
624        let (main_p, cross_p) = self.split(p);
625        let mut sizes = vec![Size::ZERO; kids.len()];
626        let mut flex_idx = Vec::new();
627        let mut yield_idx = Vec::new();
628        let mut rigid_main = 0.0;
629        for (i, &k) in kids.iter().enumerate() {
630            let f = cx.flex_of(k);
631            if self.grows_main(f) {
632                flex_idx.push(i);
633            } else if self.yields_main(f) {
634                yield_idx.push(i);
635            } else {
636                let s = cx.measure_child(k, self.proposal(None, cross_p));
637                rigid_main += self.main(s);
638                sizes[i] = s;
639            }
640        }
641        // Shrink pass: when the rigid children's natural sizes overflow a bounded main axis,
642        // re-measure the overflowing ones against the space that is left (in order, so
643        // earlier children keep their natural size first). Content that fits keeps its natural
644        // measure, so proposal-expanding kinds (text fields, lists) don't balloon; wrapping
645        // content (a capped message bubble, a long label) folds instead of spilling out of the
646        // stack.
647        if let Some(mp) = main_p {
648            let spacing_total = self.spacing * (kids.len().saturating_sub(1)) as f64;
649            let available = (mp - spacing_total).max(0.0);
650            if rigid_main > available {
651                let mut budget = available;
652                rigid_main = 0.0;
653                for (i, &k) in kids.iter().enumerate() {
654                    let f = cx.flex_of(k);
655                    if self.grows_main(f) || self.yields_main(f) {
656                        continue;
657                    }
658                    if self.main(sizes[i]) > budget {
659                        sizes[i] = cx.measure_child(k, self.proposal(Some(budget), cross_p));
660                    }
661                    let m = self.main(sizes[i]);
662                    rigid_main += m;
663                    budget = (budget - m).max(0.0);
664                }
665            }
666        }
667        // Yielding children, in order, against what the rigid ones (and any yielding one before
668        // them) left: a capped scroll shrinks before the button under it is pushed out.
669        for &i in &yield_idx {
670            let spacing_total = self.spacing * (kids.len().saturating_sub(1)) as f64;
671            let left = main_p.map(|mp| (mp - rigid_main - spacing_total).max(0.0));
672            sizes[i] = cx.measure_child(kids[i], self.proposal(left, cross_p));
673            rigid_main += self.main(sizes[i]);
674        }
675        if !flex_idx.is_empty() {
676            let spacing_total = self.spacing * (kids.len().saturating_sub(1)) as f64;
677            match main_p {
678                Some(mp) => {
679                    let remaining = (mp - rigid_main - spacing_total).max(0.0);
680                    let share = remaining / flex_idx.len() as f64;
681                    for &i in &flex_idx {
682                        let f = cx.flex_of(kids[i]);
683                        sizes[i] = if f.is_spacer {
684                            self.mk(share, 0.0)
685                        } else {
686                            cx.measure_child(kids[i], self.proposal(Some(share), cross_p))
687                        };
688                    }
689                }
690                None => {
691                    for &i in &flex_idx {
692                        let f = cx.flex_of(kids[i]);
693                        sizes[i] = if f.is_spacer {
694                            Size::ZERO
695                        } else {
696                            cx.measure_child(kids[i], self.proposal(None, cross_p))
697                        };
698                    }
699                }
700            }
701        }
702        sizes
703    }
704
705    /// Each child's first baseline at the size it settled on, or `None` where it has none
706    /// (docs/baseline.md). Only a horizontal row aligns on baselines; down a column the
707    /// baselines sit on the stacking axis, where aligning them would pile the children up.
708    fn baselines(
709        &self,
710        cx: &mut dyn LayoutOps,
711        kids: &[RNode],
712        sizes: &[Size],
713    ) -> Vec<Option<f64>> {
714        if self.align != CrossAlign::FirstBaseline || self.axis != Axis::Horizontal {
715            return vec![None; kids.len()];
716        }
717        kids.iter()
718            .zip(sizes)
719            .map(|(&k, &s)| cx.baseline_of(k, s))
720            .collect()
721    }
722
723    /// The row's own cross-axis extent once its children are baseline-shifted: the deepest
724    /// baseline plus the deepest descent below one. A row measured at the tallest child's
725    /// height would clip whichever child got shifted furthest down.
726    #[expect(
727        clippy::float_cmp,
728        reason = "`f64::MIN` is the fold's seed, compared as a no-baseline sentinel"
729    )]
730    fn baseline_cross_extent(&self, baselines: &[Option<f64>], sizes: &[Size]) -> Option<f64> {
731        let deepest = baselines.iter().flatten().copied().fold(f64::MIN, f64::max);
732        if deepest == f64::MIN {
733            return None;
734        }
735        let below = baselines
736            .iter()
737            .zip(sizes)
738            .filter_map(|(b, s)| b.map(|b| self.cross(*s) - b))
739            .fold(0.0, f64::max);
740        Some(deepest + below)
741    }
742}
743
744impl Layout for StackLayout {
745    fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
746        let mut kids = Vec::new();
747        Self::flatten(cx, children, &mut kids);
748        if kids.is_empty() {
749            return Size::ZERO;
750        }
751        let (main_p, cross_p) = self.split(p);
752        let sizes = self.negotiate(cx, &kids, p);
753        let spacing_total = self.spacing * (kids.len() - 1) as f64;
754        let has_flex = kids.iter().any(|&k| self.grows_main(cx.flex_of(k)));
755        // A stack with a stretching child fills what it is offered, but never reports less
756        // than its children need together (a `.min_width`, fixed-size pairs), so an overflow
757        // is visible to the parent (a `labeled` row stacks) instead of being clipped.
758        let needed = sizes.iter().map(|&s| self.main(s)).sum::<f64>() + spacing_total;
759        let main_total = match main_p {
760            Some(mp) if has_flex => mp.max(needed),
761            _ => needed,
762        };
763        let grows_cross = kids.iter().any(|&k| self.grows_cross(cx.flex_of(k)));
764        let tallest = sizes.iter().map(|&s| self.cross(s)).fold(0.0, f64::max);
765        // Baseline shifting can push a child below the tallest one's bottom edge, so the row
766        // takes the extent the shifted children actually occupy (docs/baseline.md).
767        let stacked = self
768            .baseline_cross_extent(&self.baselines(cx, &kids, &sizes), &sizes)
769            .unwrap_or(0.0)
770            .max(tallest);
771        let cross_total = match cross_p {
772            Some(cp) if grows_cross => cp,
773            _ => stacked,
774        };
775        self.mk(main_total, cross_total)
776    }
777
778    /// A stack's own baseline is its first baseline-bearing child's, moved by where that child
779    /// sits: down a column that is the child's offset along the axis, across a row every
780    /// aligned child already shares the deepest baseline (docs/baseline.md).
781    #[expect(
782        clippy::float_cmp,
783        reason = "`f64::MIN` is the fold's seed, compared as a no-baseline sentinel"
784    )]
785    fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
786        let mut kids = Vec::new();
787        Self::flatten(cx, children, &mut kids);
788        if kids.is_empty() {
789            return None;
790        }
791        let sizes = self.negotiate(cx, &kids, Proposal::exact(size));
792        match self.axis {
793            Axis::Horizontal => {
794                let baselines: Vec<Option<f64>> = kids
795                    .iter()
796                    .zip(&sizes)
797                    .map(|(&k, &s)| cx.baseline_of(k, s))
798                    .collect();
799                let deepest = baselines.iter().flatten().copied().fold(f64::MIN, f64::max);
800                (deepest != f64::MIN).then_some(deepest)
801            }
802            Axis::Vertical => {
803                let mut pos = 0.0;
804                for (&k, &s) in kids.iter().zip(&sizes) {
805                    if let Some(b) = cx.baseline_of(k, s) {
806                        return Some(pos + b);
807                    }
808                    pos += self.main(s) + self.spacing;
809                }
810                None
811            }
812        }
813    }
814
815    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
816        let mut kids = Vec::new();
817        Self::flatten(cx, children, &mut kids);
818        if kids.is_empty() {
819            return;
820        }
821        let sizes = self.negotiate(cx, &kids, Proposal::exact(bounds.size));
822        // The children's settled extent against what this stack was actually given: rigid
823        // children are free to answer a shrink proposal with their natural size (native
824        // buttons and labels routinely do), and then the tail of the stack lands offscreen
825        // with every assertion still green. Say so, once, where a developer will see it.
826        let needed = sizes.iter().map(|&s| self.main(s)).sum::<f64>()
827            + self.spacing * (kids.len() - 1) as f64;
828        let available = self.main(bounds.size);
829        // A container with no extent is not overflowing, it is not laid out yet: the state a
830        // native-owned surface is in until the backend reports its frame (a `cover` lays its
831        // content out once before `Event::FrameChanged` arrives, §7.6/docs/cover.md). Reporting
832        // it would name a real developer's ids for a transient the developer cannot act on:
833        // no fit policy makes a stack fit in zero points.
834        if available > 0.5 && needed > available + 0.5 {
835            cx.report_overflow(needed, available);
836        }
837        let bounds_cross = self.cross(bounds.size);
838        // Baseline row (docs/baseline.md): every child that has a baseline is shifted down so
839        // they all land on the deepest one, which is the offset that keeps every child inside
840        // the row. Children without one keep the centered fallback below.
841        let baselines = self.baselines(cx, &kids, &sizes);
842        let deepest = baselines.iter().flatten().copied().fold(f64::MIN, f64::max);
843        let mut pos = 0.0;
844        for (i, &k) in kids.iter().enumerate() {
845            let s = sizes[i];
846            let cross_off = match (self.align, baselines[i]) {
847                (CrossAlign::FirstBaseline, Some(b)) => deepest - b,
848                (CrossAlign::Leading, _) => 0.0,
849                (CrossAlign::Center | CrossAlign::FirstBaseline, _) => {
850                    ((bounds_cross - self.cross(s)) / 2.0).max(0.0)
851                }
852                (CrossAlign::Trailing, _) => (bounds_cross - self.cross(s)).max(0.0),
853            };
854            let rect = match self.axis {
855                Axis::Vertical => Rect::new(cross_off, pos, s.width, s.height),
856                Axis::Horizontal => Rect::new(pos, cross_off, s.width, s.height),
857            };
858            cx.place_child(k, rect);
859            pos += self.main(s) + self.spacing;
860        }
861    }
862}
863
864/// A wrapping row (docs/size-classes.md "Adaptive pieces"): children keep their natural
865/// measure and lay out leading-to-trailing, breaking onto a new line where the next child
866/// would overflow the proposed width. Wrapping replaces main-axis negotiation, so flex is
867/// inert here: nothing grows, and a `spacer()` contributes nothing. RTL mirroring comes from
868/// `place_child`, the same as every layout.
869pub struct FlowLayout {
870    pub spacing: f64,
871    /// Vertical gap between lines.
872    pub run_spacing: f64,
873    /// How children align within their own line (a line is as tall as its tallest child).
874    pub align: CrossAlign,
875    /// Uniform columns ([`RowFit::WrapColumns`](/api/day_pieces/enum.RowFit.html#variant.WrapColumns)): every cell takes the widest child's width and
876    /// each line holds as many as the available width fits, so the wrapped lines align into
877    /// columns; when any child grows (`grow_w`), the columns stretch to share the whole width.
878    /// `false` packs each line at natural widths, which comes out ragged.
879    pub uniform: bool,
880}
881
882/// One packed flow line: the child range it holds and its settled extent.
883struct FlowLine {
884    start: usize,
885    end: usize,
886    height: f64,
887}
888
889/// A solved flow: the size each child is placed at, and the lines they pack into. Measure and
890/// place both go through this, so the two never disagree about where a line breaks.
891struct FlowPlan {
892    sizes: Vec<Size>,
893    lines: Vec<FlowLine>,
894}
895
896impl FlowLayout {
897    /// Pack natural sizes into lines under `max_w`. Unbounded → one line, the degenerate case
898    /// that keeps a flow inside a horizontal scroll behaving like a plain row.
899    fn pack(&self, sizes: &[Size], max_w: Option<f64>) -> Vec<FlowLine> {
900        let mut lines = Vec::new();
901        let mut start = 0;
902        let mut w = 0.0;
903        let mut h: f64 = 0.0;
904        for (i, s) in sizes.iter().enumerate() {
905            let grown = if i == start {
906                s.width
907            } else {
908                w + self.spacing + s.width
909            };
910            if i > start && max_w.is_some_and(|m| grown > m + 0.5) {
911                lines.push(FlowLine {
912                    start,
913                    end: i,
914                    height: h,
915                });
916                start = i;
917                w = s.width;
918                h = s.height;
919            } else {
920                w = grown;
921                h = h.max(s.height);
922            }
923        }
924        if start < sizes.len() {
925            lines.push(FlowLine {
926                start,
927                end: sizes.len(),
928                height: h,
929            });
930        }
931        lines
932    }
933
934    fn natural_sizes(cx: &mut dyn LayoutOps, kids: &[RNode]) -> Vec<Size> {
935        kids.iter()
936            .map(|&k| cx.measure_child(k, Proposal::UNCONSTRAINED))
937            .collect()
938    }
939
940    /// Solve the flow for an available width: ragged lines at natural widths, or, under
941    /// `uniform`, one column width for every cell with as many columns per line as fit.
942    fn plan(&self, cx: &mut dyn LayoutOps, kids: &[RNode], max_w: Option<f64>) -> FlowPlan {
943        let natural = Self::natural_sizes(cx, kids);
944        if !self.uniform {
945            let lines = self.pack(&natural, max_w);
946            return FlowPlan {
947                sizes: natural,
948                lines,
949            };
950        }
951        // The widest child sets the column, so no cell is ever narrower than its content.
952        let cell_w = natural.iter().map(|s| s.width).fold(0.0, f64::max);
953        let cols = match max_w {
954            // How many whole columns fit, counting the gutter between them; never zero, or a
955            // window narrower than one cell would produce no lines at all.
956            Some(m) if cell_w > 0.0 => {
957                (((m + self.spacing) / (cell_w + self.spacing)).floor() as usize).max(1)
958            }
959            // Unbounded (inside a horizontal scroll): one line, like a plain row.
960            _ => kids.len().max(1),
961        };
962        // A growing child (`.grow(Dimension::Width)`) stretches the columns to share the whole line, the
963        // adaptive grid: `cell_w` is then the narrowest a column gets, and a line with fewer
964        // cells than columns leaves the rest empty. Without one, the leftover width trails the
965        // last column.
966        let col_w = match max_w {
967            Some(m) if kids.iter().any(|&k| cx.flex_of(k).grow_w) => {
968                ((m - self.spacing * (cols - 1) as f64) / cols as f64).max(cell_w)
969            }
970            _ => cell_w,
971        };
972        // Never wider than the line: a child whose natural width exceeds it (a card whose text
973        // runs long on a phone) takes the line's width and wraps its text, rather than running
974        // past the edge.
975        let col_w = max_w.map_or(col_w, |m| col_w.min(m));
976        // Re-measure at the column width: a child handed more width than it asked for can
977        // settle shorter (a label unwrapping), and the line's height follows what it settles
978        // on rather than what it wanted.
979        let sizes: Vec<Size> = kids
980            .iter()
981            .map(|&k| {
982                let s = cx.measure_child(k, Proposal::new(Some(col_w), None));
983                Size::new(col_w, s.height)
984            })
985            .collect();
986        let mut lines = Vec::new();
987        let mut start = 0;
988        while start < sizes.len() {
989            let end = (start + cols).min(sizes.len());
990            let height = sizes[start..end]
991                .iter()
992                .map(|s| s.height)
993                .fold(0.0, f64::max);
994            lines.push(FlowLine { start, end, height });
995            start = end;
996        }
997        FlowPlan { sizes, lines }
998    }
999}
1000
1001impl Layout for FlowLayout {
1002    fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1003        let mut kids = Vec::new();
1004        StackLayout::flatten(cx, children, &mut kids);
1005        if kids.is_empty() {
1006            return Size::ZERO;
1007        }
1008        let plan = self.plan(cx, &kids, p.width);
1009        let height = plan.lines.iter().map(|l| l.height).sum::<f64>()
1010            + self.run_spacing * plan.lines.len().saturating_sub(1) as f64;
1011        // Bounded → fill the proposal (lines pack leading inside it, like wrapped text);
1012        // unbounded → the single packed line's own extent.
1013        let width = p.width.unwrap_or_else(|| {
1014            plan.sizes.iter().map(|s| s.width).sum::<f64>()
1015                + self.spacing * plan.sizes.len().saturating_sub(1) as f64
1016        });
1017        Size::new(width, height)
1018    }
1019
1020    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1021        let mut kids = Vec::new();
1022        StackLayout::flatten(cx, children, &mut kids);
1023        if kids.is_empty() {
1024            return;
1025        }
1026        let plan = self.plan(cx, &kids, Some(bounds.size.width));
1027        let mut y = 0.0;
1028        for line in &plan.lines {
1029            let mut x = 0.0;
1030            let range = line.start..line.end;
1031            for (&k, &s) in kids[range.clone()].iter().zip(&plan.sizes[range]) {
1032                let dy = ((line.height - s.height) * self.align.fraction()).max(0.0);
1033                cx.place_child(k, Rect::new(x, y + dy, s.width, s.height));
1034                x += s.width + self.spacing;
1035            }
1036            y += line.height + self.run_spacing;
1037        }
1038    }
1039}
1040
1041/// A grid cell, resolved from the realized tree: the node, its starting column, its span, and
1042/// its layout facts (docs/grid.md).
1043struct GridCell {
1044    node: RNode,
1045    col: usize,
1046    span: usize,
1047    flex: Flex,
1048}
1049
1050/// One grid row: either a `grid_row`'s cells, or a single full-width cell (a non-row child).
1051struct GridRowRef {
1052    cells: Vec<GridCell>,
1053    full_width: bool,
1054    valign: Option<CrossAlign>,
1055}
1056
1057/// The resolved geometry both [`GridLayout::measure`] and [`GridLayout::place`] work from.
1058struct GridGeom {
1059    rows: Vec<GridRowRef>,
1060    col_x: Vec<f64>,
1061    col_w: Vec<f64>,
1062    row_y: Vec<f64>,
1063    row_h: Vec<f64>,
1064    /// Pass-B size per cell, indexed `[row][cell]`; placement uses these, never re-measuring.
1065    cell_sizes: Vec<Vec<Size>>,
1066    size: Size,
1067}
1068
1069/// SwiftUI-style grid negotiation (docs/grid.md): columns are inferred from `grid_row` children,
1070/// a column's width is the max ideal width of its span-1 cells, a `grow_w` cell makes its column
1071/// flexible (leftover width split evenly, the [`StackLayout`] share rule), and a non-row child
1072/// is a full-width cell spanning every column. `spacer()` is an inert empty cell. The contract:
1073/// exactly two measure proposals per cell per layout, unconstrained (pass A) and at the final
1074/// column width (pass B), and `place` re-runs the same proposals, so it measures from cache.
1075pub struct GridLayout {
1076    pub row_spacing: f64,
1077    pub column_spacing: f64,
1078    pub align: Alignment,
1079}
1080
1081impl GridLayout {
1082    /// Expand group anchors and classify children into rows / full-width cells.
1083    fn collect(cx: &mut dyn LayoutOps, children: &[RNode]) -> (Vec<GridRowRef>, usize) {
1084        let mut tops = Vec::new();
1085        StackLayout::flatten(cx, children, &mut tops);
1086        let mut rows = Vec::new();
1087        let mut ncols = 0usize;
1088        for &t in &tops {
1089            let f = cx.flex_of(t);
1090            if f.grid.is_row {
1091                let inner = cx.children_of(t);
1092                let mut cell_nodes = Vec::new();
1093                StackLayout::flatten(cx, &inner, &mut cell_nodes);
1094                let mut cells = Vec::new();
1095                let mut col = 0usize;
1096                for &c in &cell_nodes {
1097                    let cf = cx.flex_of(c);
1098                    let span = cf.grid.col_span.max(1) as usize;
1099                    cells.push(GridCell {
1100                        node: c,
1101                        col,
1102                        span,
1103                        flex: cf,
1104                    });
1105                    col += span;
1106                }
1107                ncols = ncols.max(col);
1108                rows.push(GridRowRef {
1109                    cells,
1110                    full_width: false,
1111                    valign: f.grid.row_valign,
1112                });
1113            } else {
1114                // A non-row child occupies a full-width row spanning every column (span is
1115                // patched to the final column count once it is known).
1116                rows.push(GridRowRef {
1117                    cells: vec![GridCell {
1118                        node: t,
1119                        col: 0,
1120                        span: 1,
1121                        flex: f,
1122                    }],
1123                    full_width: true,
1124                    valign: None,
1125                });
1126            }
1127        }
1128        (rows, ncols)
1129    }
1130
1131    fn span_width(&self, col_w: &[f64], col: usize, span: usize) -> f64 {
1132        let end = (col + span).min(col_w.len());
1133        let cols: f64 = col_w[col..end].iter().sum();
1134        cols + self.column_spacing * (end.saturating_sub(col + 1)) as f64
1135    }
1136
1137    /// The single geometry pass (docs/grid.md): pass A (unconstrained ideals → column widths),
1138    /// pass B (heights at final widths), then prefix sums. All decisions are closed-form (no
1139    /// iterative negotiation) and only `p.width` affects cell proposals, so a `measure` at
1140    /// `(Some(w), None)` and a `place` at `exact(w × h)` generate identical per-cell proposals.
1141    fn geometry(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> GridGeom {
1142        let (mut rows, ncols) = Self::collect(cx, children);
1143        if rows.is_empty() {
1144            return GridGeom {
1145                rows,
1146                col_x: Vec::new(),
1147                col_w: Vec::new(),
1148                row_y: Vec::new(),
1149                row_h: Vec::new(),
1150                cell_sizes: Vec::new(),
1151                size: Size::ZERO,
1152            };
1153        }
1154        let ncols = ncols.max(1);
1155        for r in &mut rows {
1156            if r.full_width {
1157                r.cells[0].span = ncols;
1158            }
1159        }
1160        let unconstrained = Proposal::new(None, None);
1161
1162        // Pass A1, span-1 cells: rigid ideals set their column's width; grow_w flags it
1163        // flexible (its unconstrained ideal only matters when the grid itself is unconstrained).
1164        let mut col_ideal = vec![0.0f64; ncols];
1165        let mut col_flex = vec![false; ncols];
1166        let mut flex_ideal = vec![0.0f64; ncols];
1167        for r in rows.iter().filter(|r| !r.full_width) {
1168            for c in r.cells.iter().filter(|c| c.span == 1 && !c.flex.is_spacer) {
1169                if c.flex.grow_w {
1170                    col_flex[c.col] = true;
1171                    if p.width.is_none() {
1172                        let s = cx.measure_child(c.node, unconstrained);
1173                        flex_ideal[c.col] = flex_ideal[c.col].max(s.width);
1174                    }
1175                } else {
1176                    let s = cx.measure_child(c.node, unconstrained);
1177                    col_ideal[c.col] = col_ideal[c.col].max(s.width);
1178                }
1179            }
1180        }
1181        // Pass A2: flexible spanning cells only flag their columns…
1182        for r in rows.iter().filter(|r| !r.full_width) {
1183            for c in r.cells.iter().filter(|c| c.span > 1 && !c.flex.is_spacer) {
1184                if c.flex.grow_w {
1185                    let end = (c.col + c.span).min(ncols);
1186                    col_flex[c.col..end].fill(true);
1187                }
1188            }
1189        }
1190        // …pass A3: then rigid spanning cells distribute any width deficit in one shot: onto
1191        // the spanned flexible columns if any (they absorb width anyway), else evenly.
1192        for r in rows.iter().filter(|r| !r.full_width) {
1193            for c in r.cells.iter().filter(|c| c.span > 1 && !c.flex.is_spacer) {
1194                if c.flex.grow_w {
1195                    continue;
1196                }
1197                let s = cx.measure_child(c.node, unconstrained);
1198                let end = (c.col + c.span).min(ncols);
1199                let avail = self.span_width(&col_ideal, c.col, c.span);
1200                let deficit = s.width - avail;
1201                if deficit > 0.0 {
1202                    let flexed: Vec<usize> = (c.col..end).filter(|&k| col_flex[k]).collect();
1203                    let targets = if flexed.is_empty() {
1204                        (c.col..end).collect()
1205                    } else {
1206                        flexed
1207                    };
1208                    let add = deficit / targets.len() as f64;
1209                    for k in targets {
1210                        col_ideal[k] += add;
1211                    }
1212                }
1213            }
1214        }
1215        // Full-width cells: their ideal widens the grid when nothing constrains it; a grow_w
1216        // full-width cell makes the grid width flexible like a flexible column does.
1217        let mut fw_ideal = 0.0f64;
1218        let mut fw_flex = false;
1219        for r in rows.iter().filter(|r| r.full_width) {
1220            let c = &r.cells[0];
1221            if c.flex.is_spacer {
1222                continue;
1223            }
1224            if c.flex.grow_w {
1225                fw_flex = true;
1226            } else {
1227                let s = cx.measure_child(c.node, unconstrained);
1228                fw_ideal = fw_ideal.max(s.width);
1229            }
1230        }
1231
1232        // Resolve column widths (the StackLayout::negotiate share rule for flexible columns).
1233        let gutters = self.column_spacing * (ncols - 1) as f64;
1234        let has_flex_col = col_flex.iter().any(|&f| f);
1235        let mut col_w = vec![0.0f64; ncols];
1236        match p.width {
1237            Some(pw) if has_flex_col => {
1238                let rigid: f64 = (0..ncols)
1239                    .filter(|&k| !col_flex[k])
1240                    .map(|k| col_ideal[k])
1241                    .sum();
1242                let share = (pw - rigid - gutters).max(0.0)
1243                    / col_flex.iter().filter(|&&f| f).count() as f64;
1244                for k in 0..ncols {
1245                    col_w[k] = if col_flex[k] { share } else { col_ideal[k] };
1246                }
1247            }
1248            _ => {
1249                for k in 0..ncols {
1250                    col_w[k] = if col_flex[k] {
1251                        flex_ideal[k].max(col_ideal[k])
1252                    } else {
1253                        col_ideal[k]
1254                    };
1255                }
1256            }
1257        }
1258        let cols_total: f64 = col_w.iter().sum::<f64>() + gutters;
1259        let grid_w = match p.width {
1260            Some(pw) if has_flex_col || fw_flex => pw,
1261            _ => cols_total.max(fw_ideal),
1262        };
1263
1264        // Pass B: heights at final widths (text height-for-width happens here).
1265        let nrows = rows.len();
1266        let mut cell_sizes: Vec<Vec<Size>> = Vec::with_capacity(nrows);
1267        let mut row_h = vec![0.0f64; nrows];
1268        let mut row_flex = vec![false; nrows];
1269        for (ri, r) in rows.iter().enumerate() {
1270            let mut sizes = Vec::with_capacity(r.cells.len());
1271            for c in &r.cells {
1272                if c.flex.is_spacer {
1273                    sizes.push(Size::ZERO);
1274                    continue;
1275                }
1276                let w = if r.full_width {
1277                    grid_w
1278                } else {
1279                    self.span_width(&col_w, c.col, c.span)
1280                };
1281                let s = cx.measure_child(c.node, Proposal::new(Some(w), None));
1282                row_h[ri] = row_h[ri].max(s.height);
1283                if c.flex.grow_h {
1284                    row_flex[ri] = true;
1285                }
1286                sizes.push(s);
1287            }
1288            cell_sizes.push(sizes);
1289        }
1290        // Flexible rows stretch to a height proposal (additive: this never re-measures cells,
1291        // which keeps measure/place proposal identity).
1292        let vgutters = self.row_spacing * (nrows - 1) as f64;
1293        if let Some(ph) = p.height
1294            && row_flex.iter().any(|&f| f)
1295        {
1296            let total: f64 = row_h.iter().sum::<f64>() + vgutters;
1297            let extra = (ph - total).max(0.0) / row_flex.iter().filter(|&&f| f).count() as f64;
1298            for (ri, flexed) in row_flex.iter().enumerate() {
1299                if *flexed {
1300                    row_h[ri] += extra;
1301                }
1302            }
1303        }
1304        let grid_h = row_h.iter().sum::<f64>() + vgutters;
1305
1306        let mut col_x = vec![0.0f64; ncols];
1307        let mut x = 0.0;
1308        for k in 0..ncols {
1309            col_x[k] = x;
1310            x += col_w[k] + self.column_spacing;
1311        }
1312        let mut row_y = vec![0.0f64; nrows];
1313        let mut y = 0.0;
1314        for ri in 0..nrows {
1315            row_y[ri] = y;
1316            y += row_h[ri] + self.row_spacing;
1317        }
1318        GridGeom {
1319            rows,
1320            col_x,
1321            col_w,
1322            row_y,
1323            row_h,
1324            cell_sizes,
1325            size: Size::new(grid_w, grid_h),
1326        }
1327    }
1328}
1329
1330impl Layout for GridLayout {
1331    fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1332        self.geometry(cx, children, p).size
1333    }
1334
1335    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1336        let g = self.geometry(cx, children, Proposal::exact(bounds.size));
1337        for (ri, r) in g.rows.iter().enumerate() {
1338            for (ci, c) in r.cells.iter().enumerate() {
1339                if c.flex.is_spacer {
1340                    continue;
1341                }
1342                let cell = if r.full_width {
1343                    Rect::new(0.0, g.row_y[ri], g.size.width, g.row_h[ri])
1344                } else {
1345                    Rect::new(
1346                        g.col_x[c.col],
1347                        g.row_y[ri],
1348                        self.span_width(&g.col_w, c.col, c.span),
1349                        g.row_h[ri],
1350                    )
1351                };
1352                let s = g.cell_sizes[ri][ci];
1353                let w = if c.flex.grow_w {
1354                    cell.size.width
1355                } else {
1356                    s.width.min(cell.size.width)
1357                };
1358                let h = if c.flex.grow_h {
1359                    cell.size.height
1360                } else {
1361                    s.height.min(cell.size.height)
1362                };
1363                // Alignment precedence per axis: cell `.grid_align` > row `.align` (vertical
1364                // only) > the grid's own alignment.
1365                let hf = match c.flex.grid.align {
1366                    Some(a) => a.h_fraction(),
1367                    None => self.align.h_fraction(),
1368                };
1369                let vf = match (c.flex.grid.align, r.valign) {
1370                    (Some(a), _) => a.v_fraction(),
1371                    (None, Some(v)) => v.fraction(),
1372                    (None, None) => self.align.v_fraction(),
1373                };
1374                let x = cell.origin.x + (cell.size.width - w) * hf;
1375                let y = cell.origin.y + (cell.size.height - h) * vf;
1376                cx.place_child(c.node, Rect::new(x, y, w, h));
1377            }
1378        }
1379        // Row nodes are transparent carriers and are never placed.
1380    }
1381}
1382
1383/// Two-axis placement of a child within a container's bounds (SwiftUI's `Alignment`). Used by
1384/// [`AlignmentLayout`] and the z-layering primitives ([`OverlayLayout`]).
1385#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
1386pub enum Alignment {
1387    TopLeading,
1388    Top,
1389    TopTrailing,
1390    Leading,
1391    #[default]
1392    Center,
1393    Trailing,
1394    BottomLeading,
1395    Bottom,
1396    BottomTrailing,
1397}
1398
1399impl Alignment {
1400    /// Horizontal placement fraction of the free space: 0 = leading, 0.5 = center, 1 = trailing.
1401    fn h_fraction(self) -> f64 {
1402        match self {
1403            Alignment::TopLeading | Alignment::Leading | Alignment::BottomLeading => 0.0,
1404            Alignment::Top | Alignment::Center | Alignment::Bottom => 0.5,
1405            Alignment::TopTrailing | Alignment::Trailing | Alignment::BottomTrailing => 1.0,
1406        }
1407    }
1408    /// Vertical placement fraction of the free space: 0 = top, 0.5 = center, 1 = bottom.
1409    fn v_fraction(self) -> f64 {
1410        match self {
1411            Alignment::TopLeading | Alignment::Top | Alignment::TopTrailing => 0.0,
1412            Alignment::Leading | Alignment::Center | Alignment::Trailing => 0.5,
1413            Alignment::BottomLeading | Alignment::Bottom | Alignment::BottomTrailing => 1.0,
1414        }
1415    }
1416}
1417
1418/// Position one child within the space assigned to this layout-only wrapper.
1419/// Alignment does not request extra space; use an outer grow or frame modifier for that.
1420pub struct AlignmentLayout {
1421    pub align: Alignment,
1422}
1423
1424impl Layout for AlignmentLayout {
1425    fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1426        children
1427            .first()
1428            .map_or(Size::ZERO, |&c| cx.measure_child(c, p))
1429    }
1430
1431    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1432        if let Some(&c) = children.first() {
1433            let size = cx.measure_child(c, Proposal::exact(bounds.size));
1434            // Keep oversized content at the leading/top edge; do not clip or shrink it.
1435            // LayoutOps handles logical leading/trailing in RTL, exactly once.
1436            let x = (bounds.size.width - size.width).max(0.0) * self.align.h_fraction();
1437            let y = (bounds.size.height - size.height).max(0.0) * self.align.v_fraction();
1438            cx.place_child(c, Rect::new(x, y, size.width, size.height));
1439        }
1440    }
1441
1442    fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1443        let &child = children.first()?;
1444        let child_size = cx.measure_child(child, Proposal::exact(size));
1445        let offset = (size.height - child_size.height).max(0.0) * self.align.v_fraction();
1446        cx.baseline_of(child, child_size)
1447            .map(|baseline| baseline + offset)
1448    }
1449}
1450
1451/// Dimensions in which a piece expands to fill the space offered by its parent.
1452/// Unlike [`Axis`], this can select both width and height.
1453#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1454pub enum Dimension {
1455    Width,
1456    Height,
1457    Both,
1458}
1459
1460/// Z-layering (§overlay): children share the container bounds, stacked back-to-front in child
1461/// order (first child = bottom of the z-order), each positioned by a single [`Alignment`].
1462/// `size_to_first` reports only the first child's natural size, the badge/annotation sizing of
1463/// [`overlay`](crate) (the annotation does not grow the frame); otherwise the layout reports the
1464/// union (max) of all children's natural sizes, the `ZStack` sizing of `zstack`. No native work:
1465/// the container is the same panel as `column`/`row`, so backends stack children by attach order.
1466pub struct OverlayLayout {
1467    pub align: Alignment,
1468    pub size_to_first: bool,
1469}
1470
1471impl OverlayLayout {
1472    /// Expand group anchors (`when`/`each`) inline, exactly like [`StackLayout`].
1473    fn flatten(cx: &mut dyn LayoutOps, children: &[RNode], out: &mut Vec<RNode>) {
1474        for &c in children {
1475            if cx.flex_of(c).is_group {
1476                let inner = cx.children_of(c);
1477                Self::flatten(cx, &inner, out);
1478            } else {
1479                out.push(c);
1480            }
1481        }
1482    }
1483}
1484
1485impl Layout for OverlayLayout {
1486    fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1487        let mut kids = Vec::new();
1488        Self::flatten(cx, children, &mut kids);
1489        if self.size_to_first {
1490            return match kids.first() {
1491                Some(&c) => cx.measure_child(c, p),
1492                None => Size::ZERO,
1493            };
1494        }
1495        let mut size = Size::ZERO;
1496        for &c in &kids {
1497            let s = cx.measure_child(c, p);
1498            size.width = size.width.max(s.width);
1499            size.height = size.height.max(s.height);
1500        }
1501        size
1502    }
1503    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1504        let mut kids = Vec::new();
1505        Self::flatten(cx, children, &mut kids);
1506        for &c in &kids {
1507            let s = cx.measure_child(c, Proposal::exact(bounds.size));
1508            let x = (bounds.size.width - s.width) * self.align.h_fraction();
1509            let y = (bounds.size.height - s.height) * self.align.v_fraction();
1510            cx.place_child(c, Rect::new(x, y, s.width, s.height));
1511        }
1512    }
1513}
1514
1515pub struct PaddingLayout {
1516    pub insets: Insets,
1517}
1518
1519impl Layout for PaddingLayout {
1520    fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1521        let inner = Proposal::new(
1522            p.width
1523                .map(|w| (w - self.insets.horizontal_total()).max(0.0)),
1524            p.height
1525                .map(|h| (h - self.insets.vertical_total()).max(0.0)),
1526        );
1527        let s = match children.first() {
1528            Some(&c) => cx.measure_child(c, inner),
1529            None => Size::ZERO,
1530        };
1531        Size::new(
1532            s.width + self.insets.horizontal_total(),
1533            s.height + self.insets.vertical_total(),
1534        )
1535    }
1536    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1537        if let Some(&c) = children.first() {
1538            let inner = bounds.inset_by(self.insets);
1539            let s = cx.measure_child(c, Proposal::exact(inner.size));
1540            cx.place_child(
1541                c,
1542                Rect {
1543                    origin: inner.origin,
1544                    size: s,
1545                },
1546            );
1547        }
1548    }
1549    fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1550        // The one wrapper with a real offset: its child starts below the top inset.
1551        let inner = Size::new(
1552            (size.width - self.insets.horizontal_total()).max(0.0),
1553            (size.height - self.insets.vertical_total()).max(0.0),
1554        );
1555        wrapper_baseline(cx, children, inner, self.insets.top)
1556    }
1557}
1558
1559/// The `aspect_ratio` decorator (§5.2): the largest `width / height == ratio` box that fits what
1560/// the parent proposes, with the child given that whole box.
1561///
1562/// With one axis proposed it derives the other, which is what makes `.grow(Dimension::Width).aspect_ratio(r)`
1563/// take the width a container offers and compute the height from it: a canvas that keeps its
1564/// proportions as the window resizes.
1565pub struct AspectRatioLayout {
1566    pub ratio: f64,
1567}
1568
1569impl Layout for AspectRatioLayout {
1570    fn measure(&self, cx: &mut dyn LayoutOps, _children: &[RNode], p: Proposal) -> Size {
1571        match (p.width, p.height) {
1572            (Some(w), Some(h)) => {
1573                if w / h > self.ratio {
1574                    Size::new(h * self.ratio, h)
1575                } else {
1576                    Size::new(w, w / self.ratio)
1577                }
1578            }
1579            (Some(w), None) => Size::new(w, w / self.ratio),
1580            (None, Some(h)) => Size::new(h * self.ratio, h),
1581            (None, None) => cx.measure_leaf(p),
1582        }
1583    }
1584    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1585        // The ratio has already decided the box; hand all of it to the child.
1586        for &c in children {
1587            cx.place_child(c, Rect::from_size(bounds.size));
1588        }
1589    }
1590    fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1591        wrapper_baseline(cx, children, size, 0.0)
1592    }
1593}
1594
1595/// The `grow` decorator (§5.2): a single-child wrapper carrying grow [`Flex`]
1596/// so the parent stack OFFERS it the space, and a greedy measure/place so the child actually
1597/// FILLS it. Non-grown axes hug the child (like `frame(maxWidth: .infinity)` on one axis).
1598pub struct GrowLayout {
1599    pub w: bool,
1600    pub h: bool,
1601}
1602
1603impl Layout for GrowLayout {
1604    fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1605        let cs = match children.first() {
1606            Some(&c) => cx.measure_child(c, p),
1607            None => Size::ZERO,
1608        };
1609        // A grown axis fills what is offered, but never reports less than the child needs, so
1610        // a child that cannot shrink to the offer (a `.min_width`, a fixed-size pair) overflows
1611        // visibly and its row can respond (a `labeled` row stacks) instead of clipping it.
1612        Size::new(
1613            if self.w {
1614                p.width.map_or(cs.width, |w| w.max(cs.width))
1615            } else {
1616                cs.width
1617            },
1618            if self.h {
1619                p.height.map_or(cs.height, |h| h.max(cs.height))
1620            } else {
1621                cs.height
1622            },
1623        )
1624    }
1625    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1626        if let Some(&c) = children.first() {
1627            let cs = cx.measure_child(c, Proposal::exact(bounds.size));
1628            // Fill the grown axes; hug the child on the rest.
1629            let w = if self.w { bounds.size.width } else { cs.width };
1630            let h = if self.h {
1631                bounds.size.height
1632            } else {
1633                cs.height
1634            };
1635            cx.place_child(c, Rect::from_size(Size::new(w, h)));
1636        }
1637    }
1638    fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1639        let &child = children.first()?;
1640        let measured = cx.measure_child(child, Proposal::exact(size));
1641        wrapper_baseline(
1642            cx,
1643            children,
1644            Size::new(
1645                if self.w { size.width } else { measured.width },
1646                if self.h { size.height } else { measured.height },
1647            ),
1648            0.0,
1649        )
1650    }
1651}
1652
1653/// The `.max_width(w)` decorator (docs/layout.md): proposes at most `w` to the child, so
1654/// text wraps instead of overflowing, while narrower content still hugs. The vertical axis
1655/// passes through untouched.
1656pub struct MaxWidthLayout {
1657    pub max: f64,
1658}
1659
1660impl Layout for MaxWidthLayout {
1661    fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1662        let capped = Proposal::new(
1663            Some(p.width.map_or(self.max, |w| w.min(self.max))),
1664            p.height,
1665        );
1666        match children.first() {
1667            Some(&c) => {
1668                let s = cx.measure_child(c, capped);
1669                Size::new(s.width.min(self.max), s.height)
1670            }
1671            None => Size::ZERO,
1672        }
1673    }
1674    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1675        if let Some(&c) = children.first() {
1676            let w = bounds.size.width.min(self.max);
1677            let s = cx.measure_child(c, Proposal::exact(Size::new(w, bounds.size.height)));
1678            cx.place_child(c, Rect::from_size(Size::new(s.width.min(w), s.height)));
1679        }
1680    }
1681    fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1682        PassThrough::forward(cx, children, size)
1683    }
1684}
1685
1686/// The `.max_height(h)` decorator, [`MaxWidthLayout`]'s vertical twin: proposes at most `h` to
1687/// the child, so a scroll or anything else that takes the height it is offered stops at `h`,
1688/// while shorter content still hugs. Where the parent offers less than `h` (a phone held
1689/// sideways), the child gets that, so a capped box still fits a short screen. The horizontal
1690/// axis passes through untouched.
1691pub struct MaxHeightLayout {
1692    pub max: f64,
1693}
1694
1695impl Layout for MaxHeightLayout {
1696    fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1697        let capped = Proposal::new(
1698            p.width,
1699            Some(p.height.map_or(self.max, |h| h.min(self.max))),
1700        );
1701        match children.first() {
1702            Some(&c) => {
1703                let s = cx.measure_child(c, capped);
1704                Size::new(s.width, s.height.min(self.max))
1705            }
1706            None => Size::ZERO,
1707        }
1708    }
1709    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1710        if let Some(&c) = children.first() {
1711            let h = bounds.size.height.min(self.max);
1712            let s = cx.measure_child(c, Proposal::exact(Size::new(bounds.size.width, h)));
1713            cx.place_child(c, Rect::from_size(Size::new(s.width, s.height.min(h))));
1714        }
1715    }
1716    fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1717        PassThrough::forward(cx, children, size)
1718    }
1719}
1720
1721/// The `.min_width(w)` decorator: the child measures as it would, but never reports narrower
1722/// than `w`, and is placed across whatever width the wrapper is given. A stretching control
1723/// (a slider) in a row that is being squeezed thereby overflows its row instead of shrinking
1724/// to nothing, which is what lets a `labeled` row notice and stack (docs/forms.md). The
1725/// vertical axis passes through untouched.
1726pub struct MinWidthLayout {
1727    pub min: f64,
1728}
1729
1730impl Layout for MinWidthLayout {
1731    fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1732        let floored = Proposal::new(p.width.map(|w| w.max(self.min)), p.height);
1733        match children.first() {
1734            Some(&c) => {
1735                let s = cx.measure_child(c, floored);
1736                Size::new(s.width.max(self.min), s.height)
1737            }
1738            None => Size::new(self.min, 0.0),
1739        }
1740    }
1741    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1742        if let Some(&c) = children.first() {
1743            let w = bounds.size.width.max(self.min);
1744            let s = cx.measure_child(c, Proposal::exact(Size::new(w, bounds.size.height)));
1745            cx.place_child(c, Rect::from_size(Size::new(w, s.height)));
1746        }
1747    }
1748    fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1749        PassThrough::forward(cx, children, size)
1750    }
1751}
1752
1753/// A minimum height that allows taller content and preserves the child's width.
1754/// If the parent offers less than the minimum, the child overflows instead of shrinking.
1755pub struct MinHeightLayout {
1756    pub min: f64,
1757}
1758
1759impl Layout for MinHeightLayout {
1760    fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1761        let floored = Proposal::new(p.width, p.height.map(|h| h.max(self.min)));
1762        match children.first() {
1763            Some(&c) => {
1764                let s = cx.measure_child(c, floored);
1765                Size::new(s.width, s.height.max(self.min))
1766            }
1767            None => Size::new(0.0, self.min),
1768        }
1769    }
1770    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1771        if let Some(&c) = children.first() {
1772            let height = bounds.size.height.max(self.min);
1773            let size = cx.measure_child(c, Proposal::exact(Size::new(bounds.size.width, height)));
1774            cx.place_child(c, Rect::from_size(Size::new(size.width, height)));
1775        }
1776    }
1777    fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1778        let &child = children.first()?;
1779        let height = size.height.max(self.min);
1780        let measured = cx.measure_child(child, Proposal::exact(Size::new(size.width, height)));
1781        cx.baseline_of(child, Size::new(measured.width, height))
1782    }
1783}
1784
1785/// Reserve at least the size of a sample child, then lay the content out inside it.
1786///
1787/// The problem it solves: a numeric readout beside a slider changes width as the value changes
1788/// (`1` is narrower than `8` in a proportional font, and `9` → `10` adds a whole glyph), so the
1789/// row reflows on every drag and the control you are aiming at moves. A hardcoded width "fixes"
1790/// that until the reader raises their accessibility text size, at which point the number is
1791/// clipped.
1792///
1793/// Reserves space using a hidden sample alongside the content. The piece builds the sample
1794/// with the content label's font. Children are `[content, sample]`; the sample has no visible
1795/// frame, and only the content supplies the baseline.
1796pub struct ReserveLayout;
1797
1798impl Layout for ReserveLayout {
1799    fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1800        let Some(&content) = children.first() else {
1801            return Size::ZERO;
1802        };
1803        let c = cx.measure_child(content, p);
1804        let s = children
1805            .get(1)
1806            .map_or(Size::ZERO, |&sample| cx.measure_child(sample, p));
1807        Size::new(s.width.max(c.width), s.height.max(c.height))
1808    }
1809
1810    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1811        if let Some(&content) = children.first() {
1812            cx.place_child(content, Rect::from_size(bounds.size));
1813        }
1814        if let Some(&sample) = children.get(1) {
1815            cx.place_child(sample, Rect::from_size(Size::ZERO));
1816        }
1817    }
1818
1819    fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1820        cx.baseline_of(*children.first()?, size)
1821    }
1822}
1823
1824pub struct FrameLayout {
1825    pub width: Option<f64>,
1826    pub height: Option<f64>,
1827}
1828
1829impl Layout for FrameLayout {
1830    fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1831        let child_p = Proposal::new(self.width.or(p.width), self.height.or(p.height));
1832        let s = match children.first() {
1833            Some(&c) => cx.measure_child(c, child_p),
1834            None => Size::ZERO,
1835        };
1836        Size::new(
1837            self.width.unwrap_or(s.width),
1838            self.height.unwrap_or(s.height),
1839        )
1840    }
1841    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1842        if let Some(&c) = children.first() {
1843            cx.place_child(c, bounds);
1844        }
1845    }
1846    fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1847        wrapper_baseline(cx, children, size, 0.0)
1848    }
1849}
1850
1851/// Scroll viewport (§7.6): greedy on the proposal; content measured unconstrained on the
1852/// scroll axis and reported via `set_scroll_content`. Children are placed in the scroll's
1853/// content coordinate space (the scroll node is their native ancestor).
1854pub struct ScrollLayout {
1855    pub axis: Axis,
1856}
1857
1858impl Layout for ScrollLayout {
1859    fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1860        let content_p = match self.axis {
1861            Axis::Vertical => Proposal::new(p.width, None),
1862            Axis::Horizontal => Proposal::new(None, p.height),
1863        };
1864        let cs = match children.first() {
1865            Some(&c) => cx.measure_child(c, content_p),
1866            None => Size::ZERO,
1867        };
1868        Size::new(p.width.unwrap_or(cs.width), p.height.unwrap_or(cs.height))
1869    }
1870    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1871        if let Some(&c) = children.first() {
1872            let vertical = self.axis == Axis::Vertical;
1873            let proposal = |cross: f64| match self.axis {
1874                Axis::Vertical => Proposal::new(Some(cross), None),
1875                Axis::Horizontal => Proposal::new(None, Some(cross)),
1876            };
1877            let (cross, main) = match self.axis {
1878                Axis::Vertical => (bounds.size.width, bounds.size.height),
1879                Axis::Horizontal => (bounds.size.height, bounds.size.width),
1880            };
1881            let mut cs = cx.measure_child(c, proposal(cross));
1882            let overflows = |s: Size| if vertical { s.height } else { s.width } > main;
1883            // Content that overflows brings a scroll bar up. Where that bar is a classic one
1884            // taking room from the viewport (Qt's Fusion style), lay the content out beside it,
1885            // or the content is wider than what is left and scrolls sideways by the bar's width.
1886            let mut cross = cross;
1887            if overflows(cs) {
1888                let inset = cx.scroll_bar_inset(vertical);
1889                if inset > 0.0 {
1890                    cross = (cross - inset).max(0.0);
1891                    cs = cx.measure_child(c, proposal(cross));
1892                }
1893            }
1894            let content = match self.axis {
1895                Axis::Vertical => Size::new(cross, cs.height.max(bounds.size.height)),
1896                Axis::Horizontal => Size::new(cs.width.max(bounds.size.width), cross),
1897            };
1898            cx.place_child(c, Rect::from_size(content));
1899            cx.set_scroll_content(content);
1900        }
1901    }
1902}
1903
1904/// Navigation host (docs/navigation.md): page frames are native-owned (splitter panes,
1905/// nav-controller views), so `set_frame` on pages is a toolkit no-op; Day lays each page's
1906/// content within the size the toolkit last reported via `Event::FrameChanged`, falling
1907/// back to a sidebar/detail split (or the full host) of the host bounds.
1908pub struct NavLayout {
1909    pub sizes: std::rc::Rc<std::cell::RefCell<std::collections::HashMap<RNode, Size>>>,
1910    /// The presentation as last resolved. Shared with the piece rather than copied, so a
1911    /// re-present (`NavPatch::Presentation`) changes the fallback split without rebuilding the
1912    /// layout object the host was realized with.
1913    pub presentation: std::rc::Rc<std::cell::Cell<day_spec::props::NavPresentation>>,
1914    /// The host's sidebar page, once it has one. Identity, not position: after a re-present the
1915    /// pages keep their roles but a backend may have re-homed them in a different order.
1916    pub sidebar: std::rc::Rc<std::cell::Cell<Option<RNode>>>,
1917    /// The host's content-list page (`Pane::List`), once it has one; shared like `sidebar`.
1918    pub list: std::rc::Rc<std::cell::Cell<Option<RNode>>>,
1919    /// The content-list pane's preferred width (`NavProps::list_width`), for the fallback split.
1920    pub list_width: f64,
1921    /// Whether the pane is showing (`NavPatch::ListVisible`), shared with the piece so a
1922    /// collapsed pane stops narrowing the detail's fallback immediately, rather than one
1923    /// `FrameChanged` report later.
1924    pub list_visible: std::rc::Rc<std::cell::Cell<bool>>,
1925}
1926
1927pub use day_spec::{NAV_LIST_WIDTH, NAV_SIDEBAR_WIDTH};
1928
1929impl NavLayout {
1930    /// A host with no sidebar pane and no re-presenting to do: a tab strip's page area, or a
1931    /// `nav_stack` piece, both of which stay stacked at every size.
1932    pub fn stack(
1933        sizes: std::rc::Rc<std::cell::RefCell<std::collections::HashMap<RNode, Size>>>,
1934    ) -> Self {
1935        NavLayout {
1936            sizes,
1937            presentation: std::rc::Rc::new(std::cell::Cell::new(
1938                day_spec::props::NavPresentation::Stack,
1939            )),
1940            sidebar: std::rc::Rc::new(std::cell::Cell::new(None)),
1941            list: std::rc::Rc::new(std::cell::Cell::new(None)),
1942            list_width: NAV_LIST_WIDTH,
1943            list_visible: std::rc::Rc::new(std::cell::Cell::new(true)),
1944        }
1945    }
1946}
1947
1948impl Layout for NavLayout {
1949    fn measure(&self, _cx: &mut dyn LayoutOps, _children: &[RNode], p: Proposal) -> Size {
1950        // Greedy: the host owns the window. A nested stack merges into the enclosing host's page
1951        // list rather than nesting a second host (docs/navigation.md), so one NAV host still
1952        // spans the window.
1953        Size::new(p.width.unwrap_or(480.0), p.height.unwrap_or(640.0))
1954    }
1955    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1956        let pres = self.presentation.get();
1957        let split = pres.is_split();
1958        let sidebar = self.sidebar.get();
1959        let list = self.list.get();
1960        // The list pane narrows the detail's fallback only while it has its own pane and it
1961        // is showing; a collapsed pane gives the detail its width back at once.
1962        let list_w = if split && list.is_some() && self.list_visible.get() {
1963            self.list_width
1964        } else {
1965            0.0
1966        };
1967        for &page in children {
1968            let reported = self.sizes.borrow().get(&page).copied();
1969            // Only a fallback: every backend reports each page's real frame through
1970            // `Event::FrameChanged`, and that wins. This is what the page gets for the frame
1971            // before the first report arrives.
1972            let sz = reported.unwrap_or_else(|| {
1973                let is_sidebar = Some(page) == sidebar;
1974                let is_list = Some(page) == list;
1975                if pres.rows_are_chrome() {
1976                    // The rows are the chrome (a tab bar, a rail): the backend draws them itself
1977                    // and sizes its own bar, so the sidebar page is measured but not shown. Keep
1978                    // it at the pane width rather than zero, since a zero-width menu measured here
1979                    // would have to re-measure from scratch the moment the window widens back
1980                    // into a split.
1981                    if is_sidebar {
1982                        Size::new(NAV_SIDEBAR_WIDTH, bounds.size.height)
1983                    } else if is_list {
1984                        Size::new(self.list_width, bounds.size.height)
1985                    } else {
1986                        bounds.size
1987                    }
1988                } else if !split {
1989                    // Includes a stacked host's list page: full width where it joins the stack
1990                    // (`Cap::NavContentList` Emulated); where its pane persists instead
1991                    // (Native, a narrow Mac window) the first FrameChanged report corrects it.
1992                    bounds.size
1993                } else if is_sidebar {
1994                    Size::new(NAV_SIDEBAR_WIDTH, bounds.size.height)
1995                } else if is_list {
1996                    Size::new(self.list_width, bounds.size.height)
1997                } else {
1998                    Size::new(
1999                        (bounds.size.width - NAV_SIDEBAR_WIDTH - list_w - 1.0).max(0.0),
2000                        bounds.size.height,
2001                    )
2002                }
2003            });
2004            cx.place_child_native(page, Rect::from_size(sz));
2005        }
2006    }
2007}
2008
2009/// Inspector split (docs/inspector.md): the two pane frames are native-owned (an
2010/// `NSSplitView`'s panes, a dock widget), so Day lays each pane's content within the size the
2011/// toolkit last reported via `Event::FrameChanged`, the same native-owned-frame contract as
2012/// [`NavLayout`] pages. The fallback before the first report splits the host bounds at the
2013/// pane width when visible, and gives the content everything when hidden.
2014pub struct InspectorLayout {
2015    pub sizes: std::rc::Rc<std::cell::RefCell<std::collections::HashMap<RNode, Size>>>,
2016    /// Visibility as last patched, shared with the piece so a toggle changes the fallback
2017    /// split without rebuilding the layout object the host was realized with.
2018    pub visible: std::rc::Rc<std::cell::Cell<bool>>,
2019    /// The pane's preferred width (`InspectorProps::width`), for the fallback split.
2020    pub width: f64,
2021}
2022
2023impl Layout for InspectorLayout {
2024    fn measure(&self, _cx: &mut dyn LayoutOps, _children: &[RNode], p: Proposal) -> Size {
2025        // Greedy, like a nav host: the split owns whatever its parent proposes.
2026        Size::new(p.width.unwrap_or(480.0), p.height.unwrap_or(640.0))
2027    }
2028    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
2029        // Insertion order is the contract (day-spec `Builtin::Inspector`): 0 content, 1 panel.
2030        for (i, &pane) in children.iter().enumerate() {
2031            let reported = self.sizes.borrow().get(&pane).copied();
2032            let sz = reported.unwrap_or_else(|| {
2033                let panel_w = if self.visible.get() { self.width } else { 0.0 };
2034                if i == 0 {
2035                    Size::new((bounds.size.width - panel_w).max(0.0), bounds.size.height)
2036                } else {
2037                    Size::new(panel_w, bounds.size.height)
2038                }
2039            });
2040            cx.place_child_native(pane, Rect::from_size(sz));
2041        }
2042    }
2043}
2044
2045/// Native split (docs/split.md): the two pane frames are native-owned (an `NSSplitView`'s, a
2046/// `GtkPaned`'s, a `QSplitter`'s), so Day lays each pane's content within the size the toolkit
2047/// last reported via `Event::FrameChanged`, the [`InspectorLayout`] contract. The fallback
2048/// before the first report divides the host bounds by the bound fraction along the axis.
2049pub struct SplitLayout {
2050    pub sizes: std::rc::Rc<std::cell::RefCell<std::collections::HashMap<RNode, Size>>>,
2051    /// Stacked (`true`) or side by side, as last patched; shared with the piece.
2052    pub stacked: std::rc::Rc<std::cell::Cell<bool>>,
2053    /// The first pane's share, as last patched; shared with the piece.
2054    pub fraction: std::rc::Rc<std::cell::Cell<f64>>,
2055}
2056
2057impl Layout for SplitLayout {
2058    fn measure(&self, _cx: &mut dyn LayoutOps, _children: &[RNode], p: Proposal) -> Size {
2059        // Greedy, like a nav host: the split owns whatever its parent proposes.
2060        Size::new(p.width.unwrap_or(480.0), p.height.unwrap_or(640.0))
2061    }
2062    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
2063        // Insertion order is the contract (day-spec `Builtin::Split`): 0 first, 1 second.
2064        let f = self.fraction.get().clamp(0.0, 1.0);
2065        let (w, h) = (bounds.size.width, bounds.size.height);
2066        for (i, &pane) in children.iter().enumerate() {
2067            let reported = self.sizes.borrow().get(&pane).copied();
2068            let sz = reported.unwrap_or_else(|| {
2069                let share = if i == 0 { f } else { 1.0 - f };
2070                if self.stacked.get() {
2071                    Size::new(w, (h * share).floor())
2072                } else {
2073                    Size::new((w * share).floor(), h)
2074                }
2075            });
2076            cx.place_child_native(pane, Rect::from_size(sz));
2077        }
2078    }
2079}
2080
2081/// Fullscreen cover (docs/cover.md): the cover node occupies no space where it sits in the
2082/// tree (its native surface is presented over the window, outside the parent's bounds), and
2083/// its content is laid out at the size the backend reported via `Event::FrameChanged`, the
2084/// same native-owned-frame contract as [`NavLayout`] pages.
2085pub struct CoverLayout {
2086    pub size: std::rc::Rc<std::cell::RefCell<Option<Size>>>,
2087}
2088
2089impl Layout for CoverLayout {
2090    fn measure(&self, _cx: &mut dyn LayoutOps, _children: &[RNode], _p: Proposal) -> Size {
2091        Size::new(0.0, 0.0)
2092    }
2093    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], _bounds: Rect) {
2094        let Some(sz) = *self.size.borrow() else {
2095            return; // not presented yet; content lays out on the first FrameChanged
2096        };
2097        for &child in children {
2098            cx.place_child_native(child, Rect::from_size(sz));
2099        }
2100    }
2101}
2102
2103/// Helper for constructing shared layout Rcs.
2104pub fn rc_layout<L: Layout>(l: L) -> Rc<dyn Layout> {
2105    Rc::new(l)
2106}