~tm85/lintuini

ref: dbf508fa97466afc3a2b45ae3460e50c633c9aaa lintuini/src/elements/container.rs -rw-r--r-- 2.1 KiB
dbf508fa — core feat(error): thiserror 27 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use ratatui_core::layout;
use ratatui_core::style::Style;
use ratatui_core::terminal::Frame;

use ratatui_widgets::block;
use ratatui_widgets::borders;

use super::element::{Element, ElementWithChildren};
use crate::error;

#[derive(Default)]
pub struct Container<'a> {
    children: Vec<Box<dyn Element>>,
    constraint: layout::Constraint,
    layout: layout::Layout,
    widgets: ContainerWidgets<'a>,
}

impl ElementWithChildren for Container<'_> {
    #[inline(always)]
    fn add_child(&mut self, child: impl Into<Box<dyn Element>>) -> Result<(), error::LintuiniError>{
        self.children.push(child.into());
        

        Ok(())
    }
    #[inline(always)]
    fn children(&self) -> &[Box<dyn Element>] {
        self.children.as_slice()
    }
    #[inline(always)]
    fn children_mut(&mut self) -> &mut [Box<dyn Element>] {
        self.children.as_mut_slice()
    }
}

impl Element for Container<'_> {
    #[inline(always)]
    fn constraint(&self) -> layout::Constraint {
        self.constraint
    }

    fn render(&self, frm: &mut Frame, rect: layout::Rect) -> Result<(), error::LintuiniError> {
        frm.render_widget(&self.widgets.block0, rect);

        for (el, r) in self.children.iter().zip(&*self.layout.split(rect)) {
            el.render(frm, *r);
        }

        Ok(())
    }
}

impl Container<'_> {
    #[inline(always)]
    pub fn new() -> Self {
        Container::default()
    }

    #[inline(always)]
    pub fn constraint(mut self, constraint: layout::Constraint) -> Self {
        self.constraint = constraint;
        self
    }

    #[inline(always)]
    pub fn direction(mut self, direction: layout::Direction) -> Self {
        self.layout = self.layout.direction(direction);
        self.regenerate_layout()
    }

    fn regenerate_layout(mut self) -> Self {
        if self.children.len() == 0 { return self; }
        self.layout = self.layout.constraints(
            self.children
                .iter()
                .map(|el| el.constraint())
        );
        self
    }
}
#[derive(Clone, Default)]
struct ContainerWidgets<'a> {
    block0: block::Block<'a>,
}