Skip to main content

yog_ui/
layout.rs

1use crate::text;
2use crate::widget::{Dock, Units, Widget, WidgetKind};
3
4#[derive(Debug, Clone, Copy, PartialEq)]
5pub enum FlexDir {
6    Row,
7    Column,
8}
9#[derive(Debug, Clone, Copy, PartialEq)]
10pub enum Align {
11    Start,
12    Center,
13    End,
14}
15
16#[derive(Debug, Clone, Copy, Default)]
17pub struct Rect {
18    pub x: f32,
19    pub y: f32,
20    pub w: f32,
21    pub h: f32,
22}
23
24/// Width of the strip a [`scrollbar`](crate::widget::Style::scrollbar)
25/// container reserves on its right edge.
26pub const SCROLLBAR_W: f32 = 6.0;
27/// Shortest a scrollbar knob gets.
28pub const MIN_KNOB_H: f32 = 16.0;
29
30impl Rect {
31    /// Whether `(px, py)` lies inside (edges included).
32    pub fn contains(&self, px: f32, py: f32) -> bool {
33        px >= self.x && py >= self.y && px <= self.x + self.w && py <= self.y + self.h
34    }
35
36    /// The overlap of two rects; `None` when they don't overlap.
37    pub fn intersect(&self, o: &Rect) -> Option<Rect> {
38        let x0 = self.x.max(o.x);
39        let y0 = self.y.max(o.y);
40        let x1 = (self.x + self.w).min(o.x + o.w);
41        let y1 = (self.y + self.h).min(o.y + o.h);
42        (x1 > x0 && y1 > y0).then_some(Rect {
43            x: x0,
44            y: y0,
45            w: x1 - x0,
46            h: y1 - y0,
47        })
48    }
49}
50
51#[derive(Debug, Clone)]
52pub struct LayoutNode {
53    pub rect: Rect,
54    pub id: Option<String>,
55    pub on_click: Option<String>,
56    pub children: Vec<LayoutNode>,
57    pub enabled: bool,
58    pub focused: bool,
59    /// Height of everything inside — children plus padding — before
60    /// scrolling. Larger than `rect.h` when the children overflow.
61    pub content_h: f32,
62    /// Effective vertical scroll offset: the widget's
63    /// [`scroll_y`](crate::widget::Style::scroll_y) clamped to
64    /// `0..=`[`Self::max_scroll`]. Children are already shifted by it.
65    pub scroll_y: f32,
66    /// The widget clips its children (see `Style::clip`).
67    pub clip: bool,
68    /// The widget shows a scrollbar on overflow (see `Style::scrollbar`).
69    pub scrollbar: bool,
70}
71
72impl LayoutNode {
73    /// How far the children can scroll: `content_h - rect.h`, at least 0.
74    pub fn max_scroll(&self) -> f32 {
75        (self.content_h - self.rect.h).max(0.0)
76    }
77
78    /// Scrollbar track and knob rects — `None` unless the widget has a
79    /// scrollbar and its content overflows.
80    pub fn scrollbar_rects(&self) -> Option<(Rect, Rect)> {
81        let max = self.max_scroll();
82        if !self.scrollbar || max <= 0.0 {
83            return None;
84        }
85        let r = self.rect;
86        let track = Rect {
87            x: r.x + r.w - SCROLLBAR_W,
88            y: r.y,
89            w: SCROLLBAR_W,
90            h: r.h,
91        };
92        let knob_h = (r.h * r.h / self.content_h).max(MIN_KNOB_H).min(r.h);
93        let knob = Rect {
94            y: r.y + (r.h - knob_h) * (self.scroll_y / max),
95            h: knob_h,
96            ..track
97        };
98        Some((track, knob))
99    }
100
101    fn translate_y(&mut self, dy: f32) {
102        self.rect.y += dy;
103        for c in &mut self.children {
104            c.translate_y(dy);
105        }
106    }
107}
108
109impl Default for LayoutNode {
110    fn default() -> Self {
111        Self {
112            rect: Rect::default(),
113            id: None,
114            on_click: None,
115            children: Vec::new(),
116            enabled: true,
117            focused: false,
118            content_h: 0.0,
119            scroll_y: 0.0,
120            clip: false,
121            scrollbar: false,
122        }
123    }
124}
125
126/// Compute layout starting at (0,0) with given available size.
127/// Returns the root LayoutNode with absolute coordinates.
128///
129/// Sizing rules (CSS-flexbox-like, single pass per container):
130/// - A `Units::Percent` size resolves exactly once, against the parent's
131///   content box (its size minus padding and scrollbar strip) on the same
132///   axis — in both a Row and a Column, at any depth. While a parent is
133///   still being measured for content on an axis (an auto size along an
134///   unbounded axis), a percent along that axis acts as `Auto` until the
135///   parent's final size is known.
136/// - `flex` (and `Dock::Fill`) grows a child into the parent's free main-axis
137///   space; the grown size sticks and the child's own children lay out
138///   against it. A growing [`clip`](crate::widget::Style::clip) container
139///   (e.g. a `scroll_view`) with an auto main size starts from its min size
140///   instead of its content, so it fills exactly the free space and scrolls
141///   the rest.
142pub fn compute(widget: &Widget, avail_w: f32, avail_h: f32) -> LayoutNode {
143    let mut node = LayoutNode {
144        id: widget.id.clone(),
145        on_click: widget.on_click.clone(),
146        enabled: widget.enabled,
147        focused: widget.focused,
148        ..Default::default()
149    };
150    layout_widget(widget, &mut node, 0.0, 0.0, avail_w, avail_h, avail_w, avail_h);
151    node
152}
153
154/// Sizes at or above this mean "unbounded": the axis is being measured for
155/// content (a Row's main axis while its children are measured, ...).
156const UNBOUNDED: f32 = f32::MAX;
157
158fn bounded(v: f32) -> bool {
159    v < UNBOUNDED / 2.0
160}
161
162/// `u` against `basis`; a percent of an unbounded basis is `None` (auto).
163fn resolve_size(u: Units, basis: f32) -> Option<f32> {
164    match u {
165        Units::Percent(_) if !bounded(basis) => None,
166        _ => u.resolve(basis),
167    }
168}
169
170fn new_node(w: &Widget) -> LayoutNode {
171    LayoutNode {
172        id: w.id.clone(),
173        on_click: w.on_click.clone(),
174        enabled: w.enabled,
175        focused: w.focused,
176        ..Default::default()
177    }
178}
179
180/// Measure `w` and lay out its subtree at `(x, y)`. `max_w`/`max_h` cap its
181/// size (`UNBOUNDED` = no cap: size to content); `basis_w`/`basis_h` are the
182/// parent's content box that percent sizes resolve against.
183#[allow(clippy::too_many_arguments)]
184fn layout_widget(
185    w: &Widget,
186    node: &mut LayoutNode,
187    x: f32,
188    y: f32,
189    max_w: f32,
190    max_h: f32,
191    basis_w: f32,
192    basis_h: f32,
193) {
194    let s = &w.style;
195    let has_children = !w.children.is_empty();
196    let explicit_w = resolve_size(s.w, basis_w).map(|v| v.min(max_w));
197    let explicit_h = resolve_size(s.h, basis_h).map(|v| v.min(max_h));
198
199    // Determine own size
200    let mut ww = explicit_w.unwrap_or(max_w);
201    let mut hh = explicit_h.unwrap_or(max_h);
202
203    if !has_children {
204        // Leaf: size to content (text, item slot, spacer)
205        match &w.kind {
206            WidgetKind::Label(t) | WidgetKind::Button(t) => {
207                // Wrap at the explicit width when there is one.
208                let box_w = explicit_w.unwrap_or(max_w);
209                let avail_w = (box_w - s.pad[1] - s.pad[3]).max(0.0);
210                // Wrap only when the width is a real constraint (not
211                // "unlimited") and the widget doesn't opt out of wrapping.
212                if avail_w < 4096.0 && !s.no_wrap {
213                    ww = (avail_w + s.pad[1] + s.pad[3]).max(s.min_w).min(max_w);
214                    hh = (text::text_height(t, avail_w, s.font_scale) + s.pad[0] + s.pad[2])
215                        .max(s.min_h)
216                        .min(max_h);
217                } else {
218                    let tw = text::str_width(t, s.font_scale);
219                    ww = (tw + s.pad[1] + s.pad[3]).max(s.min_w).min(max_w);
220                    hh = (text::LINE_H * s.font_scale + s.pad[0] + s.pad[2])
221                        .max(s.min_h)
222                        .min(max_h);
223                }
224            }
225            WidgetKind::ItemSlot(_) | WidgetKind::InvSlot { .. } => {
226                ww = (18.0 + s.pad[1] + s.pad[3]).max(s.min_w).min(max_w);
227                hh = (18.0 + s.pad[0] + s.pad[2]).max(s.min_h).min(max_h);
228            }
229            WidgetKind::Spacer => {
230                ww = s.min_w.max(1.0).min(max_w);
231                hh = s.min_h.max(1.0).min(max_h);
232            }
233            // Panel with no children: the available space, or its min size
234            // along an unbounded axis.
235            WidgetKind::Panel(_) => {
236                if !bounded(ww) {
237                    ww = s.min_w;
238                }
239                if !bounded(hh) {
240                    hh = s.min_h;
241                }
242            }
243            WidgetKind::McImage { img_w, img_h, .. } => {
244                ww = (*img_w + s.pad[1] + s.pad[3]).max(s.min_w).min(max_w);
245                hh = (*img_h + s.pad[0] + s.pad[2]).max(s.min_h).min(max_h);
246            }
247        }
248        // Explicit width/height always wins over content sizing.
249        if let Some(v) = explicit_w {
250            ww = v;
251        }
252        if let Some(v) = explicit_h {
253            hh = v;
254        }
255    }
256
257    node.rect = Rect { x, y, w: ww, h: hh };
258    node.content_h = hh;
259    node.scroll_y = 0.0;
260    node.clip = s.clip;
261    node.scrollbar = s.scrollbar;
262
263    if has_children {
264        let shrink = Shrink {
265            w: explicit_w.is_none(),
266            h: explicit_h.is_none(),
267            max_w,
268            max_h,
269        };
270        layout_children(w, node, Some(shrink));
271    }
272}
273
274/// Give `w` (already measured into `node`) its final rect and lay its
275/// children out against that size — nothing is re-resolved or shrunk.
276fn arrange(w: &Widget, node: &mut LayoutNode, x: f32, y: f32) {
277    node.rect.x = x;
278    node.rect.y = y;
279    node.content_h = node.rect.h;
280    if !w.children.is_empty() {
281        layout_children(w, node, None);
282    }
283}
284
285/// Which axes of a container size to its content after its children are
286/// laid out (the measure pass), and the caps on that.
287struct Shrink {
288    w: bool,
289    h: bool,
290    max_w: f32,
291    max_h: f32,
292}
293
294/// Flex layout of `w`'s children inside `node.rect` (size and position
295/// already set). With `shrink`, auto axes then fit the content.
296fn layout_children(w: &Widget, node: &mut LayoutNode, shrink: Option<Shrink>) {
297    let s = &w.style;
298    let Rect {
299        x,
300        y,
301        w: ww,
302        h: hh,
303    } = node.rect;
304
305    let dir = if matches!(w.kind, WidgetKind::Panel(_)) && w.flex_dir == FlexDir::Row {
306        FlexDir::Row
307    } else {
308        FlexDir::Column
309    };
310    let bar_w = if s.scrollbar { SCROLLBAR_W } else { 0.0 };
311    let content_w = if bounded(ww) {
312        (ww - s.pad[1] - s.pad[3] - bar_w).max(0.0)
313    } else {
314        UNBOUNDED
315    };
316    let content_h = if bounded(hh) {
317        (hh - s.pad[0] - s.pad[2]).max(0.0)
318    } else {
319        UNBOUNDED
320    };
321    let (main_bounded, cross_bounded) = match dir {
322        FlexDir::Row => (bounded(content_w), bounded(content_h)),
323        FlexDir::Column => (bounded(content_h), bounded(content_w)),
324    };
325    let cross_offset = |content: f32, size: f32| -> f32 {
326        if !cross_bounded {
327            return 0.0;
328        }
329        match s.align {
330            Align::Center => (content - size) / 2.0,
331            Align::End => content - size,
332            Align::Start => 0.0,
333        }
334    };
335
336    // Helpers for Dock
337    // Returns effective flex factor (Dock::Fill implies at least 1.0).
338    let effective_flex = |child: &Widget| -> f32 {
339        if child.style.dock == Dock::Fill {
340            child.style.flex.max(1.0)
341        } else {
342            child.style.flex
343        }
344    };
345    // Returns true if this child consumes main-axis space in the normal forward pass.
346    let in_flow = |child: &Widget| -> bool {
347        child.style.pos.is_none()
348            && !matches!(
349                (dir, child.style.dock),
350                (FlexDir::Row, Dock::Right) | (FlexDir::Column, Dock::Bottom)
351            )
352    };
353    let stretches = |dock: Dock| -> bool {
354        cross_bounded
355            && match dir {
356                FlexDir::Row => matches!(dock, Dock::Fill | Dock::Left | Dock::Right),
357                FlexDir::Column => matches!(dock, Dock::Fill | Dock::Top | Dock::Bottom),
358            }
359    };
360
361    // Measure children
362    let mut child_nodes: Vec<LayoutNode> = Vec::with_capacity(w.children.len());
363    let mut total_flex: f32 = 0.0;
364    let mut used_main: f32 = 0.0;
365
366    for child in &w.children {
367        let mut cn = new_node(child);
368        // Absolutely positioned: measured against what's left of the content
369        // box past its offset (percent sizes: against the whole content box),
370        // placed after the flow passes.
371        if let Some((px, py)) = child.style.pos {
372            let mw = if bounded(content_w) {
373                (content_w - px).max(0.0)
374            } else {
375                UNBOUNDED
376            };
377            let mh = if bounded(content_h) {
378                (content_h - py).max(0.0)
379            } else {
380                UNBOUNDED
381            };
382            layout_widget(child, &mut cn, 0.0, 0.0, mw, mh, content_w, content_h);
383            child_nodes.push(cn);
384            continue;
385        }
386        // Main axis unbounded (children size to content along it), except a
387        // Dock::Fill child which may wrap text to the container.
388        let (cmw, cmh) = match (dir, child.style.dock) {
389            (_, Dock::Fill) => (content_w, content_h),
390            (FlexDir::Row, _) => (UNBOUNDED, content_h),
391            (FlexDir::Column, _) => (content_w, UNBOUNDED),
392        };
393        layout_widget(child, &mut cn, 0.0, 0.0, cmw, cmh, content_w, content_h);
394        let ef = effective_flex(child);
395        // A growing clip container starts from its min size, not its content.
396        if ef > 0.0 && child.style.clip && main_bounded && in_flow(child) {
397            match dir {
398                FlexDir::Row if child.style.w.is_auto() => cn.rect.w = child.style.min_w,
399                FlexDir::Column if child.style.h.is_auto() => cn.rect.h = child.style.min_h,
400                _ => {}
401            }
402        }
403        // Flow and far-edge (Dock::Right / Dock::Bottom) children alike
404        // take main-axis space.
405        used_main += match dir {
406            FlexDir::Row => cn.rect.w,
407            FlexDir::Column => cn.rect.h,
408        };
409        if in_flow(child) {
410            total_flex += ef;
411        }
412        child_nodes.push(cn);
413    }
414    let placed = w.children.iter().filter(|c| c.style.pos.is_none()).count();
415    used_main += s.gap * (placed.saturating_sub(1) as f32);
416
417    // Free main-axis space to grow into — none while measuring for content.
418    let available = if main_bounded {
419        (match dir {
420            FlexDir::Row => content_w,
421            FlexDir::Column => content_h,
422        }) - used_main
423    } else {
424        0.0
425    };
426    let mut pos = match dir {
427        FlexDir::Row => s.pad[3],
428        FlexDir::Column => s.pad[0],
429    };
430
431    // --- Forward pass: position in-flow children (not Dock::Right / Dock::Bottom) ---
432    for (i, child) in w.children.iter().enumerate() {
433        if !in_flow(child) {
434            continue;
435        }
436        let cn = &mut child_nodes[i];
437        let ef = effective_flex(child);
438        let grow = if ef > 0.0 && total_flex > 0.0 && available > 0.0 {
439            available * ef / total_flex
440        } else {
441            0.0
442        };
443        let stretch = stretches(child.style.dock);
444        let (cx, cy) = if dir == FlexDir::Row {
445            cn.rect.w += grow;
446            if stretch {
447                cn.rect.h = content_h;
448            }
449            let p = (x + pos, y + s.pad[0] + cross_offset(content_h, cn.rect.h));
450            pos += cn.rect.w + s.gap;
451            p
452        } else {
453            cn.rect.h += grow;
454            if stretch {
455                cn.rect.w = content_w;
456            }
457            let p = (x + s.pad[3] + cross_offset(content_w, cn.rect.w), y + pos);
458            pos += cn.rect.h + s.gap;
459            p
460        };
461        arrange(child, cn, cx, cy);
462    }
463
464    // --- Reverse pass: position Dock::Right / Dock::Bottom children from the far edge ---
465    // While measuring for content there is no far edge: they line up right
466    // after the flow, keeping their right-to-left (bottom-to-top) order.
467    let mut rpos = if main_bounded {
468        match dir {
469            FlexDir::Row => x + s.pad[3] + content_w,
470            FlexDir::Column => y + s.pad[0] + content_h,
471        }
472    } else {
473        let docked: Vec<f32> = w
474            .children
475            .iter()
476            .zip(&child_nodes)
477            .filter(|(c, _)| !in_flow(c) && c.style.pos.is_none())
478            .map(|(_, n)| match dir {
479                FlexDir::Row => n.rect.w,
480                FlexDir::Column => n.rect.h,
481            })
482            .collect();
483        let span: f32 =
484            docked.iter().sum::<f32>() + s.gap * (docked.len().saturating_sub(1) as f32);
485        (match dir {
486            FlexDir::Row => x,
487            FlexDir::Column => y,
488        }) + pos
489            + span
490    };
491    for (i, child) in w.children.iter().enumerate() {
492        if in_flow(child) || child.style.pos.is_some() {
493            continue;
494        }
495        let cn = &mut child_nodes[i];
496        let stretch = stretches(child.style.dock);
497        let (cx, cy) = if dir == FlexDir::Row {
498            if stretch {
499                cn.rect.h = content_h;
500            }
501            rpos -= cn.rect.w;
502            (rpos, y + s.pad[0] + cross_offset(content_h, cn.rect.h))
503        } else {
504            if stretch {
505                cn.rect.w = content_w;
506            }
507            rpos -= cn.rect.h;
508            (x + s.pad[3] + cross_offset(content_w, cn.rect.w), rpos)
509        };
510        rpos -= s.gap;
511        arrange(child, cn, cx, cy);
512    }
513
514    // --- Absolutely positioned children (see `Style::pos`) ---
515    for (i, child) in w.children.iter().enumerate() {
516        let Some((px, py)) = child.style.pos else {
517            continue;
518        };
519        let cn = &mut child_nodes[i];
520        arrange(child, cn, x + s.pad[3] + px, y + s.pad[0] + py);
521    }
522
523    // Auto-size (measure pass only): shrink to content
524    let ch: f32 = child_nodes
525        .iter()
526        .map(|c| c.rect.y - y + c.rect.h)
527        .fold(0.0f32, f32::max);
528    if let Some(fit) = shrink {
529        if fit.w {
530            let cw: f32 = child_nodes
531                .iter()
532                .map(|c| c.rect.x - x + c.rect.w)
533                .fold(0.0f32, f32::max);
534            node.rect.w = (cw + s.pad[1] + bar_w).max(s.min_w).min(fit.max_w);
535        }
536        if fit.h {
537            node.rect.h = (ch + s.pad[2]).max(s.min_h).min(fit.max_h);
538        }
539    }
540
541    // Scrolling: children positioned from the content's top, then shifted up.
542    // (`ch` already includes the top padding: child y is relative to `y`.)
543    node.content_h = ch + s.pad[2];
544    node.scroll_y = s.scroll_y.clamp(0.0, node.max_scroll());
545    if node.scroll_y > 0.0 {
546        for c in &mut child_nodes {
547            c.translate_y(-node.scroll_y);
548        }
549    }
550
551    node.children = child_nodes;
552}
553
554/// Hit-test: find deepest clickable, enabled node at (mx, my).
555/// Children only count where they're inside their parent's rect, so rows
556/// scrolled out of a clipping container can't be clicked.
557pub fn hit_test(node: &LayoutNode, mx: f32, my: f32) -> Option<&LayoutNode> {
558    if !node.rect.contains(mx, my) {
559        return None;
560    }
561    for child in node.children.iter().rev() {
562        if let Some(hit) = hit_test(child, mx, my) {
563            return Some(hit);
564        }
565    }
566    if node.on_click.is_some() && node.enabled {
567        Some(node)
568    } else {
569        None
570    }
571}
572
573/// Find the resolved rect of the (first) node tagged `id` (see `Widget::id`).
574/// Meant for baking a widget tree's computed positions into some other
575/// system at "measure time" (e.g. a mod reporting real-slot pixel offsets to
576/// its host) — a WinForms-style measure-then-use pass, not a per-frame call.
577pub fn find_by_id(node: &LayoutNode, id: &str) -> Option<Rect> {
578    if node.id.as_deref() == Some(id) {
579        return Some(node.rect);
580    }
581    node.children.iter().find_map(|c| find_by_id(c, id))
582}
583
584/// The (first) node tagged `id` — its rect plus scrolling state
585/// ([`LayoutNode::scroll_y`], [`LayoutNode::scrollbar_rects`], ...).
586pub fn find_node<'a>(node: &'a LayoutNode, id: &str) -> Option<&'a LayoutNode> {
587    if node.id.as_deref() == Some(id) {
588        return Some(node);
589    }
590    node.children.iter().find_map(|c| find_node(c, id))
591}
592
593/// Walk tree and set `focused = true` on the node whose id matches, false on all others.
594pub fn set_focus(node: &mut LayoutNode, focused_id: Option<&str>) {
595    node.focused = focused_id.is_some() && node.id.as_deref() == focused_id;
596    for child in &mut node.children {
597        set_focus(child, focused_id);
598    }
599}
600
601#[cfg(test)]
602mod tests {
603    use super::*;
604    use crate::widget::{self, Units};
605
606    #[test]
607    fn positioned_children_leave_the_flow() {
608        let root = widget::panel(FlexDir::Column)
609            .w(200.0)
610            .h(100.0)
611            .padding(4.0, 4.0, 4.0, 4.0)
612            .child(widget::spacer().min_w(10.0).min_h(10.0))
613            .child(widget::button("Hi").w(40.0).h(20.0).at(50.0, 30.0))
614            .child(widget::spacer().min_w(10.0).min_h(10.0));
615        let node = compute(&root, 400.0, 400.0);
616        let r = node.children[1].rect;
617        assert_eq!((r.x, r.y, r.w, r.h), (54.0, 34.0, 40.0, 20.0));
618        // The flow children stack as if the positioned one weren't there.
619        assert_eq!(node.children[0].rect.y, 4.0);
620        assert_eq!(node.children[2].rect.y, 4.0 + 10.0 + 2.0);
621    }
622
623    #[test]
624    fn positioned_container_lays_out_its_children_in_place() {
625        let root = widget::panel(FlexDir::Column)
626            .w(Units::Percent(100.0))
627            .h(Units::Percent(100.0))
628            .child(
629                widget::panel(FlexDir::Row)
630                    .w(100.0)
631                    .h(20.0)
632                    .gap(0.0)
633                    .at(10.0, 20.0)
634                    .child(widget::spacer().min_w(30.0).min_h(5.0))
635                    .child(widget::spacer().min_w(30.0).min_h(5.0)),
636            );
637        let node = compute(&root, 320.0, 240.0);
638        let panel = &node.children[0];
639        assert_eq!((panel.rect.x, panel.rect.y), (10.0, 20.0));
640        assert_eq!(panel.children[1].rect.x, 40.0);
641        assert_eq!(panel.children[1].rect.y, 20.0);
642    }
643
644    #[test]
645    fn auto_sized_parent_grows_to_fit_positioned_children() {
646        let root = widget::panel(FlexDir::Column)
647            .child(widget::spacer().min_w(10.0).min_h(10.0).at(30.0, 40.0));
648        let node = compute(&root, 300.0, 300.0);
649        assert_eq!((node.rect.w, node.rect.h), (40.0, 50.0));
650    }
651
652    fn pct(v: f32) -> Units {
653        Units::Percent(v)
654    }
655
656    fn r(n: &LayoutNode) -> (f32, f32, f32, f32) {
657        (n.rect.x, n.rect.y, n.rect.w, n.rect.h)
658    }
659
660    #[test]
661    fn percent_width_in_a_row_resolves_once_against_the_content_box() {
662        let root = widget::panel(FlexDir::Row)
663            .w(400.0)
664            .h(100.0)
665            .padding(5.0, 10.0, 5.0, 10.0)
666            .child(
667                widget::panel(FlexDir::Column)
668                    .w(pct(50.0))
669                    .child(widget::spacer().min_w(10.0).min_h(10.0)),
670            )
671            .child(widget::spacer().w(pct(25.0)).h(pct(50.0)));
672        let node = compute(&root, 800.0, 600.0);
673        // Content box: 380 x 90.
674        assert_eq!(r(&node.children[0]).2, 190.0);
675        assert_eq!(r(&node.children[1]), (10.0 + 190.0 + 2.0, 5.0, 95.0, 45.0));
676    }
677
678    #[test]
679    fn percent_sizes_in_a_column() {
680        let root = widget::panel(FlexDir::Column)
681            .w(200.0)
682            .h(300.0)
683            .padding(10.0, 0.0, 10.0, 0.0)
684            .gap(0.0)
685            .child(
686                widget::panel(FlexDir::Row)
687                    .w(pct(50.0))
688                    .h(pct(50.0))
689                    .child(widget::spacer()),
690            )
691            .child(widget::spacer().w(pct(100.0)).h(pct(10.0)));
692        let node = compute(&root, 800.0, 600.0);
693        assert_eq!(r(&node.children[0]), (0.0, 10.0, 100.0, 140.0));
694        assert_eq!(r(&node.children[1]), (0.0, 150.0, 200.0, 28.0));
695    }
696
697    #[test]
698    fn nested_percents_compound_per_level_only() {
699        let root = widget::panel(FlexDir::Row).w(400.0).h(200.0).child(
700            widget::panel(FlexDir::Column)
701                .w(pct(50.0))
702                .h(pct(100.0))
703                .child(
704                    widget::panel(FlexDir::Row)
705                        .w(pct(50.0))
706                        .h(pct(50.0))
707                        .child(widget::spacer().w(pct(50.0)).h(pct(50.0))),
708                ),
709        );
710        let node = compute(&root, 400.0, 200.0);
711        let a = &node.children[0];
712        let b = &a.children[0];
713        let c = &b.children[0];
714        assert_eq!(r(a), (0.0, 0.0, 200.0, 200.0));
715        assert_eq!(r(b), (0.0, 0.0, 100.0, 100.0));
716        assert_eq!(r(c), (0.0, 0.0, 50.0, 50.0));
717    }
718
719    #[test]
720    fn percent_resolves_against_the_scrollbar_free_box() {
721        let root = widget::scroll_view()
722            .w(106.0)
723            .h(50.0)
724            .child(widget::spacer().w(pct(50.0)).h(10.0));
725        let node = compute(&root, 400.0, 400.0);
726        assert_eq!(node.children[0].rect.w, 50.0);
727    }
728
729    #[test]
730    fn grow_shares_free_space_with_percent_siblings() {
731        let root = widget::panel(FlexDir::Row)
732            .w(300.0)
733            .h(50.0)
734            .gap(4.0)
735            .child(widget::spacer().w(pct(50.0)))
736            .child(widget::panel(FlexDir::Column).flex(1.0).child(widget::spacer()))
737            .child(widget::spacer().w(pct(10.0)));
738        let node = compute(&root, 300.0, 50.0);
739        // 300 - 150 - 30 - 2 * 4 = 112 for the grown panel.
740        assert_eq!(r(&node.children[0]).2, 150.0);
741        assert_eq!(r(&node.children[1]), (154.0, 0.0, 112.0, 4.0));
742        assert_eq!(r(&node.children[2]), (270.0, 0.0, 30.0, 4.0));
743    }
744
745    #[test]
746    fn grown_panel_keeps_its_size_and_lays_children_out_against_it() {
747        let root = widget::panel(FlexDir::Column)
748            .w(200.0)
749            .h(200.0)
750            .gap(0.0)
751            .child(widget::spacer().min_h(20.0))
752            .child(
753                widget::panel(FlexDir::Row)
754                    .flex(1.0)
755                    .w(pct(100.0))
756                    .gap(0.0)
757                    .child(widget::spacer().w(pct(25.0)).h(pct(50.0)))
758                    .child(widget::panel(FlexDir::Column).flex(1.0).child(widget::spacer()))
759                    .child(widget::spacer().dock(Dock::Right).min_w(10.0)),
760            );
761        let node = compute(&root, 400.0, 400.0);
762        let grown = &node.children[1];
763        assert_eq!(r(grown), (0.0, 20.0, 200.0, 180.0));
764        assert_eq!(r(&grown.children[0]), (0.0, 20.0, 50.0, 90.0));
765        // The inner flex child grows into what's left of the grown width...
766        assert_eq!(r(&grown.children[1]).2, 200.0 - 50.0 - 10.0);
767        // ... and the right-docked one hugs the grown panel's far edge.
768        assert_eq!(r(&grown.children[2]), (190.0, 20.0, 10.0, 180.0));
769    }
770
771    #[test]
772    fn grown_column_panel_fills_its_parent_and_children_grow_too() {
773        let root = widget::panel(FlexDir::Column)
774            .w(100.0)
775            .h(100.0)
776            .gap(0.0)
777            .child(
778                widget::panel(FlexDir::Column)
779                    .flex(1.0)
780                    .gap(0.0)
781                    .child(widget::spacer().flex(1.0)),
782            );
783        let node = compute(&root, 100.0, 100.0);
784        assert_eq!(node.children[0].rect.h, 100.0);
785        assert_eq!(node.children[0].children[0].rect.h, 100.0);
786    }
787
788    #[test]
789    fn empty_auto_panel_in_a_row_takes_its_min_width() {
790        let root = widget::panel(FlexDir::Row)
791            .w(100.0)
792            .h(20.0)
793            .child(widget::panel(FlexDir::Column).min_w(7.0))
794            .child(widget::spacer());
795        let node = compute(&root, 100.0, 20.0);
796        assert_eq!(node.children[0].rect.w, 7.0);
797        assert_eq!(node.children[1].rect.x, 9.0);
798    }
799
800    #[test]
801    fn padding_counts_once_in_auto_size() {
802        let root = widget::panel(FlexDir::Column)
803            .padding(3.0, 4.0, 5.0, 6.0)
804            .child(widget::spacer().min_w(10.0).min_h(10.0));
805        let node = compute(&root, 300.0, 300.0);
806        assert_eq!((node.rect.w, node.rect.h), (20.0, 18.0));
807        assert_eq!((node.children[0].rect.x, node.children[0].rect.y), (6.0, 3.0));
808    }
809
810    #[test]
811    fn auto_row_in_a_column_measures_to_content() {
812        // Align::Center on an auto-height row must not centre in "infinity".
813        let root = widget::panel(FlexDir::Column).w(200.0).h(200.0).child(
814            widget::panel(FlexDir::Row)
815                .align(Align::Center)
816                .gap(0.0)
817                .child(widget::spacer().min_w(10.0).min_h(10.0))
818                .child(widget::spacer().min_w(10.0).min_h(20.0))
819                .child(widget::spacer().min_w(5.0).dock(Dock::Right)),
820        );
821        let node = compute(&root, 200.0, 200.0);
822        let row = &node.children[0];
823        assert_eq!(row.rect.h, 20.0);
824        assert_eq!(row.children[0].rect.y, 5.0);
825        assert_eq!(row.children[1].rect.y, 0.0);
826    }
827
828    #[test]
829    fn row_with_right_dock_measured_on_unbounded_axis() {
830        // An auto-width row inside a row: its Dock::Right child lines up after
831        // the flow instead of at "infinity".
832        let root = widget::panel(FlexDir::Row).w(300.0).h(20.0).child(
833            widget::panel(FlexDir::Row)
834                .gap(1.0)
835                .child(widget::spacer().min_w(10.0))
836                .child(widget::spacer().min_w(5.0).dock(Dock::Right))
837                .child(widget::spacer().min_w(7.0).dock(Dock::Right)),
838        );
839        let node = compute(&root, 300.0, 20.0);
840        let inner = &node.children[0];
841        assert_eq!(inner.rect.w, 10.0 + 1.0 + 7.0 + 1.0 + 5.0);
842        assert_eq!(inner.children[1].rect.x, 19.0);
843        assert_eq!(inner.children[2].rect.x, 11.0);
844    }
845
846    #[test]
847    fn align_center_and_end_in_both_directions() {
848        let col = widget::panel(FlexDir::Column)
849            .w(100.0)
850            .h(50.0)
851            .align(Align::Center)
852            .child(widget::spacer().min_w(20.0).min_h(5.0));
853        assert_eq!(compute(&col, 100.0, 50.0).children[0].rect.x, 40.0);
854        let row = widget::panel(FlexDir::Row)
855            .w(100.0)
856            .h(50.0)
857            .padding(10.0, 0.0, 0.0, 0.0)
858            .align(Align::End)
859            .child(widget::spacer().min_w(20.0).h(pct(20.0)));
860        // Content height 40, child 8 tall, bottom-aligned.
861        assert_eq!(compute(&row, 100.0, 50.0).children[0].rect.y, 10.0 + 32.0);
862    }
863
864    #[test]
865    fn positioned_children_with_percent_sizes() {
866        let root = widget::panel(FlexDir::Column)
867            .w(200.0)
868            .h(100.0)
869            .padding(10.0, 10.0, 10.0, 10.0)
870            .child(widget::spacer().w(pct(50.0)).h(pct(50.0)).at(20.0, 10.0))
871            .child(
872                widget::panel(FlexDir::Row)
873                    .w(pct(100.0))
874                    .h(pct(25.0))
875                    .at(0.0, 60.0)
876                    .gap(0.0)
877                    .child(widget::spacer().w(pct(50.0)))
878                    .child(widget::spacer().flex(1.0)),
879            );
880        let node = compute(&root, 400.0, 400.0);
881        // Content box 180 x 80.
882        assert_eq!(r(&node.children[0]), (30.0, 20.0, 90.0, 40.0));
883        // 100% of 180 but capped to what's left past x=0, i.e. 180; 25% of 80
884        // = 20 but capped to 80 - 60.
885        let p = &node.children[1];
886        assert_eq!(r(p), (10.0, 70.0, 180.0, 20.0));
887        assert_eq!(r(&p.children[0]), (10.0, 70.0, 90.0, 4.0));
888        assert_eq!(r(&p.children[1]), (100.0, 70.0, 90.0, 4.0));
889    }
890
891    #[test]
892    fn growing_scroll_view_fills_free_space_and_scrolls_the_rest() {
893        let list = widget::scroll_view()
894            .id("list")
895            .flex(1.0)
896            .w(pct(100.0))
897            .gap(0.0)
898            .padding(2.0, 2.0, 2.0, 2.0)
899            .scroll_y(1000.0)
900            .children((0..10).map(|_| widget::spacer().w(pct(100.0)).min_h(20.0)));
901        let root = widget::panel(FlexDir::Column)
902            .w(100.0)
903            .h(120.0)
904            .gap(0.0)
905            .child(widget::spacer().min_h(20.0))
906            .child(list);
907        let node = compute(&root, 100.0, 120.0);
908        let v = find_node(&node, "list").unwrap();
909        assert_eq!(r(v), (0.0, 20.0, 100.0, 100.0));
910        assert_eq!(v.content_h, 204.0);
911        assert_eq!(v.scroll_y, 104.0);
912        // Rows span the scrollbar-free content width.
913        assert_eq!(v.children[0].rect.w, 100.0 - 4.0 - SCROLLBAR_W);
914        // The last row's bottom sits on the view's inner bottom edge.
915        let last = v.children[9].rect;
916        assert_eq!(last.y + last.h, 20.0 + 100.0 - 2.0);
917        assert!(v.scrollbar_rects().is_some());
918    }
919
920    #[test]
921    fn label_wraps_at_its_explicit_width() {
922        let root = widget::panel(FlexDir::Column)
923            .w(300.0)
924            .child(widget::label("aaaa bbbb cccc").w(40.0));
925        let node = compute(&root, 300.0, 300.0);
926        let l = node.children[0].rect;
927        assert_eq!(l.w, 40.0);
928        assert!(l.h > text::LINE_H, "wrapped onto several lines: {l:?}");
929    }
930
931    #[test]
932    fn percent_caps_at_the_cross_axis_and_ignores_unbounded_basis() {
933        // 150% across a column caps at the content width.
934        let root = widget::panel(FlexDir::Column)
935            .w(100.0)
936            .h(100.0)
937            .child(widget::spacer().w(pct(150.0)));
938        assert_eq!(compute(&root, 100.0, 100.0).children[0].rect.w, 100.0);
939        // An auto-width row measured inside a row resolves its children's
940        // percents against its final (content) width.
941        let root = widget::panel(FlexDir::Row).w(200.0).h(20.0).child(
942            widget::panel(FlexDir::Row)
943                .gap(0.0)
944                .child(widget::spacer().min_w(40.0))
945                .child(widget::spacer().w(pct(50.0))),
946        );
947        let node = compute(&root, 200.0, 20.0);
948        let inner = &node.children[0];
949        assert_eq!(inner.rect.w, 44.0);
950        assert_eq!(inner.children[1].rect.w, 22.0);
951    }
952
953    #[test]
954    fn find_mut_and_set_text() {
955        let mut root = widget::panel(FlexDir::Column).child(widget::label("a").id("title"));
956        assert!(root.find_mut("title").unwrap().set_text("b"));
957        match &root.children[0].kind {
958            crate::widget::WidgetKind::Label(t) => assert_eq!(t, "b"),
959            _ => unreachable!(),
960        }
961        assert!(root.find_mut("missing").is_none());
962    }
963}