envision 0.17.0

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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
//! Types for the table component.

use ratatui::layout::Constraint;

use crate::component::cell::{Cell, RowStatus};

/// Trait for types that can be displayed as table rows.
///
/// Implement this trait for your data types to use them with `Table`.
///
/// # Example
///
/// ```rust
/// use envision::component::TableRow;
/// use envision::component::cell::Cell;
///
/// #[derive(Clone)]
/// struct Product {
///     name: String,
///     price: f64,
///     quantity: u32,
/// }
///
/// impl TableRow for Product {
///     fn cells(&self) -> Vec<Cell> {
///         vec![
///             Cell::new(&self.name),
///             Cell::new(format!("${:.2}", self.price)),
///             Cell::uint(self.quantity as u64),
///         ]
///     }
/// }
/// ```
pub trait TableRow: Clone {
    /// Returns the cells for this row, one per column.
    ///
    /// The order of cells should match the order of columns
    /// defined in the table.
    fn cells(&self) -> Vec<Cell>;

    /// Optional row-level status indicator. Default: `RowStatus::None` —
    /// no status column rendered. If any row in the table returns non-None,
    /// the status column is rendered for all rows.
    fn status(&self) -> RowStatus {
        RowStatus::None
    }
}

/// Column definition for a table.
///
/// Columns define the header text, width, and whether the column
/// is sortable.
///
/// # Example
///
/// ```rust
/// use envision::component::Column;
/// use ratatui::layout::Constraint;
///
/// let col = Column::new("Name", Constraint::Length(20)).sortable();
/// assert_eq!(col.header(), "Name");
/// assert!(col.is_sortable());
/// ```
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct Column {
    header: String,
    #[cfg_attr(feature = "serialization", serde(skip))]
    width: Constraint,
    sortable: bool,
    editable: bool,
    visible: bool,
    default_sort: SortDirection,
}

impl Column {
    /// Creates a new column with the given header and width.
    ///
    /// # Width semantics
    ///
    /// `Column::new` takes any `ratatui::layout::Constraint`. The most
    /// common patterns:
    ///
    /// - [`Constraint::Length`] `(n)` — a hard request for exactly `n` cells.
    /// - [`Constraint::Min`] `(n)` — a minimum of `n` cells, growing to fill
    ///   available space. Typical choice for one "flexible" column.
    /// - [`Constraint::Percentage`] `(n)` — `n%` of the resolved area,
    ///   partitioned left-to-right with the other constraints.
    ///
    /// `Length` and `Min` both declare an absolute floor. When the
    /// resolved area is narrower than the declared floor — a `Length(n)`
    /// column that got `<n` cells, or a `Min(n)` column that got `<n`
    /// cells — the column emits a warning (see "Clipping diagnostics").
    /// `Percentage` is a share of the resolved area and has no absolute
    /// floor, so it is never flagged.
    ///
    /// For these three idioms the shorthand constructors
    /// [`Column::fixed`], [`Column::min`], and [`Column::percent`] read
    /// more directly than `Column::new`.
    ///
    /// The column is not sortable by default.
    ///
    /// # Example
    ///
    /// Three-column layout: fixed ID, fixed price, flexible description.
    ///
    /// ```rust
    /// use envision::component::Column;
    /// use ratatui::layout::Constraint;
    ///
    /// let cols = vec![
    ///     Column::new("ID",          Constraint::Length(8)),
    ///     Column::new("Price",       Constraint::Length(10)),
    ///     Column::new("Description", Constraint::Min(20)),
    /// ];
    /// assert_eq!(cols.len(), 3);
    /// assert_eq!(cols[0].width(), Constraint::Length(8));
    /// assert_eq!(cols[2].width(), Constraint::Min(20));
    /// ```
    ///
    /// # Clipping diagnostics
    ///
    /// When a `Length(n)` or `Min(n)` column resolves to fewer than `n`
    /// cells, the column emits a `tracing::warn!` once. Dedup is per
    /// `(column index, area width)`: the warning re-arms when the
    /// terminal is resized. This is best-effort observability — the
    /// table still renders. Enable with the `tracing` feature.
    pub fn new(header: impl Into<String>, width: Constraint) -> Self {
        Self {
            header: header.into(),
            width,
            sortable: false,
            editable: true,
            visible: true,
            default_sort: SortDirection::Ascending,
        }
    }

