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
28impl Widget for ColumnWidget {
29 fn as_any(&self) -> &dyn std::any::Any {
30 self
31 }
32
33 fn create_render_object(&self) -> Box<dyn RenderObject> {
34 let mut col = ColumnRenderObject::new(self.spacing);
35 for child in &self.children {
36 debug_assert!(
37 child.0.parent_data().is_none(),
38 "ColumnWidget 不消费 ParentData::Flex;弹性布局请改用 mgui_layout::PanelWidget::column"
39 );
40 col = col.push(child.0.create_render_object());
41 }
42 Box::new(col)
43 }
44
45 fn children(&self) -> Vec<WidgetNode> {
46 self.children.clone()
47 }
48
49 fn is_equivalent(&self, old: &dyn Widget) -> bool {
50 old.as_any().downcast_ref::<ColumnWidget>().is_some_and(|o| {
51 self.spacing == o.spacing && crate::widget::children_equivalent(&self.children, &o.children)
52 })
53 }
54}
55
56#[cfg(test)]
57mod tests {
58 use super::*;
59 use crate::render_object::{BoxConstraints, LayoutContext};
60 use crate::{Color, RRectWidget, Size};
61
62 #[test]
63 fn column_stacks_natural_sizes_with_spacing() {
64 let mut ro = ColumnWidget::new(6.0)
65 .push(RRectWidget::new(Size::new(100.0, 20.0), Color::WHITE, 0.0))
66 .push(RRectWidget::new(Size::new(80.0, 10.0), Color::WHITE, 0.0))
67 .create_render_object();
68 let size = ro.layout(BoxConstraints::UNBOUNDED, &mut LayoutContext);
69 assert_eq!(size, Size::new(100.0, 36.0));
70 }
71}