chartlet 0.13.0

Compile structured data into deterministic, accessible static charts
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
use std::fmt::Write as _;

use super::{
    AREA_CLASSES, LABEL_LINE, LABEL_SIZE, LEGEND_HEIGHT, LEGEND_ROW, PANEL_GUTTER, PANEL_MARGIN,
    PlotArea,
    annotation::{push_marker, push_marker_label, push_rule, push_zone},
    axis::{NumericScale, format_value},
    count, fit_text,
    labels::LabelSpace,
    legend::{add_layer_legend, legend_rows},
    panel_plot_pixels,
    title::{push_title, title_extra},
    tooltip, tooltips_fit,
};
use crate::{
    error::ChartWarning,
    metrics::TextMetrics,
    scene::{Circle, Element, Hook, Line, Polyline, Scene, Text, TextAnchor},
    spec::{
        ChartSpec, ChartType, Dash, LayerRef, LayerSpec, LegendPlacement, MAX_SERIES, Mark,
        NumberStyle, Stroke, Tooltips,
    },
    time,
    time::{Precision, TimeZone},
};

/// Target distance between two time-axis ticks, in pixels: dates need room for `2026-02-02`, a
/// year label is less than half as wide, a date with a time of day such as `2026-03-01 12:00`
/// needs more.
const TIME_TICK_SPACING: u32 = 90;
const YEAR_TICK_SPACING: u32 = 64;
const MINUTE_TICK_SPACING: u32 = 120;

/// The tick spacing that fits the labels an axis of this precision writes.
const fn time_tick_spacing(precision: Precision) -> u32 {
    match precision {
        Precision::Year | Precision::Number(_) => YEAR_TICK_SPACING,
        Precision::Month | Precision::Day => TIME_TICK_SPACING,
        Precision::Minute => MINUTE_TICK_SPACING,
    }
}

/// Space between the end of the plot and the names at the ends of its lines.
const END_LABEL_GAP: f64 = 8.0;
/// Outer margin of a small-multiples grid, left and right.
pub(super) const MULTIPLES_MARGIN: f64 = 16.0;
/// Inset that keeps the outermost points and their labels inside the plot.
const TIME_INSET: f64 = 6.0;
/// Above this many observations a layer is drawn as a line only. At the default width the
/// markers and their labels would sit closer together than about eleven pixels, and every marker
/// and tooltip costs bytes in the output; the line and the data table carry the values instead.
const MAX_TIME_MARKERS: usize = 60;
/// The weight classes of a line, by [`Stroke`].
const LINE_WEIGHTS: [&str; 4] = [
    "",
    " chartlet-line-thin",
    " chartlet-line-bold",
    " chartlet-line-medium",
];
/// The pattern classes of a line: solid, dashed because modeled, dashed, dotted. A modeled line
/// keeps its own class, which the stylesheet dashes.
const LINE_DASHES: [&str; 4] = [
    "",
    " chartlet-line-modeled",
    " chartlet-line-dashed",
    " chartlet-line-dotted",
];
/// Every combination of color, pattern and weight a time line can take, built once: a declared
/// color first, then the palette colors.
static LINE_CLASSES: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
/// Fill of an uncertainty band, in the palette color of its line.
const BAND_CLASSES: [&str; MAX_SERIES] = [
    "chartlet-band chartlet-band-series-1",
    "chartlet-band chartlet-band-series-2",
    "chartlet-band chartlet-band-series-3",
    "chartlet-band chartlet-band-series-4",
];
/// Markers of a layer that takes a palette color other than the first.
pub(super) const POINT_CLASSES: [&str; MAX_SERIES] = [
    "chartlet-point chartlet-point-series-1",
    "chartlet-point chartlet-point-series-2",
    "chartlet-point chartlet-point-series-3",
    "chartlet-point chartlet-point-series-4",
];

/// Lays out a time chart: one shared time axis and one value axis per pane, with the layers of
/// every pane drawn inside it.
pub(super) fn layout_time(
    spec: &ChartSpec,
    warnings: &mut Vec<ChartWarning>,
    metrics: &impl TextMetrics,
) -> Scene {
    if spec.sparkline {
        return layout_sparkline(spec, warnings, metrics);
    }
    let zone = spec.time_zone().unwrap_or_default();
    let width = f64::from(spec.width);
    let height = f64::from(spec.height);
    let left = time_gutter(spec, zone, warnings, metrics);
    let end_labels = spec.legend == LegendPlacement::End;
    let right = f64::from(super::plot_margin(spec.width))
        + if end_labels {
            end_label_room(spec, width, metrics)
        } else {
            0.0
        };
    // Candles always take a legend entry: it says which body is rising and which is falling.
    let layered = !end_labels
        && (spec.series_names().len() > 1 || spec.layers().any(|layer| layer.mark == Mark::Ohlc));
    // Without a drawn title the legend and the plot move up into its place; a title on two lines
    // pushes them down.
    let head = -title_extra(spec, width - left - right, metrics);
    let legend = if layered {
        count(legend_rows(spec, width - left - right, metrics)) * LEGEND_HEIGHT
    } else {
        0.0
    };
    // With neither title, legend nor a value axis title above the first pane, nothing sits above
    // the plot but the half of its top tick label.
    let bare = !spec.show_title
        && legend == 0.0
        && spec
            .panes
            .first()
            .is_none_or(|pane| pane.value_axis.title.is_none());
    let top = if bare { 14.0 } else { 78.0 - head + legend };
    let bottom = if spec.time_axis.title.is_some() {
        56.0
    } else {
        36.0
    };
    let plot = PlotArea {
        left,
        top,
        width: width - left - right,
        height: super::plot_height(height - top - bottom, warnings),
        vertical_bars: true,
    };

    let frames = pane_frames(spec, zone, plot, warnings);
    let mut elements = Vec::new();
    push_title(
        &mut elements,
        spec,
        plot.left,
        plot.width,
        metrics,
        warnings,
    );
    for (pane_index, frame) in frames.iter().enumerate() {
        let bottom_pane = pane_index + 1 == frames.len();
        push_pane_axes(
            spec,
            pane_index,
            frame,
            bottom_pane,
            &mut elements,
            warnings,
            metrics,
        );
    }
    if layered {
        add_layer_legend(
            spec,
            LEGEND_ROW - head,
            plot.left,
            plot.width,
            &mut elements,
            warnings,
            metrics,
        );
    }

    for (pane_index, frame) in frames.iter().enumerate() {
        elements.push(frame.hook(pane_index));
        draw_pane(
            spec,
            pane_index,
            frame,
            Detail::Full,
            &mut elements,
            warnings,
            metrics,
        );
    }
    if end_labels {
        push_end_labels(spec, &frames, &mut elements, warnings, metrics);
    }

    push_time_axis_title(spec, plot, height, &mut elements, warnings, metrics);

    Scene {
        width: spec.width,
        height: spec.height,
        elements,
    }
}

