kitchen-ui 0.0.11

Shared UI for GPUI apps (gpui-kit): design tokens, light and dark themes with a contrast-checked accent, widgets, a parameter editor, icon bundling and its test
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
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
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
//! The table every app shows data in: plain columns in (numbers or text, no data-frame library),
//! a header, a column summary that folds down between the header and the rows, and the rows as
//! a virtual list (only those on screen are made).
//!
//! - **Header**: per column a type mark (`#` numbers, `Aa` text), its name, its unit, the sort
//!   mark and, when the app gives roles, a role tag. A click on the name sorts (ascending,
//!   descending, off); a click on the tag is the app's ([`TableEvent::RoleClicked`]). Drag a
//!   header's right edge to resize, double-click it to fit again.
//! - **Summary** (folds down, giving its height back to the rows): missing and unique; numbers
//!   draw a histogram with their minimum and maximum, text its most common values with their
//!   share (or one count when there are many). A click selects the column
//!   ([`TableEvent::Selected`]).
//! - **Rows**: one line each, values in mono, numbers to the right; the header and the summary
//!   follow the rows sideways.
//! - **Columns fill the pane**: each starts at [`TableSpec::min_column_width`] and the spare width
//!   is shared out among those not resized by hand.
//! - **Text never overflows**: every cell, name and value is one line ending in "…"; a header's
//!   full name, unit and type are in its tooltip.
//!
//! Summaries and sorting are computed off the UI thread ([`summarize`], [`sort_order`]: plain
//! functions, for tests and for apps that compute them elsewhere). [`TableSpec`] is the widget's
//! settings as JSON (the same keys as the design prototype).

use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::sync::Arc;

use gpui_kit::assets::IconName;
use gpui_kit::component::tooltip::Tooltip;
use gpui_kit::component::{Icon, Sizable as _, h_flex, v_flex};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
    AnyElement, App, Context, EventEmitter, FontWeight, Hsla, InteractiveElement as _, IntoElement,
    ListHorizontalSizingBehavior, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement as _,
    Render, SharedString, StatefulInteractiveElement as _, Styled as _, Task, UniformListScrollHandle, Window, canvas,
    div, px, relative, uniform_list,
};
use serde::{Deserialize, Serialize};

use crate::theme::{self, color, fonts};

/// One column's values, one per row (`None`: missing).
#[derive(Debug, Clone, PartialEq)]
pub enum Values {
    /// Numbers.
    Number(Vec<Option<f64>>),
    /// Text.
    Text(Vec<Option<SharedString>>),
}

impl Values {
    /// Its rows.
    pub fn len(&self) -> usize {
        match self {
            Values::Number(v) => v.len(),
            Values::Text(v) => v.len(),
        }
    }

    /// No rows.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Numbers, not text.
    pub fn is_number(&self) -> bool {
        matches!(self, Values::Number(_))
    }
}

/// A column: its name, unit and values.
#[derive(Debug, Clone, PartialEq)]
pub struct Column {
    /// Its name.
    pub name: SharedString,
    /// Its unit (`cm`, `µm²`), shown beside the name.
    pub unit: Option<SharedString>,
    /// Its values.
    pub values: Values,
}

impl Column {
    /// A number column.
    pub fn numbers(name: impl Into<SharedString>, values: Vec<Option<f64>>) -> Self {
        Self { name: name.into(), unit: None, values: Values::Number(values) }
    }

    /// A text column.
    pub fn text(name: impl Into<SharedString>, values: Vec<Option<SharedString>>) -> Self {
        Self { name: name.into(), unit: None, values: Values::Text(values) }
    }

    /// With its unit.
    pub fn unit(mut self, unit: impl Into<SharedString>) -> Self {
        self.unit = Some(unit.into());
        self
    }
}

/// A table: its name (shown by the app, not the widget) and its columns, all as long.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct TableData {
    /// Its name.
    pub name: SharedString,
    /// Its columns.
    pub columns: Vec<Column>,
}

impl TableData {
    /// A table of `columns`.
    pub fn new(name: impl Into<SharedString>, columns: Vec<Column>) -> Self {
        Self { name: name.into(), columns }
    }

    /// Its rows (the longest column's length).
    pub fn rows(&self) -> usize {
        self.columns.iter().map(|c| c.values.len()).max().unwrap_or(0)
    }
}

