facett-table 0.1.10

facett — generic data-table viewer (columns + string rows, striped grid)
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
//! **facett-table** — a generic **data-table** viewer: named columns + string
//! rows in a striped grid, with cell truncation + a row scroll. Generalised from
//! nornir's warehouse table ("oslo") — but source-agnostic (any `Vec<String>`
//! rows). A [`Facet`]; the consumer formats its cells to strings.

use facett_core::clip::{ClipKind, ClipPayload, CopySource};
use facett_core::effects::FadeTrack;
use facett_core::{Facet, FacetCaps, Semantics, clipboard};
use std::collections::BTreeSet;

/// Hover / selection cross-fade length (seconds) for a row highlight.
const ROW_FADE_SECS: f32 = 0.12;

/// The **warehouse browser** Facet — a multi-table picker + grid / auto bar-chart,
/// generalised from nornir's `src/viz/warehouse_tab.rs` (`WarehouseBrowser`) with
/// the Iceberg/gRPC source abstracted away. See [`warehouse::WarehouseTableView`].
pub mod warehouse;
pub use warehouse::{PreviewTable, WarehouseTableView};

const CELL_MAX: usize = 48;

/// A stable, domain-level identity for a row (FC-5). When present, selection is
/// keyed on this string instead of the visual `row.index()`, so an insert/delete
/// that shifts visual positions does **not** silently move the selection.
pub type RowId = String;

/// A data table: header `columns` + `rows` (each a row of cells).
pub struct Table {
    pub title: String,
    pub columns: Vec<String>,
    pub rows: Vec<Vec<String>>,
    /// Selected row indices (click to toggle). Empty = nothing selected, in
    /// which case `copy()` falls back to copying every row.
    selected: BTreeSet<usize>,
    /// Optional stable per-row identities (FC-5). When non-empty (and aligned to
    /// `rows`), the row's a11y label + identity is keyed on this rather than the
    /// visual index. Empty = fall back to the visual index (back-compatible).
    row_ids: Vec<RowId>,
    /// Uniform scale (drives row height + font); 1.0 = native.
    scale: f32,
    /// Per-row hover + selection fades (injected-clock, FC-7). Painted as a faded
    /// accent fill + selection-glow outline over the egui_extras rows.
    hover_fades: FadeTrack,
    sel_fades: FadeTrack,
}

impl Table {
    pub fn new(title: impl Into<String>, columns: Vec<String>) -> Self {
        Self {
            title: title.into(),
            columns,
            rows: Vec::new(),
            selected: BTreeSet::new(),
            row_ids: Vec::new(),
            scale: 1.0,
            hover_fades: FadeTrack::default(),
            sel_fades: FadeTrack::default(),
        }
    }
    pub fn push_row(&mut self, row: Vec<String>) {
        self.rows.push(row);
    }

    /// Attach **stable row identities** (FC-5), one per row, in row order. When
    /// set, the a11y node label + identity key derive from the `RowId` instead of
    /// the visual position, so re-ordering / inserting / deleting rows keeps each
    /// row's identity stable. Back-compatible: leave unset to key on the index.
    pub fn with_row_ids(mut self, ids: Vec<RowId>) -> Self {
        self.row_ids = ids;
        self
    }

    /// The stable identity of row `i`: its `RowId` if one is set and aligned,
    /// otherwise the visual index as a string. This is what the row's AccessKit
    /// node is labelled + keyed on.
    fn row_identity(&self, i: usize) -> String {
        self.row_ids.get(i).cloned().unwrap_or_else(|| i.to_string())
    }

    /// The unambiguous a11y label for row `i`. Prefixed with `"row: "` so the row
    /// node never collides with a cell's text (egui_extras already emits a node
    /// per cell; an unprefixed label would make `get_by_label` ambiguous when a
    /// cell's text equals the row identity).
    fn row_label(&self, i: usize) -> String {
        format!("row: {}", self.row_identity(i))
    }

    /// Toggle a row's selection (headless-test + click handler entry point).
    pub fn select_row(&mut self, i: usize) {
        if i < self.rows.len() && !self.selected.insert(i) {
            self.selected.remove(&i);
        }
    }
    /// Clear the row selection.
    pub fn clear_selection(&mut self) {
        self.selected.clear();
    }
    /// The currently-selected row indices, in order.
    pub fn selected_rows(&self) -> Vec<usize> {
        self.selected.iter().copied().collect()
    }

    /// The rows that `copy()` would emit: the selection, or all rows if none.
    fn copy_indices(&self) -> Vec<usize> {
        if self.selected.is_empty() {
            (0..self.rows.len()).collect()
        } else {
            self.selected.iter().copied().filter(|&i| i < self.rows.len()).collect()
        }
    }
}