/// The title, the legend and the shared value axis title above a small-multiples grid; returns
/// where the grid starts.
pub(super) fn multiples_header(
    spec: &ChartSpec,
    elements: &mut Vec<Element>,
    warnings: &mut Vec<ChartWarning>,
    metrics: &impl TextMetrics,
) -> f64 {
    let width = f64::from(spec.width);
    push_title(
        elements,
        spec,
        MULTIPLES_MARGIN,
        width - 2.0 * MULTIPLES_MARGIN,
        metrics,
        warnings,
    );

    let head = title_extra(spec, width - 2.0 * MULTIPLES_MARGIN, metrics);
    let mut cursor = LEGEND_ROW + head;
    if spec.series_names().len() > 1 {
        add_layer_legend(
            spec,
            LEGEND_ROW + head,
            MULTIPLES_MARGIN,
            width - 2.0 * MULTIPLES_MARGIN,
            elements,
            warnings,
            metrics,
        );
        cursor += count(legend_rows(spec, width - 2.0 * MULTIPLES_MARGIN, metrics)) * LEGEND_HEIGHT;
    }
    if let Some(axis_title) = &spec.value_axis.title {
        elements.push(Element::Text(Text {
            x: MULTIPLES_MARGIN,
            y: cursor + 10.0,
            class: "chartlet-axis-title",
            anchor: TextAnchor::Start,
            content: fit_text(
                axis_title,
                width - 2.0 * MULTIPLES_MARGIN,
                LABEL_SIZE,
                metrics,
                warnings,
                "/valueAxis/title",
            ),
        }));
        cursor += 20.0;
    }
    cursor + 8.0
}

/// Lays out small multiples: a grid of small time plots that share the value scale and the time
/// span, so that the panels can be compared by position alone.
/// A sparkline: the lines and areas of the one pane across the whole canvas, inset by the dot at
/// the end of each line.
fn layout_sparkline(
    spec: &ChartSpec,
    warnings: &mut Vec<ChartWarning>,
    metrics: &impl TextMetrics,
) -> Scene {
    let zone = spec.time_zone().unwrap_or_default();
    let inset = 4.0;
    let plot = PlotArea {
        left: inset - TIME_INSET,
        top: inset,
        width: f64::from(spec.width) - 2.0 * (inset - TIME_INSET),
        height: f64::from(spec.height) - 2.0 * inset,
        vertical_bars: true,
    };
    let frames = pane_frames(spec, zone, plot, warnings);
    let mut elements = Vec::new();
    for (pane_index, frame) in frames.iter().enumerate() {
        elements.push(frame.hook(pane_index));
        draw_pane(
            spec,
            pane_index,
            frame,
            Detail::Spark,
            &mut elements,
            warnings,
            metrics,
        );
    }
    Scene {
        width: spec.width,
        height: spec.height,
        elements,
    }
}

/// The title of the time axis, centred below the plot.
fn push_time_axis_title(
    spec: &ChartSpec,
    plot: PlotArea,
    height: f64,
    elements: &mut Vec<Element>,
    warnings: &mut Vec<ChartWarning>,
    metrics: &impl TextMetrics,
) {
    if let Some(title) = &spec.time_axis.title {
        let title = fit_text(
            title,
            plot.width,
            LABEL_SIZE,
            metrics,
            warnings,
            "/timeAxis/title",
        );
        elements.push(Element::Text(Text {
            x: plot.left + plot.width / 2.0,
            y: height - 14.0,
            class: "chartlet-axis-title",
            anchor: TextAnchor::Middle,
            content: title,
        }));
    }
}

/// The widest name a line takes at its end, with the gap before it, at most a third of the chart.
fn end_label_room(spec: &ChartSpec, width: f64, metrics: &impl TextMetrics) -> f64 {
    let widest = spec
        .data_layers()
        .map(|entry| metrics.width(&end_label(spec, entry), LABEL_SIZE))
        .fold(0.0, f64::max);
    (widest + END_LABEL_GAP).min(width / 3.0)
}

/// The name at the end of a line: its legend entry, so a modeled series says so.
fn end_label(spec: &ChartSpec, entry: LayerRef) -> String {
    let words = spec.locale.words();
    let name = entry.layer.name.as_deref().unwrap_or(words.value);
    if entry.layer.modeled {
        format!("{name} ({})", words.modeled)
    } else {
        name.to_owned()
    }
}

/// Names every line and area at its last observation, right of the plot. Names that would overlap
/// move apart, at least a line of text from each other, and stay inside their pane.
fn push_end_labels(
    spec: &ChartSpec,
    frames: &[TimeFrame],
    elements: &mut Vec<Element>,
    warnings: &mut Vec<ChartWarning>,
    metrics: &impl TextMetrics,
) {
    let width = f64::from(spec.width);
    for (pane_index, frame) in frames.iter().enumerate() {
        let mut labels: Vec<(f64, String, String)> = spec
            .data_layers()
            .filter(|entry| entry.pane == pane_index)
            .filter_map(|entry| {
                let (_, value) = *spec.drawn_points(entry, frame.zone).last()?;
                let path = format!("/panes/{}/layers/{}/name", entry.pane, entry.local);
                Some((frame.y(value) + 4.0, end_label(spec, entry), path))
            })
            .collect();
        crate::sort::by(&mut labels, |a, b| a.0.total_cmp(&b.0));
        let plot = frame.plot;
        let mut floor = plot.top + LABEL_SIZE;
        for label in &mut labels {
            label.0 = label.0.max(floor);
            floor = label.0 + LABEL_LINE;
        }
        // Pushed past the bottom of the pane, the lowest names move back up together.
        let overflow = labels
            .last()
            .map_or(0.0, |last| (last.0 - (plot.top + plot.height)).max(0.0));
        let x = plot.left + plot.width + END_LABEL_GAP;
        for (y, name, path) in labels {
            elements.push(Element::Text(Text {
                x,
                y: y - overflow,
                class: "chartlet-legend",
                anchor: TextAnchor::Start,
                content: fit_text(&name, width - x - 4.0, LABEL_SIZE, metrics, warnings, &path),
            }));
        }
    }
}

/// A text of a panel's heading on up to two lines of `width`; only the second is shortened if
/// it still does not fit.
fn panel_lines(
    text: &str,
    width: f64,
    size: f64,
    metrics: &impl TextMetrics,
    warnings: &mut Vec<ChartWarning>,
    path: &str,
) -> Vec<String> {
    match super::title::two_lines(text, width, size, metrics) {
        Some((first, rest)) => vec![
            first.to_owned(),
            fit_text(rest, width, size, metrics, warnings, path),
        ],
        None => vec![fit_text(text, width, size, metrics, warnings, path)],
    }
}

