datui-lib 0.4.4

Data Exploration in the Terminal (library)
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
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
use super::*;
use ratatui::buffer::Buffer;

/// What a test draws: the data as the chart cache holds it, with the axes' numbers.
/// Turned into the chart view's plot under the modal it is drawn with, so the titles
/// are the view's own.
enum Draw<'a> {
    XY {
        /// As drawn: logged on a log scale.
        series: Option<&'a Vec<Vec<(f64, f64)>>>,
        breaks: Option<&'a Vec<Vec<usize>>>,
        values: Option<&'a Vec<Vec<(f64, f64)>>>,
        names: &'a [String],
        x_axis_kind: XAxisTemporalKind,
        x_bounds: Option<(f64, f64)>,
        numbers: PlotNumbers,
        other: bool,
    },
    Histogram {
        data: Option<&'a HistogramData>,
        x: AxisNumbers,
    },
    BoxPlot {
        data: Option<&'a BoxPlotData>,
        y: AxisNumbers,
    },
    Kde {
        data: Option<&'a KdeData>,
        x: AxisNumbers,
    },
    Heatmap {
        data: Option<&'a HeatmapData>,
        numbers: PlotNumbers,
    },
    Bar {
        data: Option<&'a BarData>,
    },
}

#[derive(Default)]
struct PlotNumbers {
    x: AxisNumbers,
    y: AxisNumbers,
}

impl Draw<'_> {
    fn plot(self, modal: &ChartModal, ctx: &RenderContext) -> Option<Plot<'static>> {
        use crate::chart::chart_plot::{LinesData, PlotContext};
        // The data says what kind of chart it is, whatever the modal's type.
        let mut spec = modal.effective_spec();
        spec.mark = match &self {
            Draw::XY { .. } if spec.mark == Mark::Scatter => Mark::Scatter,
            Draw::XY { .. } => Mark::Line,
            Draw::Histogram { .. } => Mark::Histogram,
            Draw::BoxPlot { .. } => Mark::Box,
            Draw::Kde { .. } => Mark::Kde,
            Draw::Heatmap { .. } => Mark::Heatmap,
            Draw::Bar { .. } => Mark::Bar,
        };
        let (data, numbers, kind) = match self {
            Draw::XY {
                series,
                breaks,
                values,
                names,
                x_axis_kind,
                x_bounds,
                numbers,
                other,
            } => {
                let data = match (series, x_bounds) {
                    // `series` as drawn; `values` before the log, when it differs.
                    (Some(series), _) => Some(PlotData::Lines(LinesData {
                        names: names.to_vec(),
                        series: values.unwrap_or(series).clone(),
                        series_log: values.map(|_| series.clone()),
                        breaks: breaks.cloned().unwrap_or_default(),
                        x_axis_kind,
                        other,
                        ..LinesData::default()
                    })),
                    (None, Some((x_min, x_max))) => Some(PlotData::XRange(
                        crate::chart::chart_data::ChartXRangeResult {
                            x_min,
                            x_max,
                            x_axis_kind,
                            rows: Default::default(),
                        },
                    )),
                    (None, None) => None,
                };
                (data, Some((numbers.x, numbers.y)), Some(x_axis_kind))
            }
            Draw::Histogram { data, x } => (
                data.cloned().map(PlotData::Histogram),
                Some((x, AxisNumbers::count(&ctx.number_format))),
                None,
            ),
            Draw::BoxPlot { data, y } => (
                data.cloned().map(PlotData::Box),
                Some((AxisNumbers::default(), y)),
                None,
            ),
            Draw::Kde { data, x } => (
                data.cloned().map(PlotData::Kde),
                Some((
                    x.fractional(),
                    AxisNumbers::measure(&ctx.number_format, "Density"),
                )),
                None,
            ),
            Draw::Heatmap { data, numbers } => (
                data.cloned().map(PlotData::Heatmap),
                Some((numbers.x, numbers.y)),
                None,
            ),
            Draw::Bar { data } => (data.cloned().map(PlotData::Bars), None, None),
        };
        let mut plot = crate::chart::chart_plot::plot(
            data.as_ref(),
            &PlotContext {
                modal,
                spec: &spec,
                numbers: &ctx.number_format,
                schema: None,
            },
        )?
        .into_owned();
        if let Some((x, y)) = numbers {
            plot.x.numbers = x;
            // A share is a measure, which the test does not say.
            if !matches!(&*plot.data, PlotData::Histogram(h) if h.share) {
                plot.y.numbers = y;
            }
        }
        if let Some(kind) = kind {
            plot.x.kind = kind;
        }
        Some(plot)
    }
}

/// A chart view as a test sets it up.
struct View<'a> {
    data: Draw<'a>,
    notes: Vec<String>,
    error: Option<&'a str>,
    working: Option<Working<'a>>,
    schema: Option<&'a Schema>,
}

fn render_plot(
    area: Rect,
    buf: &mut Buffer,
    modal: &ChartModal,
    theme: &Theme,
    ctx: &RenderContext,
    data: Draw<'_>,
    g: &Glyphs,
) -> Option<PlotPlace> {
    let plot = data.plot(modal, ctx);
    super::render_plot(area, buf, modal, theme, ctx, plot, g)
}

fn render_chart_view(
    area: Rect,
    buf: &mut Buffer,
    modal: &mut ChartModal,
    theme: &Theme,
    ctx: &RenderContext,
    view: View<'_>,
) {
    let plot = view.data.plot(modal, ctx);
    super::render_chart_view(
        area,
        buf,
        modal,
        theme,
        ctx,
        ChartView {
            plot,
            notes: view.notes,
            error: view.error,
            working: view.working,
            schema: view.schema,
        },
    );
}

fn open_modal() -> ChartModal {
    let mut modal = ChartModal::new();
    modal.open(
        crate::chart::chart_modal::ChartColumns {
            numeric: &["price".to_string(), "volume".to_string()],
            datetime: &["date".to_string()],
            bucketable: &["date".to_string()],
            category: &["carrier".to_string()],
        },
        None,
        Some(10_000),
        false,
        1,
    );
    modal
}

/// Series names for test plots: as many as any test draws.
fn names() -> &'static [String] {
    static NAMES: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
    NAMES.get_or_init(|| {
        ["price", "volume", "c", "d", "e", "f", "g"]
            .iter()
            .map(|s| s.to_string())
            .collect()
    })
}

fn render_rows(modal: &mut ChartModal, width: u16, height: u16) -> Vec<String> {
    render_view(
        modal,
        View {
            data: Draw::XY {
                series: None,
                breaks: None,
                values: None,
                names: names(),
                x_axis_kind: XAxisTemporalKind::Numeric,
                x_bounds: None,
                other: false,
                numbers: PlotNumbers::default(),
            },
            notes: Vec::new(),
            error: None,
            working: None,
            schema: None,
        },
        width,
        height,
    )
}

/// The panel: every shelf in the same place for every type, then the options;
/// no border inside it.
#[test]
fn the_panel_shows_every_shelf_and_echoes_every_option() {
    let mut modal = open_modal();
    modal.spec.encoding.x.field = Some("date".to_string());
    modal.spec.encoding.y.field = vec!["price".to_string()];
    let rows = render_rows(&mut modal, 100, 30);
    let text = rows.join("\n");
    for row in &rows {
        assert!(
            !row.contains('╭') && !row.contains('╰'),
            "a border inside the panel: {row:?}"
        );
    }
    let line = |label: &str| {
        rows.iter()
            .find(|r| {
                let head: String = r.chars().take(15).collect();
                head.trim_start().trim_start_matches('▎').trim() == label
            })
            .cloned()
            .unwrap_or_else(|| panic!("{label} in {text}"))
    };
    assert!(rows[0].contains("Chart"));
    assert!(line("Type").contains("Line"));
    assert!(line("X").contains("date"));
    assert!(line("Y").contains("price"));
    assert!(line("Color").contains("none"));
    assert!(text.contains("by row"), "the bucket under a date X: {text}");
    assert!(text.contains("Options"));
    assert!(line("Y from zero").contains("off"));
    assert!(line("Rows").contains("Sample 10,000"));
    assert!(line("Aggregate").contains("none"));
    assert!(
        !text.contains("type a size"),
        "the row's keys only under focus"
    );

    // Focused, the line under Rows names its keys; a change waits for Enter.
    modal.focus = ChartFocus::LimitRows;
    modal.view_rows = Some(36_800_000);
    let under = |rows: &[String]| {
        let at = rows
            .iter()
            .position(|r| r.contains("Sample") || r.contains("Every row"));
        rows[at.unwrap() + 1].clone()
    };
    let rows = render_rows(&mut modal, 100, 30);
    assert!(under(&rows).contains("switch · type a size"), "{rows:?}");
    modal.step(ChartFocus::LimitRows, 1);
    let rows = render_rows(&mut modal, 100, 30);
    assert!(
        rows.iter().any(|r| r.contains("Every row (36.8M)")),
        "{rows:?}"
    );
    assert!(under(&rows).contains("Enter to read"), "{rows:?}");
    modal.type_rows('5');
    modal.type_rows('x');
    modal.commit_rows();
    let rows = render_rows(&mut modal, 100, 30);
    assert!(rows.iter().any(|r| r.contains("Sample 5x")), "{rows:?}");
    assert!(under(&rows).contains("not a size"), "{rows:?}");
}