    /// Makes this column sortable.
    ///
    /// Sortable columns can be sorted by clicking/selecting the header
    /// or using `TableMessage::SortAsc` / `SortDesc` / `SortToggle`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::Column;
    /// use ratatui::layout::Constraint;
    ///
    /// let col = Column::new("Name", Constraint::Length(20)).sortable();
    /// assert!(col.is_sortable());
    /// ```
    pub fn sortable(mut self) -> Self {
        self.sortable = true;
        self
    }

    /// Returns the column header text.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::Column;
    /// use ratatui::layout::Constraint;
    ///
    /// let col = Column::new("Name", Constraint::Length(20));
    /// assert_eq!(col.header(), "Name");
    /// ```
    pub fn header(&self) -> &str {
        &self.header
    }

    /// Returns the column width constraint.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::Column;
    /// use ratatui::layout::Constraint;
    ///
    /// let col = Column::new("Price", Constraint::Length(10));
    /// assert_eq!(col.width(), Constraint::Length(10));
    /// ```
    pub fn width(&self) -> Constraint {
        self.width
    }

    /// Creates a column with a fixed width.
    ///
    /// This is a shorthand for `Column::new(header, Constraint::Length(width))`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::Column;
    ///
    /// let col = Column::fixed("Name", 20);
    /// assert_eq!(col.header(), "Name");
    /// ```
    pub fn fixed(header: impl Into<String>, width: u16) -> Self {
        Self::new(header, Constraint::Length(width))
    }

    /// Creates a column with a minimum width.
    ///
    /// This is a shorthand for `Column::new(header, Constraint::Min(width))`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::Column;
    ///
    /// let col = Column::min("Description", 10);
    /// ```
    pub fn min(header: impl Into<String>, width: u16) -> Self {
        Self::new(header, Constraint::Min(width))
    }

    /// Creates a column that takes a percentage of available width.
    ///
    /// This is a shorthand for `Column::new(header, Constraint::Percentage(percent))`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::Column;
    ///
    /// let col = Column::percent("Status", 25);
    /// ```
    pub fn percent(header: impl Into<String>, percent: u16) -> Self {
        Self::new(header, Constraint::Percentage(percent))
    }

    /// Returns whether this column is sortable.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::Column;
    /// use ratatui::layout::Constraint;
    ///
    /// let col = Column::new("Name", Constraint::Length(20));
    /// assert!(!col.is_sortable());
    ///
    /// let sortable = col.sortable();
    /// assert!(sortable.is_sortable());
    /// ```
    pub fn is_sortable(&self) -> bool {
        self.sortable
    }

    /// Sets whether this column is editable (builder pattern).
    ///
    /// Columns are editable by default. Set to `false` to make a column
    /// read-only in a `DataGrid`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::Column;
    /// use ratatui::layout::Constraint;
    ///
    /// let col = Column::new("ID", Constraint::Length(10)).with_editable(false);
    /// assert!(!col.is_editable());
    /// ```
    pub fn with_editable(mut self, editable: bool) -> Self {
        self.editable = editable;
        self
    }

    /// Returns whether this column is editable.
    ///
    /// Defaults to `true`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::Column;
    /// use ratatui::layout::Constraint;
    ///
    /// let col = Column::new("Name", Constraint::Length(10));
    /// assert!(col.is_editable());
    ///
    /// let read_only = col.with_editable(false);
    /// assert!(!read_only.is_editable());
    /// ```
    pub fn is_editable(&self) -> bool {
        self.editable
    }