/// The lines of a panel's title and of its note, and the class of the note.
pub(super) type PanelHead = (Vec<String>, Vec<String>, &'static str);

/// Height of a line of a panel title and of a panel note.
const PANEL_TITLE_LINE: f64 = 16.0;
const PANEL_NOTE_LINE: f64 = 15.0;

/// The heading of every panel: its title and its note, each on up to two lines. Every panel
/// reserves as many lines as the longest heading needs, so that the plots stay aligned.
pub(super) fn panel_heads(
    spec: &ChartSpec,
    width: f64,
    warnings: &mut Vec<ChartWarning>,
    metrics: &impl TextMetrics,
) -> (Vec<PanelHead>, f64, usize) {
    let heads: Vec<PanelHead> = spec
        .panes
        .iter()
        .enumerate()
        .map(|(index, pane)| {
            let title = panel_lines(
                pane.title.as_deref().unwrap_or_default(),
                width,
                13.0,
                metrics,
                warnings,
                &format!("/panes/{index}/title"),
            );
            let note = pane.note.as_deref().map_or_else(Vec::new, |note| {
                panel_lines(
                    note,
                    width,
                    LABEL_SIZE,
                    metrics,
                    warnings,
                    &format!("/panes/{index}/note"),
                )
            });
            let class = if pane.note_emphasis {
                "chartlet-panel-note chartlet-panel-note-strong"
            } else {
                "chartlet-panel-note"
            };
            (title, note, class)
        })
        .collect();
    let title_lines = heads
        .iter()
        .map(|(title, ..)| title.len())
        .max()
        .unwrap_or(1);
    let note_lines = heads
        .iter()
        .map(|(_, note, _)| note.len())
        .max()
        .unwrap_or(0);
    let height = 14.0 + PANEL_TITLE_LINE * count(title_lines) + PANEL_NOTE_LINE * count(note_lines);
    (heads, height, title_lines)
}

/// The heading of one panel above its plot, starting at `cell_top`.
pub(super) fn push_panel_head(
    (title, note, note_class): &PanelHead,
    title_lines: usize,
    plot: PlotArea,
    cell_top: f64,
    elements: &mut Vec<Element>,
) {
    for (index, line) in title.iter().enumerate() {
        elements.push(Element::Text(Text {
            x: plot.left,
            y: cell_top + 18.0 + PANEL_TITLE_LINE * count(index),
            class: "chartlet-panel-title",
            anchor: TextAnchor::Start,
            content: line.clone(),
        }));
    }
    let below = cell_top + 18.0 + PANEL_TITLE_LINE * count(title_lines - 1);
    for (index, line) in note.iter().enumerate() {
        elements.push(Element::Text(Text {
            x: plot.left,
            y: below + PANEL_NOTE_LINE * count(index + 1),
            class: note_class,
            anchor: TextAnchor::Start,
            content: line.clone(),
        }));
    }
}

/// The title of the shared time axis below the grid of small multiples.
fn push_multiples_time_title(
    spec: &ChartSpec,
    elements: &mut Vec<Element>,
    warnings: &mut Vec<ChartWarning>,
    metrics: &impl TextMetrics,
) {
    let (width, height) = (f64::from(spec.width), f64::from(spec.height));
    if let Some(axis_title) = &spec.time_axis.title {
        elements.push(Element::Text(Text {
            x: width / 2.0,
            y: height - 14.0,
            class: "chartlet-axis-title",
            anchor: TextAnchor::Middle,
            content: fit_text(
                axis_title,
                width - 2.0 * MULTIPLES_MARGIN,
                LABEL_SIZE,
                metrics,
                warnings,
                "/timeAxis/title",
            ),
        }));
    }
}

pub(super) fn layout_multiples(
    spec: &ChartSpec,
    warnings: &mut Vec<ChartWarning>,
    metrics: &impl TextMetrics,
) -> Scene {
    let zone = spec.time_zone().unwrap_or_default();
    let width = f64::from(spec.width);
    let height = f64::from(spec.height);
    let columns = spec.multiples_columns();
    let panels = spec.panes.len();
    let rows = panels.div_ceil(usize::try_from(columns).expect("columns are limited"));

    let mut elements = Vec::new();
    let grid_top = multiples_header(spec, &mut elements, warnings, metrics);
    let grid_bottom = height
        - if spec.time_axis.title.is_some() {
            36.0
        } else {
            12.0
        };
    let cell_width = (width - 2.0 * MULTIPLES_MARGIN) / f64::from(columns);
    let cell_height = (grid_bottom - grid_top) / count(rows);
    let panel_gutter = multiples_gutter(spec, zone, warnings, metrics);
    let (heads, head_height, title_lines) = panel_heads(
        spec,
        cell_width - panel_gutter - f64::from(PANEL_MARGIN),
        warnings,
        metrics,
    );

    let (span, slots) = time_axis(spec, zone);
    let precision = spec.time_precision(zone);
    let shared = time_scale(spec, zone, None);
    let max_ticks = usize::try_from(
        (panel_plot_pixels(spec.width, columns) / time_tick_spacing(spec.observed_precision(zone)))
            .max(2),
    )
    .expect("a usize is at least 32 bits wide");

    for (pane_index, head) in heads.iter().enumerate() {
        let column = pane_index % usize::try_from(columns).expect("columns are limited");
        let row = pane_index / usize::try_from(columns).expect("columns are limited");
        let cell_left = MULTIPLES_MARGIN + cell_width * count(column);
        let cell_top = grid_top + cell_height * count(row);
        let plot = PlotArea {
            left: cell_left + panel_gutter,
            top: cell_top + head_height,
            width: cell_width - panel_gutter - f64::from(PANEL_MARGIN),
            height: cell_height - head_height - 28.0,
            vertical_bars: true,
        };
        let frame = TimeFrame {
            plot,
            span,
            slots: slots.clone(),
            zone,
            precision,
            tick_step: spec.time_axis.step,
            sub_day: spec.observed_precision(zone) == Precision::Minute,
            unit: spec.axis_unit(pane_index).map(str::to_owned),
            scale: if spec.independent_axes {
                time_scale(spec, zone, Some(pane_index))
            } else {
                shared
            },
            style: spec.number_style(),
            reversed: spec.time_axis.reverse,
        };

        push_panel_head(head, title_lines, plot, cell_top, &mut elements);
        let unit = fitted_unit(
            spec.axis_unit(pane_index),
            &frame,
            cell_left,
            "/valueAxis/unit",
            warnings,
            metrics,
        );
        push_value_grid(&frame, unit.as_deref(), &mut elements);
        push_time_ticks(&frame, max_ticks, true, width, metrics, &mut elements);
        elements.push(frame.hook(pane_index));
        draw_pane(
            spec,
            pane_index,
            &frame,
            Detail::Compact,
            &mut elements,
            warnings,
            metrics,
        );
    }

    if cell_height - head_height - 28.0 < 60.0 {
        warnings.push(ChartWarning::new(
            "dense_chart",
            "/height",
            "the panels are less than 60 pixels tall; raise height or use more columns",
        ));
    }

    push_multiples_time_title(spec, &mut elements, warnings, metrics);

    Scene {
        width: spec.width,
        height: spec.height,
        elements,
    }
}

/// Title, value grid, value ticks and time ticks, shared by every pane.
/// Draws one polyline per layer, plus markers and value labels while the observations stay far
/// enough apart for them to be readable.
/// Everything a pane needs to map an observation onto its plot.
pub(crate) struct TimeFrame {
    pub(super) plot: PlotArea,
    span: (i64, i64),
    /// With gaps collapsed, the observed timestamps in order, each placed at the same distance
    /// from the next; `None` while the axis keeps the distances in time.
    slots: Option<Vec<i64>>,
    pub(crate) zone: TimeZone,
    pub(crate) precision: Precision,
    /// The declared distance between time ticks, if any.
    tick_step: Option<f64>,
    /// Whether the observations carry a time of day, so that ticks may fall within a day; taken
    /// from the data, not from a declared precision.
    sub_day: bool,
    /// The unit of the pane's value axis, which tooltips write after a value.
    pub(crate) unit: Option<String>,
    scale: NumericScale,
    /// How the pane writes its values: its own value axis on a time chart, the shared one in
    /// small multiples.
    pub(crate) style: NumberStyle,
    /// The axis runs from right to left: the largest value, such as the oldest age in millions of
    /// years, at the left.
    reversed: bool,
}

impl TimeFrame {
    /// The position of a timestamp. With gaps collapsed, a time between two observations takes
    /// the slot of the next one.
    pub(crate) fn x(&self, epoch: i64) -> f64 {
        self.oriented(match &self.slots {
            Some(slots) => slot_x(
                slots.partition_point(|slot| *slot < epoch),
                slots.len(),
                self.plot,
            ),
            None => time_x(epoch, self.span, self.plot),
        })
    }

    /// A position mirrored across the plot when the axis runs from right to left.
    fn oriented(&self, x: f64) -> f64 {
        if self.reversed {
            2.0 * self.plot.left + self.plot.width - x
        } else {
            x
        }
    }

    /// The edge of the plot where the axis starts, and the one where it ends.
    pub(super) fn edges(&self) -> (f64, f64) {
        let (left, right) = (self.plot.left, self.plot.left + self.plot.width);
        if self.reversed {
            (right, left)
        } else {
            (left, right)
        }
    }

    /// The position of the end of a span of time. With gaps collapsed, a time between two
    /// observations takes the slot of the previous one, so a zone covers only the observations
    /// between its edges.
    pub(super) fn x_until(&self, epoch: i64) -> f64 {
        self.oriented(match &self.slots {
            Some(slots) => slot_x(
                slots
                    .partition_point(|slot| *slot <= epoch)
                    .saturating_sub(1),
                slots.len(),
                self.plot,
            ),
            None => time_x(epoch, self.span, self.plot),
        })
    }

    pub(crate) fn y(&self, value: f64) -> f64 {
        self.scale
            .map(value, self.plot.top + self.plot.height, self.plot.top)
    }

    /// The plot hook of this pane: every slot with collapsed gaps, otherwise both ends of the
    /// span, and both ends of the value scale.
    fn hook(&self, pane: usize) -> Element {
        #[allow(clippy::cast_precision_loss)]
        let x = match &self.slots {
            Some(slots) => slots
                .iter()
                .map(|slot| (*slot as f64, self.x(*slot)))
                .collect(),
            None => vec![
                (self.span.0 as f64, self.x(self.span.0)),
                (self.span.1 as f64, self.x(self.span.1)),
            ],
        };
        let (min, max) = self.scale.ends();
        Element::Hook(Hook::Plot {
            pane,
            x,
            y: [(min, self.y(min)), (max, self.y(max))],
            log: self.scale.is_log(),
        })
    }
}

/// How much a pane draws besides its lines: a time chart labels its values, a small-multiples
/// panel is too small for that and keeps smaller markers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Detail {
    Full,
    Compact,
    /// A sparkline: no markers, only a dot at the last observation of each line.
    Spark,
}