/// With a row's picker open, the picker's line carries the one rail on
/// screen; closed, the row has it back.
#[test]
fn an_open_picker_has_the_only_rail() {
    let g = crate::glyphs::get();
    let rails = |rows: &[String]| {
        rows.iter()
            .map(|row| row.matches(g.rail).count())
            .sum::<usize>()
    };
    let mut modal = open_modal();
    modal.set_mark(Mark::Line);
    modal.focus = ChartFocus::X;
    assert_eq!(rails(&render_rows(&mut modal, 100, 30)), 1);
    modal.open_picker();
    assert!(modal.picker.is_some());
    let rows = render_rows(&mut modal, 100, 30);
    assert_eq!(rails(&rows), 1, "{rows:#?}");
    let x = rows
        .iter()
        .find(|row| row.chars().skip(2).collect::<String>().starts_with("X "))
        .expect("the X row");
    assert!(!x.starts_with(g.rail), "the row gave the rail up: {x:?}");
}

/// The aggregate is a row of its own under Y, labeled, so `none` does not read
/// as a second Y column; focused, it carries the rail and the accent like any
/// row.
#[test]
fn the_aggregate_row_is_labeled() {
    let ctx = RenderContext::for_test();
    let theme = crate::config::Theme::from_config(&crate::config::ThemeConfig::default()).unwrap();
    let mut modal = open_modal();
    modal.set_mark(Mark::Scatter);
    modal.spec.encoding.x.field = Some("volume".to_string());
    modal.spec.encoding.y.field = vec!["price".to_string()];
    modal.focus = ChartFocus::Aggregate;
    let area = Rect::new(0, 0, 100, 30);
    let mut buf = Buffer::empty(area);
    render_chart_view(
        area,
        &mut buf,
        &mut modal,
        &theme,
        &ctx,
        View {
            data: Draw::XY {
                series: None,
                breaks: None,
                values: None,
                names: names(),
                x_axis_kind: XAxisTemporalKind::Numeric,
                x_bounds: None,
                other: false,
                numbers: PlotNumbers::default(),
            },
            notes: Vec::new(),
            error: None,
            working: None,
            schema: None,
        },
    );
    // Each panel row past the rail gutter: its label column and its value.
    let cells = |y: u16, xs: std::ops::Range<u16>| -> String {
        xs.map(|x| buf[(x, y)].symbol()).collect::<String>()
    };
    let label_end = 2 + LABEL_WIDTH;
    let at = |label: &str| {
        (0..area.height)
            .find(|&y| cells(y, 2..label_end).trim_end() == label)
            .unwrap_or_else(|| panic!("{label} in the panel"))
    };
    let (y, row) = (at("Y"), at("Aggregate"));
    assert_eq!(row, y + 1, "right under Y");
    assert_eq!(cells(row, label_end..SIDEBAR_WIDTH).trim_end(), "none");
    assert!(cells(y, label_end..SIDEBAR_WIDTH).contains("price"));
    assert_eq!(buf[(0, row)].symbol(), crate::glyphs::get().rail);
    assert_eq!(buf[(2, row)].fg, ctx.accent, "the focused label");
}

/// The title row says only how the rows were made; the Y column is named once,
/// at its axis. With nothing to say the row is blank.
#[test]
fn the_title_says_how_and_y_is_named_at_its_axis() {
    let mut modal = open_modal();
    modal.set_mark(Mark::Scatter);
    modal.spec.encoding.x.field = Some("volume".to_string());
    modal.spec.encoding.y.field = vec!["price".to_string()];
    let plot = |r: &String| -> String { r.chars().skip(SIDEBAR_WIDTH as usize + 1).collect() };
    let check = |modal: &mut ChartModal, how: &str| {
        let rows = render_rows(modal, 100, 30);
        assert_eq!(plot(&rows[0]).trim(), how, "{:?}", rows[0]);
        let named: Vec<String> = rows
            .iter()
            .map(plot)
            .filter(|r| r.contains("price"))
            .collect();
        assert_eq!(named.len(), 1, "price once, at its axis: {named:#?}");
        assert_eq!(named[0].trim(), "price", "{named:#?}");
    };
    check(&mut modal, "");
    modal.spec.encoding.color.field = Some("carrier".to_string());
    check(&mut modal, "colored by carrier");
    modal.spec.encoding.color.field = None;
    modal.spec.encoding.y.aggregate = Aggregate::Mean;
    check(&mut modal, "mean by volume");
    modal.set_mark(Mark::Line);
    modal.spec.encoding.y.cumulative = Cumulative::Sum;
    check(&mut modal, "by volume, running sum");
}

/// A shelf the type does not use stays, dimmed, with why.
#[test]
fn a_shelf_that_does_not_apply_is_dimmed_not_hidden() {
    let ctx = RenderContext::for_test();
    let mut modal = open_modal();
    modal.set_mark(Mark::Kde);
    modal.spec.encoding.x.field = Some("price".to_string());
    let rows = render_rows(&mut modal, 100, 30);
    let text = rows.join("\n");
    assert!(text.contains("density"), "{text}");
    assert!(text.contains("Bandwidth") && !text.contains("Log scale"));

    modal.set_mark(Mark::Box);
    let theme = crate::config::Theme::from_config(&crate::config::ThemeConfig::default()).unwrap();
    let area = Rect::new(0, 0, 100, 30);
    let mut buf = Buffer::empty(area);
    render_chart_view(
        area,
        &mut buf,
        &mut modal,
        &theme,
        &ctx,
        View {
            data: Draw::BoxPlot {
                data: None,
                y: AxisNumbers::default(),
            },
            notes: Vec::new(),
            error: None,
            working: None,
            schema: None,
        },
    );
    let row = (0..area.height)
        .find(|&y| {
            (0..14)
                .map(|x| buf[(x, y)].symbol())
                .collect::<String>()
                .trim()
                == "Color"
        })
        .expect("the Color shelf stays");
    assert_eq!(buf[(2, row)].fg, ctx.dimmed, "dimmed");
    let text: String = (0..area.height)
        .map(|y| (0..40).map(|x| buf[(x, y)].symbol()).collect::<String>())
        .collect::<Vec<_>>()
        .join("\n");
    assert!(text.contains("same as X"), "{text}");
}

/// The line under Color says how many values Other gathers while it is on: on by
/// default for a scatter, off for a line; ←/→ on the line turn it over.
#[test]
fn the_values_line_counts_other() {
    let mut modal = open_modal();
    modal.set_mark(Mark::Scatter);
    modal.spec.encoding.x.field = Some("price".to_string());
    modal.spec.encoding.y.field = vec!["volume".to_string()];
    modal.spec.encoding.color.field = Some("carrier".to_string());
    modal.color_counts = Some(crate::chart::chart_modal::ColorCounts {
        column: "carrier".to_string(),
        values: (0..16)
            .map(|i| (Some(format!("C{i}")), 100 - i as u64))
            .collect(),
    });
    let line = |modal: &mut ChartModal| -> String {
        let rows = render_rows(modal, 100, 30);
        let at = rows.iter().position(|r| r.contains("Color")).unwrap();
        rows[at + 1]
            .chars()
            .take(40)
            .collect::<String>()
            .trim()
            .to_string()
    };
    assert_eq!(line(&mut modal), "top 10 + 6 other");
    modal.step(ChartFocus::ColorValues, 1);
    assert_eq!(line(&mut modal), "top 10 of 16 by rows");
    modal.spec.encoding.color.other = None;
    modal.set_mark(Mark::Line);
    assert_eq!(line(&mut modal), "top 10 of 16 by rows");
    modal.step(ChartFocus::ColorValues, -1);
    assert_eq!(line(&mut modal), "top 10 + 6 other");
    modal.spec.encoding.color.values = vec![Some("C3".to_string()), Some("C9".to_string())];
    assert_eq!(line(&mut modal), "2 picked + 14 other");
}

