ratatui_kit/components/
positioned.rs

1use crate::{AnyElement, Component, layout_style::LayoutStyle};
2use ratatui::{
3    layout::{Constraint, Rect},
4    widgets::Clear,
5};
6use ratatui_kit_macros::Props;
7
8#[derive(Default)]
9pub struct Positioned {
10    area: Rect,
11    clear: bool,
12}
13
14#[derive(Default, Props)]
15pub struct PositionedProps<'a> {
16    /// 是否在渲染前清除该区域内容,默认为 false。
17    pub clear: bool,
18    pub x: u16,
19    pub y: u16,
20    pub width: u16,
21    pub height: u16,
22    pub children: Vec<AnyElement<'a>>,
23}
24
25impl Component for Positioned {
26    type Props<'a> = PositionedProps<'a>;
27
28    fn new(props: &Self::Props<'_>) -> Self {
29        Self {
30            area: Rect::new(props.x, props.y, props.width, props.height),
31            clear: props.clear,
32        }
33    }
34
35    fn update(
36        &mut self,
37        props: &mut Self::Props<'_>,
38        _hooks: crate::Hooks,
39        updater: &mut crate::ComponentUpdater,
40    ) {
41        *self = Self {
42            area: Rect::new(props.x, props.y, props.width, props.height),
43            clear: props.clear,
44        };
45
46        updater.update_children(&mut props.children, None);
47        updater.set_layout_style(LayoutStyle {
48            width: Constraint::Length(0),
49            height: Constraint::Length(0),
50            ..Default::default()
51        });
52    }
53
54    fn draw(&mut self, drawer: &mut crate::ComponentDrawer<'_, '_>) {
55        if self.clear {
56            drawer.render_widget(Clear, self.area);
57        }
58        drawer.area = self.area;
59    }
60}