/// The gutter left of each panel of small multiples: the regular panel gutter, wider where the
/// tick labels or the unit after the top one need it, at most 40 % of a panel.
fn multiples_gutter(
    spec: &ChartSpec,
    zone: TimeZone,
    warnings: &mut Vec<ChartWarning>,
    metrics: &impl TextMetrics,
) -> f64 {
    let gutter = f64::from(PANEL_GUTTER);
    let style = spec.number_style();
    // Panels on axes of their own each have their ticks; otherwise they share one scale.
    let panes: Vec<Option<usize>> = if spec.independent_axes {
        (0..spec.panes.len()).map(Some).collect()
    } else {
        vec![None]
    };
    let labels: Vec<String> = panes
        .into_iter()
        .flat_map(|pane| {
            let scale = time_scale(spec, zone, pane);
            scale
                .ticks()
                .map(move |value| scale.tick_label(value, style))
                .collect::<Vec<_>>()
        })
        .collect();
    let width = |text: &str| super::WithReserve(metrics).width(text, LABEL_SIZE);
    let plain = labels.iter().map(|label| width(label)).fold(0.0, f64::max);
    let with_unit = spec.value_axis.unit.as_deref().map_or(plain, |unit| {
        labels
            .iter()
            .map(|label| width(&format!("{label} {unit}")))
            .fold(0.0, f64::max)
    });
    // At most 40 % of a panel, so that its plot keeps its width; the unit gives way first.
    let cell =
        (f64::from(spec.width) - 2.0 * MULTIPLES_MARGIN) / f64::from(spec.multiples_columns());
    let most = (cell * 0.4).max(gutter);
    if plain + 16.0 > most {
        warnings.push(ChartWarning::new(
            "dense_chart",
            "/columns",
            "the value tick labels need more room than the panels leave them; use fewer columns or a wider chart",
        ));
    }
    gutter.max(with_unit + 16.0).min(most)
}

/// The gutter left of a time chart's plot: as wide as its widest value tick label needs.
fn time_gutter(
    spec: &ChartSpec,
    zone: TimeZone,
    warnings: &mut Vec<ChartWarning>,
    metrics: &impl TextMetrics,
) -> f64 {
    let gutter = f64::from(super::axis_gutter(spec.width));
    let widest = (0..spec.panes.len())
        .flat_map(|pane| {
            let scale = time_scale(spec, zone, Some(pane));
            let style = spec.pane_style(pane);
            // Measured as if every label carried the unit: one of them does, the top one.
            let unit = spec
                .axis_unit(pane)
                .map(|unit| format!(" {unit}"))
                .unwrap_or_default();
            scale
                .ticks()
                .map(move |value| format!("{}{unit}", scale.tick_label(value, style)))
                .collect::<Vec<_>>()
        })
        .map(|label| super::WithReserve(metrics).width(&label, LABEL_SIZE))
        .fold(0.0, f64::max);
    // The labels end 10 pixels left of the plot and keep 12 from the edge of the chart. Short
    // labels take less than the regular gutter; long ones, such as a value with its unit, more,
    // up to 40 % of the chart.
    let needed = widest + 22.0;
    let most = f64::from(spec.width) * 0.4;
    if needed > most.max(gutter) {
        warnings.push(ChartWarning::new(
            "dense_chart",
            "/width",
            "the value tick labels are wider than the chart leaves them and are cut at its left edge; raise width or use fewer digits",
        ));
    }
    if needed <= gutter {
        needed.max(28.0)
    } else {
        needed.min(most).max(gutter)
    }
}

