envision 0.15.1

A ratatui framework for collaborative TUI development with headless testing support
Documentation
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
//! A data table component with row selection and column sorting.
//!
//! [`Table<T>`] provides a tabular data display with keyboard navigation,
//! row selection, and column sorting capabilities. State is stored in
//! [`TableState<T>`], updated via [`TableMessage`], and produces [`TableOutput`].
//!
//!
//! See also [`DataGrid`](super::DataGrid) for a table with inline cell editing.
//!
//! # Example
//!
//! ```rust
//! use envision::component::{
//!     Column, Component, SortDirection, Table, TableMessage, TableOutput,
//!     TableRow, TableState,
//! };
//! use ratatui::layout::Constraint;
//!
//! // Define your row type
//! #[derive(Clone, Debug, PartialEq)]
//! struct User {
//!     name: String,
//!     email: String,
//! }
//!
//! impl TableRow for User {
//!     fn cells(&self) -> Vec<String> {
//!         vec![self.name.clone(), self.email.clone()]
//!     }
//! }
//!
//! // Create table state
//! let users = vec![
//!     User { name: "Alice".into(), email: "alice@example.com".into() },
//!     User { name: "Bob".into(), email: "bob@example.com".into() },
//! ];
//!
//! let columns = vec![
//!     Column::new("Name", Constraint::Length(15)).sortable(),
//!     Column::new("Email", Constraint::Length(25)),
//! ];
//!
//! let mut state = TableState::new(users, columns);
//!
//! // Navigate down
//! let output = Table::<User>::update(&mut state, TableMessage::Down);
//! assert_eq!(output, Some(TableOutput::SelectionChanged(1)));
//!
//! // Sort by name column
//! let output = Table::<User>::update(&mut state, TableMessage::SortBy(0));
//! assert_eq!(output, Some(TableOutput::Sorted {
//!     column: 0,
//!     direction: SortDirection::Ascending,
//! }));
//! ```

mod render;
mod state;
mod types;

pub use types::{
    Column, SortComparator, SortDirection, TableMessage, TableOutput, TableRow, date_comparator,
    numeric_comparator,
};

use std::marker::PhantomData;

use ratatui::prelude::*;

use super::{Component, EventContext, RenderContext};
use crate::input::{Event, Key};
use crate::scroll::ScrollState;
use crate::theme::Theme;

/// Minimum column width in characters for column resizing.
const MIN_COLUMN_WIDTH: u16 = 3;

/// State for a Table component.
///
/// Holds the rows, columns, selection state, and sort configuration.
#[derive(Clone, Debug)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct TableState<T: TableRow> {
    rows: Vec<T>,
    columns: Vec<Column>,
    selected: Option<usize>,
    sort_columns: Vec<(usize, SortDirection)>,
    display_order: Vec<usize>,
    filter_text: String,
    #[cfg_attr(feature = "serialization", serde(skip))]
    scroll: ScrollState,
}

impl<T: TableRow + PartialEq> PartialEq for TableState<T> {
    fn eq(&self, other: &Self) -> bool {
        self.rows == other.rows
            && self.columns == other.columns
            && self.selected == other.selected
            && self.sort_columns == other.sort_columns
            && self.display_order == other.display_order
            && self.filter_text == other.filter_text
    }
}

impl<T: TableRow> Default for TableState<T> {
    fn default() -> Self {
        Self {
            rows: Vec::new(),
            columns: Vec::new(),
            selected: None,
            sort_columns: Vec::new(),
            display_order: Vec::new(),
            filter_text: String::new(),
            scroll: ScrollState::default(),
        }
    }
}