/// A quantile's percentile sits on the line under Aggregate; first and last say
/// the order they read the rows in, the sort's own words when there is one, and
/// only then read the view sorted.
#[test]
fn the_aggregate_row_says_percentile_and_order() {
    let mut modal = open_modal();
    modal.set_mark(Mark::Line);
    modal.spec.encoding.x.field = Some("volume".to_string());
    modal.spec.encoding.y.field = vec!["price".to_string()];
    let panel = |modal: &mut ChartModal| -> Vec<String> {
        render_rows(modal, 100, 30)
            .iter()
            .map(|r| r.chars().take(40).collect::<String>().trim().to_string())
            .collect()
    };
    let g = crate::glyphs::get();
    modal.spec.encoding.y.aggregate = Aggregate::Quantile;
    let rows = panel(&mut modal);
    let at = rows
        .iter()
        .position(|r| r.starts_with("Aggregate"))
        .unwrap();
    assert_eq!(rows[at], "Aggregate    quantile");
    assert_eq!(rows[at + 1], "p90");
    modal.step(ChartFocus::Quantile, -1);
    assert_eq!(panel(&mut modal)[at + 1], "p75");

    modal.spec.encoding.y.aggregate = Aggregate::Last;
    let rows = panel(&mut modal);
    assert_eq!(
        rows[at],
        format!("Aggregate    last {} by row order", g.middot)
    );
    let request = crate::chart::chart_jobs::ChartRequest::from_modal(&modal).unwrap();
    assert!(!request.sorted);
    modal.row_order = Some(format!("time {}", g.sort_asc));
    let rows = panel(&mut modal);
    assert_eq!(
        rows[at],
        format!("Aggregate    last {} by time {}", g.middot, g.sort_asc)
    );
    let request = crate::chart::chart_jobs::ChartRequest::from_modal(&modal).unwrap();
    assert!(request.sorted, "first and last read the view sorted");
    modal.spec.encoding.y.aggregate = Aggregate::Mean;
    let request = crate::chart::chart_jobs::ChartRequest::from_modal(&modal).unwrap();
    assert!(!request.sorted, "a mean needs no order");
}

/// Ten series take ten colors, each its own, and the legend names all ten.
#[test]
fn ten_series_take_ten_colors() {
    let mut modal = open_modal();
    modal.set_mark(Mark::Line);
    modal.spec.encoding.x.field = Some("price".to_string());
    modal.spec.encoding.y.field = vec!["volume".to_string()];
    modal.show_legend = true;
    let series: Vec<Vec<(f64, f64)>> = (0..10)
        .map(|s| (0..5).map(|i| (i as f64, (i * 10 + s) as f64)).collect())
        .collect();
    let names: Vec<String> = (0..10).map(|i| format!("s{i}")).collect();
    let ctx = RenderContext::for_test();
    let theme = crate::config::Theme::from_config(&crate::config::ThemeConfig::default()).unwrap();
    // Hex all the way, as a true-color terminal shows them.
    let mut theme = theme;
    let config = crate::config::ColorConfig::default();
    let hex = [
        &config.chart_1,
        &config.chart_2,
        &config.chart_3,
        &config.chart_4,
        &config.chart_5,
        &config.chart_6,
        &config.chart_7,
        &config.chart_8,
        &config.chart_9,
        &config.chart_10,
    ];
    for (i, value) in hex.iter().enumerate() {
        let channel = |at: usize| u8::from_str_radix(&value[at..at + 2], 16).unwrap();
        let color = ratatui::style::Color::Rgb(channel(1), channel(3), channel(5));
        theme.colors.insert(format!("chart_{}", i + 1), color);
    }
    assert_eq!(theme.series_colors().len(), 10);
    let area = Rect::new(0, 0, 80, 30);
    let mut buf = Buffer::empty(area);
    render_plot(
        area,
        &mut buf,
        &modal,
        &theme,
        &ctx,
        Draw::XY {
            series: Some(&series),
            breaks: None,
            values: None,
            names: &names,
            x_axis_kind: XAxisTemporalKind::Numeric,
            x_bounds: None,
            numbers: PlotNumbers::default(),
            other: false,
        },
        crate::glyphs::unicode(),
    );
    let mut swatches = Vec::new();
    for y in 0..area.height {
        let row: String = (0..area.width).map(|x| buf[(x, y)].symbol()).collect();
        if let Some(name) = names.iter().find(|n| row.contains(&format!("█ {n} "))) {
            let x = (0..area.width)
                .find(|&x| buf[(x, y)].symbol() == "█")
                .unwrap();
            swatches.push((name.clone(), buf[(x, y)].fg));
        }
    }
    assert_eq!(swatches.len(), 10, "{swatches:?}");
    let mut colors: Vec<_> = swatches.iter().map(|(_, c)| format!("{c:?}")).collect();
    colors.dedup();
    assert_eq!(colors.len(), 10, "{swatches:?}");
}

/// A 16-color terminal shows the ten slots as fewer colors: the chart draws one
/// series per color, and the line under Color says how many.
#[test]
fn sixteen_colors_cap_the_series() {
    let sixteen = |hex: &str| {
        let channel = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).unwrap();
        crate::config::rgb_to_basic_ansi(channel(1), channel(3), channel(5))
    };
    let config = crate::config::ColorConfig::default();
    let mut theme =
        crate::config::Theme::from_config(&crate::config::ThemeConfig::default()).unwrap();
    for (i, value) in [
        &config.chart_1,
        &config.chart_2,
        &config.chart_3,
        &config.chart_4,
        &config.chart_5,
        &config.chart_6,
        &config.chart_7,
        &config.chart_8,
        &config.chart_9,
        &config.chart_10,
    ]
    .iter()
    .enumerate()
    {
        theme
            .colors
            .insert(format!("chart_{}", i + 1), sixteen(value));
    }
    let colors = theme.series_colors();
    assert!((2..10).contains(&colors.len()), "{colors:?}");
    let mut modal = open_modal();
    modal.series_cap = Some(colors.len());
    modal.set_mark(Mark::Line);
    modal.spec.encoding.x.field = Some("price".to_string());
    modal.spec.encoding.y.field = vec!["volume".to_string()];
    modal.spec.encoding.color.field = Some("carrier".to_string());
    modal.color_counts = Some(crate::chart::chart_modal::ColorCounts {
        column: "carrier".to_string(),
        values: (0..16)
            .map(|i| (Some(format!("C{i}")), 100 - i as u64))
            .collect(),
    });
    let rows = render_rows(&mut modal, 100, 30);
    let at = rows.iter().position(|r| r.contains("Color")).unwrap();
    assert!(
        rows[at + 1].contains(&format!("top {} of 16 by rows", colors.len())),
        "{}",
        rows[at + 1]
    );
    let request = crate::chart::chart_jobs::ChartRequest::from_modal(&modal).unwrap();
    assert_eq!(request.series_cap, colors.len());
}

/// Other is the legend's last entry and is drawn in `dimmed`, under the series.
#[test]
fn other_is_the_legends_last_entry() {
    let mut modal = open_modal();
    modal.set_mark(Mark::Scatter);
    modal.spec.encoding.x.field = Some("price".to_string());
    modal.spec.encoding.y.field = vec!["volume".to_string()];
    modal.show_legend = true;
    let series: Vec<Vec<(f64, f64)>> = (0..3)
        .map(|s| (0..5).map(|i| (i as f64, (i * 10 + s) as f64)).collect())
        .collect();
    let names: Vec<String> = ["UA", "B6", crate::chart::chart_data::OTHER]
        .iter()
        .map(|s| s.to_string())
        .collect();
    let ctx = RenderContext::for_test();
    let theme = crate::config::Theme::from_config(&crate::config::ThemeConfig::default()).unwrap();
    let area = Rect::new(0, 0, 60, 24);
    let mut buf = Buffer::empty(area);
    render_plot(
        area,
        &mut buf,
        &modal,
        &theme,
        &ctx,
        Draw::XY {
            series: Some(&series),
            breaks: None,
            values: None,
            names: &names,
            x_axis_kind: XAxisTemporalKind::Numeric,
            x_bounds: None,
            numbers: PlotNumbers::default(),
            other: true,
        },
        crate::glyphs::unicode(),
    );
    let rows: Vec<String> = crate::tests::buffer_lines(&buf);
    let at = |name: &str| {
        rows.iter()
            .position(|r| r.contains(&format!("█ {name}")))
            .unwrap_or_else(|| panic!("{name}: {rows:#?}"))
    };
    assert_eq!(at("UA") + 1, at("B6"));
    assert_eq!(at("B6") + 1, at("Other"));
    let row = at("Other") as u16;
    let swatch = (0..area.width)
        .find(|&x| buf[(x, row)].symbol() == "█")
        .unwrap();
    assert_eq!(buf[(swatch, row)].fg, theme.dimmed());
}

/// The open Picker drops over the panel under its row, with a checkbox per item
/// where it takes several, and each value's rows beside it.
#[test]
fn the_value_picker_lists_values_by_rows() {
    let g = crate::glyphs::get();
    let mut modal = open_modal();
    modal.spec.encoding.color.field = Some("carrier".to_string());
    modal.color_counts = Some(crate::chart::chart_modal::ColorCounts {
        column: "carrier".to_string(),
        values: vec![(Some("UA".to_string()), 2514), (Some("B6".to_string()), 12)],
    });
    modal.focus = ChartFocus::ColorValues;
    modal.open_picker();
    modal.picker_toggle(); // UA in
    let rows = render_rows(&mut modal, 100, 30);
    let body = rows.join("\n");
    assert!(
        body.contains(&format!("{} UA", g.checkbox_on)) && body.contains("2,514"),
        "{body}"
    );
    assert!(body.contains(&format!("{} B6", g.checkbox_off)), "{body}");
    assert!(body.contains("1 picked"), "{body}");
}