/// The value scale of one pane of a time chart, or of all small multiples when `pane` is `None`:
/// every observation, every candle's high and low, every band edge, every horizontal reference
/// line, every point marker and every zone edge, so that none of them falls outside the plot. An
/// area is filled down to zero, so a pane with one always shows zero.
fn time_scale(spec: &ChartSpec, zone: TimeZone, pane: Option<usize>) -> NumericScale {
    let inside = |pane_index: usize| pane.is_none_or(|pane| pane == pane_index);
    let layers = || {
        spec.indexed_layers()
            .filter(|entry| inside(entry.pane))
            .map(|entry| entry.layer)
    };
    let mut values = Vec::new();
    for entry in spec.data_layers().filter(|entry| inside(entry.pane)) {
        values.extend(
            spec.drawn_points(entry, zone)
                .into_iter()
                .map(|(_, value)| value),
        );
        for (_, lower, upper) in entry.layer.resolved_band(zone) {
            values.push(lower);
            values.push(upper);
        }
        for (_, [_, high, low, _]) in entry.layer.resolved_candles(zone) {
            values.push(high);
            values.push(low);
        }
    }
    values.extend(
        layers()
            .filter(|layer| layer.mark == Mark::Annotation)
            .filter_map(|layer| layer.value),
    );
    values.extend(
        layers()
            .filter(|layer| layer.mark == Mark::Band)
            .flat_map(|layer| [layer.bottom, layer.top])
            .flatten(),
    );
    let area = layers().any(|layer| layer.mark == Mark::Area);
    // Small multiples share the top-level value axis, even when every panel gets its own scale.
    let axis = match pane {
        Some(pane) if spec.chart_type != ChartType::Multiples => &spec.panes[pane].value_axis,
        _ => &spec.value_axis,
    };
    NumericScale::for_axis(values.into_iter(), area, axis)
}

/// The name a tooltip gives a layer: in small multiples the panel title comes first.
pub(crate) fn tooltip_name(spec: &ChartSpec, entry: LayerRef) -> Option<String> {
    let title = if spec.chart_type == ChartType::Multiples {
        spec.panes[entry.pane].title.clone()
    } else {
        None
    };
    match (title, &entry.layer.name) {
        (Some(title), Some(name)) => Some(format!("{title} · {name}")),
        (Some(title), None) => Some(title),
        (None, name) => name.clone(),
    }
}

/// Draws the layers of one pane: zones first, filled areas and uncertainty bands over them,
/// reference lines over those, then the lines with their markers, the point markers, and the
/// labels of every annotation last so nothing covers them.
fn draw_pane(
    spec: &ChartSpec,
    pane: usize,
    frame: &TimeFrame,
    detail: Detail,
    elements: &mut Vec<Element>,
    warnings: &mut Vec<ChartWarning>,
    metrics: &impl TextMetrics,
) {
    let entries: Vec<LayerRef> = spec
        .indexed_layers()
        .filter(|entry| entry.pane == pane)
        .collect();
    let mut space = LabelSpace::new(frame, &entries);
    let mut rule_labels = Vec::new();

    for entry in entries
        .iter()
        .filter(|entry| entry.layer.mark == Mark::Band)
    {
        elements.push(Element::Hook(Hook::Layer(entry.global)));
        push_zone(
            spec,
            *entry,
            frame,
            elements,
            &mut rule_labels,
            &mut space,
            warnings,
            metrics,
        );
        elements.push(Element::Hook(Hook::End));
    }
    for entry in entries
        .iter()
        .filter(|entry| entry.layer.mark == Mark::Area)
    {
        elements.push(Element::Hook(Hook::Layer(entry.global)));
        push_area(spec, *entry, frame, elements);
        elements.push(Element::Hook(Hook::End));
    }
    for entry in entries
        .iter()
        .filter(|entry| entry.layer.is_data() && entry.layer.has_band())
    {
        elements.push(Element::Hook(Hook::Layer(entry.global)));
        push_band(spec, *entry, frame, elements);
        elements.push(Element::Hook(Hook::End));
    }

    for entry in entries.iter().filter(|entry| entry.layer.is_rule()) {
        elements.push(Element::Hook(Hook::Layer(entry.global)));
        push_rule(
            *entry,
            frame,
            elements,
            &mut rule_labels,
            &mut space,
            warnings,
            metrics,
        );
        elements.push(Element::Hook(Hook::End));
    }

    // Candles go below the lines, so that a moving average stays readable across them.
    for entry in entries
        .iter()
        .filter(|entry| entry.layer.mark == Mark::Ohlc)
    {
        elements.push(Element::Hook(Hook::Layer(entry.global)));
        crate::ohlc::push_candles(spec, *entry, frame, elements);
        elements.push(Element::Hook(Hook::End));
    }
    for entry in entries
        .iter()
        .filter(|entry| entry.layer.is_data() && entry.layer.mark != Mark::Ohlc)
    {
        elements.push(Element::Hook(Hook::Layer(entry.global)));
        push_line(spec, *entry, frame, detail, elements, warnings, metrics);
        elements.push(Element::Hook(Hook::End));
    }

    let markers: Vec<LayerRef> = entries
        .iter()
        .filter(|entry| entry.layer.is_marker())
        .copied()
        .collect();
    let radius = if detail == Detail::Full { 6.0 } else { 4.5 };
    for entry in &markers {
        elements.push(Element::Hook(Hook::Layer(entry.global)));
        push_marker(*entry, frame, radius, elements, &mut space);
        elements.push(Element::Hook(Hook::End));
    }
    for entry in &markers {
        push_marker_label(
            *entry,
            frame,
            radius,
            &mut rule_labels,
            &mut space,
            warnings,
            metrics,
        );
    }
    elements.extend(rule_labels);
}

/// The region between an area layer's line and zero, one closed outline per run of values: along
/// the line and back along the zero line. A stacked area goes back along the top of the area
/// below it instead, which has the same times and no gaps. It takes the layer's color at the
/// band's low opacity; the line itself is drawn on top with the other lines.
fn push_area(spec: &ChartSpec, entry: LayerRef, frame: &TimeFrame, elements: &mut Vec<Element>) {
    let explicit = entry.layer.resolved_color().is_some();
    let palette = spec.palette_index(entry.layer);
    let base = spec.stack_base(entry, frame.zone);
    let segments = if base.is_some() {
        vec![spec.drawn_points(entry, frame.zone)]
    } else {
        entry.layer.resolved_segments(frame.zone)
    };
    for segment in segments {
        if segment.len() < 2 {
            continue;
        }
        let (first, last) = (segment[0].0, segment[segment.len() - 1].0);
        let mut outline = entry.layer.curve.points(
            segment
                .iter()
                .map(|(epoch, value)| (frame.x(*epoch), frame.y(*value)))
                .collect(),
        );
        extend_last_step(entry.layer, frame, last, &mut outline);
        let end = outline.last().map_or(frame.x(last), |point| point.0);
        if let Some(base) = &base {
            let below = entry.layer.curve.points(
                segment
                    .iter()
                    .zip(base)
                    .map(|((epoch, _), below)| (frame.x(*epoch), frame.y(*below)))
                    .collect(),
            );
            outline.extend(below.into_iter().rev());
        } else {
            outline.push((end, frame.y(0.0)));
            outline.push((frame.x(first), frame.y(0.0)));
        }
        elements.push(Element::Polyline(Polyline {
            points: outline,
            class: if explicit {
                "chartlet-area"
            } else {
                AREA_CLASSES[palette]
            },
            topic: None,
            series_index: None,
            style_index: explicit.then_some(entry.global),
            tooltip: None,
        }));
    }
}