/// The widget's settings; JSON with these keys (each optional: the defaults below).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct TableSpec {
    /// The summary segment unfolded.
    pub summary: bool,
    /// Row numbers on the left (the row's place in the table, not in the sort).
    pub row_numbers: bool,
    /// The role tags in the header (when the app gives roles).
    pub role_tags: bool,
    /// Bars in a number column's histogram.
    pub bins: usize,
    /// A row's height (px).
    pub row_height: f32,
    /// The narrowest a column starts (px); spare width is shared out.
    pub min_column_width: f32,
    /// The row numbers' column (px).
    pub index_width: f32,
    /// The summary segment's height (px).
    pub summary_height: f32,
    /// Most common text values listed (the rest: Other).
    pub top_values: usize,
    /// A text column with more distinct values shows only their count.
    pub many_unique: usize,
    /// Decimals of numbers.
    pub decimals: usize,
    /// Trailing zeros dropped (`1.500` → `1.5`).
    pub trim_zeros: bool,
    /// What a missing value shows.
    pub missing_text: String,
}

impl Default for TableSpec {
    fn default() -> Self {
        Self {
            summary: true,
            row_numbers: true,
            role_tags: true,
            bins: 24,
            row_height: 24.,
            min_column_width: 140.,
            index_width: 52.,
            summary_height: 128.,
            top_values: 3,
            many_unique: 30,
            decimals: 3,
            trim_zeros: true,
            missing_text: "—".into(),
        }
    }
}

impl TableSpec {
    /// `x` as the table shows it.
    pub fn format(&self, x: Option<f64>) -> String {
        match x {
            None => self.missing_text.clone(),
            Some(v) if !v.is_finite() => v.to_string(),
            Some(v) => {
                let s = format!("{v:.*}", self.decimals);
                if self.trim_zeros && s.contains('.') {
                    s.trim_end_matches('0').trim_end_matches('.').to_string()
                } else {
                    s
                }
            }
        }
    }
}

/// What a column's summary draws.
#[derive(Debug, Clone, PartialEq)]
pub enum Shape {
    /// Numbers: counts in equal bins from `min` to `max` (empty: no values).
    #[allow(missing_docs)]
    Histogram { min: f64, max: f64, counts: Vec<usize> },
    /// Text with few values: the most common with their counts; `other` rows hold `others` more.
    #[allow(missing_docs)]
    Top { values: Vec<(SharedString, usize)>, other: usize, others: usize },
    /// Text with many values: only their count is shown (the summary's `unique`).
    Distinct,
}

/// A column's summary.
#[derive(Debug, Clone, PartialEq)]
pub struct ColumnSummary {
    /// Rows in the column.
    pub rows: usize,
    /// Missing values (and non-finite numbers).
    pub missing: usize,
    /// Distinct values.
    pub unique: usize,
    /// What it draws.
    pub shape: Shape,
}

/// Where a table's summaries are computed: on the CPU here by default ([`CpuSummarizer`]), or
/// by a backend the app plugs in ([`TableView::with_summarizer`]): a GPU histogram through
/// kitchen-compute, a data-frame library, a server that already holds the table. A backend may
/// replace only [`Summarizer::histogram`] (the costly part for numbers) or the whole
/// [`Summarizer::summarize`]. Called off the UI thread.
pub trait Summarizer: Send + Sync {
    /// The minimum, the maximum and the counts in `bins` equal bins of a number column's finite
    /// values (`None` when it has none).
    fn histogram(&self, values: &[Option<f64>], bins: usize) -> Option<(f64, f64, Vec<usize>)> {
        cpu_histogram(values, bins)
    }

    /// Every column's summary.
    fn summarize(&self, data: &TableData, spec: &TableSpec) -> Vec<ColumnSummary> {
        data.columns.iter().map(|c| summarize_column(self, &c.values, spec)).collect()
    }
}

/// Summaries on the CPU, in this thread.
#[derive(Debug, Clone, Copy, Default)]
pub struct CpuSummarizer;

impl Summarizer for CpuSummarizer {}

/// Every column's summary on the CPU (blocking: run it off the UI thread for a large table).
pub fn summarize(data: &TableData, spec: &TableSpec) -> Vec<ColumnSummary> {
    CpuSummarizer.summarize(data, spec)
}

/// The CPU histogram [`Summarizer::histogram`] defaults to.
pub fn cpu_histogram(values: &[Option<f64>], bins: usize) -> Option<(f64, f64, Vec<usize>)> {
    let (mut min, mut max, mut any) = (f64::INFINITY, f64::NEG_INFINITY, false);
    for &x in values.iter().flatten().filter(|x| x.is_finite()) {
        min = min.min(x);
        max = max.max(x);
        any = true;
    }
    if !any {
        return None;
    }
    let bins = bins.max(1);
    let mut counts = vec![0; bins];
    let span = if max > min { max - min } else { 1. };
    for &x in values.iter().flatten().filter(|x| x.is_finite()) {
        counts[((((x - min) / span) * bins as f64) as usize).min(bins - 1)] += 1;
    }
    Some((min, max, counts))
}

