kitchen-ui 0.0.12

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
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
//! 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.
//!
//! Options, each off by default ([`TableOptions`], [`TableView::with_options`]):
//!
//! - **Row marks**: a colour per row given by the app ([`TableView::set_row_colors`]), a dot
//!   before the first column (a unit's colour in the plots).
//! - **Toolbar line**: a filter menu on one text column ("All labels ▾") and the row and
//!   selection counts ("279 units · 1 selected"); [`TableEvent::FilterChanged`].
//! - **Selection** of rows, single or multiple (click; shift for a range; ctrl or cmd to add or
//!   remove one), reported as [`TableEvent::RowsSelected`].
//! - **Bar cells**: a number column drawn as a bar over its range inside each cell, in the row's
//!   colour or the accent ([`Column::bar`]).
//! - **Compact**: no header, no summary, no row numbers, the columns sharing the width (a side
//!   list such as "Similar units").
//! - **Summary** per table: open, folded or off ([`SummaryStart`]); off computes none.
//! - **Theming** ([`TableStyle`], its default from the app's theme): density, stripes or grid
//!   lines, header style, numbers in mono or not, selection and hover colours, bar colour.
//!
//! Summaries, sorting and the filter are computed off the UI thread ([`summarize`],
//! [`sort_order`], [`view_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).
//!
//! The table takes plain columns; a kitchen-table table becomes them with the `kitchen-table`
//! feature (`TableData::from_table`).

use std::cell::Cell;
use std::collections::{BTreeSet, 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, ClickEvent, Context, EventEmitter, FontWeight, Hsla, InteractiveElement as _, IntoElement,
    ListHorizontalSizingBehavior, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement as _,
    Render, SharedString, StatefulInteractiveElement as _, Styled as _, Task, TestSupportExt as _,
    UniformListScrollHandle, Window, canvas, div, px, relative, uniform_list,
};
use serde::{Deserialize, Serialize};

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

/// The row marks' column (px).
const MARK_W: f32 = 18.;
/// The toolbar line's height (px).
const TOOLBAR_H: f32 = 34.;

/// 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(_))
    }
}

/// The range a bar cell spans.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BarRange {
    /// From the column's smallest to its largest value.
    Auto,
    /// From `.0` to `.1` (a score from 0 to 1).
    Fixed(f64, f64),
}

/// 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,
    /// Numbers drawn as a bar in each cell over this range (`None`: plain numbers).
    pub bar: Option<BarRange>,
}

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), bar: None }
    }

    /// 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), bar: None }
    }

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

    /// Drawn as bars over its own range (a number column; text ignores it).
    pub fn bar(mut self) -> Self {
        self.bar = Some(BarRange::Auto);
        self
    }

    /// Drawn as bars from `min` to `max`.
    pub fn bar_range(mut self, min: f64, max: f64) -> Self {
        self.bar = Some(BarRange::Fixed(min, max));
        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
                }
            }
        }
    }
}

/// Whether a table has the summary, and how it starts.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum SummaryStart {
    /// Shown, unfolded.
    #[default]
    Open,
    /// Shown folded (its bar only, a click opens it).
    Folded,
    /// No summary: none is computed or shown.
    Off,
}

/// Which rows a click selects.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Selection {
    /// None (rows are not clickable).
    #[default]
    None,
    /// One row at a time.
    Single,
    /// Many: shift selects a range, ctrl or cmd adds or removes one.
    Multiple,
}

/// The toolbar line: a filter menu on one text column and the row and selection counts.
#[derive(Debug, Clone, PartialEq)]
pub struct Toolbar {
    /// The text column the menu filters on.
    pub column: usize,
    /// The menu's first entry, every row ("All labels").
    pub all: SharedString,
    /// What a row is called in the counts ("units").
    pub noun: SharedString,
}

impl Toolbar {
    /// A filter menu on text column `column`.
    pub fn new(column: usize) -> Self {
        Self { column, all: "All".into(), noun: "rows".into() }
    }

    /// The menu's first entry ("All labels").
    pub fn all(mut self, all: impl Into<SharedString>) -> Self {
        self.all = all.into();
        self
    }