/// The band of one layer as closed outlines, one per run of values between missing ones: along
/// the upper edge and back along the lower one. A modeled band gets a hatched copy on top, so
/// that it reads as modeled without relying on color.
fn push_band(spec: &ChartSpec, entry: LayerRef, frame: &TimeFrame, elements: &mut Vec<Element>) {
    let mut runs = vec![Vec::new()];
    for point in &entry.layer.points {
        let Ok(epoch) = point.time.resolve(frame.zone) else {
            continue;
        };
        match (point.lower, point.upper) {
            (Some(lower), Some(upper)) if point.value.is_some() => runs
                .last_mut()
                .expect("there is always a current run")
                .push((epoch, lower, upper)),
            _ => runs.push(Vec::new()),
        }
    }
    for band in runs.into_iter().filter(|run| !run.is_empty()) {
        push_band_run(spec, entry, frame, &band, elements);
    }
}

/// One closed band outline, see [`push_band`].
fn push_band_run(
    spec: &ChartSpec,
    entry: LayerRef,
    frame: &TimeFrame,
    band: &[(i64, f64, f64)],
    elements: &mut Vec<Element>,
) {
    let mut outline: Vec<(f64, f64)> = band
        .iter()
        .map(|(epoch, _, upper)| (frame.x(*epoch), frame.y(*upper)))
        .collect();
    outline.extend(
        band.iter()
            .rev()
            .map(|(epoch, lower, _)| (frame.x(*epoch), frame.y(*lower))),
    );
    let explicit = entry.layer.resolved_color().is_some();
    let palette = spec.palette_index(entry.layer);
    if entry.layer.modeled {
        elements.push(Element::Polyline(Polyline {
            points: outline.clone(),
            class: if explicit {
                "chartlet-band"
            } else {
                BAND_CLASSES[palette]
            },
            topic: None,
            series_index: None,
            style_index: explicit.then_some(entry.global),
            tooltip: None,
        }));
        elements.push(Element::Polyline(Polyline {
            points: outline,
            class: "chartlet-hatch",
            topic: None,
            series_index: None,
            style_index: Some(entry.global),
            tooltip: None,
        }));
    } else {
        elements.push(Element::Polyline(Polyline {
            points: outline,
            class: if explicit {
                "chartlet-band"
            } else {
                BAND_CLASSES[palette]
            },
            topic: None,
            series_index: None,
            style_index: explicit.then_some(entry.global),
            tooltip: None,
        }));
    }
}

/// The tooltip of one observation: its time, value and layer, and its band if it has one.
fn observation_tooltip(
    spec: &ChartSpec,
    frame: &TimeFrame,
    (epoch, value): (i64, f64),
    band: Option<(f64, f64)>,
    name: Option<&str>,
    precision: Precision,
) -> String {
    let mut text = tooltip(
        &precision.format(epoch, frame.zone),
        value,
        frame.style,
        name,
    );
    if let Some(unit) = &frame.unit {
        write!(text, " {unit}").expect("writing to String cannot fail");
    }
    if let Some((lower, upper)) = band {
        write!(
            text,
            " ({} {} {} {})",
            spec.locale.words().range,
            format_value(lower, frame.style),
            spec.locale.words().to,
            format_value(upper, frame.style)
        )
        .expect("writing to String cannot fail");
    }
    text
}

/// One line, broken at every missing value, with its markers and, in a full-size chart, its
/// value labels. A point layer draws the markers alone, however many there are.
fn push_line(
    spec: &ChartSpec,
    entry: LayerRef,
    frame: &TimeFrame,
    detail: Detail,
    elements: &mut Vec<Element>,
    warnings: &mut Vec<ChartWarning>,
    metrics: &impl TextMetrics,
) {
    let layer = entry.layer;
    let points = layer.resolved_points(frame.zone);
    let explicit = layer.resolved_color().is_some();
    let palette = spec.palette_index(layer);
    let is_point = layer.mark == Mark::Point;
    // A point layer draws no line at all.
    if !is_point {
        push_line_segments(spec, entry, frame, elements);
    }

    // Markers and their labels are only drawn while the observations stay far enough apart
    // for them to be readable. Beyond that, an invisible target keeps the tooltip of each
    // observation, as long as the targets stay far enough apart to point at and the chart does
    // not limit tooltips to markers.
    let spark = detail == Detail::Spark;
    let dense = points.len() > MAX_TIME_MARKERS;
    let markers = !spark && (!dense || is_point) && layer.markers != Some(false);
    let fits = || {
        let xs: Vec<f64> = points.iter().map(|(epoch, _)| frame.x(*epoch)).collect();
        spec.tooltips == Tooltips::Observations && tooltips_fit(&xs)
    };
    let hits = !markers && fits();
    // Dense points are drawn smaller, and carry tooltips under the same rule as targets.
    let marker_tooltips = !dense || fits();
    if !markers && !hits && !spark {
        return;
    }
    let last = points.len().saturating_sub(1);
    let band = layer.resolved_band(frame.zone);
    let name = tooltip_name(spec, entry);
    let precision = spec.layer_precision(layer, frame.zone);
    // A stacked area's markers sit on top of the stack, but tell the layer's own value.
    let drawn = spec.drawn_points(entry, frame.zone);
    // Where the last value label of the layer ends: the next one stays off it.
    let mut labels_end = f64::NEG_INFINITY;
    for (index, (epoch, value)) in points.iter().enumerate() {
        let x = frame.x(*epoch);
        let y = frame.y(drawn[index].1);
        let text = observation_tooltip(
            spec,
            frame,
            (*epoch, *value),
            band.get(index).map(|(_, lower, upper)| (*lower, *upper)),
            name.as_deref(),
            precision,
        );
        let point = |radius: f64, tooltip: Option<String>| {
            Element::Circle(Circle {
                cx: x,
                cy: y,
                radius,
                class: if explicit {
                    "chartlet-point"
                } else {
                    POINT_CLASSES[palette]
                },
                topic: None,
                series_index: None,
                style_index: explicit.then_some(entry.global),
                tooltip,
            })
        };
        if !markers {
            // A sparkline marks where its line ends.
            if spark && index == last {
                elements.push(point(2.5, (!hits).then(|| text.clone())));
            }
            if hits {
                elements.push(Element::Circle(Circle {
                    cx: x,
                    cy: y,
                    radius: 4.0,
                    class: "chartlet-hit",
                    topic: None,
                    series_index: None,
                    style_index: None,
                    tooltip: Some(text),
                }));
            }
            continue;
        }
        elements.push(point(
            if detail == Detail::Full && !dense {
                4.0
            } else {
                2.5
            },
            marker_tooltips.then_some(text),
        ));
        if detail == Detail::Full && spec.show_values && !dense {
            let content = format_value(*value, frame.style);
            let half = metrics.width(&content, LABEL_SIZE) / 2.0;
            // Two neighbours that would run into each other: the later one is left out.
            if x - half < labels_end + 4.0 {
                crate::layout::warn_if_labels_omitted(true, warnings);
            } else {
                labels_end = x + half;
                elements.push(Element::Text(Text {
                    x,
                    y: y - 10.0,
                    class: "chartlet-value",
                    anchor: TextAnchor::Middle,
                    content,
                }));
            }
        }
    }
}

