Skip to main content

yog_ui/
layout.rs

1use crate::text;
2use crate::widget::{Dock, 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#[derive(Debug, Clone)]
25pub struct LayoutNode {
26    pub rect: Rect,
27    pub id: Option<String>,
28    pub on_click: Option<String>,
29    pub children: Vec<LayoutNode>,
30    pub enabled: bool,
31    pub focused: bool,
32}
33
34impl Default for LayoutNode {
35    fn default() -> Self {
36        Self {
37            rect: Rect::default(),
38            id: None,
39            on_click: None,
40            children: Vec::new(),
41            enabled: true,
42            focused: false,
43        }
44    }
45}
46
47/// Compute layout starting at (0,0) with given available size.
48/// Returns the root LayoutNode with absolute coordinates.
49pub fn compute(widget: &Widget, avail_w: f32, avail_h: f32) -> LayoutNode {
50    let mut node = LayoutNode {
51        id: widget.id.clone(),
52        on_click: widget.on_click.clone(),
53        enabled: widget.enabled,
54        focused: widget.focused,
55        ..Default::default()
56    };
57    layout_widget(widget, &mut node, 0.0, 0.0, avail_w, avail_h);
58    node
59}
60
61fn layout_widget(w: &Widget, node: &mut LayoutNode, x: f32, y: f32, max_w: f32, max_h: f32) {
62    let s = &w.style;
63    let has_children = !w.children.is_empty();
64
65    // Determine own size
66    let mut ww = if s.w > 0.0 { s.w.min(max_w) } else { max_w };
67    let mut hh = if s.h > 0.0 { s.h.min(max_h) } else { max_h };
68
69    if !has_children {
70        // Leaf: size to content (text, item slot, spacer)
71        match &w.kind {
72            WidgetKind::Label(t) | WidgetKind::Button(t) => {
73                let avail_w = (max_w - s.pad[1] - s.pad[3]).max(0.0);
74                // Wrap only when max_w is a real constraint (not "unlimited")
75                // and the widget doesn't opt out of wrapping entirely.
76                if avail_w < 4096.0 && !s.no_wrap {
77                    ww = (avail_w + s.pad[1] + s.pad[3]).max(s.min_w).min(max_w);
78                    hh = (text::text_height(t, avail_w, s.font_scale) + s.pad[0] + s.pad[2])
79                        .max(s.min_h)
80                        .min(max_h);
81                } else {
82                    let tw = text::str_width(t, s.font_scale);
83                    ww = (tw + s.pad[1] + s.pad[3]).max(s.min_w).min(max_w);
84                    hh = (text::LINE_H * s.font_scale + s.pad[0] + s.pad[2])
85                        .max(s.min_h)
86                        .min(max_h);
87                }
88            }
89            WidgetKind::ItemSlot(_) | WidgetKind::InvSlot(_) => {
90                ww = (18.0 + s.pad[1] + s.pad[3]).max(s.min_w).min(max_w);
91                hh = (18.0 + s.pad[0] + s.pad[2]).max(s.min_h).min(max_h);
92            }
93            WidgetKind::Spacer => {
94                ww = s.min_w.max(1.0).min(max_w);
95                hh = s.min_h.max(1.0).min(max_h);
96            }
97            WidgetKind::Panel(_) => {} // panel with no children → size to min or available
98            WidgetKind::McImage { img_w, img_h, .. } => {
99                ww = (*img_w + s.pad[1] + s.pad[3]).max(s.min_w).min(max_w);
100                hh = (*img_h + s.pad[0] + s.pad[2]).max(s.min_h).min(max_h);
101            }
102        }
103        // Explicit width/height always wins over content sizing.
104        if s.w > 0.0 {
105            ww = s.w.min(max_w);
106        }
107        if s.h > 0.0 {
108            hh = s.h.min(max_h);
109        }
110    }
111
112    node.rect = Rect { x, y, w: ww, h: hh };
113
114    if !has_children {
115        return;
116    }
117
118    // Flex layout for children
119    let dir = if matches!(w.kind, WidgetKind::Panel(_)) && w.flex_dir == FlexDir::Row {
120        FlexDir::Row
121    } else {
122        FlexDir::Column
123    };
124    let content_w = ww - s.pad[1] - s.pad[3];
125    let content_h = hh - s.pad[0] - s.pad[2];
126
127    // Helpers for Dock
128    // Returns effective flex factor (Dock::Fill implies at least 1.0).
129    let effective_flex = |child: &Widget| -> f32 {
130        if child.style.dock == Dock::Fill {
131            child.style.flex.max(1.0)
132        } else {
133            child.style.flex
134        }
135    };
136    // Returns true if this child consumes main-axis space in the normal forward pass.
137    let in_flow = |child: &Widget| -> bool {
138        match (dir, child.style.dock) {
139            (FlexDir::Row, Dock::Right) => false,
140            (FlexDir::Column, Dock::Bottom) => false,
141            _ => true,
142        }
143    };
144
145    // Measure children
146    let mut child_nodes: Vec<LayoutNode> = Vec::new();
147    let mut total_flex: f32 = 0.0;
148    let mut used_main: f32 = 0.0;
149
150    for child in &w.children {
151        let dock = child.style.dock;
152        let mut cn = LayoutNode {
153            id: child.id.clone(),
154            on_click: child.on_click.clone(),
155            enabled: child.enabled,
156            focused: child.focused,
157            ..Default::default()
158        };
159        // Determine measurement constraints based on Dock + direction.
160        let (cmw, cmh) = match (dir, dock) {
161            // Fill: constrain both axes so text can wrap to container dimensions.
162            (FlexDir::Row, Dock::Fill) => (content_w, content_h),
163            (FlexDir::Column, Dock::Fill) => (content_w, content_h),
164            // Cross-axis fill: constrain cross axis, unlimited main axis.
165            (FlexDir::Row, Dock::Left | Dock::Right) => (f32::MAX, content_h),
166            (FlexDir::Column, Dock::Top | Dock::Bottom) => (content_w, f32::MAX),
167            // Default flex behaviour.
168            (FlexDir::Row, _) => (f32::MAX, content_h),
169            (FlexDir::Column, _) => (content_w, f32::MAX),
170        };
171        layout_widget(child, &mut cn, 0.0, 0.0, cmw, cmh);
172        if in_flow(child) {
173            if dir == FlexDir::Row {
174                used_main += cn.rect.w;
175            } else {
176                used_main += cn.rect.h;
177            }
178        }
179        total_flex += effective_flex(child);
180        child_nodes.push(cn);
181    }
182    let flow_count = w.children.iter().filter(|c| in_flow(c)).count();
183    let gaps = s.gap * (flow_count.saturating_sub(1) as f32);
184    used_main += gaps;
185
186    let available = (if dir == FlexDir::Row {
187        content_w
188    } else {
189        content_h
190    }) - used_main;
191    let mut pos = if dir == FlexDir::Row {
192        s.pad[3]
193    } else {
194        s.pad[0]
195    };
196
197    // --- Forward pass: position in-flow children (not Dock::Right / Dock::Bottom) ---
198    for (i, child) in w.children.iter().enumerate() {
199        if !in_flow(child) {
200            continue;
201        }
202        let dock = child.style.dock;
203        let cn = &mut child_nodes[i];
204        if dir == FlexDir::Row {
205            let ef = effective_flex(child);
206            if ef > 0.0 && total_flex > 0.0 && available > 0.0 {
207                cn.rect.w += available * ef / total_flex;
208            }
209            if dock == Dock::Fill || dock == Dock::Left || dock == Dock::Right {
210                cn.rect.h = content_h; // stretch cross axis
211            }
212            cn.rect.x = x + pos;
213            cn.rect.y = y
214                + s.pad[0]
215                + match s.align {
216                    Align::Center => (content_h - cn.rect.h) / 2.0,
217                    Align::End => content_h - cn.rect.h,
218                    _ => 0.0,
219                };
220            pos += cn.rect.w + s.gap;
221        } else {
222            let ef = effective_flex(child);
223            if ef > 0.0 && total_flex > 0.0 && available > 0.0 {
224                cn.rect.h += available * ef / total_flex;
225            }
226            if dock == Dock::Fill || dock == Dock::Top || dock == Dock::Bottom {
227                cn.rect.w = content_w; // stretch cross axis
228            }
229            cn.rect.x = x
230                + s.pad[3]
231                + match s.align {
232                    Align::Center => (content_w - cn.rect.w) / 2.0,
233                    Align::End => content_w - cn.rect.w,
234                    _ => 0.0,
235                };
236            cn.rect.y = y + pos;
237            pos += cn.rect.h + s.gap;
238        }
239        if !child.children.is_empty() {
240            layout_widget(child, cn, cn.rect.x, cn.rect.y, cn.rect.w, cn.rect.h);
241        }
242    }
243
244    // --- Reverse pass: position Dock::Right / Dock::Bottom children from the far edge ---
245    let mut rpos = if dir == FlexDir::Row {
246        x + s.pad[3] + content_w
247    } else {
248        y + s.pad[0] + content_h
249    };
250    for (i, child) in w.children.iter().enumerate() {
251        if in_flow(child) {
252            continue;
253        }
254        let dock = child.style.dock;
255        let cn = &mut child_nodes[i];
256        if dir == FlexDir::Row {
257            if dock == Dock::Fill || dock == Dock::Left || dock == Dock::Right {
258                cn.rect.h = content_h;
259            }
260            rpos -= cn.rect.w;
261            cn.rect.x = rpos;
262            cn.rect.y = y
263                + s.pad[0]
264                + match s.align {
265                    Align::Center => (content_h - cn.rect.h) / 2.0,
266                    Align::End => content_h - cn.rect.h,
267                    _ => 0.0,
268                };
269            rpos -= s.gap;
270        } else {
271            if dock == Dock::Fill || dock == Dock::Top || dock == Dock::Bottom {
272                cn.rect.w = content_w;
273            }
274            rpos -= cn.rect.h;
275            cn.rect.y = rpos;
276            cn.rect.x = x
277                + s.pad[3]
278                + match s.align {
279                    Align::Center => (content_w - cn.rect.w) / 2.0,
280                    Align::End => content_w - cn.rect.w,
281                    _ => 0.0,
282                };
283            rpos -= s.gap;
284        }
285        if !child.children.is_empty() {
286            layout_widget(child, cn, cn.rect.x, cn.rect.y, cn.rect.w, cn.rect.h);
287        }
288    }
289
290    // Auto-size: shrink to content
291    if s.w <= 0.0 {
292        let cw: f32 = child_nodes
293            .iter()
294            .map(|c| c.rect.x - x + c.rect.w)
295            .fold(0.0f32, f32::max);
296        node.rect.w = (cw + s.pad[1] + s.pad[3]).max(s.min_w).min(max_w);
297    }
298    if s.h <= 0.0 {
299        let ch: f32 = child_nodes
300            .iter()
301            .map(|c| c.rect.y - y + c.rect.h)
302            .fold(0.0f32, f32::max);
303        node.rect.h = (ch + s.pad[0] + s.pad[2]).max(s.min_h).min(max_h);
304    }
305
306    node.children = child_nodes;
307}
308
309/// Hit-test: find deepest clickable, enabled node at (mx, my).
310pub fn hit_test(node: &LayoutNode, mx: f32, my: f32) -> Option<&LayoutNode> {
311    let r = &node.rect;
312    if mx < r.x || my < r.y || mx > r.x + r.w || my > r.y + r.h {
313        return None;
314    }
315    for child in node.children.iter().rev() {
316        if let Some(hit) = hit_test(child, mx, my) {
317            return Some(hit);
318        }
319    }
320    if node.on_click.is_some() && node.enabled {
321        Some(node)
322    } else {
323        None
324    }
325}
326
327/// Walk tree and set `focused = true` on the node whose id matches, false on all others.
328pub fn set_focus(node: &mut LayoutNode, focused_id: Option<&str>) {
329    node.focused = focused_id.is_some() && node.id.as_deref() == focused_id;
330    for child in &mut node.children {
331        set_focus(child, focused_id);
332    }
333}