/// A data table component with row selection and column sorting.
///
/// `Table` displays tabular data with support for keyboard navigation,
/// single row selection, and column sorting. It uses a generic row type
/// that implements the [`TableRow`] trait.
///
/// # Type Parameters
///
/// - `T`: The row data type. Must implement [`TableRow`] and `Clone`.
///
/// # Navigation
///
/// - `Up` / `Down` - Move selection by one row
/// - `First` / `Last` - Jump to beginning/end
/// - `PageUp` / `PageDown` - Move by page size
/// - `Select` - Confirm the current selection
/// - `SortBy(column)` - Sort by the given column
/// - `ClearSort` - Clear the current sort
///
/// # Sorting
///
/// Clicking the same column cycles through: Ascending -> Descending -> None.
/// Only columns marked as `sortable()` can be sorted.
///
/// # Example
///
/// ```rust
/// use envision::component::{
///     Column, Component, Table, TableMessage, TableRow, TableState,
/// };
/// use ratatui::layout::Constraint;
///
/// #[derive(Clone, Debug, PartialEq)]
/// struct Person {
///     name: String,
///     age: u32,
/// }
///
/// impl TableRow for Person {
///     fn cells(&self) -> Vec<String> {
///         vec![self.name.clone(), self.age.to_string()]
///     }
/// }
///
/// let people = vec![
///     Person { name: "Alice".into(), age: 30 },
///     Person { name: "Bob".into(), age: 25 },
/// ];
///
/// let columns = vec![
///     Column::new("Name", Constraint::Length(15)).sortable(),
///     Column::new("Age", Constraint::Length(5)).sortable(),
/// ];
///
/// let mut state = TableState::new(people, columns);
///
/// // Navigate and select
/// Table::<Person>::update(&mut state, TableMessage::Down);
/// let output = Table::<Person>::update(&mut state, TableMessage::Select);
/// // output is Some(TableOutput::Selected(Person { name: "Bob", age: 25 }))
/// ```
pub struct Table<T: TableRow>(PhantomData<T>);