/// Holds the last value of a step layer until its `stepEnd`, if `last` is the layer's last
/// observation.
fn extend_last_step(layer: &LayerSpec, frame: &TimeFrame, last: i64, points: &mut Vec<(f64, f64)>) {
    let Some(end) = layer
        .step_end
        .as_ref()
        .and_then(|time| time.resolve(frame.zone).ok())
    else {
        return;
    };
    // Only a layer whose last observation has a value holds it on; after a trailing gap the
    // line stays broken.
    let last_point = layer.points.last();
    if last_point.is_some_and(|point| point.value.is_some())
        && last_point.and_then(|point| point.time.resolve(frame.zone).ok()) == Some(last)
        && let Some(&(_, y)) = points.last()
    {
        points.push((frame.x(end), y));
    }
}

/// The line of a layer, broken at every missing value; a lone value between two gaps keeps only
/// its marker.
fn push_line_segments(
    spec: &ChartSpec,
    entry: LayerRef,
    frame: &TimeFrame,
    elements: &mut Vec<Element>,
) {
    let layer = entry.layer;
    let class = line_class(spec, entry);
    let explicit = layer.resolved_color().is_some();
    // A stacked area has no gaps; its line runs along the top of the stack.
    let segments = if spec.stack_base(entry, frame.zone).is_some() {
        vec![spec.drawn_points(entry, frame.zone)]
    } else {
        layer.resolved_segments(frame.zone)
    };
    for segment in segments {
        if segment.len() < 2 {
            continue;
        }
        let mut points = layer.curve.points(
            segment
                .iter()
                .map(|(epoch, value)| (frame.x(*epoch), frame.y(*value)))
                .collect(),
        );
        extend_last_step(layer, frame, segment[segment.len() - 1].0, &mut points);
        elements.push(Element::Polyline(Polyline {
            points,
            class,
            topic: None,
            series_index: None,
            style_index: explicit.then_some(entry.global),
            tooltip: None,
        }));
    }
}

/// The classes of a line: palette or declared color, its pattern and its weight. The legend
/// draws its sample with the same classes, so it looks exactly like the line.
pub(super) fn line_class(spec: &ChartSpec, entry: LayerRef) -> &'static str {
    let layer = entry.layer;
    let color = if layer.resolved_color().is_some() {
        0
    } else {
        spec.palette_index(layer) + 1
    };
    let dash = match (layer.effective_dash(), layer.modeled) {
        (Dash::Solid, _) => 0,
        (Dash::Dashed, true) => 1,
        (Dash::Dashed, false) => 2,
        (Dash::Dotted, _) => 3,
    };
    let weight = match layer.stroke {
        Stroke::Regular => 0,
        Stroke::Thin => 1,
        Stroke::Bold => 2,
        Stroke::Medium => 3,
    };
    let classes = LINE_CLASSES.get_or_init(|| {
        let mut classes = Vec::new();
        for color in 0..=MAX_SERIES {
            let color = if color == 0 {
                String::new()
            } else {
                format!(" chartlet-line-series-{color}")
            };
            for dash in LINE_DASHES {
                for weight in LINE_WEIGHTS {
                    classes.push(format!("chartlet-line{weight}{dash}{color}"));
                }
            }
        }
        classes
    });
    &classes[(color * LINE_DASHES.len() + dash) * LINE_WEIGHTS.len() + weight]
}

/// The horizontal grid lines and value ticks of one plot.
/// The unit after the top value tick label of a pane, shortened where it does not fit between
/// `left_edge` and the plot next to the widest tick label.
fn fitted_unit(
    unit: Option<&str>,
    frame: &TimeFrame,
    left_edge: f64,
    path: &str,
    warnings: &mut Vec<ChartWarning>,
    metrics: &impl TextMetrics,
) -> Option<String> {
    let unit = unit?;
    let widest = frame
        .scale
        .ticks()
        .map(|value| metrics.width(&frame.scale.tick_label(value, frame.style), LABEL_SIZE))
        .fold(0.0, f64::max);
    let room = frame.plot.left - 10.0 - left_edge - widest - 4.0;
    let fitted = fit_text(unit, room.max(0.0), LABEL_SIZE, metrics, warnings, path);
    // A unit shortened to nothing but the ellipsis says nothing; it stays in the table.
    (fitted != "…").then_some(fitted)
}

fn push_value_grid(frame: &TimeFrame, unit: Option<&str>, elements: &mut Vec<Element>) {
    let plot = frame.plot;
    let ticks: Vec<(f64, f64)> = frame
        .scale
        .ticks()
        .map(|value| (value, frame.y(value)))
        .collect();
    // In a low pane the ticks can stand closer than a label is tall: then every `step`-th tick is
    // labelled, the gridlines stay.
    let spacing = ticks
        .windows(2)
        .map(|pair| (pair[1].1 - pair[0].1).abs())
        .fold(f64::INFINITY, f64::min);
    // Bounded by the tick count, which is small.
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let step = if spacing.is_finite() && spacing < LABEL_SIZE + 2.0 {
        ((LABEL_SIZE + 2.0) / spacing.max(1.0)).ceil() as usize
    } else {
        1
    };
    // The unit follows the label nearest the top of the plot.
    let top = ticks
        .iter()
        .enumerate()
        .filter(|(index, _)| index % step == 0)
        .min_by(|(_, a), (_, b)| a.1.total_cmp(&b.1))
        .map(|(index, _)| index);
    for (index, &(value, y)) in ticks.iter().enumerate() {
        elements.push(Element::Line(Line {
            x1: plot.left,
            y1: y,
            x2: plot.left + plot.width,
            y2: y,
            class: if frame.scale.is_zero(value) {
                "chartlet-zero"
            } else {
                "chartlet-grid"
            },
        }));
        if index % step != 0 {
            continue;
        }
        let label = frame.scale.tick_label(value, frame.style);
        elements.push(Element::Text(Text {
            x: plot.left - 10.0,
            y: y + 4.0,
            class: "chartlet-tick",
            anchor: TextAnchor::End,
            content: match unit {
                Some(unit) if Some(index) == top => format!("{label} {unit}"),
                _ => label,
            },
        }));
    }
}

