Skip to main content

ratatui_kit/component/
instantiated_component.rs

1use super::{AnyComponent, ComponentHelperExt};
2use crate::{
3    context::ContextStack,
4    element::ElementKey,
5    hooks::{AnyHook, Hook, Hooks},
6    multimap::RemoveOnlyMultimap,
7    props::AnyProps,
8    render::{ComponentDrawer, ComponentUpdater, layout_style::LayoutStyle},
9    terminal::UpdaterTerminal,
10};
11use ratatui::layout::{Constraint, Direction};
12use std::{
13    future::poll_fn,
14    ops::{Deref, DerefMut},
15    task::{Context, Poll},
16};
17
18#[derive(Default)]
19pub struct Components {
20    pub components: RemoveOnlyMultimap<ElementKey, InstantiatedComponent>,
21}
22
23impl Deref for Components {
24    type Target = RemoveOnlyMultimap<ElementKey, InstantiatedComponent>;
25
26    fn deref(&self) -> &Self::Target {
27        &self.components
28    }
29}
30
31impl DerefMut for Components {
32    fn deref_mut(&mut self) -> &mut Self::Target {
33        &mut self.components
34    }
35}
36
37impl Components {
38    pub fn get_constraints(&self, direction: Direction) -> Vec<Constraint> {
39        self.components
40            .iter()
41            .map(|c| match direction {
42                Direction::Horizontal => c.layout_style.get_width(),
43                Direction::Vertical => c.layout_style.get_height(),
44            })
45            .collect()
46    }
47
48    fn poll_change(&mut self, cx: &mut Context) -> Poll<()> {
49        let mut is_ready = false;
50        for component in self.components.iter_mut() {
51            if component.poll_change(cx).is_ready() {
52                is_ready = true;
53            }
54        }
55
56        if is_ready {
57            Poll::Ready(())
58        } else {
59            Poll::Pending
60        }
61    }
62}
63
64#[doc(hidden)]
65pub struct InstantiatedComponent {
66    key: ElementKey,
67    hooks: Vec<Box<dyn AnyHook>>,
68    component: Box<dyn AnyComponent>,
69    helper: Box<dyn ComponentHelperExt>,
70    children: Components,
71    first_update: bool,
72    layout_style: LayoutStyle,
73    has_transparent_layout: bool,
74}
75
76impl InstantiatedComponent {
77    pub fn new(key: ElementKey, mut props: AnyProps, helper: Box<dyn ComponentHelperExt>) -> Self {
78        let component = helper.new_component(props.borrow());
79        Self {
80            key,
81            hooks: Default::default(),
82            layout_style: LayoutStyle::default(),
83            component,
84            children: Components::default(),
85            helper,
86            first_update: true,
87            has_transparent_layout: false,
88        }
89    }
90
91    pub fn component(&self) -> &dyn AnyComponent {
92        &*self.component
93    }
94
95    pub fn update(
96        &mut self,
97        terminal: &mut dyn UpdaterTerminal,
98        context_stack: &mut ContextStack,
99        mut props: AnyProps,
100    ) {
101        let mut updater = ComponentUpdater::new(
102            self.key.clone(),
103            context_stack,
104            terminal,
105            &mut self.children,
106            &mut self.layout_style,
107        );
108        self.hooks.pre_component_update(&mut updater);
109        self.helper.update_component(
110            &mut self.component,
111            props.borrow(),
112            Hooks::new(&mut self.hooks, self.first_update),
113            &mut updater,
114        );
115        self.hooks.post_component_update(&mut updater);
116        self.first_update = false;
117        self.has_transparent_layout = updater.has_transparent_layout();
118
119        if self.has_transparent_layout {
120            if let Some(child) = self.children.iter().next() {
121                self.layout_style = child.layout_style.clone();
122            } else {
123                self.layout_style = LayoutStyle::default();
124            }
125        }
126    }
127
128    pub fn draw(&mut self, drawer: &mut ComponentDrawer) {
129        let layout_style = &self.layout_style;
130
131        let area = if self.has_transparent_layout {
132            drawer.area
133        } else {
134            layout_style.inner_area(drawer.area)
135        };
136
137        drawer.area = area;
138
139        // 先渲染在计算子组件的areas
140        self.hooks.pre_component_draw(drawer);
141
142        // drawer.ares可能在组件绘制时改变
143        self.component.draw(drawer);
144
145        // 计算子组件的区域
146        let children_areas =
147            self.component
148                .calc_children_areas(&self.children, layout_style, drawer);
149        debug_assert_eq!(
150            children_areas.len(),
151            self.children.components.iter().count(),
152            "calc_children_areas must return one area per child"
153        );
154
155        for (child, area) in self
156            .children
157            .components
158            .iter_mut()
159            .zip(children_areas.iter())
160        {
161            drawer.area = *area;
162            child.draw(drawer);
163        }
164        self.hooks.post_component_draw(drawer);
165    }
166
167    pub(crate) fn poll_change(&mut self, cx: &mut Context) -> Poll<()> {
168        // 三路必须全部 poll,即使前一路已 Ready 也不能短路;否则 Pending 的路
169        // 无法在本轮注册 waker,后续变更会丢唤醒。
170        let component_status = self.component.poll_change(cx);
171        let children_status = self.children.poll_change(cx);
172        let hooks_status = self.hooks.poll_change(cx);
173        if component_status.is_ready() || children_status.is_ready() || hooks_status.is_ready() {
174            Poll::Ready(())
175        } else {
176            Poll::Pending
177        }
178    }
179
180    pub async fn wait(&mut self) {
181        poll_fn(|cx| self.poll_change(cx)).await;
182    }
183}
184
185impl Drop for InstantiatedComponent {
186    fn drop(&mut self) {
187        self.hooks.on_drop();
188    }
189}