Skip to main content

cranpose_ui/widgets/
box_widget.rs

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