fn truncate(s: &str) -> String {
    if s.chars().count() <= CELL_MAX {
        s.to_string()
    } else {
        let head: String = s.chars().take(CELL_MAX - 1).collect();
        format!("{head}")
    }
}

impl Table {
    /// TSV of the selected rows (or all rows when none selected), header first —
    /// shared by [`Facet::copy`] and [`CopySource`]. `None` for an empty table.
    pub fn copy_tsv(&self) -> Option<String> {
        if self.rows.is_empty() {
            return None;
        }
        let idx = self.copy_indices();
        let rows = idx.into_iter().map(|i| self.rows[i].clone());
        Some(clipboard::rows_to_tsv(&self.columns, rows))
    }
}

// ── typed copy (§16) — the selection (or whole table) as a TSV rectangle ───────
impl CopySource for Table {
    fn copy_kinds(&self) -> &[ClipKind] {
        &[ClipKind::Rows, ClipKind::Text]
    }
    fn copy_payload(&self) -> Option<ClipPayload> {
        self.copy_tsv().map(ClipPayload::Rows)
    }
}

impl Facet for Table {
    fn title(&self) -> &str {
        &self.title
    }
    fn ui(&mut self, ui: &mut egui::Ui) {
        use egui_extras::{Column, TableBuilder};
        let s = self.scale;
        let dt = ui.input(|i| i.stable_dt);
        let th = facett_core::theme(ui);
        ui.label(format!("{} rows × {} cols · {} selected", self.rows.len(), self.columns.len(), self.selected.len()));
        let ncols = self.columns.len().max(1);
        // Collect each visible row's rect + hover/selection so we can paint an
        // injected-clock (FC-7) hover-fill + selection-glow over the rows after the
        // (virtualised) table lays out. `(key, rect, hovered, selected)`.
        let mut row_hi: Vec<(u64, egui::Rect, bool, bool)> = Vec::new();
        let mut tb = TableBuilder::new(ui).striped(true).sense(egui::Sense::click());
        for _ in 0..ncols {
            tb = tb.column(Column::auto().at_least(60.0 * s).resizable(true));
        }
        let mut toggle: Option<usize> = None;
        tb.header(20.0 * s, |mut header| {
            for c in &self.columns {
                header.col(|ui| {
                    ui.strong(c);
                });
            }
        })
        // Virtualised: only the visible rows are built, so a million-row Arrow
        // batch scrolls at 60 fps (render time flat in row count).
        .body(|body| {
            body.rows(18.0 * s, self.rows.len(), |mut row| {
                let i = row.index();
                let is_selected = self.selected.contains(&i);
                row.set_selected(is_selected);
                for cell in &self.rows[i] {
                    row.col(|ui| {
                        ui.label(truncate(cell));
                    });
                }
                let resp = row.response();
                // FC-4 + FC-5: attach a labelled, `selected`-bearing AccessKit
                // node to the ROW's response (the union of its cells). egui_extras
                // emits nodes for the *cells*; without this the selected ROW is not
                // queryable and its toggled state is invisible to a driver / screen
                // reader. The label carries the row's STABLE identity (RowId when
                // set, else the index — FC-5) and is prefixed (`row: …`) so it
                // never collides with a cell's own text node.
                let sem = Semantics::list_item(self.row_label(i), is_selected);
                resp.widget_info(|| sem.widget_info());
                // Note the row for the post-table highlight pass (stable key on the
                // row's identity, FC-5, so the fade follows a row across re-sorts).
                row_hi.push((FadeTrack::key(self.row_label(i)), resp.rect, resp.hovered(), is_selected));
                if resp.clicked() {
                    toggle = Some(i);
                }
            });
        });

        // Whole-row highlight pass: advance the hover/selection fades from this
        // frame's set, then paint a faded accent fill + selection-glow outline over
        // each row. (egui_extras owns the row body, so the highlight rides on top at
        // a low alpha — text stays legible.)
        self.hover_fades.begin();
        self.sel_fades.begin();
        for (key, _, hovered, selected) in &row_hi {
            if *hovered {
                self.hover_fades.lit(*key);
            }
            if *selected {
                self.sel_fades.lit(*key);
            }
        }
        let a = self.hover_fades.advance(dt, ROW_FADE_SECS);
        let b = self.sel_fades.advance(dt, ROW_FADE_SECS);
        {
            let painter = ui.painter();
            for (key, rect, _, _) in &row_hi {
                let hf = self.hover_fades.factor(*key);
                let sf = self.sel_fades.factor(*key);
                if hf > 0.001 {
                    painter.rect_filled(*rect, 2.0, th.accent.linear_multiply((0.10 * hf).min(0.14)));
                }
                if sf > 0.01 {
                    painter.rect_stroke(
                        *rect,
                        2.0,
                        egui::Stroke::new(1.0, th.accent.linear_multiply(0.5 * sf)),
                        egui::StrokeKind::Inside,
                    );
                }
            }
        }
        if a || b {
            ui.ctx().request_repaint();
        }

        if let Some(i) = toggle {
            self.select_row(i);
        }

        // ── render-lane emit: this Facet::ui path RAN ─────────────────────────
        #[cfg(feature = "testmatrix")]
        facett_core::testmatrix::emit(
            "facett-table::Table::ui",
            "ui_render",
            // OK = the view drew the geometry it declares: every selected index is a
            // real row, and a non-empty table has columns to render into.
            self.selected.iter().all(|&i| i < self.rows.len()) && (self.rows.is_empty() || !self.columns.is_empty()),
            &format!("rows={} cols={} selected={}", self.rows.len(), self.columns.len(), self.selected.len()),
        );
    }
    fn state_json(&self) -> serde_json::Value {
        serde_json::json!({
            "columns": self.columns,
            "rows": self.rows.len(),
            "selected": self.selected_rows(),
            "scale": self.scale,
        })
    }

