fluidattacks-designs 0.11.0

Fluid Attacks design system, GPUI variant: desktop widgets over the shared tokens
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
//! [`TableState`] — the rows, columns and standings an app owns between
//! frames.

use std::collections::{BTreeSet, HashMap};

use fluidattacks_designs_domain::search;
use fluidattacks_designs_domain::table::{
    accepts, all_selected, columns_width, compare, dragged_width, header_pick, searched, shift_run,
    toggle_pick, write_tsv, ColumnKind, Drag, Page, PageCounts, Pick, Sort, DEFAULT_COLUMN_WIDTH,
    ROW_HEIGHT, SELECTION_WIDTH,
};
use gpui::{
    px, App, AppContext as _, ClipboardItem, Context, Entity, FocusHandle, Focusable,
    ListAlignment, ListOffset, ListState, ScrollHandle, SharedString, Window,
};

use crate::text_input::TextInputState;

type Predicate = Box<dyn Fn(&str) -> bool + 'static>;

/// What an arrow hands back when it moves the page: the page now being asked
/// for, so the caller can fetch it. Shared because both arrows carry one.
pub type PageHandler = std::rc::Rc<dyn Fn(Page, &mut App) + 'static>;

type SearchHandler = std::rc::Rc<dyn Fn(&mut TableState, &mut Context<TableState>) + 'static>;
type SortHandler = std::rc::Rc<dyn Fn(&mut TableState, &mut Context<TableState>) + 'static>;
type SelectionHandler = std::rc::Rc<dyn Fn(&mut TableState, &mut Context<TableState>) + 'static>;

/// One column: what it is called, what it holds, and how wide it sits.
pub struct Column {
    pub(crate) id: SharedString,
    pub(crate) header: SharedString,
    pub(crate) kind: ColumnKind,
    pub(crate) width: f32,
    pub(crate) visible: bool,
}

impl Column {
    #[must_use]
    pub fn new(id: impl Into<SharedString>, header: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            header: header.into(),
            kind: ColumnKind::Text,
            width: DEFAULT_COLUMN_WIDTH,
            visible: true,
        }
    }

    /// Declare the column numeric so its cells sort as numbers.
    #[must_use]
    pub const fn kind(mut self, kind: ColumnKind) -> Self {
        self.kind = kind;
        self
    }

    #[must_use]
    pub const fn width(mut self, width: f32) -> Self {
        self.width = width;
        self
    }
}

struct Filter {
    predicate: Predicate,
    negate: bool,
}

/// Where a resize drag started. A drag reports only where the pointer is now,
/// so the width it lands on is measured from here rather than from an edge —
/// the grip straddles two columns, and either edge would give a wrong answer.
struct ResizeOrigin {
    column: usize,
    x: f32,
    width: f32,
}

/// The state a [`super::Table`] renders. Hold it as an entity:
pub struct TableState {
    focus: FocusHandle,
    /// The body's rows, each measured, since a wrapped cell makes its row
    /// taller than the rest.
    list: ListState,
    /// The sideways offset, which the header and the rows share so a column
    /// heading never parts from the cells under it.
    across: ScrollHandle,
    columns: Vec<Column>,
    /// Display order as indices into `columns`, so a reorder never moves the
    /// cells a row holds.
    order: Vec<usize>,
    rows: Vec<Vec<SharedString>>,
    keys: Vec<SharedString>,
    rows_by_key: HashMap<SharedString, usize>,
    /// Row indices surviving the filters, in the order the sort puts them.
    view: Vec<usize>,
    sort: (usize, Sort),
    filters: HashMap<usize, Filter>,
    /// By key, so a sort, a filter, a reload or a page keeps them.
    selection: BTreeSet<SharedString>,
    /// Where a shift-click measures from, a key for the selection's reason.
    anchor: Option<SharedString>,
    multi: bool,
    checkboxes: bool,
    /// Whether the pointer is laying down a run of rows.
    drag: Drag,
    search: Entity<TextInputState>,
    /// The box's text, mirrored here so filtering a row never has to reach
    /// back into an entity it cannot borrow.
    query: SharedString,
    on_search: Option<SearchHandler>,
    on_sort: Option<SortHandler>,
    on_selection: Option<SelectionHandler>,
    resize: Option<ResizeOrigin>,
    page: Page,
    counts: PageCounts,
    sizes_open: bool,
    row_colors: HashMap<usize, u32>,
    cell_colors: HashMap<(usize, usize), u32>,
}