    /// Sets whether this column is visible (builder pattern).
    ///
    /// Columns are visible by default. Set to `false` to hide a column
    /// from rendering while preserving its data.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::Column;
    /// use ratatui::layout::Constraint;
    ///
    /// let col = Column::new("Internal", Constraint::Length(10)).with_visible(false);
    /// assert!(!col.is_visible());
    /// ```
    pub fn with_visible(mut self, visible: bool) -> Self {
        self.visible = visible;
        self
    }

    /// Returns whether this column is visible.
    ///
    /// Defaults to `true`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::Column;
    /// use ratatui::layout::Constraint;
    ///
    /// let col = Column::new("Name", Constraint::Length(10));
    /// assert!(col.is_visible());
    ///
    /// let hidden = col.with_visible(false);
    /// assert!(!hidden.is_visible());
    /// ```
    pub fn is_visible(&self) -> bool {
        self.visible
    }

    /// Sets column visibility.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::Column;
    /// use ratatui::layout::Constraint;
    ///
    /// let mut col = Column::new("Internal", Constraint::Length(10));
    /// assert!(col.is_visible());
    /// col.set_visible(false);
    /// assert!(!col.is_visible());
    /// ```
    pub fn set_visible(&mut self, visible: bool) {
        self.visible = visible;
    }

    /// Sets whether this column is editable.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::Column;
    /// use ratatui::layout::Constraint;
    ///
    /// let mut col = Column::new("Name", Constraint::Length(10));
    /// assert!(col.is_editable());
    /// col.set_editable(false);
    /// assert!(!col.is_editable());
    /// ```
    pub fn set_editable(&mut self, editable: bool) {
        self.editable = editable;
    }

    /// Declares this column's natural sort direction. `SortToggle` and
    /// `AddSortToggle` use this when activating the column for the first
    /// time. Default: `Ascending`.
    ///
    /// Use `Descending` for columns where bigger-is-worse (latency,
    /// regression delta, error count).
    ///
    /// # Example
    ///
    /// ```
    /// use envision::component::{Column, SortDirection};
    /// use ratatui::layout::Constraint;
    ///
    /// let c = Column::new("delta", Constraint::Length(10))
    ///     .with_default_sort(SortDirection::Descending);
    /// assert_eq!(c.default_sort(), SortDirection::Descending);
    /// ```
    pub fn with_default_sort(mut self, dir: SortDirection) -> Self {
        self.default_sort = dir;
        self
    }

    /// Returns the column's natural sort direction.
    ///
    /// Defaults to [`SortDirection::Ascending`] for newly constructed
    /// columns; override with [`Column::with_default_sort`] when a column
    /// reads more naturally in descending order (timestamps, percentages,
    /// load counters, etc.).
    ///
    /// # Example
    ///
    /// ```
    /// use envision::component::{Column, SortDirection};
    /// use ratatui::layout::Constraint;
    ///
    /// let asc = Column::new("name", Constraint::Length(10));
    /// assert_eq!(asc.default_sort(), SortDirection::Ascending);
    ///
    /// let desc = Column::new("age", Constraint::Length(8))
    ///     .with_default_sort(SortDirection::Descending);
    /// assert_eq!(desc.default_sort(), SortDirection::Descending);
    /// ```
    pub fn default_sort(&self) -> SortDirection {
        self.default_sort
    }

    /// Sets the width of this column (builder method).
    ///
    /// This is useful for column resizing operations.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::Column;
    /// use ratatui::layout::Constraint;
    ///
    /// let mut col = Column::fixed("Name", 10);
    /// assert_eq!(col.width(), Constraint::Length(10));
    /// col.set_width(Constraint::Length(20));
    /// assert_eq!(col.width(), Constraint::Length(20));
    /// ```
    pub fn set_width(&mut self, width: Constraint) {
        self.width = width;
    }
}

/// Sort direction for table columns.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub enum SortDirection {
    /// Sort in ascending order (A-Z, 0-9).
    #[default]
    Ascending,
    /// Sort in descending order (Z-A, 9-0).
    Descending,
}