/// A column's summary, its histogram from `by`.
pub fn summarize_column<S: Summarizer + ?Sized>(by: &S, values: &Values, spec: &TableSpec) -> ColumnSummary {
    let rows = values.len();
    match values {
        Values::Number(v) => {
            let present = v.iter().flatten().filter(|x| x.is_finite()).count();
            let unique =
                v.iter().flatten().filter(|x| x.is_finite()).map(|x| x.to_bits()).collect::<HashSet<_>>().len();
            let (min, max, counts) = by.histogram(v, spec.bins).unwrap_or((0., 0., Vec::new()));
            ColumnSummary { rows, missing: rows - present, unique, shape: Shape::Histogram { min, max, counts } }
        }
        Values::Text(v) => {
            let mut counts: HashMap<&str, usize> = HashMap::new();
            let mut missing = 0;
            for x in v {
                match x {
                    Some(s) => *counts.entry(s.as_ref()).or_default() += 1,
                    None => missing += 1,
                }
            }
            let unique = counts.len();
            let shape = if unique > spec.many_unique {
                Shape::Distinct
            } else {
                let mut all: Vec<(&str, usize)> = counts.into_iter().collect();
                all.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
                let k = spec.top_values.min(all.len());
                let other = all[k..].iter().map(|x| x.1).sum();
                let others = all.len() - k;
                Shape::Top {
                    values: all[..k].iter().map(|(s, n)| (SharedString::from(s.to_string()), *n)).collect(),
                    other,
                    others,
                }
            };
            ColumnSummary { rows, missing, unique, shape }
        }
    }
}

/// The rows in order of column `col` (missing values last, ties in table order).
pub fn sort_order(data: &TableData, col: usize, ascending: bool) -> Vec<usize> {
    let n = data.rows();
    let mut order: Vec<usize> = (0..n).collect();
    let Some(c) = data.columns.get(col) else { return order };
    let flip = |o: std::cmp::Ordering| if ascending { o } else { o.reverse() };
    match &c.values {
        Values::Number(v) => order.sort_by(|&a, &b| match (v.get(a).copied().flatten(), v.get(b).copied().flatten()) {
            (Some(x), Some(y)) => flip(x.total_cmp(&y)),
            (Some(_), None) => std::cmp::Ordering::Less,
            (None, Some(_)) => std::cmp::Ordering::Greater,
            (None, None) => std::cmp::Ordering::Equal,
        }),
        Values::Text(v) => order.sort_by(|&a, &b| match (v.get(a).cloned().flatten(), v.get(b).cloned().flatten()) {
            (Some(x), Some(y)) => flip(x.cmp(&y)),
            (Some(_), None) => std::cmp::Ordering::Less,
            (None, Some(_)) => std::cmp::Ordering::Greater,
            (None, None) => std::cmp::Ordering::Equal,
        }),
    }
    order
}

/// Share of `n` in `of`, as the summary writes it.
fn share(n: usize, of: usize) -> String {
    if of == 0 {
        return "0%".into();
    }
    let p = n as f64 / of as f64 * 100.;
    if n > 0 && p < 1. { "<1%".into() } else { format!("{p:.0}%") }
}

/// What the table tells the app.
#[derive(Debug, Clone, PartialEq)]
pub enum TableEvent {
    /// A column was selected (its summary clicked), or the selection cleared.
    Selected(Option<usize>),
    /// A column's role tag was clicked: the app changes the role ([`TableView::set_roles`]).
    RoleClicked(usize),
}

/// The table view.
pub struct TableView {
    id: SharedString,
    data: Arc<TableData>,
    spec: TableSpec,
    roles: Vec<Option<SharedString>>,
    summaries: Option<Arc<Vec<ColumnSummary>>>,
    order: Option<Arc<Vec<usize>>>,
    sort: Option<(usize, bool)>,
    selected: Option<usize>,
    manual: HashMap<usize, f32>,
    scroll: UniformListScrollHandle,
    width: Rc<Cell<f32>>,
    drag: Option<(usize, f32, f32)>,
    summary_task: Option<Task<()>>,
    sort_task: Option<Task<()>>,
    summarizer: Arc<dyn Summarizer>,
}

impl EventEmitter<TableEvent> for TableView {}