impl TableState {
    /// The window is what the search box needs: it owns an editable field,
    /// and gpui builds those against a window.
    #[must_use]
    pub fn new(columns: Vec<Column>, window: &mut Window, cx: &mut Context<Self>) -> Self {
        let order = (0..columns.len()).collect();
        // the cap belongs on the field, not only on what the filter reads:
        // otherwise the box shows text the search silently ignores
        let search =
            cx.new(|inner| TextInputState::new(window, inner).max_length(search::MAX_LENGTH));
        // the box has no change event, but it notifies; that is the signal
        cx.observe(&search, |table, field, inner| {
            table.search_changed(&field, inner);
        })
        .detach();
        Self {
            focus: cx.focus_handle(),
            // measuring every row, not only those in sight, is what lets the
            // bar and `scroll_to_row` know where a row sits; a page is small.
            // One row's worth is laid out past each edge, so a scroll never
            // shows a row before it is measured
            list: ListState::new(0, ListAlignment::Top, px(ROW_HEIGHT)).measure_all(),
            across: ScrollHandle::new(),
            columns,
            order,
            rows: Vec::new(),
            keys: Vec::new(),
            rows_by_key: HashMap::new(),
            view: Vec::new(),
            sort: (0, Sort::None),
            filters: HashMap::new(),
            selection: BTreeSet::new(),
            anchor: None,
            multi: true,
            checkboxes: false,
            drag: Drag::default(),
            search,
            query: SharedString::default(),
            on_search: None,
            on_sort: None,
            on_selection: None,
            resize: None,
            page: Page::default(),
            counts: PageCounts::default(),
            sizes_open: false,
            row_colors: HashMap::new(),
            cell_colors: HashMap::new(),
        }
    }

    fn search_changed(&mut self, field: &Entity<TextInputState>, cx: &mut Context<Self>) {
        // the field already holds no more than the cap, counted its own way
        let typed = field.read(cx).value().to_owned();
        if self.query == typed {
            return;
        }
        self.query = SharedString::from(typed);
        self.refresh();
        cx.notify();
        // deferred because the handler will almost always call back into this
        // same state, and an entity cannot be updated while it is updating
        if let Some(handler) = self.on_search.clone() {
            let table = cx.entity();
            cx.defer(move |app| table.update(app, |state, inner| handler(state, inner)));
        }
    }

    /// Run `handler` whenever the search box's text changes — the web's
    /// `meta.onSearch`. Only a table paging a source it does not hold needs
    /// one: it reads [`Self::query`] and re-fetches, since the box can only
    /// filter the page in hand.
    pub fn on_search(
        &mut self,
        handler: impl Fn(&mut Self, &mut Context<Self>) + 'static,
    ) -> &mut Self {
        self.on_search = Some(std::rc::Rc::new(handler));
        self
    }

    pub(crate) const fn search_box(&self) -> &Entity<TextInputState> {
        &self.search
    }

    /// The prompt inside the search box (web `searchPlaceholder`).
    pub fn set_search_placeholder(
        &self,
        placeholder: impl Into<SharedString>,
        cx: &mut Context<Self>,
    ) {
        self.search
            .update(cx, |field, inner| field.set_placeholder(placeholder, inner));
    }

    /// What the search box holds, capped at [`search::MAX_LENGTH`].
    #[must_use]
    pub fn query(&self) -> &str {
        &self.query
    }

    /// Let a click select more than one row (default). Turning it off is the
    /// web's `enableMultiRowSelection: false`.
    #[must_use]
    pub const fn multi_select(mut self, multi: bool) -> Self {
        self.multi = multi;
        self
    }