    /// What a row is called in the counts ("units").
    pub fn noun(mut self, noun: impl Into<SharedString>) -> Self {
        self.noun = noun.into();
        self
    }
}

/// What a table offers beyond its rows; the default is the plain table (header, open summary,
/// row numbers, no selection).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct TableOptions {
    /// The summary and how it starts.
    pub summary: SummaryStart,
    /// Which rows a click selects.
    pub selection: Selection,
    /// The toolbar line (`None`: no toolbar).
    pub toolbar: Option<Toolbar>,
    /// No header, no summary, no row numbers; the columns share the width (a side list).
    pub compact: bool,
}

impl TableOptions {
    /// With the summary starting as `start`.
    pub fn summary(mut self, start: SummaryStart) -> Self {
        self.summary = start;
        self
    }

    /// With rows selected by a click.
    pub fn selection(mut self, selection: Selection) -> Self {
        self.selection = selection;
        self
    }

    /// With the toolbar line.
    pub fn toolbar(mut self, toolbar: Toolbar) -> Self {
        self.toolbar = Some(toolbar);
        self
    }

    /// Compact (no header, no summary, no row numbers).
    pub fn compact(mut self, compact: bool) -> Self {
        self.compact = compact;
        self
    }
}

/// How tall rows are.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Density {
    /// 4 px shorter than [`TableSpec::row_height`].
    Compact,
    /// [`TableSpec::row_height`].
    #[default]
    Normal,
    /// 8 px taller.
    Comfortable,
}

/// The lines between rows and cells.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Lines {
    /// Every other row tinted.
    #[default]
    Stripes,
    /// A line under each row and between cells.
    Grid,
    /// Neither.
    None,
}

/// How the header looks.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum HeaderStyle {
    /// On the raised tone, names in semibold.
    #[default]
    Raised,
    /// On the table's own ground, names muted.
    Plain,
}

/// What colour bar cells take.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum BarColor {
    /// The row's mark colour (the accent when the row has none).
    #[default]
    Row,
    /// The accent.
    Accent,
}

/// How a table looks. The default follows the app's theme: colours left `None` are the theme's
/// tokens when drawn (so a switch of theme or accent follows).
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct TableStyle {
    /// Row height.
    pub density: Density,
    /// Stripes, grid lines or neither.
    pub lines: Lines,
    /// The header's look.
    pub header: HeaderStyle,
    /// Numbers in proportional figures instead of mono (`false`: mono, as before).
    pub numbers_sans: bool,
    /// Text in the UI font instead of mono (`false`: mono, as before).
    pub text_sans: bool,
    /// Selected rows' colour (`None`: the theme's selection).
    pub selection: Option<Hsla>,
    /// A hovered row's colour (`None`: the theme's hover).
    pub hover: Option<Hsla>,
    /// Bar cells' colour.
    pub bar: BarColor,
}

impl TableStyle {
    /// A row's height for `spec`.
    pub fn row_height(&self, spec: &TableSpec) -> f32 {
        match self.density {
            Density::Compact => (spec.row_height - 4.).max(14.),
            Density::Normal => spec.row_height,
            Density::Comfortable => spec.row_height + 8.,
        }
    }

    fn selection_color(&self) -> Hsla {
        self.selection.unwrap_or_else(color::selection)
    }

    fn hover_color(&self) -> Hsla {
        self.hover.unwrap_or_else(color::hover)
    }
}

/// 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
}

/// The rows a view shows, in order: sorted by `sort` (`(column, ascending)`, as [`sort_order`]),
/// keeping only those whose text column `only.0` reads `only.1` (the toolbar's filter). `None`
/// when neither is asked: every row, in table order.
pub fn view_order(data: &TableData, sort: Option<(usize, bool)>, only: Option<(usize, &str)>) -> Option<Vec<usize>> {
    if sort.is_none() && only.is_none() {
        return None;
    }
    let mut rows = match sort {
        Some((c, up)) => sort_order(data, c, up),
        None => (0..data.rows()).collect(),
    };
    if let Some((c, value)) = only {
        match data.columns.get(c).map(|c| &c.values) {
            Some(Values::Text(t)) => rows.retain(|&r| t.get(r).and_then(|x| x.as_ref()).is_some_and(|x| x == value)),
            _ => rows.clear(),
        }
    }
    Some(rows)
}