impl TableView {
    /// An empty table; `id` keeps its elements apart from another table's in the same window.
    pub fn new(id: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            data: Arc::new(TableData::default()),
            spec: TableSpec::default(),
            roles: Vec::new(),
            summaries: None,
            order: None,
            sort: None,
            selected: None,
            manual: HashMap::new(),
            scroll: UniformListScrollHandle::new(),
            width: Rc::new(Cell::new(0.)),
            drag: None,
            summary_task: None,
            sort_task: None,
            summarizer: Arc::new(CpuSummarizer),
        }
    }

    /// Computes the summaries with `by` (a backend) instead of the CPU.
    pub fn with_summarizer(mut self, by: Arc<dyn Summarizer>) -> Self {
        self.summarizer = by;
        self
    }

    /// Summaries computed elsewhere (a server's answer, a cache), in column order: shown as they
    /// are, nothing computed here until the data or the bins change.
    pub fn set_summaries(&mut self, summaries: Arc<Vec<ColumnSummary>>, cx: &mut Context<Self>) {
        self.summary_task = None;
        self.summaries = Some(summaries);
        cx.notify();
    }

    /// Shows `data` (its summaries computed off the UI thread); sort, selection and widths reset.
    pub fn set_data(&mut self, data: Arc<TableData>, cx: &mut Context<Self>) {
        if !Arc::ptr_eq(&self.data, &data) {
            self.data = data;
            self.sort = None;
            self.order = None;
            self.selected = None;
            self.manual.clear();
            self.roles.clear();
            self.resummarize(cx);
        }
        cx.notify();
    }

    /// The table shown.
    pub fn data(&self) -> &Arc<TableData> {
        &self.data
    }

    /// The settings (a change of bins or of the text limits computes the summaries again).
    pub fn set_spec(&mut self, spec: TableSpec, cx: &mut Context<Self>) {
        let again = spec.bins != self.spec.bins
            || spec.top_values != self.spec.top_values
            || spec.many_unique != self.spec.many_unique;
        self.spec = spec;
        if again {
            self.resummarize(cx);
        }
        cx.notify();
    }

    /// The settings.
    pub fn spec(&self) -> &TableSpec {
        &self.spec
    }

    /// Each column's role tag, in column order (`None`: no tag).
    pub fn set_roles(&mut self, roles: Vec<Option<SharedString>>, cx: &mut Context<Self>) {
        self.roles = roles;
        cx.notify();
    }

    /// Folds or unfolds the summary.
    pub fn toggle_summary(&mut self, cx: &mut Context<Self>) {
        self.spec.summary = !self.spec.summary;
        cx.notify();
    }

    /// The selected column.
    pub fn selected(&self) -> Option<usize> {
        self.selected
    }

    /// Selects column `col` (or none), as a click on its summary does.
    pub fn select(&mut self, col: Option<usize>, cx: &mut Context<Self>) {
        self.selected = col;
        cx.emit(TableEvent::Selected(col));
        cx.notify();
    }

    /// The summaries, once computed.
    pub fn summaries(&self) -> Option<&Arc<Vec<ColumnSummary>>> {
        self.summaries.as_ref()
    }

    fn resummarize(&mut self, cx: &mut Context<Self>) {
        self.summaries = None;
        let (data, spec, by) = (self.data.clone(), self.spec.clone(), self.summarizer.clone());
        let work = cx.background_executor().spawn(async move { by.summarize(&data, &spec) });
        self.summary_task = Some(cx.spawn(async move |this, cx| {
            let done = work.await;
            let _ = this.update(cx, |t, cx| {
                t.summaries = Some(Arc::new(done));
                cx.notify();
            });
        }));
    }

    /// Sorts by `col` (ascending, then descending, then off), off the UI thread.
    fn cycle_sort(&mut self, col: usize, cx: &mut Context<Self>) {
        self.sort = match self.sort {
            Some((c, true)) if c == col => Some((col, false)),
            Some((c, false)) if c == col => None,
            _ => Some((col, true)),
        };
        let Some((col, up)) = self.sort else {
            self.order = None;
            self.sort_task = None;
            cx.notify();
            return;
        };
        let data = self.data.clone();
        let work = cx.background_executor().spawn(async move { sort_order(&data, col, up) });
        self.sort_task = Some(cx.spawn(async move |this, cx| {
            let order = work.await;
            let _ = this.update(cx, |t, cx| {
                if t.sort == Some((col, up)) {
                    t.order = Some(Arc::new(order));
                    cx.notify();
                }
            });
        }));
        cx.notify();
    }

    /// Column widths: the minimum (or the hand-set width), the spare width of the pane shared out.
    fn widths(&self) -> Vec<f32> {
        let n = self.data.columns.len();
        let base: Vec<f32> =
            (0..n).map(|j| self.manual.get(&j).copied().unwrap_or(self.spec.min_column_width)).collect();
        let index = if self.spec.row_numbers { self.spec.index_width } else { 0. };
        let free = self.width.get() - index - base.iter().sum::<f32>();
        let auto = (0..n).filter(|j| !self.manual.contains_key(j)).count();
        base.iter()
            .enumerate()
            .map(
                |(j, &w)| {
                    if free > 0. && auto > 0 && !self.manual.contains_key(&j) { w + free / auto as f32 } else { w }
                },
            )
            .collect()
    }

    fn data_color() -> Hsla {
        if theme::is_dark() { theme::data(4) } else { theme::data(0) }
    }

    fn header(&self, widths: &[f32], cx: &mut Context<Self>) -> impl IntoElement + use<> {
        let index = self.spec.row_numbers.then(|| {
            div()
                .flex_none()
                .w(px(self.spec.index_width))
                .h(px(32.))
                .px(px(theme::SM))
                .flex()
                .items_center()
                .justify_end()
                .text_xs()
                .font_family(fonts::MONO)
                .text_color(color::text_muted())
                .border_r_1()
                .border_color(color::border())
                .child("#")
        });
        let cells = self.data.columns.iter().enumerate().map(|(j, c)| {
            let mark = if c.values.is_number() { "#" } else { "Aa" };
            let sort = match self.sort {
                Some((s, true)) if s == j => Some(IconName::ChevronUp),
                Some((s, false)) if s == j => Some(IconName::ChevronDown),
                _ => None,
            };
            let role = if self.spec.role_tags { self.roles.get(j).cloned().flatten() } else { None };
            let tip: SharedString = format!(
                "{}{} · {}{}",
                c.name,
                c.unit.as_ref().map(|u| format!(" ({u})")).unwrap_or_default(),
                if c.values.is_number() { "numbers" } else { "text" },
                role.as_ref().map(|r| format!(" · {r}")).unwrap_or_default()
            )
            .into();
            h_flex()
                .id((SharedString::from(format!("{}-head", self.id)), j))
                .relative()
                .flex_none()
                .w(px(widths[j]))
                .h(px(32.))
                .px(px(theme::SM))
                .gap(px(theme::XS))
                .items_center()
                .border_r_1()
                .border_color(color::border())
                .cursor_pointer()
                .hover(|d| d.bg(color::hover()))
                .when(self.selected == Some(j), |d| {
                    d.bg(color::selection()).border_t_2().border_color(color::selection_edge())
                })
                .tooltip(move |window, cx| Tooltip::new(tip.clone()).build(window, cx))
                .on_click(cx.listener(move |this, _, _, cx| {
                    if this.drag.is_none() {
                        this.cycle_sort(j, cx)
                    }
                }))
                .child(
                    div()
                        .flex_none()
                        .w(px(16.))
                        .text_xs()
                        .font_family(fonts::MONO)
                        .font_weight(FontWeight::SEMIBOLD)
                        .text_color(color::text_muted())
                        .child(mark),
                )
                .child(
                    div()
                        .flex_1()
                        .min_w_0()
                        .truncate()
                        .text_sm()
                        .font_weight(FontWeight::SEMIBOLD)
                        .text_color(color::text())
                        .child(c.name.clone()),
                )
                .children(c.unit.clone().map(|u| {
                    div().min_w_0().max_w(relative(0.4)).truncate().text_xs().text_color(color::text_muted()).child(u)
                }))
                .children(sort.map(|i| Icon::new(i).xsmall().text_color(color::accent_mark())))
                .children(role.map(|r| {
                    let on = r.as_ref() != "Other";
                    div()
                        .id((SharedString::from(format!("{}-role", self.id)), j))
                        .flex_none()
                        .max_w(px(72.))
                        .truncate()
                        .px(px(theme::XS))
                        .rounded(px(theme::RADIUS_SM))
                        .border_1()
                        .border_color(if on { color::accent_mark() } else { color::border() })
                        .text_xs()
                        .text_color(if on { color::accent_mark() } else { color::text_muted() })
                        .child(r)
                        .on_click(cx.listener(move |_, _, _, cx| {
                            cx.stop_propagation();
                            cx.emit(TableEvent::RoleClicked(j));
                        }))
                }))
                .child(div().absolute().top_0().bottom_0().right(px(-3.)).w(px(6.)).cursor_col_resize().on_mouse_down(
                    MouseButton::Left,
                    cx.listener(move |this, e: &MouseDownEvent, _, cx| {
                        cx.stop_propagation();
                        if e.click_count >= 2 {
                            this.manual.remove(&j);
                            this.drag = None;
                        } else {
                            let w = this.widths()[j];
                            this.drag = Some((j, e.position.x.as_f32(), w));
                        }
                        cx.notify();
                    }),
                ))
        });
        h_flex().flex_none().children(index).children(cells.collect::<Vec<_>>())
    }

    fn fold_bar(&self, cx: &mut Context<Self>) -> impl IntoElement + use<> {
        let n = self.data.columns.len();
        h_flex()
            .id(SharedString::from(format!("{}-fold", self.id)))
            .flex_none()
            .w_full()
            .h(px(24.))
            .px(px(theme::SM))
            .gap(px(theme::XS))
            .items_center()
            .bg(color::raised())
            .border_t_1()
            .border_color(color::border())
            .cursor_pointer()
            .text_xs()
            .text_color(color::text_muted())
            .hover(|d| d.text_color(color::text()))
            .on_click(cx.listener(|this, _, _, cx| this.toggle_summary(cx)))
            .child(Icon::new(if self.spec.summary { IconName::ChevronDown } else { IconName::ChevronRight }).xsmall())
            .child(div().truncate().child(if self.spec.summary {
                "SUMMARY".to_string()
            } else if self.summaries.is_none() {
                "SUMMARY · computing".to_string()
            } else {
                format!("SUMMARY · {n} columns")
            }))
    }

    fn summary_row(&self, widths: &[f32], cx: &mut Context<Self>) -> impl IntoElement + use<> {
        let h = self.spec.summary_height;
        let index = self.spec.row_numbers.then(|| {
            div()
                .flex_none()
                .w(px(self.spec.index_width))
                .h(px(h))
                .border_r_1()
                .border_t_1()
                .border_color(color::border())
        });
        let sums = self.summaries.clone();
        let cells = self.data.columns.iter().enumerate().map(|(j, c)| {
            let body: AnyElement = match sums.as_ref().and_then(|s| s.get(j)) {
                None => div().text_color(color::text_muted()).child("Computing…").into_any_element(),
                Some(s) => self.summary_body(c, s).into_any_element(),
            };
            v_flex()
                .id((SharedString::from(format!("{}-sum", self.id)), j))
                .flex_none()
                .w(px(widths[j]))
                .h(px(h))
                .p(px(theme::SM))
                .gap(px(theme::XS))
                .overflow_hidden()
                .text_xs()
                .border_r_1()
                .border_t_1()
                .border_color(color::border())
                .cursor_pointer()
                .when(self.selected == Some(j), |d| d.bg(color::selection()))
                .on_click(cx.listener(move |this, _, _, cx| {
                    let next = if this.selected == Some(j) { None } else { Some(j) };
                    this.select(next, cx);
                }))
                .child(body)
        });
        h_flex().flex_none().children(index).children(cells.collect::<Vec<_>>())
    }

    fn summary_body(&self, c: &Column, s: &ColumnSummary) -> impl IntoElement + use<> {
        let kv = |label: &'static str, value: String, warn: bool| {
            h_flex()
                .w_full()
                .gap(px(theme::SM))
                .child(div().flex_none().max_w(relative(0.4)).truncate().text_color(color::text_muted()).child(label))
                .child(
                    div().flex_1().min_w_0().flex().justify_end().child(
                        div()
                            .min_w_0()
                            .truncate()
                            .font_family(fonts::MONO)
                            .text_color(if warn { color::danger() } else { color::text() })
                            .child(value),
                    ),
                )
        };
        let head = v_flex()
            .flex_none()
            .gap(px(2.))
            .child(kv("Missing", format!("{} · {}", s.missing, share(s.missing, s.rows)), s.missing > 0))
            .child(kv("Unique", format!("{} · {}", s.unique, share(s.unique, s.rows)), false));
        let data = Self::data_color();
        let shape: AnyElement = match &s.shape {
            Shape::Histogram { min, max, counts } => {
                let top = counts.iter().copied().max().unwrap_or(0).max(1) as f32;
                let unit = c.unit.as_ref().map(|u| format!(" {u}")).unwrap_or_default();
                v_flex()
                    .flex_1()
                    .min_h_0()
                    .gap(px(2.))
                    .child(
                        h_flex()
                            .flex_1()
                            .min_h(px(16.))
                            .items_end()
                            .gap(px(1.))
                            .border_b_1()
                            .border_color(color::border())
                            .children(
                                counts.iter().map(|&n| {
                                    div().flex_1().min_w_0().h(relative(n as f32 / top)).min_h(px(1.)).bg(data)
                                }),
                            ),
                    )
                    .child(
                        h_flex()
                            .flex_none()
                            .justify_between()
                            .gap(px(theme::SM))
                            .font_family(fonts::MONO)
                            .text_color(color::text_muted())
                            .child(div().min_w_0().truncate().child(format!("{}{unit}", self.spec.format(Some(*min)))))
                            .child(div().min_w_0().truncate().child(format!("{}{unit}", self.spec.format(Some(*max))))),
                    )
                    .into_any_element()
            }
            Shape::Distinct => h_flex()
                .flex_1()
                .justify_center()
                .items_center()
                .gap(px(theme::XS))
                .child(
                    div()
                        .font_family(fonts::MONO)
                        .text_base()
                        .font_weight(FontWeight::SEMIBOLD)
                        .text_color(data)
                        .child(s.unique.to_string()),
                )
                .child(div().text_color(color::text_muted()).child("distinct"))
                .into_any_element(),
            Shape::Top { values, other, others } => {
                let most = values.first().map(|v| v.1).unwrap_or(1).max(1) as f32;
                let line = |label: SharedString, n: usize, frac: f32| {
                    div()
                        .relative()
                        .w_full()
                        .h(px(16.))
                        .rounded(px(theme::RADIUS_SM))
                        .overflow_hidden()
                        .child(
                            div()
                                .absolute()
                                .top_0()
                                .bottom_0()
                                .left_0()
                                .w(relative(frac.clamp(0., 1.)))
                                .bg(data.opacity(0.22)),
                        )
                        .child(
                            h_flex()
                                .relative()
                                .px(px(theme::XS))
                                .gap(px(theme::SM))
                                .child(div().flex_1().min_w_0().truncate().text_color(color::text()).child(label))
                                .child(
                                    div()
                                        .flex_none()
                                        .font_family(fonts::MONO)
                                        .text_color(color::text_muted())
                                        .child(share(n, s.rows)),
                                ),
                        )
                };
                v_flex()
                    .flex_1()
                    .min_h_0()
                    .gap(px(2.))
                    .children(values.iter().map(|(v, n)| line(v.clone(), *n, *n as f32 / most)))
                    .when(*other > 0, |d| {
                        d.child(line(format!("Other ({others})").into(), *other, *other as f32 / s.rows.max(1) as f32))
                    })
                    .into_any_element()
            }
        };
        v_flex().size_full().gap(px(theme::XS)).child(head).child(shape)
    }

    fn rows(&mut self, range: std::ops::Range<usize>, _: &mut Window, _: &mut Context<Self>) -> Vec<AnyElement> {
        let widths = self.widths();
        let rh = self.spec.row_height;
        let index_w = self.spec.row_numbers.then_some(self.spec.index_width);
        let row_w = widths.iter().sum::<f32>() + index_w.unwrap_or(0.);
        let data = self.data.clone();
        let order = self.order.clone();
        range
            .map(|i| {
                let r = order.as_ref().and_then(|o| o.get(i).copied()).unwrap_or(i);
                let cells = data.columns.iter().enumerate().map(|(j, c)| {
                    let (text, missing) = match &c.values {
                        Values::Number(v) => {
                            let x = v.get(r).copied().flatten();
                            (self.spec.format(x), x.is_none())
                        }
                        Values::Text(v) => match v.get(r).cloned().flatten() {
                            Some(s) => (s.to_string(), false),
                            None => (self.spec.missing_text.clone(), true),
                        },
                    };
                    div()
                        .flex_none()
                        .w(px(widths[j]))
                        .h_full()
                        .px(px(theme::SM))
                        .flex()
                        .items_center()
                        .when(c.values.is_number(), |d| d.justify_end())
                        .when(self.selected == Some(j), |d| d.bg(color::selection()))
                        .child(
                            div()
                                .min_w_0()
                                .truncate()
                                .text_color(if missing { color::text_muted() } else { color::text() })
                                .child(text),
                        )
                });
                h_flex()
                    .id(("kitchen-table-row", i))
                    .w(px(row_w))
                    .flex_none()
                    .h(px(rh))
                    .font_family(fonts::MONO)
                    .text_sm()
                    .when(i % 2 == 1, |d| d.bg(color::raised().opacity(0.55)))
                    .hover(|d| d.bg(color::hover()))
                    .children(index_w.map(|w| {
                        div()
                            .flex_none()
                            .w(px(w))
                            .h_full()
                            .px(px(theme::SM))
                            .flex()
                            .items_center()
                            .justify_end()
                            .text_color(color::text_muted())
                            .child(div().truncate().child((r + 1).to_string()))
                    }))
                    .children(cells.collect::<Vec<_>>())
                    .into_any_element()
            })
            .collect()
    }
}