impl<T: TableRow + 'static> Component for Table<T> {
    type State = TableState<T>;
    type Message = TableMessage;
    type Output = TableOutput<T>;

    fn init() -> Self::State {
        TableState::default()
    }

    fn update(state: &mut Self::State, msg: Self::Message) -> Option<Self::Output> {
        match msg {
            TableMessage::SetFilter(ref text) => {
                state.set_filter_text(text);
                return Some(TableOutput::FilterChanged(text.clone()));
            }
            TableMessage::ClearFilter => {
                state.clear_filter();
                return Some(TableOutput::FilterChanged(String::new()));
            }
            _ => {}
        }

        if state.display_order.is_empty() {
            return None;
        }

        let len = state.display_order.len();
        let current = state.selected.unwrap_or(0);

        match msg {
            TableMessage::Up => {
                if current > 0 {
                    let new_index = current - 1;
                    state.selected = Some(new_index);
                    return Some(TableOutput::SelectionChanged(new_index));
                }
            }
            TableMessage::Down => {
                if current < len - 1 {
                    let new_index = current + 1;
                    state.selected = Some(new_index);
                    return Some(TableOutput::SelectionChanged(new_index));
                }
            }
            TableMessage::First => {
                if current != 0 {
                    state.selected = Some(0);
                    return Some(TableOutput::SelectionChanged(0));
                }
            }
            TableMessage::Last => {
                let last = len - 1;
                if current != last {
                    state.selected = Some(last);
                    return Some(TableOutput::SelectionChanged(last));
                }
            }
            TableMessage::PageUp(page_size) => {
                let new_index = current.saturating_sub(page_size);
                if new_index != current {
                    state.selected = Some(new_index);
                    return Some(TableOutput::SelectionChanged(new_index));
                }
            }
            TableMessage::PageDown(page_size) => {
                let new_index = (current + page_size).min(len - 1);
                if new_index != current {
                    state.selected = Some(new_index);
                    return Some(TableOutput::SelectionChanged(new_index));
                }
            }
            TableMessage::Select => {
                if let Some(row) = state.selected_row().cloned() {
                    return Some(TableOutput::Selected(row));
                }
            }
            TableMessage::SortBy(col) => {
                // Check if column exists and is sortable
                if let Some(column) = state.columns.get(col) {
                    if !column.is_sortable() {
                        return None;
                    }

                    // If this column is already the primary sort, toggle direction
                    // If primary ascending -> descending
                    // If primary descending -> clear all
                    // Otherwise, replace all sorts with this column ascending
                    let primary = state.sort_columns.first().copied();
                    match primary {
                        Some((c, SortDirection::Ascending)) if c == col => {
                            state.sort_columns = vec![(col, SortDirection::Descending)];
                            state.rebuild_display_order();
                            return Some(TableOutput::Sorted {
                                column: col,
                                direction: SortDirection::Descending,
                            });
                        }
                        Some((c, SortDirection::Descending)) if c == col => {
                            state.sort_columns.clear();
                            state.rebuild_display_order();
                            return Some(TableOutput::SortCleared);
                        }
                        _ => {
                            state.sort_columns = vec![(col, SortDirection::Ascending)];
                            state.rebuild_display_order();
                            return Some(TableOutput::Sorted {
                                column: col,
                                direction: SortDirection::Ascending,
                            });
                        }
                    }
                }
            }
            TableMessage::AddSort(col) => {
                // Check if column exists and is sortable
                if let Some(column) = state.columns.get(col) {
                    if !column.is_sortable() {
                        return None;
                    }

                    // If the column is already in the sort stack, toggle its direction
                    if let Some(pos) = state.sort_columns.iter().position(|&(c, _)| c == col) {
                        let (_, dir) = state.sort_columns[pos];
                        let new_dir = dir.toggle();
                        state.sort_columns[pos] = (col, new_dir);
                        state.rebuild_display_order();
                        return Some(TableOutput::Sorted {
                            column: col,
                            direction: new_dir,
                        });
                    }

                    // Otherwise, add it as a new tiebreaker
                    state.sort_columns.push((col, SortDirection::Ascending));
                    state.rebuild_display_order();
                    return Some(TableOutput::Sorted {
                        column: col,
                        direction: SortDirection::Ascending,
                    });
                }
            }
            TableMessage::ClearSort => {
                if !state.sort_columns.is_empty() {
                    state.sort_columns.clear();
                    state.rebuild_display_order();
                    return Some(TableOutput::SortCleared);
                }
            }
            TableMessage::IncreaseColumnWidth(col) => {
                if let Some(column) = state.columns.get_mut(col) {
                    if let Constraint::Length(w) = column.width() {
                        let new_width = w.saturating_add(1);
                        column.set_width(Constraint::Length(new_width));
                        return Some(TableOutput::ColumnResized {
                            column: col,
                            width: new_width,
                        });
                    }
                }
            }
            TableMessage::DecreaseColumnWidth(col) => {
                if let Some(column) = state.columns.get_mut(col) {
                    if let Constraint::Length(w) = column.width() {
                        let new_width = w.saturating_sub(1).max(MIN_COLUMN_WIDTH);
                        if new_width != w {
                            column.set_width(Constraint::Length(new_width));
                            return Some(TableOutput::ColumnResized {
                                column: col,
                                width: new_width,
                            });
                        }
                    }
                }
            }
            TableMessage::SetFilter(_) | TableMessage::ClearFilter => {
                unreachable!("handled above")
            }
        }

        None
    }

    fn handle_event(
        state: &Self::State,
        event: &Event,
        ctx: &EventContext,
    ) -> Option<Self::Message> {
        if !ctx.focused || ctx.disabled {
            return None;
        }
        if let Some(key) = event.as_key() {
            let has_shift = key.modifiers.shift();
            match key.code {
                Key::Up | Key::Char('k') => Some(TableMessage::Up),
                Key::Down | Key::Char('j') => Some(TableMessage::Down),
                Key::Home => Some(TableMessage::First),
                Key::End => Some(TableMessage::Last),
                Key::Enter if has_shift => {
                    // Shift+Enter adds the current primary sort column to the sort stack
                    // This is a no-op if there's no selection context for a column
                    None
                }
                Key::Enter => Some(TableMessage::Select),
                Key::Char('+') => {
                    // Increase the width of the currently selected column
                    // Uses the primary sort column index, or column 0 if no sort
                    let col = state.sort_columns.first().map(|&(c, _)| c).unwrap_or(0);
                    Some(TableMessage::IncreaseColumnWidth(col))
                }
                Key::Char('-') => {
                    // Decrease the width of the currently selected column
                    let col = state.sort_columns.first().map(|&(c, _)| c).unwrap_or(0);
                    Some(TableMessage::DecreaseColumnWidth(col))
                }
                _ => None,
            }
        } else {
            None
        }
    }

    fn view(state: &Self::State, ctx: &mut RenderContext<'_, '_>) {
        render::render_table(
            state,
            ctx.frame,
            ctx.area,
            ctx.theme,
            ctx.focused,
            ctx.disabled,
        );
    }
}

#[cfg(test)]
mod filter_tests;
#[cfg(test)]
mod multi_sort_tests;
#[cfg(test)]
mod resize_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod view_tests;