Skip to main content

rat_ftable2/edit/
widget.rs

1use crate::derive::derive_table_widget;
2use crate::edit::{Mode, TableEditState, TableEditor};
3use crate::selection::RowSelection;
4use crate::table::Table;
5use ratatui_core::buffer::Buffer;
6use ratatui_core::layout::Rect;
7use ratatui_core::widgets::StatefulWidget;
8
9/// Table-widget and inline editor for one table-row.
10///
11/// This widget keeps a `Vec<RowData>` and modifies it.
12///
13/// It's parameterized with an `Editor` widget, that renders
14/// the input-widgets.
15///
16/// See `examples/table2_edit`.
17///
18pub struct TableEdit<'a, T, E>
19where
20    E: TableEditor<T> + 'a,
21{
22    core: Table<'a, &'a T, RowSelection>,
23    editor: E,
24}
25
26impl<'a, T, E> TableEdit<'a, T, E>
27where
28    E: TableEditor<T> + 'a,
29{
30    pub fn new(editor: E) -> Self {
31        Self {
32            core: Default::default(),
33            editor,
34        }
35    }
36
37    derive_table_widget!();
38    derive_table_widget!(REF_T);
39}
40
41impl<'a, 'b, T, E> TableEdit<'a, T, E>
42where
43    E: TableEditor<T> + 'a,
44    'b: 'a,
45{
46    pub fn render(
47        mut self,
48        area: Rect,
49        buf: &mut Buffer,
50        state: &'b mut TableEditState<T, E::State>,
51    ) {
52        self.core = self.core.data(state.data.iter());
53        self.core.render(area, buf, &mut state.table);
54
55        if state.mode == Mode::Insert || state.mode == Mode::Edit {
56            if let Some(row) = state.table.selected() {
57                // but it might be out of view
58                if let Some((row_area, cell_areas)) = state.table.row_cells(row) {
59                    self.editor
60                        .render(row_area, &cell_areas, buf, &mut state.editor);
61                }
62            }
63        }
64    }
65}