impl Render for TableView {
    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let widths = self.widths();
        let total = widths.iter().sum::<f32>() + if self.spec.row_numbers { self.spec.index_width } else { 0. };
        // The header follows the rows sideways, only as far as the rows themselves can go
        let spare = (total - self.width.get()).max(0.);
        let dx = self.scroll.0.borrow().base_handle.offset().x.as_f32().clamp(-spare, 0.);
        let rows = self.order.as_ref().map(|o| o.len()).unwrap_or_else(|| self.data.rows());
        let header = self.header(&widths, cx);
        let summary = self.spec.summary.then(|| self.summary_row(&widths, cx));
        let fold = self.fold_bar(cx);
        let list = uniform_list(SharedString::from(format!("{}-rows", self.id)), rows, cx.processor(Self::rows))
            .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
            .track_scroll(&self.scroll)
            .flex_1()
            .min_h_0()
            .w_full();
        // The pane's width, measured as it is laid out: columns fill it
        let seen = self.width.clone();
        let entity = cx.entity().downgrade();
        let measure = canvas(
            move |bounds, _, cx| {
                let w = bounds.size.width.as_f32();
                if (seen.get() - w).abs() > 0.5 {
                    seen.set(w);
                    let _ = entity.update(cx, |_, cx| cx.notify());
                }
            },
            |_, _, _, _| {},
        )
        .absolute()
        .top_0()
        .left_0()
        .size_full();
        v_flex()
            .id(SharedString::from(format!("{}-table", self.id)))
            .relative()
            .size_full()
            .min_h_0()
            .overflow_hidden()
            .bg(color::canvas())
            .border_1()
            .border_color(color::border())
            .rounded(px(theme::RADIUS_LG))
            .on_mouse_move(cx.listener(|this, e: &MouseMoveEvent, _, cx| {
                if let Some((j, x0, w0)) = this.drag {
                    this.manual.insert(j, (w0 + e.position.x.as_f32() - x0).max(64.));
                    cx.notify();
                }
            }))
            .on_mouse_up(
                MouseButton::Left,
                cx.listener(|this, _: &MouseUpEvent, _, cx| {
                    if this.drag.take().is_some() {
                        cx.notify();
                    }
                }),
            )
            .child(measure)
            .child(
                div()
                    .flex_none()
                    .w_full()
                    .overflow_hidden()
                    .bg(color::raised())
                    .border_b_1()
                    .border_color(color::border())
                    .child(
                        v_flex()
                            .w(px(total.max(self.width.get())))
                            .ml(px(dx))
                            .child(header)
                            .child(fold)
                            .children(summary),
                    ),
            )
            .child(list)
    }
}