/// The vertical grid lines and time ticks of one plot, the tick labels only with `labels`. A label
/// that would reach past an edge of the chart moves inward until it fits, since a tick can sit at
/// either end of the span and the gutter left of the plot may be narrow.
fn push_time_ticks(
    frame: &TimeFrame,
    max_ticks: usize,
    labels: bool,
    canvas_width: f64,
    metrics: &impl TextMetrics,
    elements: &mut Vec<Element>,
) {
    let plot = frame.plot;
    let sub_day = frame.sub_day;
    let ticks = match &frame.slots {
        Some(slots) => {
            time::collapsed_ticks(slots, frame.zone, max_ticks, sub_day, frame.tick_step)
        }
        None => time::ticks(
            frame.span.0,
            frame.span.1,
            frame.zone,
            max_ticks,
            sub_day,
            frame.tick_step,
        ),
    };
    // A label that would run into the one before it is left out; its gridline stays.
    let mut last_end = f64::NEG_INFINITY;
    for tick in ticks {
        let x = frame.x(tick.epoch);
        elements.push(Element::Line(Line {
            x1: x,
            y1: plot.top,
            x2: x,
            y2: plot.top + plot.height,
            class: "chartlet-grid",
        }));
        if !labels {
            continue;
        }
        let half = metrics.width(&tick.label, LABEL_SIZE) / 2.0;
        let x = x.min(canvas_width - 4.0 - half).max(4.0 + half);
        let (start, end) = if frame.reversed {
            (-(x + half), -(x - half))
        } else {
            (x - half, x + half)
        };
        if start < last_end + 6.0 {
            continue;
        }
        last_end = end;
        elements.push(Element::Text(Text {
            x,
            y: plot.top + plot.height + 24.0,
            class: "chartlet-tick",
            anchor: TextAnchor::Middle,
            content: tick.label,
        }));
    }
}

/// Space between two stacked panes; it holds the value axis title of the lower one.
const PANE_GAP: f64 = 36.0;
/// A pane lower than this cannot show its value axis in a readable way.
const MIN_PANE_HEIGHT: f64 = 40.0;

/// One frame per pane of a time chart, stacked from top to bottom within `plot`: every pane
/// shares the time span and takes a share of the height by its `heightRatio`, and scales its
/// values on its own.
fn pane_frames(
    spec: &ChartSpec,
    zone: TimeZone,
    plot: PlotArea,
    warnings: &mut Vec<ChartWarning>,
) -> Vec<TimeFrame> {
    let (span, slots) = time_axis(spec, zone);
    let precision = spec.time_precision(zone);
    let panes = spec.panes.len();
    let ratios: u32 = spec.panes.iter().map(|pane| pane.height_ratio).sum();
    let available = plot.height - PANE_GAP * count(panes - 1);
    let mut top = plot.top;
    let mut frames = Vec::new();
    for (pane_index, pane) in spec.panes.iter().enumerate() {
        let height = if panes == 1 {
            plot.height
        } else {
            available * f64::from(pane.height_ratio) / f64::from(ratios)
        };
        if panes > 1 && height < MIN_PANE_HEIGHT {
            warnings.push(ChartWarning::new(
                "dense_chart",
                format!("/panes/{pane_index}/heightRatio"),
                "the pane is less than 40 pixels tall; raise height or its heightRatio",
            ));
        }
        frames.push(TimeFrame {
            plot: PlotArea {
                top,
                height,
                ..plot
            },
            span,
            slots: slots.clone(),
            zone,
            precision,
            tick_step: spec.time_axis.step,
            sub_day: spec.observed_precision(zone) == Precision::Minute,
            unit: spec.axis_unit(pane_index).map(str::to_owned),
            scale: time_scale(spec, zone, Some(pane_index)),
            style: spec.pane_style(pane_index),
            reversed: spec.time_axis.reverse,
        });
        top += height + PANE_GAP;
    }
    frames
}

/// The value grid, the vertical time grid and the value axis title of one pane of a time chart;
/// the time tick labels only below the bottom pane, since all panes share one time axis.
fn push_pane_axes(
    spec: &ChartSpec,
    pane_index: usize,
    frame: &TimeFrame,
    bottom_pane: bool,
    elements: &mut Vec<Element>,
    warnings: &mut Vec<ChartWarning>,
    metrics: &impl TextMetrics,
) {
    let plot = frame.plot;
    let unit = fitted_unit(
        spec.axis_unit(pane_index),
        frame,
        4.0,
        &format!("/panes/{pane_index}/valueAxis/unit"),
        warnings,
        metrics,
    );
    push_value_grid(frame, unit.as_deref(), elements);
    // The plot's own width, which the measured gutter leaves it, decides how many ticks fit.
    // Plot widths are far below u32::MAX.
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let plot_width = frame.plot.width.max(0.0) as u32;
    let max_ticks = usize::try_from(
        (plot_width / time_tick_spacing(spec.observed_precision(frame.zone))).max(2),
    )
    .expect("a usize is at least 32 bits wide");
    push_time_ticks(
        frame,
        max_ticks,
        bottom_pane,
        f64::from(spec.width),
        metrics,
        elements,
    );

    if let Some(title) = spec.panes[pane_index].value_axis.title.as_deref() {
        elements.push(Element::Text(Text {
            x: plot.left,
            y: plot.top - 20.0,
            class: "chartlet-axis-title",
            anchor: TextAnchor::Start,
            content: fit_text(
                title,
                plot.width,
                LABEL_SIZE,
                metrics,
                warnings,
                &format!("/panes/{pane_index}/valueAxis/title"),
            ),
        }));
    }
}

/// The first and last timestamp any data layer, vertical reference line, point marker, zone
/// edge, step end or declared end of the time axis uses, a missing value included. Validation guarantees every data layer holds at least two observations that
/// increase, and a zoom window at least two of one layer, so the span is never empty.
fn time_span(spec: &ChartSpec, zone: TimeZone) -> (i64, i64) {
    let mut min = i64::MAX;
    let mut max = i64::MIN;
    let data = spec
        .data_layers()
        .flat_map(|entry| entry.layer.resolved_times(zone));
    let rules = spec
        .layers()
        .flat_map(|layer| [&layer.time, &layer.from, &layer.to, &layer.step_end])
        .chain([&spec.time_axis.min, &spec.time_axis.max])
        .filter_map(Option::as_ref)
        .filter_map(|time| time.resolve(zone).ok());
    for epoch in data.chain(rules) {
        min = min.min(epoch);
        max = max.max(epoch);
    }
    (min, max)
}

/// The span of the time axis and, with gaps collapsed, its slots. A collapsed axis runs from the
/// first observation to the last, since nothing else has a place on it.
fn time_axis(spec: &ChartSpec, zone: TimeZone) -> ((i64, i64), Option<Vec<i64>>) {
    let slots = spec.time_slots(zone);
    let span = match slots.as_deref() {
        Some([first, .., last]) => (*first, *last),
        _ => time_span(spec, zone),
    };
    (span, slots)
}

/// Maps the slot at `index` of `total` evenly spaced slots onto the time axis.
fn slot_x(index: usize, total: usize, plot: PlotArea) -> f64 {
    let last = total.saturating_sub(1);
    let ratio = count(index.min(last)) / count(last.max(1));
    plot.left + TIME_INSET + ratio * (plot.width - 2.0 * TIME_INSET)
}

/// Maps a timestamp onto the time axis.
fn time_x(epoch: i64, span: (i64, i64), plot: PlotArea) -> f64 {
    // The specification allows 1700 to 2200, so a span stays below 2^53 seconds and the ratio
    // keeps full precision even in 64-bit seconds.
    #[allow(clippy::cast_precision_loss)]
    let width = (span.1 - span.0).max(1) as f64;
    #[allow(clippy::cast_precision_loss)]
    let ratio = (epoch - span.0) as f64 / width;
    plot.left + TIME_INSET + ratio * (plot.width - 2.0 * TIME_INSET)
}