Skip to main content

tui_lipan/widgets/center/
mod.rs

1mod layout;
2mod node;
3mod reconcile;
4
5pub(crate) use self::layout::measure_center;
6pub use self::node::CenterNode;
7pub(crate) use self::reconcile::reconcile_center;
8
9use crate::core::element::{Element, ElementKind};
10use crate::style::{LayoutConstraints, Length, Size, Style};
11
12/// Center a single child within the available area.
13#[derive(Clone, Default)]
14pub struct Center {
15    pub(crate) child: Option<Box<Element>>,
16    pub(crate) style: Style,
17    pub(crate) width: Size,
18    pub(crate) height: Size,
19}
20
21impl Center {
22    /// Create an empty Center.
23    pub fn new() -> Self {
24        Self::default()
25    }
26
27    /// Set the centered child.
28    pub fn child(mut self, child: impl Into<Element>) -> Self {
29        self.child = Some(Box::new(child.into()));
30        self
31    }
32
33    /// Set base style.
34    pub fn style(mut self, style: Style) -> Self {
35        self.style = style;
36        self
37    }
38
39    /// Set the centered width constraint.
40    pub fn width(mut self, width: Size) -> Self {
41        self.width = width;
42        self
43    }
44
45    /// Set the centered height constraint.
46    pub fn height(mut self, height: Size) -> Self {
47        self.height = height;
48        self
49    }
50}
51
52impl From<Center> for Element {
53    fn from(value: Center) -> Self {
54        let (min_w, min_h) = measure_center(&value, None, None);
55        Element::new(ElementKind::Center(value)).with_layout(
56            LayoutConstraints::default()
57                .min_width(Length::Px(min_w))
58                .min_height(Length::Px(min_h)),
59        )
60    }
61}
62
63impl crate::layout::hash::LayoutHash for Center {
64    fn layout_hash(
65        &self,
66        hasher: &mut impl std::hash::Hasher,
67        recurse: &dyn Fn(&Element) -> Option<u64>,
68    ) -> Option<()> {
69        use std::hash::Hash;
70        self.width.hash(hasher);
71        self.height.hash(hasher);
72        if let Some(child) = self.child.as_ref() {
73            recurse(child.as_ref())?.hash(hasher);
74        } else {
75            0u8.hash(hasher);
76        }
77        Some(())
78    }
79}