    #[must_use]
    pub const fn selection_column(mut self, checkboxes: bool) -> Self {
        self.checkboxes = checkboxes;
        self
    }

    /// Clears the selection: after a reload a position names another row.
    pub fn set_rows(&mut self, rows: Vec<Vec<SharedString>>, cx: &mut Context<Self>) {
        let keys = (0..rows.len())
            .map(|row| SharedString::from(row.to_string()))
            .collect();
        self.clear_selection(cx);
        self.replace_rows(keys, rows, cx);
    }

    /// Keeps the selection, even keys not among the rows; keys must be unique.
    pub fn set_keyed_rows(
        &mut self,
        rows: Vec<(SharedString, Vec<SharedString>)>,
        cx: &mut Context<Self>,
    ) {
        let (keys, rows) = rows.into_iter().unzip();
        self.replace_rows(keys, rows, cx);
    }

    fn replace_rows(
        &mut self,
        keys: Vec<SharedString>,
        rows: Vec<Vec<SharedString>>,
        cx: &mut Context<Self>,
    ) {
        self.rows_by_key = keys.iter().cloned().zip(0..).collect();
        self.keys = keys;
        self.rows = rows;
        self.row_colors.clear();
        self.cell_colors.clear();
        self.refresh();
        cx.notify();
    }

    /// How many rows survive the filters.
    #[must_use]
    pub const fn visible_rows(&self) -> usize {
        self.view.len()
    }

    /// The cells of every visible row, in view order — Signals'
    /// `get_visible_rows`.
    #[must_use]
    pub fn visible_cells(&self) -> Vec<Vec<SharedString>> {
        self.view
            .iter()
            .filter_map(|&row| self.rows.get(row).cloned())
            .collect()
    }

    pub(crate) fn columns(&self) -> &[Column] {
        &self.columns
    }

    pub(crate) fn order(&self) -> &[usize] {
        &self.order
    }

    pub(crate) fn view(&self) -> &[usize] {
        &self.view
    }

    pub(crate) const fn sort(&self) -> (usize, Sort) {
        self.sort
    }

    /// The column being sorted and which way, or `None` when no column is.
    #[must_use]
    pub fn sorting(&self) -> Option<(&str, Sort)> {
        let (index, sort) = self.sort;
        if sort == Sort::None {
            return None;
        }
        let column = self.columns.get(index)?;
        Some((&column.id, sort))
    }

    pub(crate) const fn list(&self) -> &ListState {
        &self.list
    }

    pub(crate) const fn across_handle(&self) -> &ScrollHandle {
        &self.across
    }

    pub(crate) const fn checkboxes(&self) -> bool {
        self.checkboxes
    }

    pub(crate) const fn multi(&self) -> bool {
        self.multi
    }

    /// How wide a row spans: the checkbox column and every shown column.
    pub(crate) fn row_width(&self) -> f32 {
        columns_width(
            self.checkboxes
                .then_some(SELECTION_WIDTH)
                .into_iter()
                .chain(
                    self.order
                        .iter()
                        .filter_map(|&column| self.columns.get(column))
                        .filter(|entry| entry.visible)
                        .map(|entry| entry.width),
                ),
        )
    }

    pub(crate) fn is_selected(&self, row: usize) -> bool {
        self.keys
            .get(row)
            .is_some_and(|key| self.selection.contains(key))
    }

    pub(crate) fn row_color(&self, row: usize) -> Option<u32> {
        self.row_colors.get(&row).copied()
    }

    pub(crate) fn cell_color(&self, row: usize, column: usize) -> Option<u32> {
        self.cell_colors.get(&(row, column)).copied()
    }

    pub(crate) fn cell(&self, row: usize, column: usize) -> &str {
        self.rows
            .get(row)
            .and_then(|cells| cells.get(column))
            .map_or("", AsRef::as_ref)
    }

    fn column_index(&self, id: &str) -> Option<usize> {
        self.columns.iter().position(|column| column.id == id)
    }

