Skip to main content

yog_ui/
layout.rs

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