/// An open Picker owns the clicks, drawn or not: the panel's rows take none.
#[test]
fn an_open_picker_with_no_room_still_takes_the_clicks() {
    let mut modal = open_modal();
    modal.focus = ChartFocus::Y;
    modal.open_picker();
    let hits = crate::app::pointer::recording(|| {
        render_rows(&mut modal, 100, 7);
    });
    assert!(hits.iter().any(|(_, h)| *h == Hit::Picker), "{hits:?}");
}

fn render_view(modal: &mut ChartModal, view: View<'_>, w: u16, h: u16) -> Vec<String> {
    let ctx = RenderContext::for_test();
    let theme = crate::config::Theme::from_config(&crate::config::ThemeConfig::default())
        .expect("default theme colors must resolve");
    let area = Rect::new(0, 0, w, h);
    let mut buf = Buffer::empty(area);
    render_chart_view(area, &mut buf, modal, &theme, &ctx, view);
    (0..h)
        .map(|y| (0..w).map(|x| buf[(x, y)].symbol().to_string()).collect())
        .collect()
}

/// A sampled or clipped chart says so at the right of the title row, at 80x24
/// too; the bottom right holds only the X axis's title.
#[test]
fn notes_sit_at_the_title_rows_right() {
    let mut modal = open_modal();
    modal.spec.encoding.x.field = Some("price".to_string());
    modal.spec.encoding.y.field = vec!["volume".to_string()];
    let series = vec![vec![(0.0, 1.0), (1.0, 2.0)]];
    let note = "sample of 10,000 of 3.5M rows";
    let rows = render_view(
        &mut modal,
        View {
            data: Draw::XY {
                series: Some(&series),
                breaks: None,
                values: None,
                names: names(),
                x_axis_kind: XAxisTemporalKind::Numeric,
                x_bounds: None,
                other: false,
                numbers: PlotNumbers::default(),
            },
            notes: vec![note.to_string()],
            error: None,
            working: None,
            schema: None,
        },
        120,
        24,
    );
    assert!(rows[0].trim_end().ends_with(note), "{:?}", rows[0]);
    assert!(rows[23].trim_end().ends_with("price"), "{:?}", rows[23]);
    let canvas = |r: &String| r.chars().skip(42).collect::<String>();
    assert!(
        rows[1..].iter().all(|r| !canvas(r).contains("sample")),
        "{rows:#?}"
    );
}

/// On a narrow canvas the how keeps its room and the notes are cut to the rest,
/// with the ellipsis.
#[test]
fn notes_give_way_to_the_how() {
    let mut modal = open_modal();
    modal.set_mark(Mark::Histogram);
    let notes = [
        "sample of 1,000,000 of 36.8M rows",
        "1,207 values outside p1-p99",
    ];
    let rows = render_view(
        &mut modal,
        View {
            data: Draw::Histogram {
                data: None,
                x: AxisNumbers::default(),
            },
            notes: notes.iter().map(|n| n.to_string()).collect(),
            error: None,
            working: None,
            schema: None,
        },
        100,
        20,
    );
    let g = crate::glyphs::get();
    let title = rows[0].chars().skip(42).collect::<String>();
    assert!(title.starts_with("count per bin  "), "{title:?}");
    assert!(title.contains("sample of 1,000,000"), "{title:?}");
    assert!(title.trim_end().ends_with(g.ellipsis), "{title:?}");
    let canvas = |r: &String| r.chars().skip(42).collect::<String>();
    assert!(
        rows[1..].iter().all(|r| !canvas(r).contains("sample")),
        "{rows:#?}"
    );
}

/// A failed preparation shows its message where the plot would be.
#[test]
fn an_error_replaces_the_plot() {
    let mut modal = open_modal();
    let rows = render_view(
        &mut modal,
        View {
            data: Draw::XY {
                series: None,
                breaks: None,
                values: None,
                names: names(),
                x_axis_kind: XAxisTemporalKind::Numeric,
                x_bounds: None,
                other: false,
                numbers: PlotNumbers::default(),
            },
            notes: Vec::new(),
            error: Some("column not found: gone"),
            working: None,
            schema: None,
        },
        100,
        24,
    );
    assert!(rows.join("\n").contains("column not found: gone"));
}

/// A line breaks at a gap: nothing is drawn between the runs on either side.
#[test]
fn a_line_does_not_bridge_a_gap() {
    let mut modal = open_modal();
    modal.spec.encoding.x.field = Some("price".to_string());
    modal.spec.encoding.y.field = vec!["volume".to_string()];
    modal.show_legend = false;
    let series = vec![vec![(0.0, 0.0), (1.0, 0.0), (9.0, 0.0), (10.0, 0.0)]];
    let draw = |modal: &mut ChartModal, breaks: &Vec<Vec<usize>>| {
        render_view(
            modal,
            View {
                data: Draw::XY {
                    series: Some(&series),
                    breaks: Some(breaks),
                    values: None,
                    names: names(),
                    x_axis_kind: XAxisTemporalKind::Numeric,
                    x_bounds: None,
                    other: false,
                    numbers: PlotNumbers::default(),
                },
                notes: Vec::new(),
                error: None,
                working: None,
                schema: None,
            },
            100,
            24,
        )
    };
    let blank = |c: char| c == ' ' || c == '\u{2800}';
    let marks = |rows: &[String]| -> usize {
        rows.iter()
            .map(|r| r.chars().skip(44).filter(|c| !blank(*c)).count())
            .sum()
    };
    let joined = draw(&mut modal, &vec![Vec::new()]);
    let broken = draw(&mut modal, &vec![vec![2]]);
    assert!(
        marks(&broken) < marks(&joined),
        "the run from 1 to 9 is not drawn"
    );
}

fn bar_data(n: usize) -> BarData {
    use crate::chart::chart_data::Bar;
    BarData {
        category: "carrier".to_string(),
        value_column: "delay".to_string(),
        bars: (0..n)
            .map(|i| Bar {
                label: Some(format!("C{i}")),
                value: (n - i) as f64,
                by_group: Vec::new(),
            })
            .collect(),
        more: 0,
        no_value: 0,
        rows: Default::default(),
        value_dtype: polars::prelude::DataType::Float64,
        counted: None,
        groups: Vec::new(),
        other: false,
        rows_note: None,
    }
}

fn render_bars(data: &BarData, w: u16, h: u16) -> Vec<String> {
    let mut modal = open_modal();
    modal.set_mark(Mark::Bar);
    render_view(
        &mut modal,
        View {
            data: Draw::Bar { data: Some(data) },
            notes: Vec::new(),
            error: None,
            working: None,
            schema: None,
        },
        w,
        h,
    )
}

/// A bar per category: its label, its value beside it, and a bar as long as the
/// value, the largest filling the width.
#[test]
fn bars_draw_label_value_and_length() {
    let g = crate::glyphs::get();
    let full = g.bar_eighths[7];
    let data = bar_data(3);
    let rows = render_bars(&data, 100, 24);
    // The canvas starts past the 42-column sidebar.
    let canvas: Vec<String> = rows.iter().map(|r| r.chars().skip(42).collect()).collect();
    assert!(canvas[1].trim_start().starts_with("carrier") && canvas[1].contains("delay"));
    let bar_len = |row: &str| row.matches(full).count();
    let words = |row: &str| row.split_whitespace().take(2).collect::<Vec<_>>().join(" ");
    assert_eq!(words(&canvas[2]), "C0 3.00", "{:?}", canvas[2]);
    assert_eq!(words(&canvas[4]), "C2 1.00", "{:?}", canvas[4]);
    let (a, c) = (bar_len(&canvas[2]), bar_len(&canvas[4]));
    assert!(
        a > 40 && (a as f64 / c as f64 - 3.0).abs() < 0.2,
        "{a} vs {c}"
    );
}

/// More bars than rows: the ones that fit, then a chip counting the rest, which
/// includes those the preparation already left out.
#[test]
fn bars_past_the_height_are_counted_on_a_chip() {
    let mut data = bar_data(50);
    data.more = 200;
    let rows = render_bars(&data, 80, 24);
    let body = rows.join("\n");
    // 23 rows under the tab line: a header, 21 bars, the chip.
    assert!(body.contains("C20 "), "{body}");
    assert!(!body.contains("C21 "), "{body}");
    assert!(rows[23].contains(" + 229 more "), "{:?}", rows[23]);
}

/// A negative value draws left of the zero line; a null category reads as null.
#[test]
fn negative_bars_grow_left_and_null_categories_show() {
    use crate::chart::chart_data::Bar;
    let g = crate::glyphs::get();
    let full = g.bar_eighths[7];
    let mut data = bar_data(0);
    data.bars = vec![
        Bar {
            label: Some("UA".to_string()),
            value: 10.0,
            by_group: Vec::new(),
        },
        Bar {
            label: None,
            value: -10.0,
            by_group: Vec::new(),
        },
    ];
    let rows = render_bars(&data, 100, 24);
    let canvas: Vec<String> = rows.iter().map(|r| r.chars().skip(42).collect()).collect();
    let first = |row: &str| row.find(full).map(|i| row[..i].chars().count());
    let pos = first(&canvas[2]).unwrap();
    let neg = first(&canvas[3]).unwrap();
    assert!(neg < pos, "the negative bar starts left of zero");
    assert!(
        canvas[3].trim_start().starts_with(g.null),
        "{:?}",
        canvas[3]
    );
}

