ratatui_kit/component/
mod.rs

1use crate::{
2    element::ElementType,
3    hooks::Hooks,
4    props::{AnyProps, Props},
5    render::{ComponentDrawer, ComponentUpdater},
6};
7use std::{any::Any, pin::Pin, task::Context};
8
9mod component_helper;
10pub(crate) use component_helper::{ComponentHelper, ComponentHelperExt};
11
12mod instantiated_component;
13pub(crate) use instantiated_component::{Components, InstantiatedComponent};
14
15pub trait Component: Any + Send + Sync + Unpin {
16    type Props<'a>: Props
17    where
18        Self: 'a;
19
20    fn new(props: &Self::Props<'_>) -> Self;
21
22    fn update(
23        &mut self,
24        _props: &mut Self::Props<'_>,
25        _hooks: Hooks,
26        _updater: &mut ComponentUpdater,
27    ) {
28    }
29
30    fn draw(&mut self, drawer: &mut ComponentDrawer<'_, '_>) {
31        self.render_ref(drawer.area, drawer.frame.buffer_mut());
32    }
33
34    fn poll_change(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> std::task::Poll<()> {
35        std::task::Poll::Pending
36    }
37
38    fn render_ref(&self, _area: ratatui::layout::Rect, _buf: &mut ratatui::buffer::Buffer) {}
39}
40
41pub trait AnyComponent: Any + Send + Sync + Unpin {
42    fn update(&mut self, props: AnyProps, hooks: Hooks, updater: &mut ComponentUpdater);
43
44    fn draw(&mut self, drawer: &mut ComponentDrawer);
45
46    fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> std::task::Poll<()>;
47
48    fn render_ref(&self, area: ratatui::layout::Rect, buf: &mut ratatui::buffer::Buffer);
49}
50
51impl<C> ElementType for C
52where
53    C: Component,
54{
55    type Props<'a> = C::Props<'a>;
56}
57
58impl<C> AnyComponent for C
59where
60    C: Any + Component,
61{
62    fn update(&mut self, mut props: AnyProps, hooks: Hooks, updater: &mut ComponentUpdater) {
63        Component::update(
64            self,
65            unsafe { props.downcast_mut_unchecked() },
66            hooks,
67            updater,
68        );
69    }
70
71    fn draw(&mut self, drawer: &mut ComponentDrawer) {
72        Component::draw(self, drawer);
73    }
74
75    fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> std::task::Poll<()> {
76        Component::poll_change(self, cx)
77    }
78
79    fn render_ref(&self, area: ratatui::layout::Rect, buf: &mut ratatui::buffer::Buffer) {
80        Component::render_ref(self, area, buf);
81    }
82}