/// The distinct values of text column `col`, sorted (the toolbar's menu).
pub fn distinct_text(data: &TableData, col: usize) -> Vec<SharedString> {
    match data.columns.get(col).map(|c| &c.values) {
        Some(Values::Text(t)) => t.iter().flatten().cloned().collect::<BTreeSet<SharedString>>().into_iter().collect(),
        _ => Vec::new(),
    }
}

/// The rows selected after a click on the row shown at `pos` of `order` (`shift`: the range from
/// `anchor`; `toggle`: ctrl or cmd, add or remove the row). Returns the selection and the new
/// anchor.
pub fn click_selection(
    selected: &BTreeSet<usize>,
    anchor: Option<usize>,
    order: &[usize],
    pos: usize,
    mode: Selection,
    shift: bool,
    toggle: bool,
) -> (BTreeSet<usize>, Option<usize>) {
    let Some(&row) = order.get(pos) else { return (selected.clone(), anchor) };
    match mode {
        Selection::None => (selected.clone(), anchor),
        Selection::Single => {
            if toggle && selected.contains(&row) {
                (BTreeSet::new(), None)
            } else {
                (BTreeSet::from([row]), Some(row))
            }
        }
        Selection::Multiple => {
            if shift && let Some(from) = anchor.and_then(|a| order.iter().position(|&r| r == a)) {
                let (lo, hi) = if from <= pos { (from, pos) } else { (pos, from) };
                let mut out = if toggle { selected.clone() } else { BTreeSet::new() };
                out.extend(order[lo..=hi].iter().copied());
                (out, anchor)
            } else if toggle {
                let mut out = selected.clone();
                if !out.remove(&row) {
                    out.insert(row);
                }
                (out, Some(row))
            } else {
                (BTreeSet::from([row]), Some(row))
            }
        }
    }
}

/// The range a bar column spans (`None`: no finite values).
fn bar_range(c: &Column) -> Option<(f64, f64)> {
    match (c.bar?, &c.values) {
        (BarRange::Fixed(lo, hi), Values::Number(_)) => Some((lo, hi)),
        (BarRange::Auto, Values::Number(v)) => {
            let finite = v.iter().flatten().copied().filter(|x| x.is_finite());
            let (lo, hi) = finite.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), x| (lo.min(x), hi.max(x)));
            // A bar starts at zero when every value is on one side of it
            (lo <= hi).then(|| (lo.min(0.), hi.max(0.)))
        }
        _ => None,
    }
}

/// How much of a bar over `range` `x` fills.
fn bar_fraction(x: f64, (lo, hi): (f64, f64)) -> f32 {
    if hi > lo { ((x - lo) / (hi - lo)).clamp(0., 1.) as f32 } else { 1. }
}

/// 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 rows selected by a click (rows of the table, ascending; empty: none).
    RowsSelected(Vec<usize>),
    /// The toolbar's filter was picked (`None`: every row).
    FilterChanged(Option<SharedString>),
}

