rat_ftable/edit/
table.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//! More general editing in a table.
//!
//! A widget that renders the table and can render
//! an edit-widget on top.
//!
//! __Examples__
//! For examples go to the rat-widget crate.
//! There is `examples/table_edit1.rs`.

use crate::edit::{Editor, EditorState, Mode};
use crate::event::EditOutcome;
use crate::rowselection::RowSelection;
use crate::{Table, TableSelection, TableState};
use log::warn;
use rat_cursor::HasScreenCursor;
use rat_event::util::MouseFlags;
use rat_event::{ct_event, flow, HandleEvent, Outcome, Regular};
use rat_focus::{FocusBuilder, FocusFlag, HasFocus, Navigation};
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::prelude::StatefulWidget;
#[cfg(feature = "unstable-widget-ref")]
use ratatui::widgets::StatefulWidgetRef;

/// Widget that supports row-wise editing of a table.
///
/// It's parameterized with a `Editor` widget, that renders
/// the input line and handles events. The result of event-handling
/// is an [EditOutcome] that can be used to do the actual editing.
#[derive(Debug)]
pub struct EditTable<'a, E>
where
    E: Editor + 'a,
{
    table: Table<'a, RowSelection>,
    editor: E,
}

/// State for EditTable.
///
/// Contains `mode` to differentiate between edit/non-edit.
/// This will lock the focus to the input line while editing.
///
#[derive(Debug)]
pub struct EditTableState<S> {
    /// Editing mode.
    pub mode: Mode,

    /// Backing table.
    pub table: TableState<RowSelection>,
    /// Editor
    pub editor: S,
    /// Focus-flag for the whole editor widget.
    pub editor_focus: FocusFlag,

    pub mouse: MouseFlags,
}

impl<'a, E> EditTable<'a, E>
where
    E: Editor + 'a,
{
    pub fn new(table: Table<'a, RowSelection>, editor: E) -> Self {
        Self { table, editor }
    }
}

#[cfg(feature = "unstable-widget-ref")]
impl<'a, E> StatefulWidgetRef for EditTable<'a, E>
where
    E: Editor + 'a,
{
    type State = EditTableState<E::State>;

    fn render_ref(&self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        self.table.render_ref(area, buf, &mut state.table);

        if state.mode == Mode::Edit || state.mode == Mode::Insert {
            if let Some(row) = state.table.selected() {
                // but it might be out of view
                if let Some((row_area, cell_areas)) = state.table.row_cells(row) {
                    self.editor
                        .render(row_area, &cell_areas, buf, &mut state.editor);
                }
            } else {
                if cfg!(debug_assertions) {
                    warn!("no row selection, not rendering editor");
                }
            }
        }
    }
}

impl<'a, E> StatefulWidget for EditTable<'a, E>
where
    E: Editor + 'a,
{
    type State = EditTableState<E::State>;

    #[allow(clippy::collapsible_else_if)]
    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        self.table.render(area, buf, &mut state.table);

        if state.mode == Mode::Insert || state.mode == Mode::Edit {
            if let Some(row) = state.table.selected() {
                // but it might be out of view
                if let Some((row_area, cell_areas)) = state.table.row_cells(row) {
                    self.editor
                        .render(row_area, &cell_areas, buf, &mut state.editor);
                }
            } else {
                if cfg!(debug_assertions) {
                    warn!("no row selection, not rendering editor");
                }
            }
        }
    }
}

impl<S> Default for EditTableState<S>
where
    S: Default,
{
    fn default() -> Self {
        Self {
            mode: Mode::View,
            table: Default::default(),
            editor: S::default(),
            editor_focus: Default::default(),
            mouse: Default::default(),
        }
    }
}

impl<S> HasFocus for EditTableState<S> {
    fn focus(&self) -> FocusFlag {
        match self.mode {
            Mode::View => self.table.focus(),
            Mode::Edit => self.editor_focus.clone(),
            Mode::Insert => self.editor_focus.clone(),
        }
    }