/// A value far smaller than the rest still draws a mark, either side of zero, so
/// no bar that is not zero reads as zero.
#[test]
fn a_tiny_value_still_draws_a_mark() {
    use crate::chart::chart_data::Bar;
    let g = crate::glyphs::get();
    let mut data = bar_data(0);
    data.bars = [
        ("big", 10_000.0),
        ("tiny", 0.1),
        ("zero", 0.0),
        ("neg", -0.1),
    ]
    .into_iter()
    .map(|(label, value)| Bar {
        label: Some(label.to_string()),
        value,
        by_group: Vec::new(),
    })
    .collect();
    let rows = render_bars(&data, 100, 24);
    let canvas: Vec<String> = rows.iter().map(|r| r.chars().skip(42).collect()).collect();
    // The bar zone: the row with its label and value taken out.
    let marks = |row: &str| {
        let mut words = row.split_whitespace();
        let (label, value) = (words.next().unwrap(), words.next().unwrap());
        let zone = row.replacen(label, "", 1).replacen(value, "", 1);
        g.bar_eighths
            .iter()
            .filter(|m| !m.trim().is_empty() && zone.contains(**m))
            .count()
    };
    assert!(marks(&canvas[3]) > 0, "tiny: {:?}", canvas[3]);
    assert_eq!(marks(&canvas[4]), 0, "zero: {:?}", canvas[4]);
    assert!(marks(&canvas[5]) > 0, "neg: {:?}", canvas[5]);
}

fn plot_text(modal: &ChartModal, data: Draw<'_>, g: &Glyphs) -> String {
    plot_text_in(modal, data, g, Rect::new(0, 0, 60, 20))
}

fn plot_text_in(modal: &ChartModal, data: Draw<'_>, g: &Glyphs, area: Rect) -> String {
    plot_text_with(&RenderContext::for_test(), modal, data, g, area)
}

fn plot_text_with(
    ctx: &RenderContext,
    modal: &ChartModal,
    data: Draw<'_>,
    g: &Glyphs,
    area: Rect,
) -> String {
    let theme = crate::config::Theme::from_config(&crate::config::ThemeConfig::default())
        .expect("default theme colors must resolve");
    let mut buf = Buffer::empty(area);
    render_plot(area, &mut buf, modal, &theme, ctx, data, g);
    crate::tests::buffer_text(&buf)
}

/// At 40, 60 and 80 columns, in both glyph sets, every plot's x labels stand a
/// space apart with both ends kept, and its axis titles sit on rows of their own
/// that hold nothing of the plot.
#[test]
fn axis_labels_stand_apart_and_titles_keep_their_rows() {
    /// A plot, its x and y titles, and what its x labels look like.
    type Case<'a> = (
        &'a str,
        Draw<'a>,
        &'a str,
        &'a str,
        &'a dyn Fn(&str) -> bool,
    );
    use crate::chart::chart_data::{HistogramBin, KdeSeries};
    // 2020-01-01 to 2024-12-31, in days since the epoch.
    let dates: Vec<Vec<(f64, f64)>> = vec![
        (0..=100)
            .map(|i| (18262.0 + f64::from(i) * 18.26, f64::from(i % 7) * 1000.0))
            .collect(),
    ];
    let numbers: Vec<Vec<(f64, f64)>> = vec![
        (0..20)
            .map(|i| (i as f64 * 1234.5, (i * i) as f64))
            .collect(),
    ];
    let histogram = HistogramData {
        column: "price".to_string(),
        groups: Vec::new(),
        other: false,
        share: false,
        bins: (0..10)
            .map(|i| HistogramBin {
                center: i as f64 * 250.0 + 125.0,
                count: (1 + i % 4) as f64 * 1000.0,
            })
            .collect(),
        x_min: 0.0,
        x_max: 2500.0,
        max_count: 4000.0,
        rows: Default::default(),
        clipped: None,
    };
    let kde = KdeData {
        other: false,
        series: vec![KdeSeries {
            name: "price".to_string(),
            points: (0..=100)
                .map(|i| {
                    let x = i as f64 * 100.0 - 5000.0;
                    (x, (-x * x / 2e6).exp())
                })
                .collect(),
        }],
        x_min: -5000.0,
        x_max: 5000.0,
        y_max: 1.0,
        rows: Default::default(),
        clipped: None,
    };
    let is_date = |t: &str| {
        [4, 5, 7, 10].contains(&t.len()) && t.chars().all(|c| c.is_ascii_digit() || c == '-')
    };
    let is_number = |t: &str| {
        t.trim_end_matches(['k', 'M', 'G', 'T'])
            .parse::<f64>()
            .is_ok()
    };

    let mut modal = open_modal();
    modal.spec.encoding.y.field = vec!["price".to_string()];
    modal.show_legend = false;
    for columns in [40u16, 60, 80] {
        let area = Rect::new(0, 0, columns - SIDEBAR_WIDTH.min(columns / 2), 18);
        for g in [crate::glyphs::ascii(), crate::glyphs::unicode()] {
            let cases: [Case; 4] = [
                (
                    "date",
                    Draw::XY {
                        series: Some(&dates),
                        breaks: None,
                        values: None,
                        names: names(),
                        x_axis_kind: XAxisTemporalKind::Date,
                        x_bounds: None,
                        other: false,
                        numbers: PlotNumbers::default(),
                    },
                    "date",
                    "price",
                    &is_date,
                ),
                (
                    "number",
                    Draw::XY {
                        series: Some(&numbers),
                        breaks: None,
                        values: None,
                        names: names(),
                        x_axis_kind: XAxisTemporalKind::Numeric,
                        x_bounds: None,
                        other: false,
                        numbers: PlotNumbers::default(),
                    },
                    "volume",
                    "price",
                    &is_number,
                ),
                (
                    "histogram",
                    Draw::Histogram {
                        data: Some(&histogram),
                        x: AxisNumbers::default(),
                    },
                    "price",
                    "Count",
                    &is_number,
                ),
                (
                    "KDE",
                    Draw::Kde {
                        data: Some(&kde),
                        x: AxisNumbers::default(),
                    },
                    "Value",
                    "Density",
                    &is_number,
                ),
            ];
            for (what, data, x_title, y_title, is_label) in cases {
                modal.spec.encoding.x.field = Some(x_title.to_string());
                let text = plot_text_in(&modal, data, g, area);
                let rows: Vec<&str> = text.lines().collect();
                let what = format!("{what} at {columns} columns:\n{text}");
                let axis = rows
                    .iter()
                    .rposition(|r| r.contains(g.plot.axis.bottom_left))
                    .expect(&what);
                let labels: Vec<&str> = rows[axis + 1].split_whitespace().collect();
                assert!(labels.len() >= 2, "both ends: {what}");
                assert!(labels.iter().all(|l| is_label(l)), "apart: {what}");
                assert_eq!(rows[0].trim_end(), y_title, "y title row: {what}");
                assert_eq!(rows[axis + 2].trim_start(), x_title, "x title row: {what}");
            }
        }
    }
}

/// Every label on an axis in one format, in the table's number style: KDE
/// densities around 0.01 keep one precision all the way up, and under the
/// european format a narrow axis's short form reads `12,5k`.
#[test]
fn an_axis_writes_every_label_in_one_format() {
    use crate::chart::chart_data::KdeSeries;
    use crate::numfmt::NumberFormat;
    let g = crate::glyphs::unicode();
    let y_labels = |text: &str| -> Vec<String> {
        text.lines()
            .filter_map(|r| r.split_once(['│', '┤'])?.0.split_whitespace().next())
            .map(String::from)
            .collect()
    };
    let mut modal = open_modal();
    modal.show_legend = false;

    let kde = KdeData {
        other: false,
        series: vec![KdeSeries {
            name: "price".to_string(),
            points: (0..=100)
                .map(|i| {
                    let x = f64::from(i);
                    (x, 0.0126 * (-(x - 50.0).powi(2) / 400.0).exp())
                })
                .collect(),
        }],
        x_min: 0.0,
        x_max: 100.0,
        y_max: 0.0126,
        rows: Default::default(),
        clipped: None,
    };
    let data = Draw::Kde {
        data: Some(&kde),
        x: AxisNumbers::default(),
    };
    let text = plot_text_in(&modal, data, g, Rect::new(0, 0, 40, 12));
    assert_eq!(y_labels(&text), ["0.02", "0.01", "0.00"], "{text}");

    let european = NumberFormat::preset("european").unwrap();
    let mut ctx = RenderContext::for_test();
    ctx.number_format.format = european.clone();
    modal.spec.encoding.x.field = Some("volume".to_string());
    modal.spec.encoding.y.field = vec!["price".to_string()];
    modal.y_starts_at_zero = false;
    let series = vec![vec![(0.0, 12_000.0), (5.0, 12_600.0)]];
    let xy = || Draw::XY {
        series: Some(&series),
        breaks: None,
        values: None,
        names: names(),
        x_axis_kind: XAxisTemporalKind::Numeric,
        x_bounds: None,
        other: false,
        numbers: PlotNumbers {
            x: AxisNumbers::default(),
            y: AxisNumbers {
                format: european.clone(),
                whole: false,
            },
        },
    };
    // 12,000 to 12,600 fits in steps of 200, not out to 13,000 in steps of 500.
    let text = plot_text_with(&ctx, &modal, xy(), g, Rect::new(0, 0, 40, 12));
    assert_eq!(
        y_labels(&text),
        ["12.600", "12.400", "12.200", "12.000"],
        "{text}"
    );
    // Too narrow for those: the short form, each in the same unit and places.
    let text = plot_text_with(&ctx, &modal, xy(), g, Rect::new(0, 0, 16, 12));
    assert_eq!(
        y_labels(&text),
        ["12,6k", "12,4k", "12,2k", "12,0k"],
        "{text}"
    );
}

