mgui_core/layout/
column.rs1use crate::render_object::{ColumnRenderObject, RenderObject};
8use crate::widget::{Widget, WidgetNode};
9
10#[derive(Debug, Default)]
12pub struct ColumnWidget {
13 pub spacing: f32,
14 pub children: Vec<WidgetNode>,
15}
16
17impl ColumnWidget {
18 pub fn new(spacing: f32) -> Self {
19 Self { spacing, children: Vec::new() }
20 }
21
22 pub fn push(mut self, child: impl Widget) -> Self {
23 self.children.push(WidgetNode::new(child));
24 self
25 }
26
27 pub fn push_node(mut self, child: WidgetNode) -> Self {
29 self.children.push(child);
30 self
31 }
32}
33
34impl Widget for ColumnWidget {
35 fn as_any(&self) -> &dyn std::any::Any {
36 self
37 }
38
39 fn create_render_object(&self) -> Box<dyn RenderObject> {
40 let mut col = ColumnRenderObject::new(self.spacing);
41 for child in &self.children {
42 debug_assert!(
43 child.0.parent_data().is_none(),
44 "ColumnWidget 不消费 ParentData::Flex;弹性布局请改用 mgui_layout::PanelWidget::column"
45 );
46 col = col.push(child.0.create_render_object());
47 }
48 Box::new(col)
49 }
50
51 fn children(&self) -> Vec<WidgetNode> {
52 self.children.clone()
53 }
54
55 fn is_equivalent(&self, old: &dyn Widget) -> bool {
56 old.as_any().downcast_ref::<ColumnWidget>().is_some_and(|o| {
57 self.spacing == o.spacing && crate::widget::children_equivalent(&self.children, &o.children)
58 })
59 }
60}
61
62#[cfg(test)]
63mod tests {
64 use super::*;
65 use crate::render_object::{BoxConstraints, LayoutContext};
66 use crate::{Color, RRectWidget, Size};
67
68 #[test]
69 fn column_stacks_natural_sizes_with_spacing() {
70 let mut ro = ColumnWidget::new(6.0)
71 .push(RRectWidget::new(Size::new(100.0, 20.0), Color::WHITE, 0.0))
72 .push(RRectWidget::new(Size::new(80.0, 10.0), Color::WHITE, 0.0))
73 .create_render_object();
74 let size = ro.layout(BoxConstraints::UNBOUNDED, &mut LayoutContext);
75 assert_eq!(size, Size::new(100.0, 36.0));
76 }
77}