    fn area(&self) -> Rect {
        self.table.area()
    }

    fn navigable(&self) -> Navigation {
        match self.mode {
            Mode::View => self.table.navigable(),
            Mode::Edit | Mode::Insert => Navigation::Lock,
        }
    }

    fn is_focused(&self) -> bool {
        match self.mode {
            Mode::View => self.table.is_focused(),
            Mode::Edit | Mode::Insert => self.editor_focus.get(),
        }
    }

    fn lost_focus(&self) -> bool {
        match self.mode {
            Mode::View => self.table.is_focused(),
            Mode::Edit | Mode::Insert => self.editor_focus.lost(),
        }
    }

    fn gained_focus(&self) -> bool {
        match self.mode {
            Mode::View => self.table.is_focused(),
            Mode::Edit | Mode::Insert => self.editor_focus.gained(),
        }
    }
}

impl<S> HasScreenCursor for EditTableState<S>
where
    S: HasScreenCursor,
{
    fn screen_cursor(&self) -> Option<(u16, u16)> {
        match self.mode {
            Mode::View => None,
            Mode::Edit | Mode::Insert => self.editor.screen_cursor(),
        }
    }
}

impl<S> EditTableState<S> {
    /// New state.
    pub fn new(editor: S) -> Self {
        Self {
            mode: Mode::View,
            table: TableState::new(),
            editor,
            editor_focus: Default::default(),
            mouse: Default::default(),
        }
    }

    /// New state with a named focus.
    pub fn named(name: &str, editor: S) -> Self {
        Self {
            mode: Mode::View,
            table: TableState::named(name),
            editor,
            mouse: Default::default(),
            editor_focus: Default::default(),
        }
    }
}

impl<S> EditTableState<S>
where
    S: EditorState,
{
    /// Editing is active?
    pub fn is_editing(&self) -> bool {
        self.mode == Mode::Edit || self.mode == Mode::Insert
    }

    /// Is the current edit an insert?
    pub fn is_insert(&self) -> bool {
        self.mode == Mode::Insert
    }

    /// Remove the item at the selected row.
    ///
    /// This doesn't change the actual list of items, but does
    /// all the bookkeeping with the table-state.
    pub fn remove(&mut self, row: usize) {
        if self.mode != Mode::View {
            return;
        }
        self.table.items_removed(row, 1);
        if !self.table.scroll_to_row(row) {
            self.table.scroll_to_row(row.saturating_sub(1));
        }
    }

    /// Edit a new item inserted at the selected row.
    ///
    /// The editor state must be initialized to an appropriate state
    /// beforehand.
    ///
    /// __See__
    /// [EditorState::set_edit_data]
    ///
    /// This does all the bookkeeping with the table-state and
    /// switches the mode to Mode::Insert.
    pub fn edit_new(&mut self, row: usize) {
        if self.mode != Mode::View {
            return;
        }
        self._start(row, Mode::Insert);
    }

    /// Edit the item at the selected row.
    ///
    /// The editor state must be initialized to an appropriate state
    /// beforehand.
    ///
    /// __See__
    /// [EditorState::set_edit_data]
    ///
    /// This does all the bookkeeping with the table-state and
    /// switches the mode to Mode::Edit.
    pub fn edit(&mut self, row: usize) {
        if self.mode != Mode::View {
            return;
        }
        self._start(row, Mode::Edit);
    }

    fn _start(&mut self, pos: usize, mode: Mode) {
        if self.table.is_focused() {
            self.table.focus().set(false);
            self.editor_focus.set(true);
            FocusBuilder::for_container(&self.editor).first();
        }

        self.mode = mode;
        if self.mode == Mode::Insert {
            self.table.items_added(pos, 1);
        }
        self.table.move_to(pos);
        self.table.scroll_to_col(0);
    }

    /// Cancel editing.
    ///
    /// This doesn't reset the edit-widget.
    ///
    /// __See__
    /// [EditorState::set_edit_data]
    ///
    /// But it does all the bookkeeping with the table-state and
    /// switches the mode back to Mode::View.
    pub fn cancel(&mut self) {
        if self.mode == Mode::View {
            return;
        }
        let Some(row) = self.table.selected() else {
            return;
        };
        if self.mode == Mode::Insert {
            self.table.items_removed(row, 1);
        }
        self._stop();
    }

    /// Commit the changes in the editor.
    ///
    /// This doesn't copy the data back from the editor to the
    /// row-item.
    ///
    /// __See__
    /// [EditorState::get_edit_data]
    ///
    /// But it does all the bookkeeping with the table-state and
    /// switches the mode back to Mode::View.
    pub fn commit(&mut self) {
        if self.mode == Mode::View {
            return;
        }
        self._stop();
    }

    fn _stop(&mut self) {
        self.mode = Mode::View;
        if self.editor_focus.get() {
            self.table.focus.set(true);
            self.editor_focus.set(false);
        }
        self.table.scroll_to_col(0);
    }
}