/// The table view.
pub struct TableView {
    id: SharedString,
    data: Arc<TableData>,
    spec: TableSpec,
    options: TableOptions,
    style: TableStyle,
    roles: Vec<Option<SharedString>>,
    summaries: Option<Arc<Vec<ColumnSummary>>>,
    order: Option<Arc<Vec<usize>>>,
    order_gen: u64,
    sort: Option<(usize, bool)>,
    filter: Option<SharedString>,
    filter_values: Vec<SharedString>,
    row_colors: Arc<Vec<Option<Hsla>>>,
    bar_ranges: Vec<Option<(f64, f64)>>,
    selected_rows: BTreeSet<usize>,
    anchor: Option<usize>,
    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(),
            options: TableOptions::default(),
            style: TableStyle::default(),
            roles: Vec::new(),
            summaries: None,
            order: None,
            order_gen: 0,
            sort: None,
            filter: None,
            filter_values: Vec::new(),
            row_colors: Arc::new(Vec::new()),
            bar_ranges: Vec::new(),
            selected_rows: BTreeSet::new(),
            anchor: 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();
    }

    /// With `options` (set before the data; [`TableView::set_options`] later).
    pub fn with_options(mut self, options: TableOptions) -> Self {
        self.spec.summary = options.summary == SummaryStart::Open;
        self.options = options;
        self
    }

    /// With `style`.
    pub fn with_style(mut self, style: TableStyle) -> Self {
        self.style = style;
        self
    }

    /// Changes the options: the summary starts again as they say, the toolbar's filter clears.
    pub fn set_options(&mut self, options: TableOptions, cx: &mut Context<Self>) {
        self.spec.summary = options.summary == SummaryStart::Open;
        self.options = options;
        self.filter = None;
        self.filter_values =
            self.options.toolbar.as_ref().map(|t| distinct_text(&self.data, t.column)).unwrap_or_default();
        // Summaries the old options did not compute (off, or compact)
        if self.summaries.is_none() && self.summary_task.is_none() {
            self.resummarize(cx);
        }
        self.refresh_order(cx);
    }

    /// The options.
    pub fn options(&self) -> &TableOptions {
        &self.options
    }

    /// Changes the style.
    pub fn set_style(&mut self, style: TableStyle, cx: &mut Context<Self>) {
        self.style = style;
        cx.notify();
    }

    /// The style.
    pub fn style(&self) -> &TableStyle {
        &self.style
    }

    /// Each row's mark colour, in table order (`None`: no mark). Set it again with new data.
    pub fn set_row_colors(&mut self, colors: Vec<Option<Hsla>>, cx: &mut Context<Self>) {
        self.row_colors = Arc::new(colors);
        cx.notify();
    }

    /// The selected rows (rows of the table, ascending).
    pub fn selected_rows(&self) -> Vec<usize> {
        self.selected_rows.iter().copied().collect()
    }

    /// Selects `rows` (rows of the table), as the app decides; no event is sent.
    pub fn set_selected_rows(&mut self, rows: impl IntoIterator<Item = usize>, cx: &mut Context<Self>) {
        self.selected_rows = rows.into_iter().collect();
        self.anchor = self.selected_rows.first().copied();
        cx.notify();
    }

    /// The toolbar's filter (`None`: every row).
    pub fn filter(&self) -> Option<&SharedString> {
        self.filter.as_ref()
    }

    /// Filters the rows to those whose toolbar column reads `value` (`None`: every row); no
    /// event is sent.
    pub fn set_filter(&mut self, value: Option<SharedString>, cx: &mut Context<Self>) {
        self.filter = value;
        self.refresh_order(cx);
    }

    /// The values the toolbar's menu offers (after its "All" entry).
    pub fn filter_values(&self) -> &[SharedString] {
        &self.filter_values
    }

    /// The rows shown, in the order shown (the sort and the filter applied).
    pub fn shown_rows(&self) -> Vec<usize> {
        match &self.order {
            Some(o) => o.as_ref().clone(),
            None => (0..self.data.rows()).collect(),
        }
    }

    /// A click on the row shown at `pos` (`shift`: a range; `toggle`: ctrl or cmd), as a mouse
    /// click does; reports the selection.
    pub fn click_row(&mut self, pos: usize, shift: bool, toggle: bool, cx: &mut Context<Self>) {
        if self.options.selection == Selection::None {
            return;
        }
        let order = self.shown_rows();
        let (rows, anchor) =
            click_selection(&self.selected_rows, self.anchor, &order, pos, self.options.selection, shift, toggle);
        self.selected_rows = rows;
        self.anchor = anchor;
        cx.emit(TableEvent::RowsSelected(self.selected_rows()));
        cx.notify();
    }

    fn pick_filter(&mut self, i: usize, cx: &mut Context<Self>) {
        let value = i.checked_sub(1).and_then(|k| self.filter_values.get(k).cloned());
        if value != self.filter {
            self.set_filter(value.clone(), cx);
            cx.emit(TableEvent::FilterChanged(value));
        }
    }

    /// Shows `data` (its summaries computed off the UI thread); sort, row selection and widths
    /// reset; the toolbar's filter stays when the new data has its value.
    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.selected_rows.clear();
            self.anchor = None;
            self.manual.clear();
            self.roles.clear();
            self.bar_ranges = self.data.columns.iter().map(bar_range).collect();
            self.filter_values =
                self.options.toolbar.as_ref().map(|t| distinct_text(&self.data, t.column)).unwrap_or_default();
            if self.filter.as_ref().is_some_and(|f| !self.filter_values.contains(f)) {
                self.filter = None;
            }
            self.resummarize(cx);
            self.refresh_order(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 (none when the options turn it off).
    pub fn toggle_summary(&mut self, cx: &mut Context<Self>) {
        if self.options.summary != SummaryStart::Off {
            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;
        if self.options.summary == SummaryStart::Off || self.options.compact {
            self.summary_task = None;
            return;
        }
        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)),
        };
        self.refresh_order(cx);
    }

    /// The rows shown again (the sort and the filter), off the UI thread.
    fn refresh_order(&mut self, cx: &mut Context<Self>) {
        self.order_gen += 1;
        let generation = self.order_gen;
        let only = self.filter.clone().zip(self.options.toolbar.as_ref().map(|t| t.column));
        if self.sort.is_none() && only.is_none() {
            self.order = None;
            self.sort_task = None;
            cx.notify();
            return;
        }
        let (data, sort) = (self.data.clone(), self.sort);
        let work = cx
            .background_executor()
            .spawn(async move { view_order(&data, sort, only.as_ref().map(|(v, c)| (*c, v.as_ref()))) });
        self.sort_task = Some(cx.spawn(async move |this, cx| {
            let order = work.await;
            let _ = this.update(cx, |t, cx| {
                if t.order_gen == generation {
                    t.order = order.map(Arc::new);
                    cx.notify();
                }
            });
        }));
        cx.notify();
    }

    /// Row numbers shown.
    fn row_numbers(&self) -> bool {
        self.spec.row_numbers && !self.options.compact
    }

    /// The row marks' column, when the app gave colours.
    fn mark_width(&self) -> f32 {
        if self.row_colors.iter().any(Option::is_some) { MARK_W } else { 0. }
    }

    /// Column widths: the minimum (or the hand-set width), the spare width of the pane shared out.
    /// Compact: the columns share the pane, none narrower than it allows.
    fn widths(&self) -> Vec<f32> {
        let n = self.data.columns.len();
        let index = if self.row_numbers() { self.spec.index_width } else { 0. };
        let lead = index + self.mark_width();
        let min = if self.options.compact && n > 0 {
            ((self.width.get() - lead) / n as f32).clamp(24., self.spec.min_column_width)
        } else {
            self.spec.min_column_width
        };
        let base: Vec<f32> = (0..n).map(|j| self.manual.get(&j).copied().unwrap_or(min)).collect();
        let free = self.width.get() - lead - 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 plain = self.style.header == HeaderStyle::Plain;
        let mark = self.mark_spacer(32.);
        let index = self.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(if plain { FontWeight::NORMAL } else { FontWeight::SEMIBOLD })
                        .text_color(if plain { color::text_muted() } else { 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(mark).children(cells.collect::<Vec<_>>())
    }

    /// The space over (or under) the row marks' column.
    fn mark_spacer(&self, h: f32) -> Option<impl IntoElement + use<>> {
        let w = self.mark_width();
        (w > 0.).then(|| div().flex_none().w(px(w)).h(px(h)))
    }

    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 mark = self.mark_spacer(h);
        let index = self.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(mark).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, cx: &mut Context<Self>) -> Vec<AnyElement> {
        let widths = self.widths();
        let style = self.style;
        let rh = style.row_height(&self.spec);
        let index_w = self.row_numbers().then_some(self.spec.index_width);
        let mark_w = self.mark_width();
        let row_w = widths.iter().sum::<f32>() + index_w.unwrap_or(0.) + mark_w;
        let data = self.data.clone();
        let order = self.order.clone();
        let colors = self.row_colors.clone();
        let clickable = self.options.selection != Selection::None;
        let grid = style.lines == Lines::Grid;
        range
            .map(|i| {
                let r = order.as_ref().and_then(|o| o.get(i).copied()).unwrap_or(i);
                let row_color = colors.get(r).copied().flatten();
                let selected = self.selected_rows.contains(&r);
                let cells = data.columns.iter().enumerate().map(|(j, c)| {
                    let (text, missing, x) = match &c.values {
                        Values::Number(v) => {
                            let x = v.get(r).copied().flatten();
                            (self.spec.format(x), x.is_none(), x)
                        }
                        Values::Text(v) => match v.get(r).cloned().flatten() {
                            Some(s) => (s.to_string(), false, None),
                            None => (self.spec.missing_text.clone(), true, None),
                        },
                    };
                    let mono = if c.values.is_number() { !style.numbers_sans } else { !style.text_sans };
                    let bar = self.bar_ranges.get(j).copied().flatten().zip(x).map(|(range, x)| {
                        let fill = match style.bar {
                            BarColor::Row => row_color.unwrap_or_else(color::accent),
                            BarColor::Accent => color::accent(),
                        };
                        div()
                            .absolute()
                            .left(px(theme::XS))
                            .top(px(3.))
                            .bottom(px(3.))
                            .w(relative(bar_fraction(x, range) * 0.94))
                            .rounded(px(theme::RADIUS_SM))
                            .bg(fill.opacity(0.38))
                    });
                    div()
                        .relative()
                        .flex_none()
                        .w(px(widths[j]))
                        .h_full()
                        .px(px(theme::SM))
                        .flex()
                        .items_center()
                        .when(mono, |d| d.font_family(fonts::MONO))
                        .when(c.values.is_number(), |d| d.justify_end())
                        .when(self.selected == Some(j) && !selected, |d| d.bg(color::selection()))
                        .when(grid, |d| d.border_r_1().border_color(color::grid()))
                        .children(bar)
                        .child(
                            div()
                                .relative()
                                .min_w_0()
                                .truncate()
                                .text_color(if missing { color::text_muted() } else { color::text() })
                                .child(text),
                        )
                });
                let hover = style.hover_color();
                h_flex()
                    .id(SharedString::from(format!("{}-row-{i}", self.id)))
                    .w(px(row_w))
                    .flex_none()
                    .h(px(rh))
                    .text_sm()
                    .when(style.lines == Lines::Stripes && i % 2 == 1 && !selected, |d| {
                        d.bg(color::raised().opacity(0.55))
                    })
                    .when(grid, |d| d.border_b_1().border_color(color::grid()))
                    .when(selected, |d| d.bg(style.selection_color()))
                    .when(!selected, |d| d.hover(move |d| d.bg(hover)))
                    .when(clickable, |d| {
                        d.cursor_pointer().on_click(cx.listener(move |this, e: &ClickEvent, _, cx| {
                            let m = e.modifiers();
                            this.click_row(i, m.shift, m.control || m.platform, cx);
                        }))
                    })
                    .children(index_w.map(|w| {
                        div()
                            .flex_none()
                            .w(px(w))
                            .h_full()
                            .px(px(theme::SM))
                            .flex()
                            .items_center()
                            .justify_end()
                            .font_family(fonts::MONO)
                            .text_color(color::text_muted())
                            .child(div().truncate().child((r + 1).to_string()))
                    }))
                    .when(mark_w > 0., |d| {
                        d.child(
                            div()
                                .flex_none()
                                .w(px(mark_w))
                                .h_full()
                                .flex()
                                .items_center()
                                .justify_center()
                                .children(row_color.map(|c| div().size(px(8.)).rounded_full().bg(c))),
                        )
                    })
                    .children(cells.collect::<Vec<_>>())
                    .test_support()
                    .into_any_element()
            })
            .collect()
    }

    /// The toolbar line: the filter menu, the counts.
    fn toolbar(&self, cx: &mut Context<Self>) -> Option<impl IntoElement + use<>> {
        let bar = self.options.toolbar.as_ref()?;
        let mut options: Vec<SharedString> = vec![bar.all.clone()];
        options.extend(self.filter_values.iter().cloned());
        let current = match &self.filter {
            Some(f) => self.filter_values.iter().position(|v| v == f).map(|k| k + 1),
            None => Some(0),
        };
        let this = cx.entity().downgrade();
        let menu =
            MenuSelect::new(SharedString::from(format!("{}-filter", self.id)), options, current, move |i, _, cx| {
                let _ = this.update(cx, |t, cx| t.pick_filter(i, cx));
            });
        let shown = self.order.as_ref().map(|o| o.len()).unwrap_or_else(|| self.data.rows());
        let mut counts = format!("{shown} {}", bar.noun);
        if self.options.selection != Selection::None && !self.selected_rows.is_empty() {
            counts.push_str(&format!(" · {} selected", self.selected_rows.len()));
        }
        Some(
            h_flex()
                .id(SharedString::from(format!("{}-toolbar", self.id)))
                .flex_none()
                .w_full()
                .h(px(TOOLBAR_H))
                .px(px(theme::SM))
                .gap(px(theme::SM))
                .items_center()
                .bg(color::raised())
                .border_b_1()
                .border_color(color::border())
                .child(div().w(px(168.)).flex_none().child(menu))
                .child(div().flex_1())
                .child(
                    div()
                        .min_w_0()
                        .truncate()
                        .text_xs()
                        .text_color(color::text_muted())
                        .child(SharedString::from(counts)),
                ),
        )
    }
}