/// A heatmap's y labels in one format; an integer column's middle label is left
/// out when it falls between two whole numbers, where it read `0` twice.
#[test]
fn heatmap_y_labels_are_whole_where_the_column_is() {
    let heatmap = |(y_min, y_max)| HeatmapData {
        x_column: "price".to_string(),
        y_column: "flag".to_string(),
        x_min: 0.0,
        x_max: 10.0,
        y_min,
        y_max,
        x_bins: 4,
        y_bins: 4,
        counts: vec![vec![1.0; 4]; 4],
        max_count: 1.0,
        rows: Default::default(),
    };
    let y_labels = |text: &str| -> Vec<String> {
        // The plot's rows, each starting with its label if it has one.
        text.lines()
            .filter(|r| r.contains('@'))
            .filter_map(|r| r.split_whitespace().next())
            .filter(|l| !l.starts_with('@'))
            .map(String::from)
            .collect()
    };
    let whole = PlotNumbers {
        x: AxisNumbers::default(),
        y: AxisNumbers {
            whole: true,
            ..AxisNumbers::default()
        },
    };
    let g = crate::glyphs::unicode();
    let modal = open_modal();
    let area = Rect::new(0, 0, 40, 12);
    let data = heatmap((0.0, 1.0));
    let text = plot_text_in(
        &modal,
        Draw::Heatmap {
            data: Some(&data),
            numbers: whole,
        },
        g,
        area,
    );
    assert_eq!(y_labels(&text), ["1", "0"], "{text}");
    let data = heatmap((0.0, 0.0126));
    let text = plot_text_in(
        &modal,
        Draw::Heatmap {
            data: Some(&data),
            numbers: PlotNumbers::default(),
        },
        g,
        area,
    );
    assert_eq!(y_labels(&text), ["0.010", "0.005", "0.000"], "{text}");
}

/// A count, or an integer column, ticks in whole numbers as the table prints
/// them: never `4321.00`, and never a tick between two whole numbers.
#[test]
fn whole_number_axes_tick_whole_in_the_table_format() {
    use crate::chart::chart_data::HistogramBin;
    use crate::numfmt::NumberFormat;
    let thousands = NumberFormat::preset("thousands").unwrap();
    let whole = AxisNumbers {
        format: thousands.clone(),
        whole: true,
    };
    let mut ctx = RenderContext::for_test();
    ctx.number_format.format = thousands.clone();
    let g = crate::glyphs::unicode();
    let area = Rect::new(0, 0, 40, 12);
    // What sits left of the y axis.
    let y_labels = |text: &str| -> Vec<String> {
        text.lines()
            .filter_map(|r| r.split_once(['│', '┤'])?.0.split_whitespace().next())
            .map(String::from)
            .collect()
    };
    let axis_row = |text: &str| {
        let rows: Vec<&str> = text.lines().collect();
        let axis = rows.iter().rposition(|r| r.contains('└')).expect(text);
        rows[axis + 1]
            .split_whitespace()
            .collect::<Vec<_>>()
            .join(" ")
    };

    // Counts up the side; an integer column's values, 0 to 7, along the bottom.
    let histogram = HistogramData {
        column: "passengers".to_string(),
        groups: Vec::new(),
        other: false,
        share: false,
        bins: (0..7)
            .map(|i| HistogramBin {
                center: f64::from(i) + 0.5,
                count: [4321.0, 12.0, 900.0][i as usize % 3],
            })
            .collect(),
        x_min: 0.0,
        x_max: 7.0,
        max_count: 4321.0,
        rows: Default::default(),
        clipped: None,
    };
    let data = Draw::Histogram {
        data: Some(&histogram),
        x: whole.clone(),
    };
    let text = plot_text_with(&ctx, &open_modal(), data, g, area);
    // Up to the nice value past the tallest bar, in thousands-grouped whole steps.
    assert_eq!(y_labels(&text), ["5,000", "2,500", "0"], "{text}");
    // Four labels fit, so not the two of the step nearest the spacing.
    assert_eq!(axis_row(&text), "0 2 4 6", "{text}");

    // The same for an XY chart of integer columns.
    let series = vec![vec![(0.0, 3.0), (5.0, 10.0)]];
    let mut modal = open_modal();
    modal.spec.encoding.x.field = Some("volume".to_string());
    modal.spec.encoding.y.field = vec!["price".to_string()];
    modal.show_legend = false;
    let xy = |numbers| Draw::XY {
        series: Some(&series),
        breaks: None,
        values: None,
        names: names(),
        x_axis_kind: XAxisTemporalKind::Numeric,
        x_bounds: None,
        other: false,
        numbers,
    };
    let numbers = PlotNumbers {
        x: whole.clone(),
        y: whole,
    };
    let text = plot_text_with(&ctx, &modal, xy(numbers), g, area);
    // 3 to 10 widens out to whole steps either side.
    assert_eq!(y_labels(&text), ["10", "5", "0"], "{text}");
    assert_eq!(axis_row(&text), "0 2 4", "{text}");
    // A float column ticks at the same nice values, written as exactly as they are.
    let text = plot_text_with(&ctx, &modal, xy(PlotNumbers::default()), g, area);
    assert_eq!(axis_row(&text), "0 2 4", "{text}");
}

/// Under the ASCII set every plot draws ASCII only, and still draws: its marks,
/// its bars, its axes and its legend. The Unicode set keeps its own.
#[test]
fn every_plot_is_ascii_under_the_ascii_set() {
    use crate::chart::chart_data::{BoxPlotStats, HistogramBin, KdeSeries};
    let (ascii, unicode) = (crate::glyphs::ascii(), crate::glyphs::unicode());
    let check = |what: &str, text: &str, marks: &[char]| {
        assert!(text.is_ascii(), "{what}:\n{text}");
        assert!(text.contains("+-"), "{what} has its axis corner:\n{text}");
        for mark in marks {
            assert!(text.contains(*mark), "{what} draws {mark:?}:\n{text}");
        }
    };

    let mut modal = open_modal();
    modal.spec.encoding.x.field = Some("price".to_string());
    modal.spec.encoding.y.field = vec!["price".to_string(), "volume".to_string()];
    modal.show_legend = true;
    let series = vec![
        (0..20).map(|i| (i as f64, (i * i) as f64)).collect(),
        (0..20)
            .map(|i| (i as f64, 400.0 - (i * i) as f64))
            .collect(),
    ];
    let xy = |series| Draw::XY {
        series,
        breaks: None,
        values: None,
        names: names(),
        x_axis_kind: XAxisTemporalKind::Numeric,
        x_bounds: None,
        other: false,
        numbers: PlotNumbers::default(),
    };
    for (chart_type, mark) in [(Mark::Line, '*'), (Mark::Scatter, 'o')] {
        modal.spec.mark = chart_type;
        let text = plot_text(&modal, xy(Some(&series)), ascii);
        check(chart_type.label(), &text, &[mark]);
        // The legend's swatches, ASCII too.
        assert!(text.contains("# price"), "{text}");
        let text = plot_text(&modal, xy(Some(&series)), unicode);
        assert!(text.contains("█ price"), "{text}");
    }
    // Axes before the data is in.
    check("placeholder", &plot_text(&modal, xy(None), ascii), &[]);

    let histogram = HistogramData {
        column: "price".to_string(),
        groups: Vec::new(),
        other: false,
        share: false,
        bins: (0..10)
            .map(|i| HistogramBin {
                center: i as f64 + 0.5,
                count: (1 + i % 4) as f64,
            })
            .collect(),
        x_min: 0.0,
        x_max: 10.0,
        max_count: 4.0,
        rows: Default::default(),
        clipped: None,
    };
    let data = Draw::Histogram {
        data: Some(&histogram),
        x: AxisNumbers::default(),
    };
    check("histogram", &plot_text(&modal, data, ascii), &['#']);

    let box_plot = BoxPlotData {
        stats: ["price", "volume"]
            .iter()
            .map(|name| BoxPlotStats {
                name: name.to_string(),
                min: 0.0,
                q1: 2.0,
                median: 5.0,
                q3: 7.0,
                max: 10.0,
            })
            .collect(),
        of: 0,
        y_min: 0.0,
        y_max: 10.0,
        rows: Default::default(),
        clipped: None,
    };
    let data = Draw::BoxPlot {
        data: Some(&box_plot),
        y: AxisNumbers::default(),
    };
    check("box plot", &plot_text(&modal, data, ascii), &['o']);

    let kde = KdeData {
        other: false,
        series: vec![KdeSeries {
            name: "price".to_string(),
            points: (0..=100)
                .map(|i| {
                    let x = i as f64 / 10.0 - 5.0;
                    (x, (-x * x / 2.0).exp())
                })
                .collect(),
        }],
        x_min: -5.0,
        x_max: 5.0,
        y_max: 1.0,
        rows: Default::default(),
        clipped: None,
    };
    let data = Draw::Kde {
        data: Some(&kde),
        x: AxisNumbers::default(),
    };
    check("KDE", &plot_text(&modal, data, ascii), &['*']);

    // Bars draw no axes of their own.
    let bars = bar_data(5);
    let text = plot_text(&modal, Draw::Bar { data: Some(&bars) }, ascii);
    assert!(text.is_ascii() && text.contains('#'), "bars:\n{text}");
}