impl<'a, S> HandleEvent<crossterm::event::Event, &'a S::Context<'a>, EditOutcome>
    for EditTableState<S>
where
    S: HandleEvent<crossterm::event::Event, &'a S::Context<'a>, EditOutcome>,
    S: EditorState,
{
    fn handle(&mut self, event: &crossterm::event::Event, ctx: &'a S::Context<'a>) -> EditOutcome {
        if self.mode == Mode::Edit || self.mode == Mode::Insert {
            if self.editor_focus.is_focused() {
                flow!(match self.editor.handle(event, ctx) {
                    EditOutcome::Continue => EditOutcome::Continue,
                    EditOutcome::Unchanged => EditOutcome::Unchanged,
                    r => {
                        if let Some(col) = self.editor.focused_col() {
                            self.table.scroll_to_col(col);
                        }
                        r
                    }
                });

                flow!(match event {
                    ct_event!(keycode press Esc) => {
                        EditOutcome::Cancel
                    }
                    ct_event!(keycode press Enter) => {
                        if self.table.selected() < Some(self.table.rows().saturating_sub(1)) {
                            EditOutcome::CommitAndEdit
                        } else {
                            EditOutcome::CommitAndAppend
                        }
                    }
                    ct_event!(keycode press Up) => {
                        EditOutcome::Commit
                    }
                    ct_event!(keycode press Down) => {
                        EditOutcome::Commit
                    }
                    _ => EditOutcome::Continue,
                });
            }
            EditOutcome::Continue
        } else {
            flow!(match event {
                ct_event!(mouse any for m) if self.mouse.doubleclick(self.table.table_area, m) => {
                    if self.table.cell_at_clicked((m.column, m.row)).is_some() {
                        EditOutcome::Edit
                    } else {
                        EditOutcome::Continue
                    }
                }
                _ => EditOutcome::Continue,
            });

            if self.table.is_focused() {
                flow!(match event {
                    ct_event!(keycode press Insert) => {
                        EditOutcome::Insert
                    }
                    ct_event!(keycode press Delete) => {
                        EditOutcome::Remove
                    }
                    ct_event!(keycode press Enter) | ct_event!(keycode press F(2)) => {
                        EditOutcome::Edit
                    }
                    ct_event!(keycode press Down) => {
                        if let Some((_column, row)) = self.table.selection.lead_selection() {
                            if row == self.table.rows().saturating_sub(1) {
                                EditOutcome::Append
                            } else {
                                EditOutcome::Continue
                            }
                        } else {
                            EditOutcome::Continue
                        }
                    }
                    _ => {
                        EditOutcome::Continue
                    }
                });
            }

            match self.table.handle(event, Regular) {
                Outcome::Continue => EditOutcome::Continue,
                Outcome::Unchanged => EditOutcome::Unchanged,
                Outcome::Changed => EditOutcome::Changed,
            }
        }
    }
}