1use crate::text;
2use crate::widget::{Action, Dock, HAlign, SLOT_SIZE, Units, VAlign, Widget, WidgetKind};
3
4mod grid;
5
6#[derive(Debug, Clone, Copy, PartialEq)]
7pub enum FlexDir {
8 Row,
9 Column,
10}
11#[derive(Debug, Clone, Copy, PartialEq)]
12pub enum Align {
13 Start,
14 Center,
15 End,
16}
17
18#[derive(Debug, Clone, Copy, Default)]
19pub struct Rect {
20 pub x: f32,
21 pub y: f32,
22 pub w: f32,
23 pub h: f32,
24}
25
26pub const SCROLLBAR_W: f32 = 6.0;
29pub const MIN_KNOB_H: f32 = 16.0;
31
32impl Rect {
33 pub fn inset(&self, pad: [f32; 4]) -> Rect {
35 Rect {
36 x: self.x + pad[3],
37 y: self.y + pad[0],
38 w: (self.w - pad[1] - pad[3]).max(0.0),
39 h: (self.h - pad[0] - pad[2]).max(0.0),
40 }
41 }
42
43 pub fn contains(&self, px: f32, py: f32) -> bool {
45 px >= self.x && py >= self.y && px <= self.x + self.w && py <= self.y + self.h
46 }
47
48 pub fn intersect(&self, o: &Rect) -> Option<Rect> {
50 let x0 = self.x.max(o.x);
51 let y0 = self.y.max(o.y);
52 let x1 = (self.x + self.w).min(o.x + o.w);
53 let y1 = (self.y + self.h).min(o.y + o.h);
54 (x1 > x0 && y1 > y0).then_some(Rect {
55 x: x0,
56 y: y0,
57 w: x1 - x0,
58 h: y1 - y0,
59 })
60 }
61}
62
63#[derive(Debug, Clone)]
64pub struct LayoutNode {
65 pub rect: Rect,
66 pub id: Option<String>,
67 pub on_click: Option<String>,
68 pub children: Vec<LayoutNode>,
69 pub enabled: bool,
70 pub focused: bool,
71 pub content_h: f32,
74 pub scroll_y: f32,
78 pub clip: bool,
80 pub scrollbar: bool,
82 pub action: Option<Action>,
84 pub visible: bool,
87 pub grid: Option<Box<GridLines>>,
89}
90
91#[derive(Debug, Clone, Default, PartialEq)]
94pub struct GridLines {
95 pub rows: Vec<(f32, f32)>,
97 pub cols: Vec<(f32, f32)>,
99 pub(crate) floor_rows: Vec<f32>,
103 pub(crate) floor_cols: Vec<f32>,
104}
105
106impl LayoutNode {
107 pub fn max_scroll(&self) -> f32 {
109 (self.content_h - self.rect.h).max(0.0)
110 }
111
112 pub fn scrollbar_rects(&self) -> Option<(Rect, Rect)> {
115 let max = self.max_scroll();
116 if !self.scrollbar || max <= 0.0 {
117 return None;
118 }
119 let r = self.rect;
120 let track = Rect {
121 x: r.x + r.w - SCROLLBAR_W,
122 y: r.y,
123 w: SCROLLBAR_W,
124 h: r.h,
125 };
126 let knob_h = (r.h * r.h / self.content_h).max(MIN_KNOB_H).min(r.h);
127 let knob = Rect {
128 y: r.y + (r.h - knob_h) * (self.scroll_y / max),
129 h: knob_h,
130 ..track
131 };
132 Some((track, knob))
133 }
134
135 fn translate_y(&mut self, dy: f32) {
136 self.rect.y += dy;
137 if let Some(g) = &mut self.grid {
138 for r in &mut g.rows {
139 r.0 += dy;
140 }
141 }
142 for c in &mut self.children {
143 c.translate_y(dy);
144 }
145 }
146}
147
148impl Default for LayoutNode {
149 fn default() -> Self {
150 Self {
151 rect: Rect::default(),
152 id: None,
153 on_click: None,
154 children: Vec::new(),
155 enabled: true,
156 focused: false,
157 content_h: 0.0,
158 scroll_y: 0.0,
159 clip: false,
160 scrollbar: false,
161 action: None,
162 visible: true,
163 grid: None,
164 }
165 }
166}
167
168pub fn compute(widget: &Widget, avail_w: f32, avail_h: f32) -> LayoutNode {
185 let mut node = new_node(widget);
186 if widget.visible {
187 layout_widget(
188 widget,
189 &mut node,
190 0.0,
191 0.0,
192 avail_w,
193 avail_h,
194 avail_w,
195 avail_h,
196 Depth::Full,
197 );
198 }
199 node
200}
201
202const UNBOUNDED: f32 = f32::MAX;
205
206const NO_WRAP_W: f32 = 4096.0;
209const TEXT_BOX_W: f32 = 100.0;
211const TEXT_BOX_CHROME_H: f32 = 7.0;
213
214fn bounded(v: f32) -> bool {
215 v < UNBOUNDED / 2.0
216}
217
218fn resolve_size(u: Units, basis: f32) -> Option<f32> {
220 match u {
221 Units::Percent(_) if !bounded(basis) => None,
222 _ => u.resolve(basis),
223 }
224}
225
226fn new_node(w: &Widget) -> LayoutNode {
227 LayoutNode {
228 id: w.id.clone(),
229 on_click: w.on_click.clone(),
230 enabled: w.enabled,
231 focused: w.focused,
232 action: w.action,
233 visible: w.visible,
234 ..Default::default()
235 }
236}
237
238#[derive(Clone, Copy, PartialEq)]
240enum Depth {
241 Size,
246 Full,
248}
249
250fn measure(w: &Widget, node: &mut LayoutNode, max_w: f32, max_h: f32, basis_w: f32, basis_h: f32) {
254 layout_widget(
255 w,
256 node,
257 0.0,
258 0.0,
259 max_w,
260 max_h,
261 basis_w,
262 basis_h,
263 Depth::Size,
264 );
265}
266
267#[allow(clippy::too_many_arguments)]
268fn layout_widget(
269 w: &Widget,
270 node: &mut LayoutNode,
271 x: f32,
272 y: f32,
273 max_w: f32,
274 max_h: f32,
275 basis_w: f32,
276 basis_h: f32,
277 depth: Depth,
278) {
279 let s = &w.style;
280 let has_children = is_container(w);
281 let explicit_w = resolve_size(s.w, basis_w).map(|v| v.min(max_w));
282 let explicit_h = resolve_size(s.h, basis_h).map(|v| v.min(max_h));
283
284 let mut ww = explicit_w.unwrap_or(max_w);
286 let mut hh = explicit_h.unwrap_or(max_h);
287
288 if !has_children {
289 let fit_w = |content: f32| (content + s.pad[1] + s.pad[3]).max(s.min_w).min(max_w);
292 let fit_h = |content: f32| (content + s.pad[0] + s.pad[2]).max(s.min_h).min(max_h);
293 match &w.kind {
294 WidgetKind::Label(t) | WidgetKind::Button(t) => {
295 let avail_w = (ww - s.pad[1] - s.pad[3]).max(0.0);
297 if avail_w < NO_WRAP_W && !s.no_wrap {
300 ww = fit_w(avail_w);
301 hh = fit_h(text::text_height_in(t, avail_w, s.font_scale, &s.font));
302 } else {
303 ww = fit_w(text::str_width_in(t, s.font_scale, &s.font));
304 hh = fit_h(text::LINE_H * s.font_scale);
305 }
306 }
307 WidgetKind::ItemSlot(_) | WidgetKind::InvSlot { .. } => {
308 ww = fit_w(SLOT_SIZE);
309 hh = fit_h(SLOT_SIZE);
310 }
311 WidgetKind::Spacer | WidgetKind::Surface(_) => {
312 ww = s.min_w.max(1.0).min(max_w);
313 hh = s.min_h.max(1.0).min(max_h);
314 }
315 WidgetKind::Panel(_) | WidgetKind::Grid(_) => {
318 if !bounded(ww) {
319 ww = s.min_w;
320 }
321 if !bounded(hh) {
322 hh = s.min_h;
323 }
324 }
325 WidgetKind::TextBox(_) => {
328 if !bounded(ww) {
329 ww = TEXT_BOX_W;
330 }
331 ww = ww.max(s.min_w).min(max_w);
332 hh = fit_h(text::LINE_H * s.font_scale + TEXT_BOX_CHROME_H);
333 }
334 WidgetKind::Image(image) => {
335 let (nw, nh) = crate::image::natural_size(image);
336 ww = fit_w(nw);
337 hh = fit_h(nh);
338 }
339 }
340 if let Some(v) = explicit_w {
342 ww = v;
343 }
344 if let Some(v) = explicit_h {
345 hh = v;
346 }
347 }
348
349 node.rect = Rect { x, y, w: ww, h: hh };
350 node.grid = None;
351 node.content_h = hh;
352 node.scroll_y = 0.0;
353 node.clip = s.clip;
354 node.scrollbar = s.scrollbar;
355
356 if has_children {
357 let shrink = Shrink {
358 w: explicit_w.is_none(),
359 h: explicit_h.is_none(),
360 max_w,
361 max_h,
362 };
363 layout_children(w, node, Some(shrink), depth);
364 }
365}
366
367fn arrange(w: &Widget, node: &mut LayoutNode, x: f32, y: f32) {
370 node.rect.x = x;
371 node.rect.y = y;
372 node.content_h = node.rect.h;
373 if is_container(w) {
374 layout_children(w, node, None, Depth::Full);
375 }
376}
377
378fn is_container(w: &Widget) -> bool {
380 !w.children.is_empty() || matches!(w.kind, WidgetKind::Grid(_))
381}
382
383struct Shrink {
386 w: bool,
387 h: bool,
388 max_w: f32,
389 max_h: f32,
390}
391
392fn place(child: &Widget, cn: &mut LayoutNode, x: f32, y: f32, depth: Depth) {
395 match depth {
396 Depth::Full => arrange(child, cn, x, y),
397 Depth::Size => {
398 cn.rect.x = x;
399 cn.rect.y = y;
400 }
401 }
402}
403
404fn layout_children(w: &Widget, node: &mut LayoutNode, shrink: Option<Shrink>, depth: Depth) {
407 if let WidgetKind::Grid(spec) = &w.kind {
408 return grid::layout(w, spec, node, shrink, depth);
409 }
410 let s = &w.style;
411 let Rect { x, y, w: ww, h: hh } = node.rect;
412
413 let dir = if matches!(w.kind, WidgetKind::Panel(_)) && w.flex_dir == FlexDir::Row {
414 FlexDir::Row
415 } else {
416 FlexDir::Column
417 };
418 let bar_w = if s.scrollbar { SCROLLBAR_W } else { 0.0 };
419 let content_w = if bounded(ww) {
420 (ww - s.pad[1] - s.pad[3] - bar_w).max(0.0)
421 } else {
422 UNBOUNDED
423 };
424 let content_h = if bounded(hh) {
425 (hh - s.pad[0] - s.pad[2]).max(0.0)
426 } else {
427 UNBOUNDED
428 };
429 let (main_bounded, cross_bounded) = match dir {
430 FlexDir::Row => (bounded(content_w), bounded(content_h)),
431 FlexDir::Column => (bounded(content_h), bounded(content_w)),
432 };
433 let cross_shrinks = shrink.as_ref().is_some_and(|f| match dir {
436 FlexDir::Row => f.h,
437 FlexDir::Column => f.w,
438 });
439 let self_place = |child: &Widget| -> Option<Option<Align>> {
443 match dir {
444 FlexDir::Column => child.style.halign.map(|a| match a {
445 HAlign::Left => Some(Align::Start),
446 HAlign::Center => Some(Align::Center),
447 HAlign::Right => Some(Align::End),
448 HAlign::Stretch => None,
449 }),
450 FlexDir::Row => child.style.valign.map(|a| match a {
451 VAlign::Top => Some(Align::Start),
452 VAlign::Center => Some(Align::Center),
453 VAlign::Bottom => Some(Align::End),
454 VAlign::Stretch => None,
455 }),
456 }
457 };
458 let cross_offset = |child: &Widget, content: f32, size: f32| -> f32 {
460 if !cross_bounded || cross_shrinks {
461 return 0.0;
462 }
463 match self_place(child).flatten().unwrap_or(s.align) {
464 Align::Center => (content - size) / 2.0,
465 Align::End => content - size,
466 Align::Start => 0.0,
467 }
468 };
469 let main_m = |c: &Widget| -> (f32, f32) {
471 let m = c.style.margin;
472 match dir {
473 FlexDir::Row => (m[3], m[1] + m[3]),
474 FlexDir::Column => (m[0], m[0] + m[2]),
475 }
476 };
477 let cross_m = |c: &Widget| -> (f32, f32) {
478 let m = c.style.margin;
479 match dir {
480 FlexDir::Row => (m[0], m[0] + m[2]),
481 FlexDir::Column => (m[3], m[1] + m[3]),
482 }
483 };
484
485 let effective_flex = |child: &Widget| -> f32 {
488 if child.style.dock == Dock::Fill {
489 child.style.flex.max(1.0)
490 } else {
491 child.style.flex
492 }
493 };
494 let in_flow = |child: &Widget| -> bool {
496 child.visible
497 && child.style.pos.is_none()
498 && !matches!(
499 (dir, child.style.dock),
500 (FlexDir::Row, Dock::Right) | (FlexDir::Column, Dock::Bottom)
501 )
502 };
503 let stretches = |child: &Widget| -> bool {
504 let dock = child.style.dock;
505 let auto_cross = match dir {
506 FlexDir::Row => child.style.h.is_auto(),
507 FlexDir::Column => child.style.w.is_auto(),
508 };
509 cross_bounded
510 && (match dir {
511 FlexDir::Row => matches!(dock, Dock::Fill | Dock::Left | Dock::Right),
512 FlexDir::Column => matches!(dock, Dock::Fill | Dock::Top | Dock::Bottom),
513 } || (auto_cross && self_place(child) == Some(None)))
514 };
515
516 let mut child_nodes: Vec<LayoutNode> = Vec::with_capacity(w.children.len());
518 let mut total_flex: f32 = 0.0;
519 let mut used_main: f32 = 0.0;
520
521 for child in &w.children {
522 let mut cn = new_node(child);
523 if !child.visible {
525 cn.rect = Rect {
526 x: x + s.pad[3],
527 y: y + s.pad[0],
528 w: 0.0,
529 h: 0.0,
530 };
531 child_nodes.push(cn);
532 continue;
533 }
534 let m = child.style.margin;
535 if let Some((px, py)) = child.style.pos {
539 let mw = less(content_w, px + m[1] + m[3]);
540 let mh = less(content_h, py + m[0] + m[2]);
541 measure(child, &mut cn, mw, mh, content_w, content_h);
542 child_nodes.push(cn);
543 continue;
544 }
545 let (cmw, cmh) = match (dir, child.style.dock) {
548 (_, Dock::Fill) => (content_w, content_h),
549 (FlexDir::Row, _) => (UNBOUNDED, content_h),
550 (FlexDir::Column, _) => (content_w, UNBOUNDED),
551 };
552 let (cmw, cmh) = (less(cmw, m[1] + m[3]), less(cmh, m[0] + m[2]));
553 if dir == FlexDir::Column
554 && child.style.dock != Dock::Fill
555 && matches!(self_place(child), Some(Some(_)))
556 {
557 measure_aligned(child, &mut cn, cmw, cmh, content_w, content_h);
558 } else {
559 measure(child, &mut cn, cmw, cmh, content_w, content_h);
560 }
561 let ef = effective_flex(child);
562 if ef > 0.0 && main_bounded && in_flow(child) {
567 match dir {
568 FlexDir::Row if child.style.w.is_auto() => cn.rect.w = child.style.min_w,
569 FlexDir::Column if child.style.h.is_auto() => cn.rect.h = child.style.min_h,
570 _ => {}
571 }
572 }
573 used_main += main_m(child).1
576 + match dir {
577 FlexDir::Row => cn.rect.w,
578 FlexDir::Column => cn.rect.h,
579 };
580 if in_flow(child) {
581 total_flex += ef;
582 }
583 child_nodes.push(cn);
584 }
585 let placed = w
586 .children
587 .iter()
588 .filter(|c| c.visible && c.style.pos.is_none())
589 .count();
590 used_main += s.gap * (placed.saturating_sub(1) as f32);
591
592 let available = if main_bounded {
594 (match dir {
595 FlexDir::Row => content_w,
596 FlexDir::Column => content_h,
597 }) - used_main
598 } else {
599 0.0
600 };
601 let mut pos = match dir {
602 FlexDir::Row => s.pad[3],
603 FlexDir::Column => s.pad[0],
604 };
605
606 for (i, child) in w.children.iter().enumerate() {
608 if !in_flow(child) {
609 continue;
610 }
611 let cn = &mut child_nodes[i];
612 let ef = effective_flex(child);
613 let grow = if ef > 0.0 && total_flex > 0.0 && available > 0.0 {
614 available * ef / total_flex
615 } else {
616 0.0
617 };
618 let stretch = stretches(child);
619 let (ml, mt) = main_m(child);
620 let (cl, ct) = cross_m(child);
621 let (cx, cy) = if dir == FlexDir::Row {
622 cn.rect.w += grow;
623 if stretch {
624 cn.rect.h = (content_h - ct).max(0.0);
625 }
626 let p = (
627 x + pos + ml,
628 y + s.pad[0] + cl + cross_offset(child, content_h, cn.rect.h + ct),
629 );
630 pos += cn.rect.w + mt + s.gap;
631 p
632 } else {
633 cn.rect.h += grow;
634 if stretch {
635 cn.rect.w = (content_w - ct).max(0.0);
636 }
637 let p = (
638 x + s.pad[3] + cl + cross_offset(child, content_w, cn.rect.w + ct),
639 y + pos + ml,
640 );
641 pos += cn.rect.h + mt + s.gap;
642 p
643 };
644 place(child, cn, cx, cy, depth);
645 }
646
647 let mut rpos = if main_bounded {
651 match dir {
652 FlexDir::Row => x + s.pad[3] + content_w,
653 FlexDir::Column => y + s.pad[0] + content_h,
654 }
655 } else {
656 let docked: Vec<f32> = w
657 .children
658 .iter()
659 .zip(&child_nodes)
660 .filter(|(c, _)| c.visible && !in_flow(c) && c.style.pos.is_none())
661 .map(|(c, n)| {
662 main_m(c).1
663 + match dir {
664 FlexDir::Row => n.rect.w,
665 FlexDir::Column => n.rect.h,
666 }
667 })
668 .collect();
669 let span: f32 =
670 docked.iter().sum::<f32>() + s.gap * (docked.len().saturating_sub(1) as f32);
671 (match dir {
672 FlexDir::Row => x,
673 FlexDir::Column => y,
674 }) + pos
675 + span
676 };
677 for (i, child) in w.children.iter().enumerate() {
678 if !child.visible || in_flow(child) || child.style.pos.is_some() {
679 continue;
680 }
681 let cn = &mut child_nodes[i];
682 let stretch = stretches(child);
683 let (ml, mt) = main_m(child);
684 let (cl, ct) = cross_m(child);
685 rpos -= mt - ml;
687 let (cx, cy) = if dir == FlexDir::Row {
688 if stretch {
689 cn.rect.h = (content_h - ct).max(0.0);
690 }
691 rpos -= cn.rect.w;
692 (
693 rpos,
694 y + s.pad[0] + cl + cross_offset(child, content_h, cn.rect.h + ct),
695 )
696 } else {
697 if stretch {
698 cn.rect.w = (content_w - ct).max(0.0);
699 }
700 rpos -= cn.rect.h;
701 (
702 x + s.pad[3] + cl + cross_offset(child, content_w, cn.rect.w + ct),
703 rpos,
704 )
705 };
706 rpos -= ml + s.gap;
707 place(child, cn, cx, cy, depth);
708 }
709
710 for (i, child) in w.children.iter().enumerate() {
712 let Some((px, py)) = child.style.pos else {
713 continue;
714 };
715 if !child.visible {
716 continue;
717 }
718 let m = child.style.margin;
719 let cn = &mut child_nodes[i];
720 place(
721 child,
722 cn,
723 x + s.pad[3] + px + m[3],
724 y + s.pad[0] + py + m[0],
725 depth,
726 );
727 }
728
729 finish(w, node, child_nodes, shrink, bar_w);
730}
731
732fn measure_aligned(
736 w: &Widget,
737 node: &mut LayoutNode,
738 max_w: f32,
739 max_h: f32,
740 basis_w: f32,
741 basis_h: f32,
742) {
743 if bounded(max_w) && w.style.w.is_auto() {
744 measure(w, node, UNBOUNDED, max_h, basis_w, basis_h);
745 if node.rect.w <= max_w {
746 return;
747 }
748 }
749 measure(w, node, max_w, max_h, basis_w, basis_h);
750}
751
752fn vis_margin(c: &Widget, side: usize) -> f32 {
754 if c.visible { c.style.margin[side] } else { 0.0 }
755}
756
757fn less(v: f32, by: f32) -> f32 {
759 if bounded(v) {
760 (v - by).max(0.0)
761 } else {
762 UNBOUNDED
763 }
764}
765
766fn finish(
769 w: &Widget,
770 node: &mut LayoutNode,
771 mut child_nodes: Vec<LayoutNode>,
772 shrink: Option<Shrink>,
773 bar_w: f32,
774) {
775 let s = &w.style;
776 let Rect { x, y, .. } = node.rect;
777 let extent = |f: &dyn Fn(&Widget, &LayoutNode) -> f32| -> f32 {
778 w.children
779 .iter()
780 .zip(&child_nodes)
781 .map(|(c, n)| f(c, n))
782 .fold(0.0f32, f32::max)
783 };
784 let ch = extent(&|c, n| n.rect.y - y + n.rect.h + vis_margin(c, 2));
785 if let Some(fit) = shrink {
786 if fit.w {
787 let cw = extent(&|c, n| n.rect.x - x + n.rect.w + vis_margin(c, 1));
788 node.rect.w = (cw + s.pad[1] + bar_w).max(s.min_w).min(fit.max_w);
789 }
790 if fit.h {
791 node.rect.h = (ch + s.pad[2]).max(s.min_h).min(fit.max_h);
792 }
793 }
794
795 node.content_h = ch + s.pad[2];
798 node.scroll_y = s.scroll_y.clamp(0.0, node.max_scroll());
799 if node.scroll_y > 0.0 {
800 for c in &mut child_nodes {
801 c.translate_y(-node.scroll_y);
802 }
803 }
804
805 node.children = child_nodes;
806}
807
808pub fn hit_test(node: &LayoutNode, mx: f32, my: f32) -> Option<&LayoutNode> {
812 if !node.visible || !node.rect.contains(mx, my) {
813 return None;
814 }
815 for child in node.children.iter().rev() {
816 if let Some(hit) = hit_test(child, mx, my) {
817 return Some(hit);
818 }
819 }
820 if node.is_clickable() {
821 Some(node)
822 } else {
823 None
824 }
825}
826
827pub fn hit_path(node: &LayoutNode, mx: f32, my: f32) -> Option<Vec<u16>> {
830 fn walk(node: &LayoutNode, mx: f32, my: f32, path: &mut Vec<u16>) -> bool {
831 if !node.visible || !node.rect.contains(mx, my) {
832 return false;
833 }
834 for (i, child) in node.children.iter().enumerate().rev() {
835 path.push(i as u16);
836 if walk(child, mx, my, path) {
837 return true;
838 }
839 path.pop();
840 }
841 node.is_clickable()
842 }
843 let mut path = Vec::new();
844 walk(node, mx, my, &mut path).then_some(path)
845}
846
847pub fn deepest_path(node: &LayoutNode, mx: f32, my: f32) -> Option<Vec<u16>> {
850 if !node.visible || !node.rect.contains(mx, my) {
851 return None;
852 }
853 let mut path = Vec::new();
854 let mut n = node;
855 'outer: loop {
856 for (i, child) in n.children.iter().enumerate().rev() {
857 if child.visible && child.rect.contains(mx, my) {
858 path.push(i as u16);
859 n = child;
860 continue 'outer;
861 }
862 }
863 return Some(path);
864 }
865}
866
867pub fn node_at<'a>(node: &'a LayoutNode, path: &[u16]) -> Option<&'a LayoutNode> {
869 let mut n = node;
870 for &i in path {
871 n = n.children.get(i as usize)?;
872 }
873 Some(n)
874}
875
876pub fn node_at_mut<'a>(node: &'a mut LayoutNode, path: &[u16]) -> Option<&'a mut LayoutNode> {
878 let mut n = node;
879 for &i in path {
880 n = n.children.get_mut(i as usize)?;
881 }
882 Some(n)
883}
884
885impl LayoutNode {
886 pub fn is_clickable(&self) -> bool {
889 self.visible && self.enabled && (self.action.is_some() || self.on_click.is_some())
890 }
891}
892
893pub fn find_by_id(node: &LayoutNode, id: &str) -> Option<Rect> {
898 if node.id.as_deref() == Some(id) {
899 return Some(node.rect);
900 }
901 node.children.iter().find_map(|c| find_by_id(c, id))
902}
903
904pub fn find_node<'a>(node: &'a LayoutNode, id: &str) -> Option<&'a LayoutNode> {
907 if node.id.as_deref() == Some(id) {
908 return Some(node);
909 }
910 node.children.iter().find_map(|c| find_node(c, id))
911}
912
913pub fn set_focus(node: &mut LayoutNode, focused_id: Option<&str>) {
915 node.focused = focused_id.is_some() && node.id.as_deref() == focused_id;
916 for child in &mut node.children {
917 set_focus(child, focused_id);
918 }
919}
920
921#[cfg(test)]
922mod tests {
923 use super::*;
924 use crate::widget::{self, Units};
925
926 #[test]
927 fn positioned_children_leave_the_flow() {
928 let root = widget::panel(FlexDir::Column)
929 .w(200.0)
930 .h(100.0)
931 .padding(4.0, 4.0, 4.0, 4.0)
932 .child(widget::spacer().min_w(10.0).min_h(10.0))
933 .child(widget::button("Hi").w(40.0).h(20.0).at(50.0, 30.0))
934 .child(widget::spacer().min_w(10.0).min_h(10.0));
935 let node = compute(&root, 400.0, 400.0);
936 let r = node.children[1].rect;
937 assert_eq!((r.x, r.y, r.w, r.h), (54.0, 34.0, 40.0, 20.0));
938 assert_eq!(node.children[0].rect.y, 4.0);
940 assert_eq!(node.children[2].rect.y, 4.0 + 10.0 + 2.0);
941 }
942
943 #[test]
944 fn positioned_container_lays_out_its_children_in_place() {
945 let root = widget::panel(FlexDir::Column)
946 .w(Units::Percent(100.0))
947 .h(Units::Percent(100.0))
948 .child(
949 widget::panel(FlexDir::Row)
950 .w(100.0)
951 .h(20.0)
952 .gap(0.0)
953 .at(10.0, 20.0)
954 .child(widget::spacer().min_w(30.0).min_h(5.0))
955 .child(widget::spacer().min_w(30.0).min_h(5.0)),
956 );
957 let node = compute(&root, 320.0, 240.0);
958 let panel = &node.children[0];
959 assert_eq!((panel.rect.x, panel.rect.y), (10.0, 20.0));
960 assert_eq!(panel.children[1].rect.x, 40.0);
961 assert_eq!(panel.children[1].rect.y, 20.0);
962 }
963
964 #[test]
965 fn auto_sized_parent_grows_to_fit_positioned_children() {
966 let root = widget::panel(FlexDir::Column)
967 .child(widget::spacer().min_w(10.0).min_h(10.0).at(30.0, 40.0));
968 let node = compute(&root, 300.0, 300.0);
969 assert_eq!((node.rect.w, node.rect.h), (40.0, 50.0));
970 }
971
972 fn pct(v: f32) -> Units {
973 Units::Percent(v)
974 }
975
976 fn r(n: &LayoutNode) -> (f32, f32, f32, f32) {
977 (n.rect.x, n.rect.y, n.rect.w, n.rect.h)
978 }
979
980 #[test]
981 fn percent_width_in_a_row_resolves_once_against_the_content_box() {
982 let root = widget::panel(FlexDir::Row)
983 .w(400.0)
984 .h(100.0)
985 .padding(5.0, 10.0, 5.0, 10.0)
986 .child(
987 widget::panel(FlexDir::Column)
988 .w(pct(50.0))
989 .child(widget::spacer().min_w(10.0).min_h(10.0)),
990 )
991 .child(widget::spacer().w(pct(25.0)).h(pct(50.0)));
992 let node = compute(&root, 800.0, 600.0);
993 assert_eq!(r(&node.children[0]).2, 190.0);
995 assert_eq!(r(&node.children[1]), (10.0 + 190.0 + 2.0, 5.0, 95.0, 45.0));
996 }
997
998 #[test]
999 fn percent_sizes_in_a_column() {
1000 let root = widget::panel(FlexDir::Column)
1001 .w(200.0)
1002 .h(300.0)
1003 .padding(10.0, 0.0, 10.0, 0.0)
1004 .gap(0.0)
1005 .child(
1006 widget::panel(FlexDir::Row)
1007 .w(pct(50.0))
1008 .h(pct(50.0))
1009 .child(widget::spacer()),
1010 )
1011 .child(widget::spacer().w(pct(100.0)).h(pct(10.0)));
1012 let node = compute(&root, 800.0, 600.0);
1013 assert_eq!(r(&node.children[0]), (0.0, 10.0, 100.0, 140.0));
1014 assert_eq!(r(&node.children[1]), (0.0, 150.0, 200.0, 28.0));
1015 }
1016
1017 #[test]
1018 fn nested_percents_compound_per_level_only() {
1019 let root = widget::panel(FlexDir::Row).w(400.0).h(200.0).child(
1020 widget::panel(FlexDir::Column)
1021 .w(pct(50.0))
1022 .h(pct(100.0))
1023 .child(
1024 widget::panel(FlexDir::Row)
1025 .w(pct(50.0))
1026 .h(pct(50.0))
1027 .child(widget::spacer().w(pct(50.0)).h(pct(50.0))),
1028 ),
1029 );
1030 let node = compute(&root, 400.0, 200.0);
1031 let a = &node.children[0];
1032 let b = &a.children[0];
1033 let c = &b.children[0];
1034 assert_eq!(r(a), (0.0, 0.0, 200.0, 200.0));
1035 assert_eq!(r(b), (0.0, 0.0, 100.0, 100.0));
1036 assert_eq!(r(c), (0.0, 0.0, 50.0, 50.0));
1037 }
1038
1039 #[test]
1040 fn percent_resolves_against_the_scrollbar_free_box() {
1041 let root = widget::scroll_view()
1042 .w(106.0)
1043 .h(50.0)
1044 .child(widget::spacer().w(pct(50.0)).h(10.0));
1045 let node = compute(&root, 400.0, 400.0);
1046 assert_eq!(node.children[0].rect.w, 50.0);
1047 }
1048
1049 #[test]
1050 fn grow_shares_free_space_with_percent_siblings() {
1051 let root = widget::panel(FlexDir::Row)
1052 .w(300.0)
1053 .h(50.0)
1054 .gap(4.0)
1055 .child(widget::spacer().w(pct(50.0)))
1056 .child(
1057 widget::panel(FlexDir::Column)
1058 .flex(1.0)
1059 .child(widget::spacer()),
1060 )
1061 .child(widget::spacer().w(pct(10.0)));
1062 let node = compute(&root, 300.0, 50.0);
1063 assert_eq!(r(&node.children[0]).2, 150.0);
1065 assert_eq!(r(&node.children[1]), (154.0, 0.0, 112.0, 4.0));
1066 assert_eq!(r(&node.children[2]), (270.0, 0.0, 30.0, 4.0));
1067 }
1068
1069 #[test]
1070 fn grown_panel_keeps_its_size_and_lays_children_out_against_it() {
1071 let root = widget::panel(FlexDir::Column)
1072 .w(200.0)
1073 .h(200.0)
1074 .gap(0.0)
1075 .child(widget::spacer().min_h(20.0))
1076 .child(
1077 widget::panel(FlexDir::Row)
1078 .flex(1.0)
1079 .w(pct(100.0))
1080 .gap(0.0)
1081 .child(widget::spacer().w(pct(25.0)).h(pct(50.0)))
1082 .child(
1083 widget::panel(FlexDir::Column)
1084 .flex(1.0)
1085 .child(widget::spacer()),
1086 )
1087 .child(widget::spacer().dock(Dock::Right).min_w(10.0)),
1088 );
1089 let node = compute(&root, 400.0, 400.0);
1090 let grown = &node.children[1];
1091 assert_eq!(r(grown), (0.0, 20.0, 200.0, 180.0));
1092 assert_eq!(r(&grown.children[0]), (0.0, 20.0, 50.0, 90.0));
1093 assert_eq!(r(&grown.children[1]).2, 200.0 - 50.0 - 10.0);
1095 assert_eq!(r(&grown.children[2]), (190.0, 20.0, 10.0, 180.0));
1097 }
1098
1099 #[test]
1100 fn long_list_deep_inside_a_grown_row_does_not_push_siblings_out() {
1101 let mut list = widget::scroll_view().flex(1.0).w(pct(100.0));
1104 for _ in 0..60 {
1105 list = list.child(widget::spacer().h(25.0));
1106 }
1107 let root = widget::panel(FlexDir::Column)
1108 .w(400.0)
1109 .h(252.0)
1110 .gap(0.0)
1111 .child(widget::spacer().h(20.0))
1112 .child(
1113 widget::panel(FlexDir::Row).flex(1.0).w(pct(100.0)).child(
1114 widget::panel(FlexDir::Column)
1115 .w(pct(50.0))
1116 .h(pct(100.0))
1117 .child(widget::spacer().h(16.0))
1118 .child(list),
1119 ),
1120 )
1121 .child(widget::spacer().h(26.0));
1122 let node = compute(&root, 400.0, 252.0);
1123 assert_eq!(r(&node.children[1]), (0.0, 20.0, 400.0, 206.0));
1124 let footer = r(&node.children[2]);
1125 assert_eq!((footer.1, footer.3), (226.0, 26.0));
1126 let column = &node.children[1].children[0];
1127 assert_eq!(column.rect.h, 206.0);
1128 let list = &column.children[1];
1129 assert!(list.rect.y + list.rect.h <= 226.0, "{:?}", list.rect);
1130 assert!(list.content_h > list.rect.h);
1131 }
1132
1133 #[test]
1134 fn grown_column_panel_fills_its_parent_and_children_grow_too() {
1135 let root = widget::panel(FlexDir::Column)
1136 .w(100.0)
1137 .h(100.0)
1138 .gap(0.0)
1139 .child(
1140 widget::panel(FlexDir::Column)
1141 .flex(1.0)
1142 .gap(0.0)
1143 .child(widget::spacer().flex(1.0)),
1144 );
1145 let node = compute(&root, 100.0, 100.0);
1146 assert_eq!(node.children[0].rect.h, 100.0);
1147 assert_eq!(node.children[0].children[0].rect.h, 100.0);
1148 }
1149
1150 #[test]
1151 fn empty_auto_panel_in_a_row_takes_its_min_width() {
1152 let root = widget::panel(FlexDir::Row)
1153 .w(100.0)
1154 .h(20.0)
1155 .child(widget::panel(FlexDir::Column).min_w(7.0))
1156 .child(widget::spacer());
1157 let node = compute(&root, 100.0, 20.0);
1158 assert_eq!(node.children[0].rect.w, 7.0);
1159 assert_eq!(node.children[1].rect.x, 9.0);
1160 }
1161
1162 #[test]
1163 fn padding_counts_once_in_auto_size() {
1164 let root = widget::panel(FlexDir::Column)
1165 .padding(3.0, 4.0, 5.0, 6.0)
1166 .child(widget::spacer().min_w(10.0).min_h(10.0));
1167 let node = compute(&root, 300.0, 300.0);
1168 assert_eq!((node.rect.w, node.rect.h), (20.0, 18.0));
1169 assert_eq!(
1170 (node.children[0].rect.x, node.children[0].rect.y),
1171 (6.0, 3.0)
1172 );
1173 }
1174
1175 #[test]
1176 fn auto_row_in_a_column_measures_to_content() {
1177 let root = widget::panel(FlexDir::Column).w(200.0).h(200.0).child(
1179 widget::panel(FlexDir::Row)
1180 .align(Align::Center)
1181 .gap(0.0)
1182 .child(widget::spacer().min_w(10.0).min_h(10.0))
1183 .child(widget::spacer().min_w(10.0).min_h(20.0))
1184 .child(widget::spacer().min_w(5.0).dock(Dock::Right)),
1185 );
1186 let node = compute(&root, 200.0, 200.0);
1187 let row = &node.children[0];
1188 assert_eq!(row.rect.h, 20.0);
1189 assert_eq!(row.children[0].rect.y, 5.0);
1190 assert_eq!(row.children[1].rect.y, 0.0);
1191 }
1192
1193 #[test]
1194 fn positioned_auto_row_measures_to_content() {
1195 let pill = widget::panel(FlexDir::Row)
1198 .padding(1.0, 1.0, 1.0, 1.0)
1199 .child(
1200 widget::panel(FlexDir::Row)
1201 .align(Align::Center)
1202 .child(widget::spacer().min_w(10.0).min_h(9.0)),
1203 );
1204 let root = widget::panel(FlexDir::Column)
1205 .w(500.0)
1206 .h(500.0)
1207 .child(pill.at(3.0, 4.0));
1208 let node = compute(&root, 500.0, 500.0);
1209 let r = node.children[0].rect;
1210 assert_eq!((r.x, r.y, r.w, r.h), (3.0, 4.0, 12.0, 11.0));
1211 assert_eq!(node.children[0].children[0].children[0].rect.y, 5.0);
1212 }
1213
1214 #[test]
1215 fn row_with_right_dock_measured_on_unbounded_axis() {
1216 let root = widget::panel(FlexDir::Row).w(300.0).h(20.0).child(
1219 widget::panel(FlexDir::Row)
1220 .gap(1.0)
1221 .child(widget::spacer().min_w(10.0))
1222 .child(widget::spacer().min_w(5.0).dock(Dock::Right))
1223 .child(widget::spacer().min_w(7.0).dock(Dock::Right)),
1224 );
1225 let node = compute(&root, 300.0, 20.0);
1226 let inner = &node.children[0];
1227 assert_eq!(inner.rect.w, 10.0 + 1.0 + 7.0 + 1.0 + 5.0);
1228 assert_eq!(inner.children[1].rect.x, 19.0);
1229 assert_eq!(inner.children[2].rect.x, 11.0);
1230 }
1231
1232 #[test]
1233 fn align_center_and_end_in_both_directions() {
1234 let col = widget::panel(FlexDir::Column)
1235 .w(100.0)
1236 .h(50.0)
1237 .align(Align::Center)
1238 .child(widget::spacer().min_w(20.0).min_h(5.0));
1239 assert_eq!(compute(&col, 100.0, 50.0).children[0].rect.x, 40.0);
1240 let row = widget::panel(FlexDir::Row)
1241 .w(100.0)
1242 .h(50.0)
1243 .padding(10.0, 0.0, 0.0, 0.0)
1244 .align(Align::End)
1245 .child(widget::spacer().min_w(20.0).h(pct(20.0)));
1246 assert_eq!(compute(&row, 100.0, 50.0).children[0].rect.y, 10.0 + 32.0);
1248 }
1249
1250 #[test]
1251 fn positioned_children_with_percent_sizes() {
1252 let root = widget::panel(FlexDir::Column)
1253 .w(200.0)
1254 .h(100.0)
1255 .padding(10.0, 10.0, 10.0, 10.0)
1256 .child(widget::spacer().w(pct(50.0)).h(pct(50.0)).at(20.0, 10.0))
1257 .child(
1258 widget::panel(FlexDir::Row)
1259 .w(pct(100.0))
1260 .h(pct(25.0))
1261 .at(0.0, 60.0)
1262 .gap(0.0)
1263 .child(widget::spacer().w(pct(50.0)))
1264 .child(widget::spacer().flex(1.0)),
1265 );
1266 let node = compute(&root, 400.0, 400.0);
1267 assert_eq!(r(&node.children[0]), (30.0, 20.0, 90.0, 40.0));
1269 let p = &node.children[1];
1272 assert_eq!(r(p), (10.0, 70.0, 180.0, 20.0));
1273 assert_eq!(r(&p.children[0]), (10.0, 70.0, 90.0, 4.0));
1274 assert_eq!(r(&p.children[1]), (100.0, 70.0, 90.0, 4.0));
1275 }
1276
1277 #[test]
1278 fn growing_scroll_view_fills_free_space_and_scrolls_the_rest() {
1279 let list = widget::scroll_view()
1280 .id("list")
1281 .flex(1.0)
1282 .w(pct(100.0))
1283 .gap(0.0)
1284 .padding(2.0, 2.0, 2.0, 2.0)
1285 .scroll_y(1000.0)
1286 .children((0..10).map(|_| widget::spacer().w(pct(100.0)).min_h(20.0)));
1287 let root = widget::panel(FlexDir::Column)
1288 .w(100.0)
1289 .h(120.0)
1290 .gap(0.0)
1291 .child(widget::spacer().min_h(20.0))
1292 .child(list);
1293 let node = compute(&root, 100.0, 120.0);
1294 let v = find_node(&node, "list").unwrap();
1295 assert_eq!(r(v), (0.0, 20.0, 100.0, 100.0));
1296 assert_eq!(v.content_h, 204.0);
1297 assert_eq!(v.scroll_y, 104.0);
1298 assert_eq!(v.children[0].rect.w, 100.0 - 4.0 - SCROLLBAR_W);
1300 let last = v.children[9].rect;
1302 assert_eq!(last.y + last.h, 20.0 + 100.0 - 2.0);
1303 assert!(v.scrollbar_rects().is_some());
1304 }
1305
1306 #[test]
1307 fn label_wraps_at_its_explicit_width() {
1308 let root = widget::panel(FlexDir::Column)
1309 .w(300.0)
1310 .child(widget::label("aaaa bbbb cccc").w(40.0));
1311 let node = compute(&root, 300.0, 300.0);
1312 let l = node.children[0].rect;
1313 assert_eq!(l.w, 40.0);
1314 assert!(l.h > text::LINE_H, "wrapped onto several lines: {l:?}");
1315 }
1316
1317 #[test]
1318 fn percent_caps_at_the_cross_axis_and_ignores_unbounded_basis() {
1319 let root = widget::panel(FlexDir::Column)
1321 .w(100.0)
1322 .h(100.0)
1323 .child(widget::spacer().w(pct(150.0)));
1324 assert_eq!(compute(&root, 100.0, 100.0).children[0].rect.w, 100.0);
1325 let root = widget::panel(FlexDir::Row).w(200.0).h(20.0).child(
1328 widget::panel(FlexDir::Row)
1329 .gap(0.0)
1330 .child(widget::spacer().min_w(40.0))
1331 .child(widget::spacer().w(pct(50.0))),
1332 );
1333 let node = compute(&root, 200.0, 20.0);
1334 let inner = &node.children[0];
1335 assert_eq!(inner.rect.w, 44.0);
1336 assert_eq!(inner.children[1].rect.w, 22.0);
1337 }
1338
1339 #[test]
1340 fn find_mut_and_set_text() {
1341 let mut root = widget::panel(FlexDir::Column).child(widget::label("a").id("title"));
1342 assert!(root.find_mut("title").unwrap().set_text("b"));
1343 match &root.children[0].kind {
1344 crate::widget::WidgetKind::Label(t) => assert_eq!(t, "b"),
1345 _ => unreachable!(),
1346 }
1347 assert!(root.find_mut("missing").is_none());
1348 }
1349}