    fn passes(&self, row: usize) -> bool {
        self.matches_query(row)
            && self.filters.iter().all(|(&column, filter)| {
                accepts((filter.predicate)(self.cell(row, column)), filter.negate)
            })
    }

    /// A hidden column cannot answer for a row the reader cannot see it in, so
    /// only the shown ones are offered; whether one match is enough is
    /// [`searched`]'s call.
    fn matches_query(&self, row: usize) -> bool {
        searched(
            &self.query,
            self.order
                .iter()
                .filter(|&&column| self.columns.get(column).is_some_and(|entry| entry.visible))
                .map(|&column| self.cell(row, column)),
        )
    }

    /// Rebuild the visible order from the filters and the sort. The sort is
    /// stable, so rows a column cannot tell apart stay as they arrived.
    fn refresh(&mut self) {
        let mut view: Vec<usize> = (0..self.rows.len())
            .filter(|&row| self.passes(row))
            .collect();
        let (column, sort) = self.sort;
        if sort != Sort::None {
            let kind = self
                .columns
                .get(column)
                .map_or(ColumnKind::Text, |c| c.kind);
            view.sort_by(|&left, &right| {
                sort.apply(compare(
                    kind,
                    self.cell(left, column),
                    self.cell(right, column),
                ))
            });
        }
        self.view = view;
        self.remeasure();
    }

    /// Any row may now stand at another height: its cells changed, or so did
    /// the columns wrapping them. Keeping the rows already there keeps the
    /// reader's place.
    fn remeasure(&self) {
        let held = self.list.item_count();
        let count = self.view.len();
        self.list
            .splice(count.min(held)..held, count.saturating_sub(held));
        self.list.remeasure_items(0..count);
    }
}

/// Sorting.
impl TableState {
    /// Put `column` under `sort`. Sorting one column releases every other, as
    /// the web and Signals both do.
    pub fn sort_by(&mut self, column: &str, sort: Sort, cx: &mut Context<Self>) {
        let Some(index) = self.column_index(column) else {
            return;
        };
        self.sort = (index, sort);
        self.refresh();
        cx.notify();
        self.sorted(cx);
    }

    /// The header click: none becomes ascending, ascending descending, and
    /// descending releases the column.
    pub(crate) fn cycle_sort(&mut self, column: usize, cx: &mut Context<Self>) {
        let (current, sort) = self.sort;
        self.sort = (column, sort.next(current == column));
        self.refresh();
        cx.notify();
        self.sorted(cx);
    }

    /// Run `handler` whenever the sorted column or its direction changes — the
    /// counterpart of [`Self::on_search`], and needed for the same reason:
    /// sorting the rows in hand orders a page, not the set they came from.
    pub fn on_sort(
        &mut self,
        handler: impl Fn(&mut Self, &mut Context<Self>) + 'static,
    ) -> &mut Self {
        self.on_sort = Some(std::rc::Rc::new(handler));
        self
    }

    /// Deferred for the same reason [`Self::search_changed`] defers: the
    /// handler calls back into this state, which cannot be updated while it is
    /// updating.
    fn sorted(&self, cx: &mut Context<Self>) {
        if let Some(handler) = self.on_sort.clone() {
            let table = cx.entity();
            cx.defer(move |app| table.update(app, |state, inner| handler(state, inner)));
        }
    }
}

/// Filtering.
impl TableState {
    /// Keep only the rows whose cell in `column` matches. With `negate`, keep
    /// the ones that do not — Signals' `negative_match`.
    pub fn set_filter(
        &mut self,
        column: &str,
        predicate: impl Fn(&str) -> bool + 'static,
        negate: bool,
        cx: &mut Context<Self>,
    ) {
        let Some(index) = self.column_index(column) else {
            return;
        };
        self.filters.insert(
            index,
            Filter {
                predicate: Box::new(predicate),
                negate,
            },
        );
        self.refresh();
        cx.notify();
    }

    /// Stop filtering on `column`; its rows come back.
    pub fn clear_filter(&mut self, column: &str, cx: &mut Context<Self>) {
        let Some(index) = self.column_index(column) else {
            return;
        };
        self.filters.remove(&index);
        self.refresh();
        cx.notify();
    }
}