impl SortDirection {
    /// Returns the opposite sort direction.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SortDirection;
    ///
    /// assert_eq!(SortDirection::Ascending.toggle(), SortDirection::Descending);
    /// assert_eq!(SortDirection::Descending.toggle(), SortDirection::Ascending);
    /// ```
    pub fn toggle(self) -> Self {
        match self {
            SortDirection::Ascending => SortDirection::Descending,
            SortDirection::Descending => SortDirection::Ascending,
        }
    }
}

/// Pair of (column index, direction) for declarative initial sort.
///
/// Used with `TableState::with_initial_sorts` to bootstrap the table
/// into a sorted state on frame 1.
///
/// # Example
///
/// ```
/// use envision::component::{InitialSort, SortDirection};
/// let s = InitialSort { column: 4, direction: SortDirection::Descending };
/// assert_eq!(s.column, 4);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct InitialSort {
    /// Index of the column to sort by.
    pub column: usize,
    /// Sort direction to apply.
    pub direction: SortDirection,
}

/// Messages that can be sent to a Table component.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TableMessage {
    /// Move selection up by one row.
    Up,
    /// Move selection down by one row.
    Down,
    /// Move selection to the first row.
    First,
    /// Move selection to the last row.
    Last,
    /// Move selection up by a page.
    PageUp(usize),
    /// Move selection down by a page.
    PageDown(usize),
    /// Confirm the current selection.
    Select,

    /// Set the primary sort to this column, ascending. Replaces the entire
    /// sort stack with just this entry.
    #[allow(dead_code)] // Handler lands in Phase 2; allow until then.
    SortAsc(usize),

    /// Set the primary sort to this column, descending. Replaces the entire
    /// sort stack with just this entry.
    #[allow(dead_code)]
    SortDesc(usize),

    /// 2-cycle toggle. Never clears.
    /// - If this column is already the primary sort: flip Asc <-> Desc.
    /// - If this column is not currently in the sort stack: activate it
    ///   using `Column::default_sort()`. Default fallback: `Ascending`.
    #[allow(dead_code)]
    SortToggle(usize),

    /// Drop the primary sort and any tiebreakers. Returns to load order.
    /// (Renamed from `ClearSort` for naming consistency with the rest of
    /// the family. The old `ClearSort` is removed in Phase 2 Task 16.)
    #[allow(dead_code)]
    SortClear,

    /// Drop just one column from the multi-sort stack. The remaining
    /// columns keep their relative order. If the dropped column was
    /// primary, the next tiebreaker is promoted.
    #[allow(dead_code)]
    RemoveSort(usize),

    // ----- NEW tiebreaker family -----
    /// Add this column to the sort stack as a lowest-priority Asc
    /// tiebreaker. If the column is already in the stack, replace its
    /// direction in place -- do not reorder.
    #[allow(dead_code)]
    AddSortAsc(usize),

    /// Add this column to the sort stack as a lowest-priority Desc
    /// tiebreaker. If already in the stack, replace direction in place.
    #[allow(dead_code)]
    AddSortDesc(usize),

    /// Toggle this column's tiebreaker direction. If not in the stack,
    /// add it using `Column::default_sort()`.
    #[allow(dead_code)]
    AddSortToggle(usize),

    /// Increase the width of the column at the given index.
    IncreaseColumnWidth(usize),
    /// Decrease the width of the column at the given index.
    ///
    /// The width will not go below the minimum of 3 characters.
    DecreaseColumnWidth(usize),
    /// Set the filter text for searching rows.
    SetFilter(String),
    /// Clear the filter text.
    ClearFilter,
}

/// Output messages from a Table component.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TableOutput<T: Clone> {
    /// A row was selected (e.g., Enter pressed).
    Selected(T),
    /// The selection changed to a new row index.
    SelectionChanged(usize),
    /// The sort changed.
    Sorted {
        /// The column being sorted by.
        column: usize,
        /// The sort direction.
        direction: SortDirection,
    },
    /// Sort was cleared.
    SortCleared,
    /// The filter text changed.
    FilterChanged(String),
    /// A column was resized.
    ColumnResized {
        /// The column that was resized.
        column: usize,
        /// The new width of the column.
        width: u16,
    },
}