Skip to main content

cranpose_ui/widgets/
box_widget.rs

1//! Box widget implementation
2
3use cranpose_core::NodeId;
4use cranpose_ui_layout::Alignment;
5
6use super::layout::Layout;
7use crate::{composable, layout::policies::BoxMeasurePolicy, modifier::Modifier};
8
9/// Specification for Box layout behavior.
10#[derive(Clone, Copy, Debug, PartialEq)]
11pub struct BoxSpec {
12    pub content_alignment: Alignment,
13    pub propagate_min_constraints: bool,
14}
15
16impl BoxSpec {
17    pub fn new() -> Self {
18        Self::default()
19    }
20
21    pub fn content_alignment(mut self, alignment: Alignment) -> Self {
22        self.content_alignment = alignment;
23        self
24    }
25
26    pub fn propagate_min_constraints(mut self, propagate: bool) -> Self {
27        self.propagate_min_constraints = propagate;
28        self
29    }
30}
31
32impl Default for BoxSpec {
33    fn default() -> Self {
34        Self {
35            content_alignment: Alignment::TOP_START,
36            propagate_min_constraints: false,
37        }
38    }
39}
40
41/// A layout composable that stacks its children on top of each other.
42///
43/// Use `Box` to:
44/// - Overlay elements (e.g., text over an image).
45/// - Size a child to match its parent.
46/// - Apply a background or border to a single child.
47///
48/// # Arguments
49///
50/// * `modifier` - Modifiers to apply to the box layout.
51/// * `spec` - Configuration for content alignment.
52/// * `content` - The children composables to layout (z-order is first-to-last).
53///
54/// # Example
55///
56/// ```rust,ignore
57/// Box(
58///     Modifier::size(100.0, 100.0).background(Color::Blue),
59///     BoxSpec::default().content_alignment(Alignment::Center),
60///     || {
61///         Text("Centered", Modifier::empty());
62///     }
63/// );
64/// ```
65#[composable]
66pub fn Box<F>(modifier: Modifier, spec: BoxSpec, content: F) -> NodeId
67where
68    F: FnMut() + 'static,
69{
70    let policy = BoxMeasurePolicy::new(spec.content_alignment, spec.propagate_min_constraints);
71    Layout(modifier, policy, content)
72}