    fn caps(&self) -> FacetCaps {
        // egui_extras' `TableBuilder` + `ui.label/strong` are standard widgets, so
        // they follow the active `Theme`'s `Visuals` (set by `set_theme`).
        FacetCaps::NONE.selectable().copyable().searchable().scalable().resizable().themeable()
    }

    fn scale(&self) -> f32 {
        self.scale
    }
    fn set_scale(&mut self, scale: f32) {
        self.scale = scale.clamp(0.25, 4.0);
    }

    fn selection_json(&self) -> serde_json::Value {
        serde_json::json!(self.selected_rows())
    }

    /// TSV: header row + selected rows (or all rows when none selected),
    /// `\t`-joined cells, `\n` between rows. `None` only for an empty table.
    fn copy(&mut self) -> Option<String> {
        self.copy_tsv()
    }

    // ── cross-instance clone (copy/paste BETWEEN two Tables) ──────────────────

    fn kind(&self) -> &'static str {
        "table"
    }

    /// The portable arrangement: the **column order** (the header sequence), the
    /// **row selection**, and the uniform **scale**. (The row *data* belongs to
    /// each table's own source; this clones how the table is arranged/selected so
    /// a sibling over the same shape mirrors it.)
    fn portable_state(&self) -> Option<serde_json::Value> {
        Some(serde_json::json!({
            "columns": self.columns,
            "selected": self.selected_rows(),
            "scale": self.scale,
        }))
    }

    fn load_state(&mut self, state: &serde_json::Value) -> bool {
        let obj = match state.as_object() {
            Some(o) => o,
            None => return false,
        };
        if let Some(cols) = obj.get("columns").and_then(|v| v.as_array()) {
            self.columns = cols.iter().filter_map(|v| v.as_str().map(|s| s.to_string())).collect();
        }
        if let Some(sel) = obj.get("selected").and_then(|v| v.as_array()) {
            // Only adopt indices that exist in THIS table's rows (a sibling may be
            // shorter); selection is clamped, never out of range.
            self.selected = sel
                .iter()
                .filter_map(|v| v.as_u64().map(|n| n as usize))
                .filter(|&i| i < self.rows.len())
                .collect();
        }
        if let Some(s) = obj.get("scale").and_then(|v| v.as_f64()) {
            self.set_scale(s as f32);
        }
        true
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn truncate_caps_long_cells() {
        assert_eq!(truncate("short"), "short");
        let long = "x".repeat(100);
        let t = truncate(&long);
        assert_eq!(t.chars().count(), CELL_MAX);
        assert!(t.ends_with(''));
    }

    #[test]
    fn state_json_reports_shape() {
        let mut t = Table::new("repos", vec!["name".into(), "version".into()]);
        t.push_row(vec!["knut".into(), "0.1".into()]);
        t.push_row(vec!["korp".into(), "0.1".into()]);
        let j = t.state_json();
        assert_eq!(j["rows"], 2);
        assert_eq!(j["columns"].as_array().unwrap().len(), 2);
    }

    fn repos() -> Table {
        let mut t = Table::new("repos", vec!["name".into(), "version".into()]);
        t.push_row(vec!["knut".into(), "0.1".into()]);
        t.push_row(vec!["korp".into(), "0.2".into()]);
        t
    }

    #[test]
    fn caps_declares_table_surface() {
        let c = repos().caps();
        assert!(c.selectable && c.copyable && c.searchable && c.scalable && c.resizable);
        assert!(!c.pasteable && !c.cuttable);
    }

    #[test]
    fn portable_state_round_trips_columns_selection_scale_between_instances() {
        // A: reordered columns (version first), a row selected, scaled up.
        let mut a = Table::new("repos", vec!["version".into(), "name".into()]);
        a.push_row(vec!["0.1".into(), "knut".into()]);
        a.push_row(vec!["0.2".into(), "korp".into()]);
        a.select_row(1);
        a.set_scale(1.5);

        let env = clipboard::encode_component(a.kind(), &a.portable_state().unwrap());
        let (kind, state) = clipboard::decode_component(&env).unwrap();
        assert_eq!(kind, "table");

        // B starts default-arranged with the same number of rows.
        let mut b = repos(); // 2 rows, columns name/version, no selection, scale 1.0
        assert_ne!(b.portable_state(), a.portable_state(), "differ before paste");
        assert!(b.load_state(&state));
        assert_eq!(b.portable_state(), a.portable_state(), "B mirrors A's column order/selection/scale");
        assert_eq!(b.columns, vec!["version".to_string(), "name".to_string()]);
        assert_eq!(b.selected_rows(), vec![1]);
        assert_eq!(b.scale(), 1.5);
    }

    #[test]
    fn paste_component_clamps_a_selection_out_of_range() {
        // A selects row 5; B has only 2 rows → the stray index is dropped, no panic.
        let a_state = serde_json::json!({ "columns": ["name", "version"], "selected": [5], "scale": 1.0 });
        let mut b = repos();
        assert!(b.load_state(&a_state));
        assert!(b.selected_rows().is_empty(), "out-of-range selection is clamped away");
    }

    #[test]
    fn typed_copy_is_the_selection_as_rows() {
        use facett_core::clip::{ClipKind, CopySource};
        let mut t = repos();
        t.select_row(1);
        let p = t.copy_payload().expect("selection copies");
        assert_eq!(p.kind(), ClipKind::Rows);
        assert_eq!(p.as_text(), "name\tversion\nkorp\t0.2");
        // Empty table offers nothing.
        assert!(Table::new("e", vec!["a".into()]).copy_payload().is_none());
    }

    #[test]
    fn copy_all_rows_when_nothing_selected() {
        let mut t = repos();
        let tsv = t.copy().expect("non-empty table copies");
        assert_eq!(tsv, "name\tversion\nknut\t0.1\nkorp\t0.2");
    }

    #[test]
    fn copy_only_selected_rows() {
        let mut t = repos();
        t.select_row(1);
        let tsv = t.copy().expect("selection copies");
        assert_eq!(tsv, "name\tversion\nkorp\t0.2");
        assert_eq!(t.selection_json(), serde_json::json!([1]));
    }

    #[test]
    fn row_identity_falls_back_to_index_without_row_ids() {
        let t = repos();
        // No row_ids set → identity is the visual index; label is prefixed.
        assert_eq!(t.row_identity(0), "0");
        assert_eq!(t.row_identity(1), "1");
        assert_eq!(t.row_label(0), "row: 0");
    }

    #[test]
    fn with_row_ids_keys_identity_on_stable_id() {
        let t = repos().with_row_ids(vec!["pkg-knut".into(), "pkg-korp".into()]);
        // Identity now derives from the stable RowId, not the visual position.
        assert_eq!(t.row_identity(0), "pkg-knut");
        assert_eq!(t.row_identity(1), "pkg-korp");
        assert_eq!(t.row_label(1), "row: pkg-korp");
        // Selection/copy semantics are unchanged & back-compatible.
        let mut t = t;
        t.select_row(0);
        assert_eq!(t.selected_rows(), vec![0]);
    }

    #[test]
    fn select_row_toggles() {
        let mut t = repos();
        t.select_row(0);
        assert_eq!(t.selected_rows(), vec![0]);
        t.select_row(0);
        assert!(t.selected_rows().is_empty());
    }

    #[test]
    fn cut_falls_back_to_copy_for_read_only_table() {
        let mut t = repos();
        // Table is not cuttable; cut() defaults to copy() (no removal).
        let cut = t.cut().expect("cut delegates to copy");
        assert_eq!(cut, "name\tversion\nknut\t0.1\nkorp\t0.2");
        assert_eq!(t.rows.len(), 2, "cut must not remove rows on a read-only viewer");
    }

    #[test]
    fn paste_is_rejected() {
        let mut t = repos();
        assert!(!t.paste("anything"), "read-only table does not consume paste");
    }

    #[test]
    fn empty_table_copies_nothing() {
        let mut t = Table::new("empty", vec!["a".into()]);
        assert_eq!(t.copy(), None);
    }

    #[test]
    fn set_scale_clamps() {
        let mut t = repos();
        t.set_scale(99.0);
        assert_eq!(t.scale(), 4.0);
        t.set_scale(0.001);
        assert_eq!(t.scale(), 0.25);
        assert_eq!(t.state_json()["scale"], 0.25);
    }
}