/// The legend reads clean over a full plot, with no frame: a short name's row is
/// blank past the name, not the marks behind it.
#[test]
fn the_legend_hides_the_plot_behind_it() {
    let mut modal = open_modal();
    modal.spec.encoding.x.field = Some("price".to_string());
    modal.spec.encoding.y.field = vec!["price".to_string(), "volume".to_string()];
    modal.show_legend = true;
    // A line up and down in every column fills the plot, legend corner included.
    let series: Vec<Vec<(f64, f64)>> = vec![
        (0..240)
            .map(|i| (i as f64 / 2.0, if i % 2 == 0 { 0.0 } else { 100.0 }))
            .collect();
        2
    ];
    for g in [crate::glyphs::ascii(), crate::glyphs::unicode()] {
        let text = plot_text(
            &modal,
            Draw::XY {
                series: Some(&series),
                breaks: None,
                values: None,
                names: names(),
                x_axis_kind: XAxisTemporalKind::Numeric,
                x_bounds: None,
                other: false,
                numbers: PlotNumbers::default(),
            },
            g,
        );
        let swatch = g.bar_eighths[7];
        let price = format!(" {swatch} price  ");
        let volume = format!(" {swatch} volume ");
        let lines: Vec<&str> = text.lines().collect();
        let at = lines
            .iter()
            .position(|l| l.contains(&price))
            .unwrap_or_else(|| panic!("{text}"));
        assert!(lines[at + 1].contains(&volume), "{text}");
        let corner = g.plot.axis.top_left;
        assert!(!lines[at - 1].contains(corner), "no frame: {text}");
    }
}

/// Ten years of daily dates against a value, as the XY view gets them.
fn decade() -> Vec<Vec<(f64, f64)>> {
    // 2015-01-01 on, in days since the epoch.
    vec![
        (0..3653)
            .map(|i| (16436.0 + f64::from(i), 1000.0 + f64::from(i % 400) * 6.0))
            .collect(),
    ]
}

fn xy_dates(series: &Vec<Vec<(f64, f64)>>) -> Draw<'_> {
    Draw::XY {
        series: Some(series),
        breaks: None,
        values: None,
        names: names(),
        x_axis_kind: XAxisTemporalKind::Date,
        x_bounds: None,
        other: false,
        numbers: PlotNumbers::default(),
    }
}

/// On a 300-column terminal a line chart labels its x axis 15 to 20 times, on
/// calendar boundaries, and its y axis about once per four rows, at round values.
#[test]
fn a_wide_chart_carries_ticks_scaled_to_the_space() {
    let mut modal = open_modal();
    modal.spec.encoding.x.field = Some("date".to_string());
    modal.spec.encoding.y.field = vec!["price".to_string()];
    let series = decade();
    let rows = render_view(
        &mut modal,
        View {
            data: xy_dates(&series),
            notes: Vec::new(),
            error: None,
            working: None,
            schema: None,
        },
        300,
        60,
    );
    // The canvas, right of the sidebar.
    let rows: Vec<String> = rows
        .iter()
        .map(|r| r.chars().skip(SIDEBAR_WIDTH as usize + 2).collect())
        .collect();
    let axis = rows.iter().rposition(|r| r.contains('└')).unwrap();
    let x_labels: Vec<&str> = rows[axis + 1].split_whitespace().collect();
    assert!(
        (15..=20).contains(&x_labels.len()),
        "{} x labels: {x_labels:?}",
        x_labels.len()
    );
    assert!(
        x_labels
            .iter()
            .all(|l| l.len() == 4 || ["Apr", "Jul", "Oct"].contains(l)),
        "{x_labels:?}"
    );
    let y_labels: Vec<f64> = rows[..axis]
        .iter()
        .filter_map(|r| r.split_once('┤')?.0.split_whitespace().last()?.parse().ok())
        .collect();
    let plot_rows = axis - 2; // the tab line and the y title
    let per_label = plot_rows as f64 / y_labels.len() as f64;
    assert!(
        (3.0..=5.0).contains(&per_label),
        "{per_label}: {y_labels:?}"
    );
    let step = y_labels[0] - y_labels[1];
    let mantissa = step / 10f64.powf(step.log10().floor());
    assert!([1.0, 2.0, 2.5, 5.0].contains(&mantissa), "{y_labels:?}");
    assert!(
        y_labels.windows(2).all(|w| w[0] - w[1] == step)
            && y_labels.iter().all(|v| v % step == 0.0),
        "{y_labels:?}"
    );
}

/// The grid shows in the view only while it is on, in the `chart_grid` color.
#[test]
fn the_grid_follows_the_toggle() {
    let g = crate::glyphs::unicode();
    let mut modal = open_modal();
    modal.spec.encoding.x.field = Some("date".to_string());
    modal.spec.encoding.y.field = vec!["price".to_string()];
    let series = decade();
    let theme = crate::config::Theme::from_config(&crate::config::ThemeConfig::default())
        .expect("default theme colors must resolve");
    let draw = |modal: &ChartModal| {
        let area = Rect::new(0, 0, 100, 30);
        let mut buf = Buffer::empty(area);
        let ctx = RenderContext::for_test();
        render_plot(area, &mut buf, modal, &theme, &ctx, xy_dates(&series), g);
        buf
    };
    let grid_cells = |buf: &Buffer| {
        buf.content()
            .iter()
            .filter(|c| c.symbol() == g.plot.grid_down || c.symbol() == g.plot.grid_across)
            .collect::<Vec<_>>()
            .len()
    };
    assert_eq!(grid_cells(&draw(&modal)), 0);
    modal.toggle_grid();
    let on = draw(&modal);
    assert!(grid_cells(&on) > 100);
    let grid = theme.chart_grid();
    assert!(
        on.content()
            .iter()
            .filter(|c| c.symbol() == g.plot.grid_across)
            .all(|c| c.fg == grid)
    );
}

/// The light theme's grid stays a color under 16 colors, not the white of the
/// background, and the grid draws in it.
#[test]
fn the_light_grid_survives_sixteen_colors() {
    use ratatui::style::Color;
    let g = crate::glyphs::unicode();
    let sixteen = |hex: &str| {
        let channel = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).unwrap();
        crate::config::rgb_to_basic_ansi(channel(1), channel(3), channel(5))
    };
    let light = crate::config::ColorConfig::light();
    let grid = sixteen(&light.chart_grid);
    assert!(
        !matches!(grid, Color::White | Color::Black | Color::Reset),
        "{grid:?}"
    );
    let dark = sixteen(&crate::config::ColorConfig::default().chart_grid);
    assert!(!matches!(dark, Color::White | Color::Black), "{dark:?}");

    let mut theme =
        crate::config::Theme::from_config(&crate::config::ThemeConfig::default()).unwrap();
    theme.colors.insert("chart_grid".to_string(), grid);
    let mut modal = open_modal();
    modal.spec.encoding.x.field = Some("date".to_string());
    modal.spec.encoding.y.field = vec!["price".to_string()];
    modal.toggle_grid();
    let series = decade();
    let area = Rect::new(0, 0, 80, 24);
    let mut buf = Buffer::empty(area);
    let ctx = RenderContext::for_test();
    render_plot(area, &mut buf, &modal, &theme, &ctx, xy_dates(&series), g);
    let cells: Vec<_> = buf
        .content()
        .iter()
        .filter(|c| c.symbol() == g.plot.grid_across || c.symbol() == g.plot.grid_down)
        .collect();
    assert!(cells.len() > 50);
    assert!(cells.iter().all(|c| c.fg == grid));
}