/// The view's own entity, made for `data` (convenience for apps).
pub fn table(id: impl Into<SharedString>, data: Arc<TableData>, cx: &mut App) -> gpui_kit::Entity<TableView> {
    use gpui_kit::AppContext as _;
    cx.new(|cx| {
        let mut t = TableView::new(id);
        t.set_data(data, cx);
        t
    })
}

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

    fn iris_like() -> TableData {
        TableData::new(
            "t",
            vec![
                Column::numbers("x", vec![Some(1.), Some(2.), None, Some(4.), Some(4.)]).unit("cm"),
                Column::text("g", ["a", "b", "a", "c", "a"].iter().map(|s| Some(SharedString::from(*s))).collect()),
            ],
        )
    }

    #[test]
    fn summaries_count_missing_unique_bins_and_top_values() {
        let spec = TableSpec { bins: 3, top_values: 2, ..TableSpec::default() };
        let s = summarize(&iris_like(), &spec);
        assert_eq!((s[0].rows, s[0].missing, s[0].unique), (5, 1, 3));
        assert_eq!(s[0].shape, Shape::Histogram { min: 1., max: 4., counts: vec![1, 1, 2] });
        assert_eq!((s[1].missing, s[1].unique), (0, 3));
        match &s[1].shape {
            Shape::Top { values, other, others } => {
                assert_eq!(values[0], ("a".into(), 3));
                assert_eq!((values.len(), *other, *others), (2, 1, 1));
            }
            other => panic!("{other:?}"),
        }
        // A backend that replaces only the histogram
        struct Fixed;
        impl Summarizer for Fixed {
            fn histogram(&self, _: &[Option<f64>], _: usize) -> Option<(f64, f64, Vec<usize>)> {
                Some((0., 9., vec![7]))
            }
        }
        assert_eq!(
            Fixed.summarize(&iris_like(), &spec)[0].shape,
            Shape::Histogram { min: 0., max: 9., counts: vec![7] }
        );
        assert_eq!(Fixed.summarize(&iris_like(), &spec)[0].missing, 1);
        let many = TableSpec { many_unique: 2, ..spec };
        assert_eq!(summarize(&iris_like(), &many)[1].shape, Shape::Distinct);
    }

    #[test]
    fn sorting_puts_missing_last_both_ways() {
        let t = iris_like();
        assert_eq!(sort_order(&t, 0, true), vec![0, 1, 3, 4, 2]);
        assert_eq!(sort_order(&t, 0, false), vec![3, 4, 1, 0, 2]);
        assert_eq!(sort_order(&t, 1, true), vec![0, 2, 4, 1, 3]);
    }

    #[test]
    fn numbers_format_with_trimmed_zeros_and_the_spec_round_trips() {
        let s = TableSpec::default();
        assert_eq!(s.format(Some(1.5)), "1.5");
        assert_eq!(s.format(Some(2.0)), "2");
        assert_eq!(s.format(None), "—");
        assert_eq!(share(1, 1000), "<1%");
        let json = serde_json::to_string(&s).unwrap();
        assert_eq!(serde_json::from_str::<TableSpec>(&json).unwrap(), s);
        let partial: TableSpec = serde_json::from_str(r#"{"bins": 10}"#).unwrap();
        assert_eq!(partial.bins, 10);
        assert!(partial.summary);
    }
}