impl Render for TableView {
    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let widths = self.widths();
        let lead = if self.row_numbers() { self.spec.index_width } else { 0. } + self.mark_width();
        let total = widths.iter().sum::<f32>() + lead;
        // 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 toolbar = self.toolbar(cx);
        let has_summary = self.options.summary != SummaryStart::Off;
        let top = (!self.options.compact).then(|| {
            let header = self.header(&widths, cx);
            let summary = (has_summary && self.spec.summary).then(|| self.summary_row(&widths, cx));
            let fold = has_summary.then(|| self.fold_bar(cx));
            div()
                .flex_none()
                .w_full()
                .overflow_hidden()
                .when(self.style.header == HeaderStyle::Raised, |d| d.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)
                        .children(fold)
                        .children(summary),
                )
        });
        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)
            .children(toolbar)
            .children(top)
            .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
    })
}

/// A kitchen-table table as the widget's plain columns (feature `kitchen-table`): numeric
/// columns as numbers, the rest as text, units from each column's meta. The widget itself takes
/// no Arrow; this is the one place that reads it.
#[cfg(feature = "kitchen-table")]
impl TableData {
    /// The columns of `table`, named `name`.
    pub fn from_table(name: impl Into<SharedString>, table: &kitchen_table::Table) -> Self {
        let columns = table
            .names()
            .into_iter()
            .map(|n| {
                let meta = table.meta(&n);
                let column = if table.is_numeric(&n) {
                    Column::numbers(n.clone(), table.values(&n).unwrap_or_default())
                } else {
                    let text = table.text(&n).unwrap_or_default();
                    Column::text(n.clone(), text.into_iter().map(|t| t.map(SharedString::from)).collect())
                };
                match meta.unit {
                    Some(u) => column.unit(u),
                    None => column,
                }
            })
            .collect();
        Self::new(name, columns)
    }