/// Selection and the clipboard.
impl TableState {
    /// Positions into the rows last handed over; a key not among them has none.
    #[must_use]
    pub fn selected(&self) -> Vec<usize> {
        (0..self.rows.len())
            .filter(|&row| self.is_selected(row))
            .collect()
    }

    /// Includes keys not among the rows in hand, in no promised order.
    #[must_use]
    pub fn selected_keys(&self) -> Vec<SharedString> {
        self.selection.iter().cloned().collect()
    }

    pub fn set_selected(
        &mut self,
        keys: impl IntoIterator<Item = SharedString>,
        cx: &mut Context<Self>,
    ) {
        self.anchor = None;
        self.reselect(keys.into_iter().collect(), cx);
    }

    pub fn clear_selection(&mut self, cx: &mut Context<Self>) {
        self.set_selected([], cx);
    }

    /// Called once per change, whatever made it.
    pub fn on_selection(
        &mut self,
        handler: impl Fn(&mut Self, &mut Context<Self>) + 'static,
    ) -> &mut Self {
        self.on_selection = Some(std::rc::Rc::new(handler));
        self
    }

    pub(crate) fn toggle_row(&mut self, position: usize, cx: &mut Context<Self>) {
        let Some(&row) = self.view.get(position) else {
            return;
        };
        let pick = toggle_pick(self.is_selected(row), self.multi);
        let next = self.picked(pick, &[row]);
        self.reselect(next, cx);
    }

    pub(crate) fn all_shown_selected(&self) -> bool {
        all_selected(self.view.iter().map(|&row| self.is_selected(row)))
    }

    pub(crate) fn toggle_shown(&mut self, cx: &mut Context<Self>) {
        let pick = header_pick(self.all_shown_selected());
        let next = self.picked(pick, &self.view);
        self.reselect(next, cx);
    }

    fn picked(&self, pick: Pick, rows: &[usize]) -> BTreeSet<SharedString> {
        let keys = rows.iter().filter_map(|&row| self.keys.get(row).cloned());
        match pick {
            Pick::Add => self.selection.iter().cloned().chain(keys).collect(),
            Pick::Only => keys.collect(),
            Pick::Release => {
                let released: BTreeSet<SharedString> = keys.collect();
                self.selection.difference(&released).cloned().collect()
            }
        }
    }

    fn reselect(&mut self, next: BTreeSet<SharedString>, cx: &mut Context<Self>) {
        if next == self.selection {
            return;
        }
        self.selection = next;
        cx.notify();
        // deferred for the reason Self::search_changed gives
        if let Some(handler) = self.on_selection.clone() {
            let table = cx.entity();
            cx.defer(move |app| table.update(app, |state, inner| handler(state, inner)));
        }
    }

    /// A press on the row sitting at `position` in the current view, and the
    /// start of a drag from it. Selection rides the press because that is
    /// where a drag begins; a click arriving after would re-anchor the run it
    /// had just laid down.
    pub(crate) fn press_row(
        &mut self,
        position: usize,
        extend: bool,
        toggle: bool,
        cx: &mut Context<Self>,
    ) {
        let landed = self
            .select_at(position, extend, toggle, cx)
            .then_some(position);
        self.drag = Drag::pressed(self.multi, toggle, landed);
    }

    /// The pointer has reached the row at `position`; `button_held` is whether
    /// it arrived with a button down.
    pub(crate) fn drag_over_row(
        &mut self,
        position: usize,
        button_held: bool,
        cx: &mut Context<Self>,
    ) {
        let Some(moved) = self.drag.reaching(button_held, position) else {
            // the run already ends here, so there is nothing to rebuild and
            // nothing to repaint — which is most of what a drag reports
            return;
        };
        self.drag = moved;
        self.extend_to(position, cx);
    }

    /// The button came up, wherever it did.
    pub(crate) const fn end_row_drag(&mut self) {
        self.drag = Drag::Idle;
    }