/// A log scale ticks at the powers of ten, and 2 and 5 between when there is
/// room, every label in one format; the short form names each tick's own k or M.
#[test]
fn log_scale_ticks_fall_on_the_decades() {
    let g = crate::glyphs::unicode();
    let mut modal = open_modal();
    modal.spec.encoding.x.field = Some("x".to_string());
    modal.spec.encoding.y.field = vec!["count".to_string()];
    modal.log_scale = true;
    // 0 to 300,000, as the view has it: ln(1 + y).
    let linear: Vec<Vec<(f64, f64)>> = vec![
        (0..=300)
            .map(|i| (f64::from(i), f64::from(i).powi(2) * 3.333))
            .collect(),
    ];
    let logged: Vec<Vec<(f64, f64)>> = linear
        .iter()
        .map(|points| points.iter().map(|&(x, y)| (x, y.ln_1p())).collect())
        .collect();
    let theme = crate::config::Theme::from_config(&crate::config::ThemeConfig::default()).unwrap();
    let ctx = RenderContext::for_test();
    let y_labels = |height: u16| {
        let area = Rect::new(0, 0, 60, height);
        let mut buf = Buffer::empty(area);
        let data = Draw::XY {
            series: Some(&logged),
            breaks: None,
            values: Some(&linear),
            names: names(),
            x_axis_kind: XAxisTemporalKind::Numeric,
            x_bounds: None,
            other: false,
            numbers: PlotNumbers::default(),
        };
        render_plot(area, &mut buf, &modal, &theme, &ctx, data, g);
        let rows = crate::tests::buffer_lines(&buf);
        let labels: Vec<String> = rows
            .iter()
            .filter_map(|row| {
                let (label, _) = row.split_once(g.plot.tick_y)?;
                let label = label.trim();
                (!label.is_empty()).then(|| label.to_string())
            })
            .collect();
        (labels, rows)
    };
    // Top down: falling, each a 1, 2 or 5 a power of ten up, or zero.
    let nice = |labels: &[String]| {
        let values: Vec<f64> = labels.iter().map(|l| l.parse().unwrap()).collect();
        values.windows(2).all(|w| w[0] > w[1])
            && values.iter().all(|&v| {
                let decade = 10f64.powf(v.log10().floor());
                v == 0.0 || [1.0, 2.0, 5.0].contains(&(v / decade))
            })
    };
    let (tall, rows) = y_labels(40);
    assert!(nice(&tall), "{rows:#?}");
    // Every power of ten up to the top, which the axis widens to.
    for decade in ["0", "10", "100", "1000", "10000", "100000", "1000000"] {
        assert!(tall.contains(&decade.to_string()), "{decade}: {rows:#?}");
    }
    assert_eq!(tall[0], "1000000", "{rows:#?}");
    assert_eq!(tall.last().unwrap(), "0", "{rows:#?}");
    let (short, rows) = y_labels(12);
    assert!(nice(&short), "{rows:#?}");
    assert!(short.len() >= 3 && short.len() < tall.len(), "{rows:#?}");
}

/// With the plot focused the crosshair stands on a point: a line down its column
/// in the accent, and under the plot each series' value there.
#[test]
fn the_crosshair_reads_out_every_series() {
    let mut modal = open_modal();
    modal.spec.encoding.x.field = Some("date".to_string());
    modal.spec.encoding.y.field = vec!["price".to_string(), "volume".to_string()];
    let series: Vec<Vec<(f64, f64)>> = vec![
        (0..10)
            .map(|i| (19_783.0 + f64::from(i), 1.5 * f64::from(i)))
            .collect(),
        (0..10)
            .filter(|i| *i != 4)
            .map(|i| (19_783.0 + f64::from(i), f64::from(i * 100)))
            .collect(),
    ];
    let theme = crate::config::Theme::from_config(&crate::config::ThemeConfig::default()).unwrap();
    let ctx = RenderContext::for_test();
    let draw = |modal: &ChartModal, g: &Glyphs| {
        let area = Rect::new(0, 0, 60, 20);
        let mut buf = Buffer::empty(area);
        let data = Draw::XY {
            series: Some(&series),
            breaks: None,
            values: None,
            names: names(),
            x_axis_kind: XAxisTemporalKind::Date,
            x_bounds: None,
            other: false,
            numbers: PlotNumbers::default(),
        };
        let place = render_plot(area, &mut buf, modal, &theme, &ctx, data, g);
        (buf, place)
    };
    for g in [crate::glyphs::unicode(), crate::glyphs::ascii()] {
        // The options have the keys: no crosshair, no readout.
        modal.plot_focus = false;
        modal.cursor_x = Some(19_786.0);
        let (off, place) = draw(&modal, g);
        let place = place.expect("an XY plot with points says where it is");
        assert!(!crate::tests::buffer_lines(&off).concat().contains("price:"));

        modal.plot_focus = true;
        let (on, _) = draw(&modal, g);
        let rows = crate::tests::buffer_lines(&on);
        let last = rows.last().unwrap().trim_end();
        assert_eq!(
            last, "date: 2024-03-04   price: 4.5   volume: 300",
            "{rows:#?}"
        );
        let column = place.column(19_786.0);
        let accent = theme.accent();
        let marks = (place.graph.top()..place.graph.bottom())
            .filter(|&y| on[(column, y)].symbol() == g.plot.axis.vertical)
            .inspect(|&y| assert_eq!(on[(column, y)].fg, accent))
            .count();
        assert!(marks > 5, "{rows:#?}");

        // A gap in a series reads as one.
        modal.cursor_x = Some(19_787.0);
        let (gap, _) = draw(&modal, g);
        let rows = crate::tests::buffer_lines(&gap);
        assert!(
            rows.last()
                .unwrap()
                .contains(&format!("volume: {}", g.null)),
            "{rows:#?}"
        );
    }
}

/// A scatter of a few points marks each with a whole-cell dot; a dense one
/// switches to braille, which keeps neighbors apart.
#[test]
fn a_scatter_picks_its_marker_by_density() {
    let g = crate::glyphs::unicode();
    let mut modal = open_modal();
    modal.spec.encoding.x.field = Some("price".to_string());
    modal.spec.encoding.y.field = vec!["volume".to_string()];
    modal.spec.mark = Mark::Scatter;
    let draw = |n: usize| {
        let series = vec![
            (0..n)
                .map(|i| (i as f64, ((i * 7919) % 1000) as f64))
                .collect::<Vec<_>>(),
        ];
        let data = Draw::XY {
            series: Some(&series),
            breaks: None,
            values: None,
            names: names(),
            x_axis_kind: XAxisTemporalKind::Numeric,
            x_bounds: None,
            other: false,
            numbers: PlotNumbers::default(),
        };
        plot_text_in(&modal, data, g, Rect::new(0, 0, 60, 20))
    };
    let braille = |text: &str| text.chars().any(|c| ('\u{2801}'..='\u{28ff}').contains(&c));
    let sparse = draw(20);
    assert!(
        sparse.contains(ratatui::symbols::DOT) && !braille(&sparse),
        "{sparse}"
    );
    let dense = draw(2000);
    assert!(
        braille(&dense) && !dense.contains(ratatui::symbols::DOT),
        "{dense}"
    );
}

/// A histogram's bins fill their columns, with a column of air between bins wide
/// enough to spare one.
#[test]
fn histogram_bins_fill_their_columns() {
    use crate::chart::chart_data::HistogramBin;
    let histogram = HistogramData {
        column: "price".to_string(),
        groups: Vec::new(),
        other: false,
        share: false,
        bins: (0..4)
            .map(|i| HistogramBin {
                center: f64::from(i) * 25.0 + 12.5,
                count: 10.0,
            })
            .collect(),
        x_min: 0.0,
        x_max: 100.0,
        max_count: 10.0,
        rows: Default::default(),
        clipped: None,
    };
    let points = bin_columns(&histogram, [0.0, 100.0], 41);
    // Four bins of about ten columns, less a gap after each but the last.
    assert_eq!(points.len(), 41 - 3, "{points:?}");
    let text = plot_text_in(
        &open_modal(),
        Draw::Histogram {
            data: Some(&histogram),
            x: AxisNumbers::default(),
        },
        crate::glyphs::unicode(),
        Rect::new(0, 0, 60, 20),
    );
    let row = text.lines().find(|r| r.contains('█')).expect(&text);
    let bars: Vec<&str> = row.split(' ').filter(|r| r.contains('█')).collect();
    assert_eq!(bars.len(), 4, "{text}");
}

#[test]
fn a_tiny_area_never_panics() {
    for (w, h) in [(0, 0), (3, 2), (10, 4), (20, 6), (60, 20), (80, 24)] {
        let mut modal = open_modal();
        modal.focus = ChartFocus::X;
        modal.open_picker();
        let _ = render_rows(&mut modal, w, h);
        let mut data = bar_data(30);
        data.bars[3].value = -4.0;
        data.bars[4].label = Some("a label longer than the whole canvas is".to_string());
        let _ = render_bars(&data, w, h);
    }
}