rat_ftable/
edit.rs

1//! Extra widgets for inline editing in a table.
2//!
3//! Extra keys while viewing are
4//! * Insert - Insert a row and start the editor widget.
5//! * Delete - Delete row.
6//! * Enter - Start editor widget.
7//! * Double-Click - Start editor widget.
8//! * Down - Append after the last row and start the editor widget.
9//!
10//! Keys while editing are
11//! * Esc - Cancel editing.
12//! * Enter - Commit current edit and edit next/append a row.
13//! * Up/Down - Commit current edit.
14use rat_focus::HasFocus;
15use ratatui::buffer::Buffer;
16use ratatui::layout::Rect;
17
18pub mod table;
19pub mod vec;
20
21/// StatefulWidget alike trait.
22///
23/// This one takes a slice of areas for all the cells in the table,
24/// and renders all input widgets as it needs.
25pub trait TableEditor {
26    /// State associated with the stateful widget.
27    type State: TableEditorState;
28
29    /// Standard render call, but with added areas for each cell.
30    fn render(&self, area: Rect, cell_areas: &[Rect], buf: &mut Buffer, state: &mut Self::State);
31}
32
33/// Trait for the editor widget state
34pub trait TableEditorState: HasFocus {
35    /// Some external context.
36    type Context<'a>;
37    /// Type of data.
38    type Value: Clone;
39    /// Error type.
40    type Err;
41
42    /// Create a fresh value with all the defaults.
43    fn create_value<'a>(&self, ctx: &'a Self::Context<'a>) -> Result<Self::Value, Self::Err>;
44
45    /// Set the current value for the editor.
46    fn set_value<'a>(
47        &mut self,
48        value: Self::Value,
49        ctx: &'a Self::Context<'a>,
50    ) -> Result<(), Self::Err>;
51
52    /// Return the current value from the editor.
53    fn value<'a>(&mut self, ctx: &'a Self::Context<'a>) -> Result<Option<Self::Value>, Self::Err>;
54
55    /// Returns the currently focused column.
56    /// Used to scroll the column to fully visible.
57    fn focused_col(&self) -> Option<usize>;
58
59    /// Allows setting the focus for the editor.
60    fn set_focused_col(&self, col: usize);
61}
62
63/// Editing mode.
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum Mode {
66    View,
67    Edit,
68    Insert,
69}