    /// Move the selection to `position`, reporting whether a row was there.
    fn select_at(
        &mut self,
        position: usize,
        extend: bool,
        toggle: bool,
        cx: &mut Context<Self>,
    ) -> bool {
        let Some(&row) = self.view.get(position) else {
            return false;
        };
        if self.multi && extend {
            // the anchor stays put: a run of shift-clicks all measure from
            // where the selection started, as every desktop list does
            self.extend_to(position, cx);
            return true;
        }
        let pick = if self.multi && toggle {
            toggle_pick(self.is_selected(row), true)
        } else {
            Pick::Only
        };
        self.anchor = self.keys.get(row).cloned();
        let next = self.picked(pick, &[row]);
        self.reselect(next, cx);
        true
    }

    fn extend_to(&mut self, position: usize, cx: &mut Context<Self>) {
        let anchor = self
            .anchor
            .as_ref()
            .and_then(|key| self.rows_by_key.get(key).copied())
            .and_then(|row| self.position_of(row));
        let Some((first, last)) = shift_run(anchor, position, self.view.len()) else {
            return;
        };
        let next = self.picked(Pick::Only, self.view.get(first..=last).unwrap_or_default());
        self.reselect(next, cx);
    }

    /// Copy the selection as the clipboard's tab-separated grid. Only visible
    /// columns travel, in the order they are shown.
    pub fn copy_selection(&self, cx: &App) {
        let rows: Vec<Vec<&str>> = self
            .view
            .iter()
            .filter(|&&row| self.is_selected(row))
            .map(|&row| self.shown_cells(row))
            .collect();
        if rows.is_empty() {
            return;
        }
        let borrowed: Vec<&[&str]> = rows.iter().map(Vec::as_slice).collect();
        let mut payload = String::new();
        if write_tsv(&borrowed, &mut payload).is_ok() {
            cx.write_to_clipboard(ClipboardItem::new_string(payload));
        }
    }

    fn shown_cells(&self, row: usize) -> Vec<&str> {
        self.order
            .iter()
            .filter(|&&column| self.columns.get(column).is_some_and(|c| c.visible))
            .map(|&column| self.cell(row, column))
            .collect()
    }
}

/// Moving to a row.
impl TableState {
    /// Bring the row at `position` in the current view into sight — Signals'
    /// `scrollTo`.
    pub fn scroll_to_row(&self, position: usize) {
        self.list.scroll_to_reveal_item(position);
    }

    /// The same, and take the keyboard — Signals' `focusOn`.
    pub fn focus_row(&self, position: usize, window: &mut Window, cx: &mut App) {
        self.scroll_to_row(position);
        self.focus.focus(window, cx);
    }

    /// Where a row sits in the current view, if the filters kept it.
    #[must_use]
    pub fn position_of(&self, row: usize) -> Option<usize> {
        self.view.iter().position(|&candidate| candidate == row)
    }
}

/// Columns.
impl TableState {
    /// Show or hide a column. A hidden column keeps its cells, its width and
    /// its place in the order.
    pub fn set_column_visible(&mut self, column: &str, visible: bool, cx: &mut Context<Self>) {
        let Some(index) = self.column_index(column) else {
            return;
        };
        if let Some(entry) = self.columns.get_mut(index) {
            entry.visible = visible;
        }
        // the search asks the shown columns, so hiding one can change which
        // rows survive it
        self.refresh();
        cx.notify();
    }

    #[must_use]
    pub fn is_column_visible(&self, column: &str) -> bool {
        self.column_index(column)
            .and_then(|index| self.columns.get(index))
            .is_some_and(|entry| entry.visible)
    }

    /// Remember what a resize drag is moving, and from where. The pointer
    /// press is the only moment both are known.
    pub fn begin_resize(&mut self, column: usize, x: f32) {
        let width = self
            .columns
            .get(column)
            .map_or(DEFAULT_COLUMN_WIDTH, |entry| entry.width);
        self.resize = Some(ResizeOrigin { column, x, width });
    }