    /// Each column's role tag for [`TableView::set_roles`] (`Measure`, `Group`, `Id`, `Other`).
    pub fn roles_of(table: &kitchen_table::Table) -> Vec<Option<SharedString>> {
        use kitchen_table::Role;
        table
            .names()
            .iter()
            .map(|n| {
                Some(SharedString::from(match table.meta(n).role {
                    Role::Measure => "Measure",
                    Role::Group => "Group",
                    Role::Id => "Id",
                    Role::Other => "Other",
                }))
            })
            .collect()
    }
}

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

    #[cfg(feature = "kitchen-table")]
    #[test]
    fn a_kitchen_table_table_becomes_plain_columns() {
        use kitchen_table::{ColumnData, ColumnMeta, Role, Table};
        let t = Table::from_columns(vec![
            ("label", ColumnData::OptText(vec![Some("good".into()), None])),
            ("rate", ColumnData::F64(vec![4.0, f64::NAN])),
        ])
        .unwrap()
        .with_meta("rate", ColumnMeta::role(Role::Measure).unit("Hz"))
        .unwrap();
        let d = TableData::from_table("units", &t);
        assert_eq!(d.rows(), 2);
        assert_eq!(d.columns[0].values, Values::Text(vec![Some("good".into()), None]));
        assert_eq!(d.columns[1].values, Values::Number(vec![Some(4.0), None]));
        assert_eq!(d.columns[1].unit.as_ref().map(|u| u.as_ref()), Some("Hz"));
        assert_eq!(TableData::roles_of(&t), vec![Some("Other".into()), Some("Measure".into())]);
    }

    #[test]
    fn view_order_sorts_and_filters_and_clicks_select() {
        let t = iris_like();
        assert_eq!(view_order(&t, None, None), None);
        assert_eq!(view_order(&t, None, Some((1, "a"))), Some(vec![0, 2, 4]));
        assert_eq!(view_order(&t, Some((0, false)), Some((1, "a"))), Some(vec![4, 0, 2]));
        assert_eq!(view_order(&t, None, Some((0, "a"))), Some(vec![]));
        assert_eq!(distinct_text(&t, 1), vec![SharedString::from("a"), "b".into(), "c".into()]);
        assert!(distinct_text(&t, 0).is_empty());
        let order = [4, 0, 2];
        let none = BTreeSet::new();
        // Single: a click selects one row; ctrl on it clears
        let (s, a) = click_selection(&none, None, &order, 1, Selection::Single, false, false);
        assert_eq!((s.iter().copied().collect::<Vec<_>>(), a), (vec![0], Some(0)));
        assert!(click_selection(&s, a, &order, 1, Selection::Single, false, true).0.is_empty());
        // Multiple: shift selects the range shown between the anchor and the click
        let (s, a) = click_selection(&none, None, &order, 0, Selection::Multiple, false, false);
        let (s, a) = click_selection(&s, a, &order, 2, Selection::Multiple, true, false);
        assert_eq!(s.iter().copied().collect::<Vec<_>>(), vec![0, 2, 4]);
        // ctrl removes one and adds it back
        let (s, a) = click_selection(&s, a, &order, 1, Selection::Multiple, false, true);
        assert_eq!(s.iter().copied().collect::<Vec<_>>(), vec![2, 4]);
        let (s, _) = click_selection(&s, a, &order, 1, Selection::Multiple, false, true);
        assert_eq!(s.len(), 3);
        assert_eq!(click_selection(&s, a, &order, 9, Selection::Multiple, false, false).0, s);
        assert!(click_selection(&none, None, &order, 0, Selection::None, false, false).0.is_empty());
    }

    #[test]
    fn bars_span_their_range_and_styles_set_row_heights() {
        let c = Column::numbers("s", vec![Some(0.5), Some(1.0), None]).bar();
        assert_eq!(bar_range(&c), Some((0., 1.)));
        assert_eq!(bar_range(&Column::numbers("s", vec![Some(-2.), Some(-1.)]).bar()), Some((-2., 0.)));
        assert_eq!(bar_range(&c.clone().bar_range(0., 2.)), Some((0., 2.)));
        assert_eq!(bar_range(&Column::numbers("s", vec![None]).bar()), None);
        assert_eq!(bar_range(&Column::numbers("s", vec![Some(1.)])), None);
        assert_eq!(bar_fraction(0.5, (0., 1.)), 0.5);
        assert_eq!(bar_fraction(3., (0., 1.)), 1.);
        assert_eq!(bar_fraction(3., (3., 3.)), 1.);
        let spec = TableSpec::default();
        let rows = |density| TableStyle { density, ..TableStyle::default() }.row_height(&spec);
        assert_eq!((rows(Density::Compact), rows(Density::Normal), rows(Density::Comfortable)), (20., 24., 32.));
        assert_eq!(TableOptions::default().summary, SummaryStart::Open);
        let t = Toolbar::new(2).all("All labels").noun("units");
        assert_eq!((t.column, t.all.as_ref(), t.noun.as_ref()), (2, "All labels", "units"));
    }

    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);
    }
}