Skip to main content

cranpose_ui/widgets/
box_widget.rs

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