    /// Carry the resize to where the pointer has reached.
    pub fn drag_resize(&mut self, x: f32, cx: &mut Context<Self>) {
        let Some(origin) = self.resize.as_ref() else {
            return;
        };
        let column = origin.column;
        let width = dragged_width(origin.width, origin.x, x);
        if let Some(entry) = self.columns.get_mut(column) {
            entry.width = width;
        }
        self.remeasure();
        cx.notify();
    }

    /// Move the column shown at `from` to the place shown at `to`.
    pub(crate) fn move_column(&mut self, from: usize, to: usize, cx: &mut Context<Self>) {
        if from >= self.order.len() || to >= self.order.len() {
            return;
        }
        let column = self.order.remove(from);
        self.order.insert(to, column);
        cx.notify();
    }
}

/// Paging, server-side.
impl TableState {
    #[must_use]
    pub const fn page(&self) -> Page {
        self.page
    }

    #[must_use]
    pub const fn page_counts(&self) -> PageCounts {
        self.counts
    }

    /// Move to `page` without fetching anything. The arrows call this and then
    /// hand the same page to the caller's handler.
    ///
    /// The offset reset belongs here rather than in [`Self::set_rows`], which
    /// a table polling for fresh rows calls on a timer — that would yank the
    /// reader to the top every few seconds.
    pub fn set_page(&mut self, page: Page, cx: &mut Context<Self>) {
        self.page = page;
        self.list.scroll_to(ListOffset {
            item_ix: 0,
            offset_in_item: px(0.0),
        });
        cx.notify();
    }

    /// Tell the table what the source has said about its size, which is what
    /// the range label reads, what the next arrow obeys, and which page sizes
    /// the footer offers.
    pub fn set_page_counts(&mut self, counts: PageCounts, cx: &mut Context<Self>) {
        self.counts = counts;
        cx.notify();
    }

    pub(crate) const fn sizes_open(&self) -> bool {
        self.sizes_open
    }

    pub(crate) fn toggle_sizes(&mut self, cx: &mut Context<Self>) {
        self.sizes_open = !self.sizes_open;
        cx.notify();
    }

    pub(crate) fn close_sizes(&mut self, cx: &mut Context<Self>) {
        if self.sizes_open {
            self.sizes_open = false;
            cx.notify();
        }
    }

    /// Change the page size, which returns to the first page. Unlike the
    /// arrows this fires no handler: the caller fetches the new first page
    /// itself.
    pub fn set_page_size(&mut self, size: usize, cx: &mut Context<Self>) {
        self.set_page(Page::resized(size), cx);
    }
}

/// Per-row and per-cell color.
impl TableState {
    /// Paint a row's background — Signals' upload status greens and reds.
    ///
    /// Name the shade the light surface wants (`SUCCESS_50` for a row that
    /// went through); the table re-anchors it for the active mode when it
    /// paints, the same as its own fills, and picks the cell color that reads
    /// on whatever it lands on. Nothing here is stored per mode, so a table
    /// tinted once is right in both.
    ///
    /// A row the table does not hold is ignored rather than remembered: a
    /// color kept for a row that never arrives outlives every redraw and only
    /// [`Self::set_rows`] would ever clear it.
    pub fn set_row_color(&mut self, row: usize, color: u32, cx: &mut Context<Self>) {
        if row >= self.rows.len() {
            return;
        }
        self.row_colors.insert(row, color);
        cx.notify();
    }

    /// Paint one cell's background, which wins over its row's. It re-anchors
    /// like [`Self::set_row_color`].
    pub fn set_cell_color(&mut self, row: usize, column: &str, color: u32, cx: &mut Context<Self>) {
        let Some(index) = self.column_index(column) else {
            return;
        };
        if row >= self.rows.len() {
            return;
        }
        self.cell_colors.insert((row, index), color);
        cx.notify();
    }

    pub fn clear_colors(&mut self, cx: &mut Context<Self>) {
        self.row_colors.clear();
        self.cell_colors.clear();
        cx.notify();
    }
}

impl Focusable for TableState {
    fn focus_handle(&self, _: &App) -> FocusHandle {
        self.focus.clone()
    }
}