Skip to main content

rab/tui/components/
ref_container.rs

1use std::cell::RefCell;
2use std::rc::Rc;
3
4use crate::tui::Component;
5use crate::tui::Container;
6
7/// A Component wrapper around `Rc<RefCell<Container>>` that allows
8/// dynamically adding/removing children while sharing ownership with App.
9///
10/// Matches pi's pattern of keeping references to sub-containers for mutation:
11/// ```typescript
12/// this.chatContainer = new Container();
13/// this.ui.addChild(this.chatContainer);
14/// // Later:
15/// this.chatContainer.addChild(component);
16/// ```
17#[derive(Clone)]
18pub struct RefContainer {
19    pub inner: Rc<RefCell<Container>>,
20}
21
22impl RefContainer {
23    pub fn new() -> Self {
24        Self {
25            inner: Rc::new(RefCell::new(Container::new())),
26        }
27    }
28
29    pub fn new_rc() -> Rc<RefCell<Container>> {
30        Rc::new(RefCell::new(Container::new()))
31    }
32}
33
34impl Default for RefContainer {
35    fn default() -> Self {
36        Self::new()
37    }
38}
39
40impl Component for RefContainer {
41    fn render(&self, width: usize) -> Vec<String> {
42        self.inner.borrow().render(width)
43    }
44
45    fn invalidate(&mut self) {
46        self.inner.borrow_mut().invalidate();
47    }
48}