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