1use std::rc::Rc;
9
10day_reactive::tls_slots! {
11 layout;
12 static REPORTED: std::cell::RefCell<std::collections::HashSet<RNode>> =
15 std::cell::RefCell::new(std::collections::HashSet::new());
16}
17
18use day_spec::*;
19
20use crate::tree::{Flex, RNode, Tree, TreeOps};
21
22pub trait Layout: 'static {
25 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size;
26 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect);
27 fn baseline(&self, _cx: &mut dyn LayoutOps, _children: &[RNode], _size: Size) -> Option<f64> {
35 None
36 }
37}
38
39pub trait LayoutOps {
41 fn measure_child(&mut self, child: RNode, p: Proposal) -> Size;
42 fn place_child(&mut self, child: RNode, rect: Rect);
43 fn place_child_native(&mut self, child: RNode, rect: Rect) {
46 self.place_child(child, rect);
47 }
48 fn flex_of(&self, child: RNode) -> Flex;
49 fn children_of(&self, node: RNode) -> Vec<RNode>;
50 fn measure_leaf(&mut self, p: Proposal) -> Size;
52 fn baseline_of(&mut self, child: RNode, size: Size) -> Option<f64>;
56 fn set_scroll_content(&mut self, content: Size);
58 fn scroll_bar_inset(&mut self, _vertical: bool) -> f64 {
61 0.0
62 }
63 fn report_overflow(&mut self, _needed: f64, _available: f64) {}
69}
70
71pub struct EngineCx<'a, B: Toolkit> {
72 pub(crate) tree: &'a mut Tree<B>,
73 pub(crate) offset: Point,
74 pub(crate) current: RNode,
75 pub(crate) parent_size: Size,
77}
78
79impl<B: Toolkit> LayoutOps for EngineCx<'_, B> {
80 fn measure_child(&mut self, child: RNode, p: Proposal) -> Size {
81 measure_node(self.tree, child, p)
82 }
83 fn place_child(&mut self, child: RNode, rect: Rect) {
84 let rect = if crate::layout_direction() == day_geometry::LayoutDirection::Rtl {
90 Rect::new(
91 self.parent_size.width - rect.origin.x - rect.size.width,
92 rect.origin.y,
93 rect.size.width,
94 rect.size.height,
95 )
96 } else {
97 rect
98 };
99 place_node(self.tree, child, rect, self.offset, false);
100 }
101 fn place_child_native(&mut self, child: RNode, rect: Rect) {
102 place_node(self.tree, child, rect, self.offset, false);
103 }
104 fn flex_of(&self, child: RNode) -> Flex {
105 self.tree.node(child).map_or_default(|n| n.flex)
106 }
107 fn children_of(&self, node: RNode) -> Vec<RNode> {
108 self.tree.node(node).map_or_default(|n| n.children.clone())
109 }
110 fn measure_leaf(&mut self, p: Proposal) -> Size {
111 let Some(n) = self.tree.node(self.current) else {
112 return Size::ZERO;
113 };
114 let kind = n.kind;
115 let Some(h) = n.handle.clone() else {
116 return Size::ZERO;
117 };
118 self.tree.toolkit.measure(&h, kind, p)
119 }
120 fn baseline_of(&mut self, child: RNode, size: Size) -> Option<f64> {
121 baseline_node(self.tree, child, size)
122 }
123 fn set_scroll_content(&mut self, content: Size) {
124 let current = self.current;
125 let Some(n) = self.tree.node_mut(current) else {
126 return;
127 };
128 n.scroll_content = Some(content);
130 let Some(h) = n.handle.clone() else { return };
131 self.tree.toolkit.set_scroll_content(&h, content);
132 }
133 fn scroll_bar_inset(&mut self, vertical: bool) -> f64 {
134 let Some(h) = self.tree.node(self.current).and_then(|n| n.handle.clone()) else {
135 return 0.0;
136 };
137 self.tree.toolkit.scroll_bar_inset(&h, vertical).max(0.0)
138 }
139
140 #[cfg(debug_assertions)]
141 fn report_overflow(&mut self, needed: f64, available: f64) {
142 if REPORTED.with(|r| !r.borrow_mut().insert(self.current)) {
146 return;
147 }
148 let mut ids: Vec<String> = Vec::new();
153 let mut stack = vec![self.current];
154 while let Some(node) = stack.pop() {
155 if ids.len() >= 6 {
156 break;
157 }
158 if let Some(n) = self.tree.node(node) {
159 ids.extend(n.id.clone());
160 stack.extend(n.children.iter().rev());
161 }
162 }
163 let who = if ids.is_empty() {
164 String::from("no .id in reach")
165 } else {
166 ids.join(", ")
167 };
168 log::warn!(
169 "day layout: children overflow their container by {:.0}pt ({needed:.0} needed, \
170 {available:.0} available; {who}) — give the row a fit policy: \
171 .fit(RowFit::Wrap/Scroll) or adaptive(..) (docs/size-classes.md)",
172 needed - available,
173 );
174 }
175}
176
177pub(crate) fn measure_node<B: Toolkit>(tree: &mut Tree<B>, node: RNode, p: Proposal) -> Size {
178 let key = p.cache_key();
179 let (layout, children) = {
180 let Some(n) = tree.node(node) else {
181 return Size::ZERO;
182 };
183 if !n.needs_measure
184 && let Some(&(_, s)) = n.cache.iter().find(|(k, _)| *k == key)
185 {
186 return s;
187 }
188 (n.layout.clone(), n.children.clone())
189 };
190 let mut cx = EngineCx {
191 tree,
192 offset: Point::ZERO,
193 current: node,
194 parent_size: Size::ZERO, };
196 let size = layout.measure(&mut cx, &children, p);
197 if let Some(n) = tree.node_mut(node) {
198 n.needs_measure = false;
199 if n.cache.len() >= 4 {
200 n.cache.clear();
201 }
202 n.cache.push((key, size));
203 }
204 size
205}
206
207pub(crate) fn baseline_node<B: Toolkit>(
213 tree: &mut Tree<B>,
214 node: RNode,
215 size: Size,
216) -> Option<f64> {
217 let key = Proposal::exact(size).cache_key();
218 let (layout, children, handle, kind) = {
219 let n = tree.node(node)?;
220 if !n.needs_measure
221 && let Some((k, b)) = n.baseline_cache
222 && k == key
223 {
224 return b;
225 }
226 (
227 n.layout.clone(),
228 n.children.clone(),
229 n.handle.clone(),
230 n.kind,
231 )
232 };
233 let baseline = match handle {
235 Some(h) if children.is_empty() => tree.toolkit.first_baseline(&h, kind, size),
236 _ => {
237 let mut cx = EngineCx {
238 tree,
239 offset: Point::ZERO,
240 current: node,
241 parent_size: Size::ZERO,
242 };
243 layout.baseline(&mut cx, &children, size)
244 }
245 };
246 if let Some(n) = tree.node_mut(node) {
247 n.baseline_cache = Some((key, baseline));
248 }
249 baseline
250}
251
252pub(crate) fn place_node<B: Toolkit>(
255 tree: &mut Tree<B>,
256 node: RNode,
257 rect: Rect,
258 offset: Point,
259 is_root: bool,
260) {
261 let abs = Rect {
262 origin: rect.origin.offset(offset.x, offset.y),
263 size: rect.size,
264 };
265 let (layout, children, has_handle) = {
266 let Some(n) = tree.node(node) else { return };
267 (n.layout.clone(), n.children.clone(), n.handle.is_some())
268 };
269 let native_frame = tree
277 .node(node)
278 .is_some_and(|n| n.kind == day_spec::kinds::COVER);
279 let child_offset = if has_handle {
280 if !is_root && !native_frame {
281 let changed = tree
282 .node(node)
283 .is_some_and(|n| n.last_native_frame.is_none_or(|f| !f.approx_eq(&abs, 0.25)));
284 if changed {
285 let h = tree.node(node).and_then(|n| n.handle.clone());
286 if let Some(h) = h {
287 let anim = tree.resolve_anim(node);
288 tree.toolkit.set_frame(&h, abs, anim.as_ref());
289 }
290 if tree
291 .node(node)
292 .is_some_and(|n| n.kind == day_spec::kinds::CANVAS)
293 {
294 crate::tree::enqueue_event(
296 crate::tree::rnode_to_id(node),
297 day_spec::Event::FrameChanged(abs.size),
298 );
299 }
300 }
301 }
302 Point::ZERO
303 } else {
304 abs.origin
305 };
306 let relayout_cells = tree.node(node).is_some_and(|n| {
313 n.kind == day_spec::kinds::LIST
314 && n.last_native_frame
315 .is_some_and(|f| (f.size.width - abs.size.width).abs() > 0.25)
316 });
317 if let Some(n) = tree.node_mut(node) {
318 n.last_native_frame = Some(abs);
319 n.needs_layout = false;
320 }
321 if relayout_cells {
322 for key in tree.list_cell_keys(node) {
323 tree.list_layout_cell(node, key);
324 }
325 }
326 let mut cx = EngineCx {
327 tree,
328 offset: child_offset,
329 current: node,
330 parent_size: rect.size,
331 };
332 layout.place(&mut cx, &children, Rect::from_size(rect.size));
333}
334
335fn wrapper_baseline(
348 cx: &mut dyn LayoutOps,
349 children: &[RNode],
350 child_size: Size,
351 dy: f64,
352) -> Option<f64> {
353 let &c = children.first()?;
354 Some(cx.baseline_of(c, child_size)? + dy)
355}
356
357pub struct PassThrough;
359
360impl Layout for PassThrough {
361 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
362 match children.first() {
363 Some(&c) => cx.measure_child(c, p),
364 None => Size::ZERO,
365 }
366 }
367 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
368 if let Some(&c) = children.first() {
369 let s = cx.measure_child(c, Proposal::exact(bounds.size));
370 cx.place_child(c, Rect::from_size(s));
371 }
372 }
373}
374
375pub struct CellCenter;
380
381impl Layout for CellCenter {
382 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
383 match children.first() {
384 Some(&c) => cx.measure_child(c, p),
385 None => Size::ZERO,
386 }
387 }
388 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
389 if let Some(&c) = children.first() {
390 let s = cx.measure_child(c, Proposal::exact(bounds.size));
391 let y = ((bounds.size.height - s.height) / 2.0).max(0.0);
392 cx.place_child(
393 c,
394 Rect::new(0.0, y, s.width, s.height.min(bounds.size.height)),
395 );
396 }
397 }
398 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
399 PassThrough::forward(cx, children, size)
400 }
401}
402
403pub struct CellMetrics(pub day_spec::RowMetrics);
407
408impl CellMetrics {
409 fn for_child(&self, cx: &dyn LayoutOps, child: RNode) -> day_spec::RowMetrics {
412 let mut node = child;
414 for _ in 0..8 {
415 if cx.flex_of(node).whole_row {
416 let i = self.0.insets;
417 return day_spec::RowMetrics {
418 insets: day_spec::Insets {
419 top: 0.0,
420 leading: i.leading,
421 bottom: 0.0,
422 trailing: i.trailing,
423 },
424 min_height: 0.0,
425 };
426 }
427 match cx.children_of(node)[..] {
428 [only] => node = only,
429 _ => break,
430 }
431 }
432 self.0
433 }
434}
435
436impl Layout for CellMetrics {
437 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
438 let Some(&c) = children.first() else {
439 return Size::ZERO;
440 };
441 let m = self.for_child(cx, c);
442 let i = m.insets;
443 let (dx, dy) = (i.leading + i.trailing, i.top + i.bottom);
444 let s = cx.measure_child(
445 c,
446 Proposal::new(
447 p.width.map(|w| (w - dx).max(0.0)),
448 p.height.map(|h| (h - dy).max(0.0)),
449 ),
450 );
451 Size::new(s.width + dx, (s.height + dy).max(m.min_height))
452 }
453 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
454 let Some(&c) = children.first() else {
455 return;
456 };
457 let i = self.for_child(cx, c).insets;
458 let inner = Size::new(
459 (bounds.size.width - i.leading - i.trailing).max(0.0),
460 (bounds.size.height - i.top - i.bottom).max(0.0),
461 );
462 let s = cx.measure_child(c, Proposal::new(Some(inner.width), None));
463 let (y, h) = if s.height <= inner.height {
466 (i.top + (inner.height - s.height) / 2.0, s.height)
467 } else {
468 let h = s.height.min(bounds.size.height);
469 (((bounds.size.height - h) / 2.0).max(0.0), h)
470 };
471 cx.place_child(c, Rect::new(i.leading, y, inner.width, h));
472 }
473 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
474 PassThrough::forward(cx, children, size)
475 }
476}
477
478impl PassThrough {
479 fn forward(cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
481 let &c = children.first()?;
482 let cs = cx.measure_child(c, Proposal::exact(size));
483 wrapper_baseline(cx, children, cs, 0.0)
484 }
485}
486
487pub struct FillThrough;
494
495impl Layout for FillThrough {
496 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
497 match children.first() {
498 Some(&c) => cx.measure_child(c, p),
499 None => Size::ZERO,
500 }
501 }
502 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
503 if let Some(&c) = children.first() {
504 cx.place_child(c, Rect::from_size(bounds.size));
505 }
506 }
507 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
508 wrapper_baseline(cx, children, size, 0.0)
509 }
510}
511
512pub struct LeafLayout;
514
515impl Layout for LeafLayout {
516 fn measure(&self, cx: &mut dyn LayoutOps, _children: &[RNode], p: Proposal) -> Size {
517 cx.measure_leaf(p)
518 }
519 fn place(&self, _cx: &mut dyn LayoutOps, _children: &[RNode], _bounds: Rect) {}
520}
521
522#[derive(Clone, Copy, PartialEq, Eq)]
523pub enum Axis {
524 Vertical,
525 Horizontal,
526}
527
528#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
529pub enum CrossAlign {
530 Leading,
531 #[default]
532 Center,
533 Trailing,
534 FirstBaseline,
539}
540
541impl CrossAlign {
542 fn fraction(self) -> f64 {
544 match self {
545 CrossAlign::Leading => 0.0,
546 CrossAlign::Center | CrossAlign::FirstBaseline => 0.5,
549 CrossAlign::Trailing => 1.0,
550 }
551 }
552}
553
554pub struct StackLayout {
557 pub axis: Axis,
558 pub spacing: f64,
559 pub align: CrossAlign,
560}
561
562impl StackLayout {
563 fn main(&self, s: Size) -> f64 {
564 match self.axis {
565 Axis::Vertical => s.height,
566 Axis::Horizontal => s.width,
567 }
568 }
569 fn cross(&self, s: Size) -> f64 {
570 match self.axis {
571 Axis::Vertical => s.width,
572 Axis::Horizontal => s.height,
573 }
574 }
575 fn mk(&self, main: f64, cross: f64) -> Size {
576 match self.axis {
577 Axis::Vertical => Size::new(cross, main),
578 Axis::Horizontal => Size::new(main, cross),
579 }
580 }
581 fn split(&self, p: Proposal) -> (Option<f64>, Option<f64>) {
582 match self.axis {
583 Axis::Vertical => (p.height, p.width),
584 Axis::Horizontal => (p.width, p.height),
585 }
586 }
587 fn proposal(&self, main: Option<f64>, cross: Option<f64>) -> Proposal {
588 match self.axis {
589 Axis::Vertical => Proposal::new(cross, main),
590 Axis::Horizontal => Proposal::new(main, cross),
591 }
592 }
593 fn grows_main(&self, f: Flex) -> bool {
594 f.is_spacer
595 || match self.axis {
596 Axis::Vertical => f.grow_h,
597 Axis::Horizontal => f.grow_w,
598 }
599 }
600 fn yields_main(&self, f: Flex) -> bool {
603 self.axis == Axis::Vertical && f.yields_h && !self.grows_main(f)
604 }
605 fn grows_cross(&self, f: Flex) -> bool {
606 match self.axis {
607 Axis::Vertical => f.grow_w,
608 Axis::Horizontal => f.grow_h,
609 }
610 }
611
612 fn flatten(cx: &mut dyn LayoutOps, children: &[RNode], out: &mut Vec<RNode>) {
613 for &c in children {
614 if cx.flex_of(c).is_group {
615 let inner = cx.children_of(c);
616 Self::flatten(cx, &inner, out);
617 } else {
618 out.push(c);
619 }
620 }
621 }
622
623 fn negotiate(&self, cx: &mut dyn LayoutOps, kids: &[RNode], p: Proposal) -> Vec<Size> {
624 let (main_p, cross_p) = self.split(p);
625 let mut sizes = vec![Size::ZERO; kids.len()];
626 let mut flex_idx = Vec::new();
627 let mut yield_idx = Vec::new();
628 let mut rigid_main = 0.0;
629 for (i, &k) in kids.iter().enumerate() {
630 let f = cx.flex_of(k);
631 if self.grows_main(f) {
632 flex_idx.push(i);
633 } else if self.yields_main(f) {
634 yield_idx.push(i);
635 } else {
636 let s = cx.measure_child(k, self.proposal(None, cross_p));
637 rigid_main += self.main(s);
638 sizes[i] = s;
639 }
640 }
641 if let Some(mp) = main_p {
648 let spacing_total = self.spacing * (kids.len().saturating_sub(1)) as f64;
649 let available = (mp - spacing_total).max(0.0);
650 if rigid_main > available {
651 let mut budget = available;
652 rigid_main = 0.0;
653 for (i, &k) in kids.iter().enumerate() {
654 let f = cx.flex_of(k);
655 if self.grows_main(f) || self.yields_main(f) {
656 continue;
657 }
658 if self.main(sizes[i]) > budget {
659 sizes[i] = cx.measure_child(k, self.proposal(Some(budget), cross_p));
660 }
661 let m = self.main(sizes[i]);
662 rigid_main += m;
663 budget = (budget - m).max(0.0);
664 }
665 }
666 }
667 for &i in &yield_idx {
670 let spacing_total = self.spacing * (kids.len().saturating_sub(1)) as f64;
671 let left = main_p.map(|mp| (mp - rigid_main - spacing_total).max(0.0));
672 sizes[i] = cx.measure_child(kids[i], self.proposal(left, cross_p));
673 rigid_main += self.main(sizes[i]);
674 }
675 if !flex_idx.is_empty() {
676 let spacing_total = self.spacing * (kids.len().saturating_sub(1)) as f64;
677 match main_p {
678 Some(mp) => {
679 let remaining = (mp - rigid_main - spacing_total).max(0.0);
680 let share = remaining / flex_idx.len() as f64;
681 for &i in &flex_idx {
682 let f = cx.flex_of(kids[i]);
683 sizes[i] = if f.is_spacer {
684 self.mk(share, 0.0)
685 } else {
686 cx.measure_child(kids[i], self.proposal(Some(share), cross_p))
687 };
688 }
689 }
690 None => {
691 for &i in &flex_idx {
692 let f = cx.flex_of(kids[i]);
693 sizes[i] = if f.is_spacer {
694 Size::ZERO
695 } else {
696 cx.measure_child(kids[i], self.proposal(None, cross_p))
697 };
698 }
699 }
700 }
701 }
702 sizes
703 }
704
705 fn baselines(
709 &self,
710 cx: &mut dyn LayoutOps,
711 kids: &[RNode],
712 sizes: &[Size],
713 ) -> Vec<Option<f64>> {
714 if self.align != CrossAlign::FirstBaseline || self.axis != Axis::Horizontal {
715 return vec![None; kids.len()];
716 }
717 kids.iter()
718 .zip(sizes)
719 .map(|(&k, &s)| cx.baseline_of(k, s))
720 .collect()
721 }
722
723 #[expect(
727 clippy::float_cmp,
728 reason = "`f64::MIN` is the fold's seed, compared as a no-baseline sentinel"
729 )]
730 fn baseline_cross_extent(&self, baselines: &[Option<f64>], sizes: &[Size]) -> Option<f64> {
731 let deepest = baselines.iter().flatten().copied().fold(f64::MIN, f64::max);
732 if deepest == f64::MIN {
733 return None;
734 }
735 let below = baselines
736 .iter()
737 .zip(sizes)
738 .filter_map(|(b, s)| b.map(|b| self.cross(*s) - b))
739 .fold(0.0, f64::max);
740 Some(deepest + below)
741 }
742}
743
744impl Layout for StackLayout {
745 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
746 let mut kids = Vec::new();
747 Self::flatten(cx, children, &mut kids);
748 if kids.is_empty() {
749 return Size::ZERO;
750 }
751 let (main_p, cross_p) = self.split(p);
752 let sizes = self.negotiate(cx, &kids, p);
753 let spacing_total = self.spacing * (kids.len() - 1) as f64;
754 let has_flex = kids.iter().any(|&k| self.grows_main(cx.flex_of(k)));
755 let needed = sizes.iter().map(|&s| self.main(s)).sum::<f64>() + spacing_total;
759 let main_total = match main_p {
760 Some(mp) if has_flex => mp.max(needed),
761 _ => needed,
762 };
763 let grows_cross = kids.iter().any(|&k| self.grows_cross(cx.flex_of(k)));
764 let tallest = sizes.iter().map(|&s| self.cross(s)).fold(0.0, f64::max);
765 let stacked = self
768 .baseline_cross_extent(&self.baselines(cx, &kids, &sizes), &sizes)
769 .unwrap_or(0.0)
770 .max(tallest);
771 let cross_total = match cross_p {
772 Some(cp) if grows_cross => cp,
773 _ => stacked,
774 };
775 self.mk(main_total, cross_total)
776 }
777
778 #[expect(
782 clippy::float_cmp,
783 reason = "`f64::MIN` is the fold's seed, compared as a no-baseline sentinel"
784 )]
785 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
786 let mut kids = Vec::new();
787 Self::flatten(cx, children, &mut kids);
788 if kids.is_empty() {
789 return None;
790 }
791 let sizes = self.negotiate(cx, &kids, Proposal::exact(size));
792 match self.axis {
793 Axis::Horizontal => {
794 let baselines: Vec<Option<f64>> = kids
795 .iter()
796 .zip(&sizes)
797 .map(|(&k, &s)| cx.baseline_of(k, s))
798 .collect();
799 let deepest = baselines.iter().flatten().copied().fold(f64::MIN, f64::max);
800 (deepest != f64::MIN).then_some(deepest)
801 }
802 Axis::Vertical => {
803 let mut pos = 0.0;
804 for (&k, &s) in kids.iter().zip(&sizes) {
805 if let Some(b) = cx.baseline_of(k, s) {
806 return Some(pos + b);
807 }
808 pos += self.main(s) + self.spacing;
809 }
810 None
811 }
812 }
813 }
814
815 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
816 let mut kids = Vec::new();
817 Self::flatten(cx, children, &mut kids);
818 if kids.is_empty() {
819 return;
820 }
821 let sizes = self.negotiate(cx, &kids, Proposal::exact(bounds.size));
822 let needed = sizes.iter().map(|&s| self.main(s)).sum::<f64>()
827 + self.spacing * (kids.len() - 1) as f64;
828 let available = self.main(bounds.size);
829 if available > 0.5 && needed > available + 0.5 {
835 cx.report_overflow(needed, available);
836 }
837 let bounds_cross = self.cross(bounds.size);
838 let baselines = self.baselines(cx, &kids, &sizes);
842 let deepest = baselines.iter().flatten().copied().fold(f64::MIN, f64::max);
843 let mut pos = 0.0;
844 for (i, &k) in kids.iter().enumerate() {
845 let s = sizes[i];
846 let cross_off = match (self.align, baselines[i]) {
847 (CrossAlign::FirstBaseline, Some(b)) => deepest - b,
848 (CrossAlign::Leading, _) => 0.0,
849 (CrossAlign::Center | CrossAlign::FirstBaseline, _) => {
850 ((bounds_cross - self.cross(s)) / 2.0).max(0.0)
851 }
852 (CrossAlign::Trailing, _) => (bounds_cross - self.cross(s)).max(0.0),
853 };
854 let rect = match self.axis {
855 Axis::Vertical => Rect::new(cross_off, pos, s.width, s.height),
856 Axis::Horizontal => Rect::new(pos, cross_off, s.width, s.height),
857 };
858 cx.place_child(k, rect);
859 pos += self.main(s) + self.spacing;
860 }
861 }
862}
863
864pub struct FlowLayout {
870 pub spacing: f64,
871 pub run_spacing: f64,
873 pub align: CrossAlign,
875 pub uniform: bool,
880}
881
882struct FlowLine {
884 start: usize,
885 end: usize,
886 height: f64,
887}
888
889struct FlowPlan {
892 sizes: Vec<Size>,
893 lines: Vec<FlowLine>,
894}
895
896impl FlowLayout {
897 fn pack(&self, sizes: &[Size], max_w: Option<f64>) -> Vec<FlowLine> {
900 let mut lines = Vec::new();
901 let mut start = 0;
902 let mut w = 0.0;
903 let mut h: f64 = 0.0;
904 for (i, s) in sizes.iter().enumerate() {
905 let grown = if i == start {
906 s.width
907 } else {
908 w + self.spacing + s.width
909 };
910 if i > start && max_w.is_some_and(|m| grown > m + 0.5) {
911 lines.push(FlowLine {
912 start,
913 end: i,
914 height: h,
915 });
916 start = i;
917 w = s.width;
918 h = s.height;
919 } else {
920 w = grown;
921 h = h.max(s.height);
922 }
923 }
924 if start < sizes.len() {
925 lines.push(FlowLine {
926 start,
927 end: sizes.len(),
928 height: h,
929 });
930 }
931 lines
932 }
933
934 fn natural_sizes(cx: &mut dyn LayoutOps, kids: &[RNode]) -> Vec<Size> {
935 kids.iter()
936 .map(|&k| cx.measure_child(k, Proposal::UNCONSTRAINED))
937 .collect()
938 }
939
940 fn plan(&self, cx: &mut dyn LayoutOps, kids: &[RNode], max_w: Option<f64>) -> FlowPlan {
943 let natural = Self::natural_sizes(cx, kids);
944 if !self.uniform {
945 let lines = self.pack(&natural, max_w);
946 return FlowPlan {
947 sizes: natural,
948 lines,
949 };
950 }
951 let cell_w = natural.iter().map(|s| s.width).fold(0.0, f64::max);
953 let cols = match max_w {
954 Some(m) if cell_w > 0.0 => {
957 (((m + self.spacing) / (cell_w + self.spacing)).floor() as usize).max(1)
958 }
959 _ => kids.len().max(1),
961 };
962 let col_w = match max_w {
967 Some(m) if kids.iter().any(|&k| cx.flex_of(k).grow_w) => {
968 ((m - self.spacing * (cols - 1) as f64) / cols as f64).max(cell_w)
969 }
970 _ => cell_w,
971 };
972 let col_w = max_w.map_or(col_w, |m| col_w.min(m));
976 let sizes: Vec<Size> = kids
980 .iter()
981 .map(|&k| {
982 let s = cx.measure_child(k, Proposal::new(Some(col_w), None));
983 Size::new(col_w, s.height)
984 })
985 .collect();
986 let mut lines = Vec::new();
987 let mut start = 0;
988 while start < sizes.len() {
989 let end = (start + cols).min(sizes.len());
990 let height = sizes[start..end]
991 .iter()
992 .map(|s| s.height)
993 .fold(0.0, f64::max);
994 lines.push(FlowLine { start, end, height });
995 start = end;
996 }
997 FlowPlan { sizes, lines }
998 }
999}
1000
1001impl Layout for FlowLayout {
1002 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1003 let mut kids = Vec::new();
1004 StackLayout::flatten(cx, children, &mut kids);
1005 if kids.is_empty() {
1006 return Size::ZERO;
1007 }
1008 let plan = self.plan(cx, &kids, p.width);
1009 let height = plan.lines.iter().map(|l| l.height).sum::<f64>()
1010 + self.run_spacing * plan.lines.len().saturating_sub(1) as f64;
1011 let width = p.width.unwrap_or_else(|| {
1014 plan.sizes.iter().map(|s| s.width).sum::<f64>()
1015 + self.spacing * plan.sizes.len().saturating_sub(1) as f64
1016 });
1017 Size::new(width, height)
1018 }
1019
1020 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1021 let mut kids = Vec::new();
1022 StackLayout::flatten(cx, children, &mut kids);
1023 if kids.is_empty() {
1024 return;
1025 }
1026 let plan = self.plan(cx, &kids, Some(bounds.size.width));
1027 let mut y = 0.0;
1028 for line in &plan.lines {
1029 let mut x = 0.0;
1030 let range = line.start..line.end;
1031 for (&k, &s) in kids[range.clone()].iter().zip(&plan.sizes[range]) {
1032 let dy = ((line.height - s.height) * self.align.fraction()).max(0.0);
1033 cx.place_child(k, Rect::new(x, y + dy, s.width, s.height));
1034 x += s.width + self.spacing;
1035 }
1036 y += line.height + self.run_spacing;
1037 }
1038 }
1039}
1040
1041struct GridCell {
1044 node: RNode,
1045 col: usize,
1046 span: usize,
1047 flex: Flex,
1048}
1049
1050struct GridRowRef {
1052 cells: Vec<GridCell>,
1053 full_width: bool,
1054 valign: Option<CrossAlign>,
1055}
1056
1057struct GridGeom {
1059 rows: Vec<GridRowRef>,
1060 col_x: Vec<f64>,
1061 col_w: Vec<f64>,
1062 row_y: Vec<f64>,
1063 row_h: Vec<f64>,
1064 cell_sizes: Vec<Vec<Size>>,
1066 size: Size,
1067}
1068
1069pub struct GridLayout {
1076 pub row_spacing: f64,
1077 pub column_spacing: f64,
1078 pub align: Alignment,
1079}
1080
1081impl GridLayout {
1082 fn collect(cx: &mut dyn LayoutOps, children: &[RNode]) -> (Vec<GridRowRef>, usize) {
1084 let mut tops = Vec::new();
1085 StackLayout::flatten(cx, children, &mut tops);
1086 let mut rows = Vec::new();
1087 let mut ncols = 0usize;
1088 for &t in &tops {
1089 let f = cx.flex_of(t);
1090 if f.grid.is_row {
1091 let inner = cx.children_of(t);
1092 let mut cell_nodes = Vec::new();
1093 StackLayout::flatten(cx, &inner, &mut cell_nodes);
1094 let mut cells = Vec::new();
1095 let mut col = 0usize;
1096 for &c in &cell_nodes {
1097 let cf = cx.flex_of(c);
1098 let span = cf.grid.col_span.max(1) as usize;
1099 cells.push(GridCell {
1100 node: c,
1101 col,
1102 span,
1103 flex: cf,
1104 });
1105 col += span;
1106 }
1107 ncols = ncols.max(col);
1108 rows.push(GridRowRef {
1109 cells,
1110 full_width: false,
1111 valign: f.grid.row_valign,
1112 });
1113 } else {
1114 rows.push(GridRowRef {
1117 cells: vec![GridCell {
1118 node: t,
1119 col: 0,
1120 span: 1,
1121 flex: f,
1122 }],
1123 full_width: true,
1124 valign: None,
1125 });
1126 }
1127 }
1128 (rows, ncols)
1129 }
1130
1131 fn span_width(&self, col_w: &[f64], col: usize, span: usize) -> f64 {
1132 let end = (col + span).min(col_w.len());
1133 let cols: f64 = col_w[col..end].iter().sum();
1134 cols + self.column_spacing * (end.saturating_sub(col + 1)) as f64
1135 }
1136
1137 fn geometry(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> GridGeom {
1142 let (mut rows, ncols) = Self::collect(cx, children);
1143 if rows.is_empty() {
1144 return GridGeom {
1145 rows,
1146 col_x: Vec::new(),
1147 col_w: Vec::new(),
1148 row_y: Vec::new(),
1149 row_h: Vec::new(),
1150 cell_sizes: Vec::new(),
1151 size: Size::ZERO,
1152 };
1153 }
1154 let ncols = ncols.max(1);
1155 for r in &mut rows {
1156 if r.full_width {
1157 r.cells[0].span = ncols;
1158 }
1159 }
1160 let unconstrained = Proposal::new(None, None);
1161
1162 let mut col_ideal = vec![0.0f64; ncols];
1165 let mut col_flex = vec![false; ncols];
1166 let mut flex_ideal = vec![0.0f64; ncols];
1167 for r in rows.iter().filter(|r| !r.full_width) {
1168 for c in r.cells.iter().filter(|c| c.span == 1 && !c.flex.is_spacer) {
1169 if c.flex.grow_w {
1170 col_flex[c.col] = true;
1171 if p.width.is_none() {
1172 let s = cx.measure_child(c.node, unconstrained);
1173 flex_ideal[c.col] = flex_ideal[c.col].max(s.width);
1174 }
1175 } else {
1176 let s = cx.measure_child(c.node, unconstrained);
1177 col_ideal[c.col] = col_ideal[c.col].max(s.width);
1178 }
1179 }
1180 }
1181 for r in rows.iter().filter(|r| !r.full_width) {
1183 for c in r.cells.iter().filter(|c| c.span > 1 && !c.flex.is_spacer) {
1184 if c.flex.grow_w {
1185 let end = (c.col + c.span).min(ncols);
1186 col_flex[c.col..end].fill(true);
1187 }
1188 }
1189 }
1190 for r in rows.iter().filter(|r| !r.full_width) {
1193 for c in r.cells.iter().filter(|c| c.span > 1 && !c.flex.is_spacer) {
1194 if c.flex.grow_w {
1195 continue;
1196 }
1197 let s = cx.measure_child(c.node, unconstrained);
1198 let end = (c.col + c.span).min(ncols);
1199 let avail = self.span_width(&col_ideal, c.col, c.span);
1200 let deficit = s.width - avail;
1201 if deficit > 0.0 {
1202 let flexed: Vec<usize> = (c.col..end).filter(|&k| col_flex[k]).collect();
1203 let targets = if flexed.is_empty() {
1204 (c.col..end).collect()
1205 } else {
1206 flexed
1207 };
1208 let add = deficit / targets.len() as f64;
1209 for k in targets {
1210 col_ideal[k] += add;
1211 }
1212 }
1213 }
1214 }
1215 let mut fw_ideal = 0.0f64;
1218 let mut fw_flex = false;
1219 for r in rows.iter().filter(|r| r.full_width) {
1220 let c = &r.cells[0];
1221 if c.flex.is_spacer {
1222 continue;
1223 }
1224 if c.flex.grow_w {
1225 fw_flex = true;
1226 } else {
1227 let s = cx.measure_child(c.node, unconstrained);
1228 fw_ideal = fw_ideal.max(s.width);
1229 }
1230 }
1231
1232 let gutters = self.column_spacing * (ncols - 1) as f64;
1234 let has_flex_col = col_flex.iter().any(|&f| f);
1235 let mut col_w = vec![0.0f64; ncols];
1236 match p.width {
1237 Some(pw) if has_flex_col => {
1238 let rigid: f64 = (0..ncols)
1239 .filter(|&k| !col_flex[k])
1240 .map(|k| col_ideal[k])
1241 .sum();
1242 let share = (pw - rigid - gutters).max(0.0)
1243 / col_flex.iter().filter(|&&f| f).count() as f64;
1244 for k in 0..ncols {
1245 col_w[k] = if col_flex[k] { share } else { col_ideal[k] };
1246 }
1247 }
1248 _ => {
1249 for k in 0..ncols {
1250 col_w[k] = if col_flex[k] {
1251 flex_ideal[k].max(col_ideal[k])
1252 } else {
1253 col_ideal[k]
1254 };
1255 }
1256 }
1257 }
1258 let cols_total: f64 = col_w.iter().sum::<f64>() + gutters;
1259 let grid_w = match p.width {
1260 Some(pw) if has_flex_col || fw_flex => pw,
1261 _ => cols_total.max(fw_ideal),
1262 };
1263
1264 let nrows = rows.len();
1266 let mut cell_sizes: Vec<Vec<Size>> = Vec::with_capacity(nrows);
1267 let mut row_h = vec![0.0f64; nrows];
1268 let mut row_flex = vec![false; nrows];
1269 for (ri, r) in rows.iter().enumerate() {
1270 let mut sizes = Vec::with_capacity(r.cells.len());
1271 for c in &r.cells {
1272 if c.flex.is_spacer {
1273 sizes.push(Size::ZERO);
1274 continue;
1275 }
1276 let w = if r.full_width {
1277 grid_w
1278 } else {
1279 self.span_width(&col_w, c.col, c.span)
1280 };
1281 let s = cx.measure_child(c.node, Proposal::new(Some(w), None));
1282 row_h[ri] = row_h[ri].max(s.height);
1283 if c.flex.grow_h {
1284 row_flex[ri] = true;
1285 }
1286 sizes.push(s);
1287 }
1288 cell_sizes.push(sizes);
1289 }
1290 let vgutters = self.row_spacing * (nrows - 1) as f64;
1293 if let Some(ph) = p.height
1294 && row_flex.iter().any(|&f| f)
1295 {
1296 let total: f64 = row_h.iter().sum::<f64>() + vgutters;
1297 let extra = (ph - total).max(0.0) / row_flex.iter().filter(|&&f| f).count() as f64;
1298 for (ri, flexed) in row_flex.iter().enumerate() {
1299 if *flexed {
1300 row_h[ri] += extra;
1301 }
1302 }
1303 }
1304 let grid_h = row_h.iter().sum::<f64>() + vgutters;
1305
1306 let mut col_x = vec![0.0f64; ncols];
1307 let mut x = 0.0;
1308 for k in 0..ncols {
1309 col_x[k] = x;
1310 x += col_w[k] + self.column_spacing;
1311 }
1312 let mut row_y = vec![0.0f64; nrows];
1313 let mut y = 0.0;
1314 for ri in 0..nrows {
1315 row_y[ri] = y;
1316 y += row_h[ri] + self.row_spacing;
1317 }
1318 GridGeom {
1319 rows,
1320 col_x,
1321 col_w,
1322 row_y,
1323 row_h,
1324 cell_sizes,
1325 size: Size::new(grid_w, grid_h),
1326 }
1327 }
1328}
1329
1330impl Layout for GridLayout {
1331 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1332 self.geometry(cx, children, p).size
1333 }
1334
1335 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1336 let g = self.geometry(cx, children, Proposal::exact(bounds.size));
1337 for (ri, r) in g.rows.iter().enumerate() {
1338 for (ci, c) in r.cells.iter().enumerate() {
1339 if c.flex.is_spacer {
1340 continue;
1341 }
1342 let cell = if r.full_width {
1343 Rect::new(0.0, g.row_y[ri], g.size.width, g.row_h[ri])
1344 } else {
1345 Rect::new(
1346 g.col_x[c.col],
1347 g.row_y[ri],
1348 self.span_width(&g.col_w, c.col, c.span),
1349 g.row_h[ri],
1350 )
1351 };
1352 let s = g.cell_sizes[ri][ci];
1353 let w = if c.flex.grow_w {
1354 cell.size.width
1355 } else {
1356 s.width.min(cell.size.width)
1357 };
1358 let h = if c.flex.grow_h {
1359 cell.size.height
1360 } else {
1361 s.height.min(cell.size.height)
1362 };
1363 let hf = match c.flex.grid.align {
1366 Some(a) => a.h_fraction(),
1367 None => self.align.h_fraction(),
1368 };
1369 let vf = match (c.flex.grid.align, r.valign) {
1370 (Some(a), _) => a.v_fraction(),
1371 (None, Some(v)) => v.fraction(),
1372 (None, None) => self.align.v_fraction(),
1373 };
1374 let x = cell.origin.x + (cell.size.width - w) * hf;
1375 let y = cell.origin.y + (cell.size.height - h) * vf;
1376 cx.place_child(c.node, Rect::new(x, y, w, h));
1377 }
1378 }
1379 }
1381}
1382
1383#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
1386pub enum Alignment {
1387 TopLeading,
1388 Top,
1389 TopTrailing,
1390 Leading,
1391 #[default]
1392 Center,
1393 Trailing,
1394 BottomLeading,
1395 Bottom,
1396 BottomTrailing,
1397}
1398
1399impl Alignment {
1400 fn h_fraction(self) -> f64 {
1402 match self {
1403 Alignment::TopLeading | Alignment::Leading | Alignment::BottomLeading => 0.0,
1404 Alignment::Top | Alignment::Center | Alignment::Bottom => 0.5,
1405 Alignment::TopTrailing | Alignment::Trailing | Alignment::BottomTrailing => 1.0,
1406 }
1407 }
1408 fn v_fraction(self) -> f64 {
1410 match self {
1411 Alignment::TopLeading | Alignment::Top | Alignment::TopTrailing => 0.0,
1412 Alignment::Leading | Alignment::Center | Alignment::Trailing => 0.5,
1413 Alignment::BottomLeading | Alignment::Bottom | Alignment::BottomTrailing => 1.0,
1414 }
1415 }
1416}
1417
1418pub struct AlignmentLayout {
1421 pub align: Alignment,
1422}
1423
1424impl Layout for AlignmentLayout {
1425 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1426 children
1427 .first()
1428 .map_or(Size::ZERO, |&c| cx.measure_child(c, p))
1429 }
1430
1431 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1432 if let Some(&c) = children.first() {
1433 let size = cx.measure_child(c, Proposal::exact(bounds.size));
1434 let x = (bounds.size.width - size.width).max(0.0) * self.align.h_fraction();
1437 let y = (bounds.size.height - size.height).max(0.0) * self.align.v_fraction();
1438 cx.place_child(c, Rect::new(x, y, size.width, size.height));
1439 }
1440 }
1441
1442 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1443 let &child = children.first()?;
1444 let child_size = cx.measure_child(child, Proposal::exact(size));
1445 let offset = (size.height - child_size.height).max(0.0) * self.align.v_fraction();
1446 cx.baseline_of(child, child_size)
1447 .map(|baseline| baseline + offset)
1448 }
1449}
1450
1451#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1454pub enum Dimension {
1455 Width,
1456 Height,
1457 Both,
1458}
1459
1460pub struct OverlayLayout {
1467 pub align: Alignment,
1468 pub size_to_first: bool,
1469}
1470
1471impl OverlayLayout {
1472 fn flatten(cx: &mut dyn LayoutOps, children: &[RNode], out: &mut Vec<RNode>) {
1474 for &c in children {
1475 if cx.flex_of(c).is_group {
1476 let inner = cx.children_of(c);
1477 Self::flatten(cx, &inner, out);
1478 } else {
1479 out.push(c);
1480 }
1481 }
1482 }
1483}
1484
1485impl Layout for OverlayLayout {
1486 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1487 let mut kids = Vec::new();
1488 Self::flatten(cx, children, &mut kids);
1489 if self.size_to_first {
1490 return match kids.first() {
1491 Some(&c) => cx.measure_child(c, p),
1492 None => Size::ZERO,
1493 };
1494 }
1495 let mut size = Size::ZERO;
1496 for &c in &kids {
1497 let s = cx.measure_child(c, p);
1498 size.width = size.width.max(s.width);
1499 size.height = size.height.max(s.height);
1500 }
1501 size
1502 }
1503 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1504 let mut kids = Vec::new();
1505 Self::flatten(cx, children, &mut kids);
1506 for &c in &kids {
1507 let s = cx.measure_child(c, Proposal::exact(bounds.size));
1508 let x = (bounds.size.width - s.width) * self.align.h_fraction();
1509 let y = (bounds.size.height - s.height) * self.align.v_fraction();
1510 cx.place_child(c, Rect::new(x, y, s.width, s.height));
1511 }
1512 }
1513}
1514
1515pub struct PaddingLayout {
1516 pub insets: Insets,
1517}
1518
1519impl Layout for PaddingLayout {
1520 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1521 let inner = Proposal::new(
1522 p.width
1523 .map(|w| (w - self.insets.horizontal_total()).max(0.0)),
1524 p.height
1525 .map(|h| (h - self.insets.vertical_total()).max(0.0)),
1526 );
1527 let s = match children.first() {
1528 Some(&c) => cx.measure_child(c, inner),
1529 None => Size::ZERO,
1530 };
1531 Size::new(
1532 s.width + self.insets.horizontal_total(),
1533 s.height + self.insets.vertical_total(),
1534 )
1535 }
1536 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1537 if let Some(&c) = children.first() {
1538 let inner = bounds.inset_by(self.insets);
1539 let s = cx.measure_child(c, Proposal::exact(inner.size));
1540 cx.place_child(
1541 c,
1542 Rect {
1543 origin: inner.origin,
1544 size: s,
1545 },
1546 );
1547 }
1548 }
1549 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1550 let inner = Size::new(
1552 (size.width - self.insets.horizontal_total()).max(0.0),
1553 (size.height - self.insets.vertical_total()).max(0.0),
1554 );
1555 wrapper_baseline(cx, children, inner, self.insets.top)
1556 }
1557}
1558
1559pub struct AspectRatioLayout {
1566 pub ratio: f64,
1567}
1568
1569impl Layout for AspectRatioLayout {
1570 fn measure(&self, cx: &mut dyn LayoutOps, _children: &[RNode], p: Proposal) -> Size {
1571 match (p.width, p.height) {
1572 (Some(w), Some(h)) => {
1573 if w / h > self.ratio {
1574 Size::new(h * self.ratio, h)
1575 } else {
1576 Size::new(w, w / self.ratio)
1577 }
1578 }
1579 (Some(w), None) => Size::new(w, w / self.ratio),
1580 (None, Some(h)) => Size::new(h * self.ratio, h),
1581 (None, None) => cx.measure_leaf(p),
1582 }
1583 }
1584 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1585 for &c in children {
1587 cx.place_child(c, Rect::from_size(bounds.size));
1588 }
1589 }
1590 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1591 wrapper_baseline(cx, children, size, 0.0)
1592 }
1593}
1594
1595pub struct GrowLayout {
1599 pub w: bool,
1600 pub h: bool,
1601}
1602
1603impl Layout for GrowLayout {
1604 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1605 let cs = match children.first() {
1606 Some(&c) => cx.measure_child(c, p),
1607 None => Size::ZERO,
1608 };
1609 Size::new(
1613 if self.w {
1614 p.width.map_or(cs.width, |w| w.max(cs.width))
1615 } else {
1616 cs.width
1617 },
1618 if self.h {
1619 p.height.map_or(cs.height, |h| h.max(cs.height))
1620 } else {
1621 cs.height
1622 },
1623 )
1624 }
1625 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1626 if let Some(&c) = children.first() {
1627 let cs = cx.measure_child(c, Proposal::exact(bounds.size));
1628 let w = if self.w { bounds.size.width } else { cs.width };
1630 let h = if self.h {
1631 bounds.size.height
1632 } else {
1633 cs.height
1634 };
1635 cx.place_child(c, Rect::from_size(Size::new(w, h)));
1636 }
1637 }
1638 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1639 let &child = children.first()?;
1640 let measured = cx.measure_child(child, Proposal::exact(size));
1641 wrapper_baseline(
1642 cx,
1643 children,
1644 Size::new(
1645 if self.w { size.width } else { measured.width },
1646 if self.h { size.height } else { measured.height },
1647 ),
1648 0.0,
1649 )
1650 }
1651}
1652
1653pub struct MaxWidthLayout {
1657 pub max: f64,
1658}
1659
1660impl Layout for MaxWidthLayout {
1661 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1662 let capped = Proposal::new(
1663 Some(p.width.map_or(self.max, |w| w.min(self.max))),
1664 p.height,
1665 );
1666 match children.first() {
1667 Some(&c) => {
1668 let s = cx.measure_child(c, capped);
1669 Size::new(s.width.min(self.max), s.height)
1670 }
1671 None => Size::ZERO,
1672 }
1673 }
1674 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1675 if let Some(&c) = children.first() {
1676 let w = bounds.size.width.min(self.max);
1677 let s = cx.measure_child(c, Proposal::exact(Size::new(w, bounds.size.height)));
1678 cx.place_child(c, Rect::from_size(Size::new(s.width.min(w), s.height)));
1679 }
1680 }
1681 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1682 PassThrough::forward(cx, children, size)
1683 }
1684}
1685
1686pub struct MaxHeightLayout {
1692 pub max: f64,
1693}
1694
1695impl Layout for MaxHeightLayout {
1696 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1697 let capped = Proposal::new(
1698 p.width,
1699 Some(p.height.map_or(self.max, |h| h.min(self.max))),
1700 );
1701 match children.first() {
1702 Some(&c) => {
1703 let s = cx.measure_child(c, capped);
1704 Size::new(s.width, s.height.min(self.max))
1705 }
1706 None => Size::ZERO,
1707 }
1708 }
1709 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1710 if let Some(&c) = children.first() {
1711 let h = bounds.size.height.min(self.max);
1712 let s = cx.measure_child(c, Proposal::exact(Size::new(bounds.size.width, h)));
1713 cx.place_child(c, Rect::from_size(Size::new(s.width, s.height.min(h))));
1714 }
1715 }
1716 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1717 PassThrough::forward(cx, children, size)
1718 }
1719}
1720
1721pub struct MinWidthLayout {
1727 pub min: f64,
1728}
1729
1730impl Layout for MinWidthLayout {
1731 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1732 let floored = Proposal::new(p.width.map(|w| w.max(self.min)), p.height);
1733 match children.first() {
1734 Some(&c) => {
1735 let s = cx.measure_child(c, floored);
1736 Size::new(s.width.max(self.min), s.height)
1737 }
1738 None => Size::new(self.min, 0.0),
1739 }
1740 }
1741 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1742 if let Some(&c) = children.first() {
1743 let w = bounds.size.width.max(self.min);
1744 let s = cx.measure_child(c, Proposal::exact(Size::new(w, bounds.size.height)));
1745 cx.place_child(c, Rect::from_size(Size::new(w, s.height)));
1746 }
1747 }
1748 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1749 PassThrough::forward(cx, children, size)
1750 }
1751}
1752
1753pub struct MinHeightLayout {
1756 pub min: f64,
1757}
1758
1759impl Layout for MinHeightLayout {
1760 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1761 let floored = Proposal::new(p.width, p.height.map(|h| h.max(self.min)));
1762 match children.first() {
1763 Some(&c) => {
1764 let s = cx.measure_child(c, floored);
1765 Size::new(s.width, s.height.max(self.min))
1766 }
1767 None => Size::new(0.0, self.min),
1768 }
1769 }
1770 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1771 if let Some(&c) = children.first() {
1772 let height = bounds.size.height.max(self.min);
1773 let size = cx.measure_child(c, Proposal::exact(Size::new(bounds.size.width, height)));
1774 cx.place_child(c, Rect::from_size(Size::new(size.width, height)));
1775 }
1776 }
1777 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1778 let &child = children.first()?;
1779 let height = size.height.max(self.min);
1780 let measured = cx.measure_child(child, Proposal::exact(Size::new(size.width, height)));
1781 cx.baseline_of(child, Size::new(measured.width, height))
1782 }
1783}
1784
1785pub struct ReserveLayout;
1797
1798impl Layout for ReserveLayout {
1799 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1800 let Some(&content) = children.first() else {
1801 return Size::ZERO;
1802 };
1803 let c = cx.measure_child(content, p);
1804 let s = children
1805 .get(1)
1806 .map_or(Size::ZERO, |&sample| cx.measure_child(sample, p));
1807 Size::new(s.width.max(c.width), s.height.max(c.height))
1808 }
1809
1810 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1811 if let Some(&content) = children.first() {
1812 cx.place_child(content, Rect::from_size(bounds.size));
1813 }
1814 if let Some(&sample) = children.get(1) {
1815 cx.place_child(sample, Rect::from_size(Size::ZERO));
1816 }
1817 }
1818
1819 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1820 cx.baseline_of(*children.first()?, size)
1821 }
1822}
1823
1824pub struct FrameLayout {
1825 pub width: Option<f64>,
1826 pub height: Option<f64>,
1827}
1828
1829impl Layout for FrameLayout {
1830 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1831 let child_p = Proposal::new(self.width.or(p.width), self.height.or(p.height));
1832 let s = match children.first() {
1833 Some(&c) => cx.measure_child(c, child_p),
1834 None => Size::ZERO,
1835 };
1836 Size::new(
1837 self.width.unwrap_or(s.width),
1838 self.height.unwrap_or(s.height),
1839 )
1840 }
1841 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1842 if let Some(&c) = children.first() {
1843 cx.place_child(c, bounds);
1844 }
1845 }
1846 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1847 wrapper_baseline(cx, children, size, 0.0)
1848 }
1849}
1850
1851pub struct ScrollLayout {
1855 pub axis: Axis,
1856}
1857
1858impl Layout for ScrollLayout {
1859 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1860 let content_p = match self.axis {
1861 Axis::Vertical => Proposal::new(p.width, None),
1862 Axis::Horizontal => Proposal::new(None, p.height),
1863 };
1864 let cs = match children.first() {
1865 Some(&c) => cx.measure_child(c, content_p),
1866 None => Size::ZERO,
1867 };
1868 Size::new(p.width.unwrap_or(cs.width), p.height.unwrap_or(cs.height))
1869 }
1870 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1871 if let Some(&c) = children.first() {
1872 let vertical = self.axis == Axis::Vertical;
1873 let proposal = |cross: f64| match self.axis {
1874 Axis::Vertical => Proposal::new(Some(cross), None),
1875 Axis::Horizontal => Proposal::new(None, Some(cross)),
1876 };
1877 let (cross, main) = match self.axis {
1878 Axis::Vertical => (bounds.size.width, bounds.size.height),
1879 Axis::Horizontal => (bounds.size.height, bounds.size.width),
1880 };
1881 let mut cs = cx.measure_child(c, proposal(cross));
1882 let overflows = |s: Size| if vertical { s.height } else { s.width } > main;
1883 let mut cross = cross;
1887 if overflows(cs) {
1888 let inset = cx.scroll_bar_inset(vertical);
1889 if inset > 0.0 {
1890 cross = (cross - inset).max(0.0);
1891 cs = cx.measure_child(c, proposal(cross));
1892 }
1893 }
1894 let content = match self.axis {
1895 Axis::Vertical => Size::new(cross, cs.height.max(bounds.size.height)),
1896 Axis::Horizontal => Size::new(cs.width.max(bounds.size.width), cross),
1897 };
1898 cx.place_child(c, Rect::from_size(content));
1899 cx.set_scroll_content(content);
1900 }
1901 }
1902}
1903
1904pub struct NavLayout {
1909 pub sizes: std::rc::Rc<std::cell::RefCell<std::collections::HashMap<RNode, Size>>>,
1910 pub presentation: std::rc::Rc<std::cell::Cell<day_spec::props::NavPresentation>>,
1914 pub sidebar: std::rc::Rc<std::cell::Cell<Option<RNode>>>,
1917 pub list: std::rc::Rc<std::cell::Cell<Option<RNode>>>,
1919 pub list_width: f64,
1921 pub list_visible: std::rc::Rc<std::cell::Cell<bool>>,
1925}
1926
1927pub use day_spec::{NAV_LIST_WIDTH, NAV_SIDEBAR_WIDTH};
1928
1929impl NavLayout {
1930 pub fn stack(
1933 sizes: std::rc::Rc<std::cell::RefCell<std::collections::HashMap<RNode, Size>>>,
1934 ) -> Self {
1935 NavLayout {
1936 sizes,
1937 presentation: std::rc::Rc::new(std::cell::Cell::new(
1938 day_spec::props::NavPresentation::Stack,
1939 )),
1940 sidebar: std::rc::Rc::new(std::cell::Cell::new(None)),
1941 list: std::rc::Rc::new(std::cell::Cell::new(None)),
1942 list_width: NAV_LIST_WIDTH,
1943 list_visible: std::rc::Rc::new(std::cell::Cell::new(true)),
1944 }
1945 }
1946}
1947
1948impl Layout for NavLayout {
1949 fn measure(&self, _cx: &mut dyn LayoutOps, _children: &[RNode], p: Proposal) -> Size {
1950 Size::new(p.width.unwrap_or(480.0), p.height.unwrap_or(640.0))
1954 }
1955 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1956 let pres = self.presentation.get();
1957 let split = pres.is_split();
1958 let sidebar = self.sidebar.get();
1959 let list = self.list.get();
1960 let list_w = if split && list.is_some() && self.list_visible.get() {
1963 self.list_width
1964 } else {
1965 0.0
1966 };
1967 for &page in children {
1968 let reported = self.sizes.borrow().get(&page).copied();
1969 let sz = reported.unwrap_or_else(|| {
1973 let is_sidebar = Some(page) == sidebar;
1974 let is_list = Some(page) == list;
1975 if pres.rows_are_chrome() {
1976 if is_sidebar {
1982 Size::new(NAV_SIDEBAR_WIDTH, bounds.size.height)
1983 } else if is_list {
1984 Size::new(self.list_width, bounds.size.height)
1985 } else {
1986 bounds.size
1987 }
1988 } else if !split {
1989 bounds.size
1993 } else if is_sidebar {
1994 Size::new(NAV_SIDEBAR_WIDTH, bounds.size.height)
1995 } else if is_list {
1996 Size::new(self.list_width, bounds.size.height)
1997 } else {
1998 Size::new(
1999 (bounds.size.width - NAV_SIDEBAR_WIDTH - list_w - 1.0).max(0.0),
2000 bounds.size.height,
2001 )
2002 }
2003 });
2004 cx.place_child_native(page, Rect::from_size(sz));
2005 }
2006 }
2007}
2008
2009pub struct InspectorLayout {
2015 pub sizes: std::rc::Rc<std::cell::RefCell<std::collections::HashMap<RNode, Size>>>,
2016 pub visible: std::rc::Rc<std::cell::Cell<bool>>,
2019 pub width: f64,
2021}
2022
2023impl Layout for InspectorLayout {
2024 fn measure(&self, _cx: &mut dyn LayoutOps, _children: &[RNode], p: Proposal) -> Size {
2025 Size::new(p.width.unwrap_or(480.0), p.height.unwrap_or(640.0))
2027 }
2028 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
2029 for (i, &pane) in children.iter().enumerate() {
2031 let reported = self.sizes.borrow().get(&pane).copied();
2032 let sz = reported.unwrap_or_else(|| {
2033 let panel_w = if self.visible.get() { self.width } else { 0.0 };
2034 if i == 0 {
2035 Size::new((bounds.size.width - panel_w).max(0.0), bounds.size.height)
2036 } else {
2037 Size::new(panel_w, bounds.size.height)
2038 }
2039 });
2040 cx.place_child_native(pane, Rect::from_size(sz));
2041 }
2042 }
2043}
2044
2045pub struct SplitLayout {
2050 pub sizes: std::rc::Rc<std::cell::RefCell<std::collections::HashMap<RNode, Size>>>,
2051 pub stacked: std::rc::Rc<std::cell::Cell<bool>>,
2053 pub fraction: std::rc::Rc<std::cell::Cell<f64>>,
2055}
2056
2057impl Layout for SplitLayout {
2058 fn measure(&self, _cx: &mut dyn LayoutOps, _children: &[RNode], p: Proposal) -> Size {
2059 Size::new(p.width.unwrap_or(480.0), p.height.unwrap_or(640.0))
2061 }
2062 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
2063 let f = self.fraction.get().clamp(0.0, 1.0);
2065 let (w, h) = (bounds.size.width, bounds.size.height);
2066 for (i, &pane) in children.iter().enumerate() {
2067 let reported = self.sizes.borrow().get(&pane).copied();
2068 let sz = reported.unwrap_or_else(|| {
2069 let share = if i == 0 { f } else { 1.0 - f };
2070 if self.stacked.get() {
2071 Size::new(w, (h * share).floor())
2072 } else {
2073 Size::new((w * share).floor(), h)
2074 }
2075 });
2076 cx.place_child_native(pane, Rect::from_size(sz));
2077 }
2078 }
2079}
2080
2081pub struct CoverLayout {
2086 pub size: std::rc::Rc<std::cell::RefCell<Option<Size>>>,
2087}
2088
2089impl Layout for CoverLayout {
2090 fn measure(&self, _cx: &mut dyn LayoutOps, _children: &[RNode], _p: Proposal) -> Size {
2091 Size::new(0.0, 0.0)
2092 }
2093 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], _bounds: Rect) {
2094 let Some(sz) = *self.size.borrow() else {
2095 return; };
2097 for &child in children {
2098 cx.place_child_native(child, Rect::from_size(sz));
2099 }
2100 }
2101}
2102
2103pub fn rc_layout<L: Layout>(l: L) -> Rc<dyn Layout> {
2105 Rc::new(l)
2106}