chartlet 0.22.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
mod architecture;
mod boxplot;
mod calendar;
mod categorical;
mod classes;
mod cycle;
mod dataset;
mod deployment;
mod fishbone;
mod flow;
mod funnel;
mod heatmap;
mod journey;
mod kanban;
mod layers;
mod mosaic;
mod network;
mod parliament;
mod plan;
mod polar;
mod radar;
mod rangebar;
mod sankey;
mod scatter;
mod sequence;
mod state;
mod storymap;
mod stripes;
mod survival;
mod timechart;
mod timeline;
mod tree;
mod treemap;
pub(crate) mod untagged;
mod validate;
mod valuemap;
mod venn;
mod view;
mod waffle;
mod waterfall;

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

use crate::{
    error::{ChartError, ChartWarning},
    time::TimeValue,
};
pub use architecture::{
    ArchitectureSpec, BoundarySpec, CategorySpec, ComponentKind, ComponentSpec,
    ConnectionDirection, ConnectionSpec, DeltaSpec, InterfaceSpec, PerspectiveSpec,
};
pub(crate) use boxplot::BoxSummary;
pub use boxplot::{BoxDisplay, BoxSpec, ViolinScale};
pub(crate) use calendar::calendar_date;
pub use calendar::{CalendarDay, CalendarLayout, CalendarSpec};
pub use categorical::{DataPoint, SeriesSpec};
pub use classes::{ClassKind, ClassSpec, ClassesSpec, PackageSpec, RelationKind, RelationSpec};
pub use cycle::{CycleHubSpec, CycleLabels, CycleSpec, CycleStepSpec};
pub use fishbone::{FishboneBoneSpec, FishboneCauseSpec, FishboneSpec, FishboneSubcauseSpec};
pub use flow::{
    DiagramRole, DiagramSpacing, FlowEdgeSpec, FlowNodeSpec, FlowSpec, GroupSpec, LaneSpec,
    MainPath, NodeKind, NoteSpec, PartSpec, PortSide,
};
pub use funnel::{FunnelDisplay, FunnelSpec, FunnelStageSpec};
pub use heatmap::{HeatmapCellSpec, HeatmapOrder, HeatmapScale, HeatmapSpec};
pub(crate) use journey::JourneyRow;
pub use journey::{JourneyDisplay, JourneySpec, JourneyStageSpec};
pub use kanban::{KanbanCardSpec, KanbanColumnSpec, KanbanSpec};
pub use layers::{LayersDisplay, LayersProjection, LayersSpec, StackLayerSpec};
pub use mosaic::{MosaicColumnSpec, MosaicSegmentSpec, MosaicSpec};
pub use network::{NetworkEdgeSpec, NetworkLayout, NetworkNodeSpec, NetworkOrder, NetworkSpec};
pub use parliament::{ParliamentSpec, PartySpec};
pub use plan::{AreaKind, AreaSpec, ItemKind, ItemSpec, PlanSpec};
pub use polar::{PolarDisplay, PolarPointSpec, PolarSpec};
pub(crate) use radar::RINGS;
pub use radar::{RadarAxisSpec, RadarSeriesSpec, RadarSpec};
pub use rangebar::{RangeDisplay, RangeSort, RangeSpec};
pub(crate) use sankey::SankeyGraph;
pub use sankey::{SankeyLinkSpec, SankeyNodeSpec, SankeyOrder, SankeySpec};
pub(crate) use scatter::Quadrant;
pub use scatter::{
    ScatterAxis, ScatterLineSpec, ScatterPointSpec, ScatterQuadrantLabels, ScatterQuadrantsSpec,
    ScatterSpec, ScatterTickSpec,
};
pub use sequence::{
    BranchSpec, DiagramOrientation, FragmentKind, FragmentSpec, MessageKind, MessageSpec,
    ParticipantKind, ParticipantSpec, SequenceSpec,
};
pub use state::{StateKind, StateNodeSpec, StateSpec, TransitionSpec};
pub use storymap::{StorymapActivitySpec, StorymapSpec, StorymapStorySpec, StorymapTaskSpec};
pub(crate) use stripes::Diverging;
pub use stripes::StripesSpec;
pub(crate) use survival::{KmCurve, KmStep};
pub use survival::{SurvivalGroupSpec, SurvivalObservationSpec, SurvivalSpec};
pub use timechart::{
    Curve, Dash, Gaps, LayerSpec, Mark, OhlcPoint, PaneSpec, Shape, Stroke, TimeAxisKind,
    TimeAxisSpec, TimePoint, TimePrecision, Tooltips,
};
pub(crate) use timechart::{LayerContext, MAX_TIME_POINTS_PER_LAYER, validate_layer_name};
pub(crate) use timeline::Span;
pub use timeline::{MarkerSpec, TimelineItemSpec, TimelineSpec};
pub use tree::{DistancesSpec, Linkage, TreeLayout, TreeNodeKind, TreeNodeSpec, TreeSpec};
pub(crate) use treemap::{TmNode, TmTree};
pub use treemap::{TreemapItemSpec, TreemapSpec};
pub(crate) use validate::validate_number;
use validate::{json_pointer, validate_optional_text, validate_text};
pub(crate) use valuemap::{VALUEMAP_STAGES, ValuemapStage};
pub use valuemap::{ValuemapComponentSpec, ValuemapDependencySpec, ValuemapMoveSpec, ValuemapSpec};
pub use venn::{VennRegionSpec, VennSpec};
pub use view::{InstanceSpec, ViewSpec, ViewStepSpec};
pub use waffle::{WafflePartSpec, WaffleSpec};
pub(crate) use waterfall::WaterfallBar;
pub use waterfall::{StepKind, StepSpec, WaterfallSpec};

const MAX_DATA_POINTS: usize = 100;
/// Limited so that every series keeps a color that stays distinguishable for common
/// color-vision deficiencies.
pub(crate) const MAX_SERIES: usize = 4;
/// The most ticks a declared step may put on an axis.
pub(crate) const MAX_AXIS_TICKS: f64 = 50.0;
/// Reference lines on a bar chart; beyond this the lines crowd the bars they explain.
pub(crate) const MAX_REFERENCES: usize = 4;
/// The largest specification that is read, in bytes. The largest figure at the declared limits
/// (six time-series layers of 2000 points) is about a tenth of it; the cap keeps a browser tab or
/// an MCP server from parsing a payload of any size before a count limit can refuse it.
pub(crate) const MAX_SPEC_BYTES: usize = 4 * 1024 * 1024;
/// Fixed decimal places; beyond this a value stops being readable as a number.
pub(crate) const MAX_DECIMALS: u8 = 6;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[allow(
    clippy::struct_excessive_bools,
    reason = "every bool is a switch of the JSON specification"
)]
pub struct ChartSpec {
    pub schema_version: u8,
    #[serde(rename = "type")]
    pub chart_type: ChartType,
    #[serde(default)]
    pub orientation: Orientation,
    /// How a `type: "boxplot"` chart draws its observations: boxes (the default), violins or strips.
    #[serde(default, skip_serializing_if = "BoxDisplay::is_box")]
    pub box_display: BoxDisplay,
    /// How a `type: "rangebar"` chart draws its spans: bars (the default) or dumbbells.
    #[serde(default, skip_serializing_if = "RangeDisplay::is_bar")]
    pub display: RangeDisplay,
    /// The order of the spans of a `type: "rangebar"` chart: as listed (the default) or the
    /// widest first.
    #[serde(default, skip_serializing_if = "RangeSort::is_none")]
    pub sort: RangeSort,
    /// With `"boxDisplay": "violin"`: `width` (default) makes every violin as wide as the others at
    /// its widest, `area` gives them the same area, `count` an area that follows their number of
    /// observations.
    #[serde(default, skip_serializing_if = "ViolinScale::is_width")]
    pub violin_scale: ViolinScale,
    /// With `"boxDisplay": "beeswarm"`: draws the box and its whiskers under the points.
    #[serde(default, skip_serializing_if = "is_false")]
    pub show_box: bool,
    /// Marks the mean of the observations of every box of a `type: "boxplot"` chart with a
    /// diamond and adds a column to the table. Needs `values` on every box.
    #[serde(default, skip_serializing_if = "is_false")]
    pub show_mean: bool,
    /// Draws every other series of a `type: "bar"` chart as an outline, so that series differ
    /// in form as well as in color.
    #[serde(default, skip_serializing_if = "is_false")]
    pub patterns: bool,
    /// Draws a `type: "line"` chart of two categories as a slope chart: one line per series from
    /// the first value to the second, with the names at both ends instead of a legend.
    #[serde(default, skip_serializing_if = "is_false")]
    pub slope: bool,
    /// Draws a `type: "line"` chart as a rank chart: the rank of each series, 1 at the top, in
    /// every category, with the names at both ends instead of a legend.
    #[serde(default, skip_serializing_if = "is_false")]
    pub rank: bool,
    /// Stacks the series of a `type: "bar"` chart instead of setting them side by side.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stack: Option<Stack>,
    pub title: String,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub source: Option<String>,
    #[serde(default)]
    pub category_axis: CategoryAxisSpec,
    #[serde(default)]
    pub value_axis: ValueAxisSpec,
    /// A named canvas size: sets `width` and `height` unless the specification gives them.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub size: Option<SizePreset>,
    #[serde(default = "default_width")]
    pub width: u32,
    #[serde(default = "default_height")]
    pub height: u32,
    #[serde(default = "default_show_values")]
    pub show_values: bool,
    /// Whether the SVG profile draws the title in the chart. It always remains the accessible name;
    /// the HTML profile never draws it, its caption is the visible title.
    #[serde(default = "default_true", skip_serializing_if = "is_true")]
    pub show_title: bool,
    /// Single-series data. Use either `data` or `categories` with `series`.
    #[serde(default)]
    pub data: Vec<DataPoint>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub categories: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub series: Vec<SeriesSpec>,
    /// Optional zoom steps rendered as radio-selectable, pre-computed variants (HTML profile).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub zoom_steps: Vec<ZoomStep>,
    /// Palette a chart is rendered in. Skipped while it is the default so that adding the field
    /// did not change the serialized form, and with it the generated accessibility IDs, of every
    /// existing specification.
    #[serde(default, skip_serializing_if = "Theme::is_light")]
    pub theme: Theme,
    /// How strokes and shapes are drawn: `clean` (the default) or `sketch`, slightly wobbly, for
    /// essays and slides. Text is not affected.
    #[serde(default, skip_serializing_if = "StrokeStyle::is_clean")]
    pub stroke: StrokeStyle,
    /// Font families and the width scale the layout reserves for them.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub typography: Option<crate::typography::TypographySpec>,
    /// Colors of the palette, by the name of the `--chartlet-*` custom property without its
    /// prefix, as hex values. They win over the theme. Skipped while empty, like `theme`.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub tokens: BTreeMap<String, String>,
    /// The time axis of a `type: "time"` chart.
    #[serde(default, skip_serializing_if = "TimeAxisSpec::is_default")]
    pub time_axis: TimeAxisSpec,
    /// The panes of a `type: "time"` chart; every pane stacks one value axis over the shared
    /// time axis and holds its own layers.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub panes: Vec<PaneSpec>,
    /// The yearly values of a `type: "stripes"` chart. Skipped while absent, for the same reason as `theme`:
    /// adding the field must not change the serialized form, and with it the generated
    /// accessibility IDs, of every existing specification.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stripes: Option<StripesSpec>,
    /// The daily values of a `type: "calendar"` chart. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub calendar: Option<CalendarSpec>,
    /// The participants and messages of a `type: "sequence"` diagram. Skipped while absent, like
    /// `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sequence: Option<SequenceSpec>,
    /// The steps and edges of a `type: "flow"` chart. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub flow: Option<FlowSpec>,
    /// The states and transitions of a `type: "state"` diagram. Skipped while absent, like
    /// `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub state: Option<StateSpec>,
    /// The components, connections and boundaries of a `type: "architecture"` diagram. Skipped
    /// while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub architecture: Option<ArchitectureSpec>,
    /// The nodes of a `type: "tree"` diagram. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tree: Option<TreeSpec>,
    /// A waterfall: a running total that rises and falls step by step. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub waterfall: Option<WaterfallSpec>,
    /// A waffle: squares that each stand for a share of a whole. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub waffle: Option<WaffleSpec>,
    /// A funnel or pyramid: stages that narrow, or ranked levels. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub funnel: Option<FunnelSpec>,
    /// A radar chart: one axis per measure, one polygon per series. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub radar: Option<RadarSpec>,
    /// A polar chart: one value per category of a cycle, as wedges or lollipops around a center. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub polar: Option<PolarSpec>,
    /// A mosaic chart: columns as wide as their share, split by the share of their segments. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mosaic: Option<MosaicSpec>,
    /// A heatmap: values or categories in a grid of rows and columns. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub heatmap: Option<HeatmapSpec>,
    /// A Venn diagram of two or three sets. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub venn: Option<VennSpec>,
    /// A value chain map: components by visibility and evolution. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub valuemap: Option<ValuemapSpec>,
    /// A user journey or service blueprint: stages with rows of actions, touchpoints, thoughts and sentiment. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub journey: Option<JourneySpec>,
    /// A user story map: activities, tasks and stories in release slices. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub storymap: Option<StorymapSpec>,
    /// A kanban board: columns for states with cards. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kanban: Option<KanbanSpec>,
    /// A fishbone diagram: one effect and the categories of its causes on bones. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fishbone: Option<FishboneSpec>,
    /// A parliament: seats as dots in a semicircle, in blocks by party. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parliament: Option<ParliamentSpec>,
    /// A treemap: rectangles whose areas follow the values. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub treemap: Option<TreemapSpec>,
    /// A Sankey diagram: bands between nodes in columns, as thick as the flow. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sankey: Option<SankeySpec>,
    /// Kaplan-Meier survival curves: step curves of groups, with censoring marks, optional confidence bands and the number at risk. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub survival: Option<SurvivalSpec>,
    /// A scatter plot: points on two numeric axes, in groups, with threshold lines and named points. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scatter: Option<ScatterSpec>,
    /// A class or entity-relationship diagram: classes with compartments, joined by relations. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub classes: Option<ClassesSpec>,
    /// A network: nodes joined by edges on a circle or in rings around one node. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub network: Option<NetworkSpec>,
    /// A cycle: steps on a ring where the last feeds the first, optionally around a hub. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cycle: Option<CycleSpec>,
    /// Layers: levels of abstraction stacked on each other, or scopes drawn inside each other. Skipped while absent, like `stripes`.
    #[serde(default, rename = "layers", skip_serializing_if = "Option::is_none")]
    pub layer_stack: Option<LayersSpec>,
    /// A plan: rooms, buildings and open ground on a grid, seen at an angle. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub plan: Option<PlanSpec>,
    /// The items of a `type: "timeline"` chart. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeline: Option<TimelineSpec>,
    /// The boxes of a `type: "boxplot"` chart, one per category.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub boxes: Vec<BoxSpec>,
    /// The spans of a `type: "rangebar"` chart, one per category.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub ranges: Vec<RangeSpec>,
    /// Reference lines across a `type: "bar"` chart, such as an average or a target.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub references: Vec<ReferenceSpec>,
    /// Draws a `type: "time"` chart as a sparkline: only its lines and areas, no axes, title or
    /// legend, at a size down to 60 × 16. Title and description stay its accessible name.
    #[serde(default, skip_serializing_if = "is_false")]
    pub sparkline: bool,
    /// Which observations of a `type: "time"` chart carry a tooltip.
    #[serde(default, skip_serializing_if = "Tooltips::is_observations")]
    pub tooltips: Tooltips,
    /// Where a `type: "time"` chart names its series: in a legend above the plot, or at the end
    /// of every line.
    #[serde(default, skip_serializing_if = "LegendPlacement::is_top")]
    pub legend: LegendPlacement,
    /// Gives every panel of a `type: "multiples"` chart its own value axis, for panels whose
    /// values differ in unit or size; they can then no longer be compared by height.
    #[serde(default, skip_serializing_if = "is_false")]
    pub independent_axes: bool,
    /// Number of grid columns of a `type: "multiples"` chart; defaults to up to three.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub columns: Option<u32>,
    /// Language of every text chartlet generates: description, legend additions, tooltips, the
    /// HTML figure and its data table, and the number format. Skipped while it is the default,
    /// like `theme`.
    #[serde(default, skip_serializing_if = "Locale::is_en")]
    pub locale: Locale,
    /// A second layout for narrow containers. Skipped while absent, like `stripes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mobile: Option<MobileSpec>,
}

/// A named canvas size for a destination: documents, slides, print or social previews.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum SizePreset {
    Doc,
    DocWide,
    #[serde(rename = "slide-16x9")]
    Slide16x9,
    #[serde(rename = "slide-4x3")]
    Slide4x3,
    SocialOg,
    SocialSquare,
    PrintA4Landscape,
    PrintA3Landscape,
    PrintLetterLandscape,
}

impl SizePreset {
    /// Width and height in CSS pixels. Print sizes are the paper at 96 dpi.
    #[must_use]
    pub const fn dimensions(self) -> (u32, u32) {
        match self {
            Self::Doc => (800, 450),
            Self::DocWide => (1_200, 500),
            Self::Slide16x9 => (1_920, 1_080),
            Self::Slide4x3 => (1_600, 1_200),
            Self::SocialOg => (1_200, 630),
            Self::SocialSquare => (1_080, 1_080),
            Self::PrintA4Landscape => (1_123, 794),
            Self::PrintA3Landscape => (1_587, 1_123),
            Self::PrintLetterLandscape => (1_056, 816),
        }
    }

    /// How much larger than the document ramp the preset draws everything. The chart is laid out
    /// at the canvas divided by this factor and drawn that much larger, so type, strokes,
    /// margins, label wrapping and legend rows all follow the destination. A body label of 12
    /// pixels becomes about 19 pixels on a slide.
    #[must_use]
    pub const fn scale(self) -> f64 {
        match self {
            Self::Doc
            | Self::DocWide
            | Self::PrintA4Landscape
            | Self::PrintA3Landscape
            | Self::PrintLetterLandscape => 1.0,
            Self::Slide16x9 | Self::Slide4x3 => 1.6,
            Self::SocialOg => 1.25,
            Self::SocialSquare => 1.2,
        }
    }

    /// Whether the SVG is drawn with literal colors, as the print variant draws it.
    #[must_use]
    pub const fn is_print(self) -> bool {
        matches!(
            self,
            Self::PrintA4Landscape | Self::PrintA3Landscape | Self::PrintLetterLandscape
        )
    }
}

/// The size of the mobile variant, and the container width below which the HTML profile shows it
/// instead of the chart at `width` × `height`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct MobileSpec {
    pub width: u32,
    #[serde(default = "default_mobile_height")]
    pub height: u32,
    /// Container width in CSS pixels; the mobile variant shows below it.
    #[serde(default = "default_breakpoint")]
    pub breakpoint: u32,
    /// Grid columns of small multiples in the mobile variant, usually fewer than on the wide
    /// chart.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub columns: Option<u32>,
}

/// The palette a chart is rendered in. Both palettes are expressed as CSS custom properties, so a
/// host page can override any single color.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Theme {
    #[default]
    Light,
    Dark,
    /// Diagrams only: a deep blue ground with pale lines.
    Blueprint,
}

impl Theme {
    // serde hands this function a reference, so the signature follows serde's shape.
    #[allow(clippy::trivially_copy_pass_by_ref)]
    const fn is_light(&self) -> bool {
        matches!(self, Self::Light)
    }
}

/// How the lines and shapes of a chart are drawn.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum StrokeStyle {
    #[default]
    Clean,
    /// Lines and shapes are displaced by a fraction of a pixel to a few, from a seed derived from
    /// the specification: the same bytes every time. Text, colors and geometry that carries data
    /// stay where they are within that distance. Not applied to the print variant or PNG.
    Sketch,
}

impl StrokeStyle {
    // serde hands this function a reference, so the signature follows serde's shape.
    #[allow(clippy::trivially_copy_pass_by_ref)]
    const fn is_clean(&self) -> bool {
        matches!(self, Self::Clean)
    }
}

/// The language of generated texts and numbers.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Locale {
    #[default]
    En,
    De,
}

impl Locale {
    /// The language code the specification uses: `en` or `de`.
    pub(crate) const fn code(self) -> &'static str {
        match self {
            Self::En => "en",
            Self::De => "de",
        }
    }

    // serde hands this function a reference, so the signature follows serde's shape.
    #[allow(clippy::trivially_copy_pass_by_ref)]
    const fn is_en(&self) -> bool {
        matches!(self, Self::En)
    }
}

/// How a value is written: format, fixed decimals if any, locale, and whether thousands are
/// separated.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct NumberStyle {
    pub format: ValueFormat,
    pub decimals: Option<u8>,
    pub locale: Locale,
    pub thousands: bool,
}

impl From<ValueFormat> for NumberStyle {
    fn from(format: ValueFormat) -> Self {
        Self {
            format,
            ..Self::default()
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ChartType {
    Bar,
    Line,
    /// A time series on a shared time axis, drawn from panes and layers.
    Time,
    /// Warming stripes: one colored stripe per year on a diverging scale.
    Stripes,
    /// A calendar heatmap: one cell per day of a year on a diverging scale.
    Calendar,
    /// Spans with a low and a high value per category, optionally with a central estimate.
    Rangebar,
    /// Small multiples: several small time charts in a grid, sharing both axes.
    Multiples,
    /// A sequence diagram: participants and the messages they exchange, in order.
    Sequence,
    /// A flow chart: steps joined by arrows, in layers along the flow.
    Flow,
    /// A state diagram: states joined by transitions, laid out like a flow chart.
    State,
    /// An architecture diagram: components and connections inside nested boundaries.
    Architecture,
    /// A tree: a root and the nodes below it, such as an organization chart.
    Tree,
    /// Boxes with whiskers and outliers, one per category: distributions side by side.
    Boxplot,
    /// A timeline: phases, milestones and the days that matter, in rows over one time axis.
    Timeline,
    /// A waterfall: a running total that rises and falls step by step.
    Waterfall,
    /// A waffle: squares that each stand for a share of a whole.
    Waffle,
    /// A funnel or pyramid: stages that narrow, or ranked levels.
    Funnel,
    /// A radar chart: one axis per measure, one polygon per series.
    Radar,
    /// A polar chart: one value per category of a cycle, as wedges or lollipops around a center.
    Polar,
    /// A mosaic chart: columns as wide as their share, split by the share of their segments.
    Mosaic,
    /// A heatmap: values or categories in a grid of rows and columns.
    Heatmap,
    /// A Venn diagram of two or three sets.
    Venn,
    /// A value chain map: components by visibility and evolution.
    Valuemap,
    /// A user journey or service blueprint: stages with rows of actions, touchpoints, thoughts and sentiment.
    Journey,
    /// A user story map: activities, tasks and stories in release slices.
    Storymap,
    /// A kanban board: columns for states with cards.
    Kanban,
    /// A fishbone diagram: one effect and the categories of its causes on bones.
    Fishbone,
    /// A parliament: seats as dots in a semicircle, in blocks by party.
    Parliament,
    /// A treemap: rectangles whose areas follow the values.
    Treemap,
    /// A Sankey diagram: bands between nodes in columns, as thick as the flow.
    Sankey,
    /// Kaplan-Meier survival curves: step curves of groups, with censoring marks, optional confidence bands and the number at risk.
    Survival,
    /// A scatter plot: points on two numeric axes, in groups, with threshold lines and named points.
    Scatter,
    /// A class or entity-relationship diagram: classes with compartments, joined by relations.
    Classes,
    /// A network: nodes joined by edges, on a circle or in rings around one node.
    Network,
    /// A cycle: steps on a ring where the last step feeds the first, optionally around a hub.
    Cycle,
    /// Layers: levels of abstraction stacked on each other, or scopes drawn inside each other.
    Layers,
    /// A plan: rooms, buildings and open ground on a grid, seen at an angle with the walls cut low.
    Plan,
}

impl ChartType {
    /// Every chart type, in the order of the specification's documentation.
    pub const ALL: [Self; 37] = [
        Self::Bar,
        Self::Line,
        Self::Time,
        Self::Stripes,
        Self::Calendar,
        Self::Rangebar,
        Self::Multiples,
        Self::Sequence,
        Self::Flow,
        Self::State,
        Self::Architecture,
        Self::Tree,
        Self::Boxplot,
        Self::Timeline,
        Self::Waterfall,
        Self::Waffle,
        Self::Funnel,
        Self::Radar,
        Self::Polar,
        Self::Mosaic,
        Self::Heatmap,
        Self::Venn,
        Self::Valuemap,
        Self::Journey,
        Self::Storymap,
        Self::Kanban,
        Self::Fishbone,
        Self::Parliament,
        Self::Treemap,
        Self::Sankey,
        Self::Survival,
        Self::Scatter,
        Self::Classes,
        Self::Network,
        Self::Cycle,
        Self::Layers,
        Self::Plan,
    ];

    /// The chart type that `type` names, such as `"bar"`.
    #[must_use]
    pub fn from_name(name: &str) -> Option<Self> {
        Self::ALL
            .into_iter()
            .find(|chart_type| type_name(*chart_type) == name)
    }
}

/// Where a time chart names its series.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum LegendPlacement {
    /// A legend above the plot.
    #[default]
    Top,
    /// The name of each line at its last observation, right of the plot.
    End,
}

impl LegendPlacement {
    // serde hands this function a reference, so the signature follows serde's shape.
    #[allow(clippy::trivially_copy_pass_by_ref)]
    const fn is_top(&self) -> bool {
        matches!(self, Self::Top)
    }
}

/// How the series of a bar chart share a category: stacked by value, or as shares of the
/// category's total.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Stack {
    Normal,
    Percent,
    /// The areas of a time pane stacked around a moving baseline instead of zero, so that the
    /// stack is centered: a streamgraph.
    Stream,
}

#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Orientation {
    #[default]
    Vertical,
    Horizontal,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct CategoryAxisSpec {
    #[serde(default)]
    pub title: Option<String>,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ValueAxisSpec {
    #[serde(default)]
    pub title: Option<String>,
    #[serde(default)]
    pub format: ValueFormat,
    /// Fixed number of decimal places for values in labels, tooltips, the description and the
    /// data table. Axis ticks take theirs from the tick step.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub decimals: Option<u8>,
    /// The axis reaches at least down to this value; without it, a line never pads below zero
    /// when all values are zero or more.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min: Option<f64>,
    /// The axis reaches at least up to this value.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max: Option<f64>,
    /// Separates thousands in every written value: `12,500` or, in German, `12.500`. Off by
    /// default, because four digits are often years.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub thousands_separator: bool,
    /// Linear by default; `log` spaces powers of ten evenly, for values across several orders of
    /// magnitude.
    #[serde(default, skip_serializing_if = "AxisScale::is_linear")]
    pub scale: AxisScale,
    /// Runs the axis the other way: larger values down (or left), as δ18O records are drawn.
    #[serde(default, skip_serializing_if = "is_false")]
    pub reverse: bool,
    /// The distance between two ticks, instead of a round step chosen from the values.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub step: Option<f64>,
    /// `min` and `max` are the ends of the axis, not only values it reaches; every value has to
    /// lie between them.
    #[serde(default, skip_serializing_if = "is_false")]
    pub exact: bool,
    /// The unit of the values, such as `W/m²`, written after the top tick label instead of in a
    /// title above the plot, and after the column names of the data table.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub unit: Option<String>,
}

impl ChartSpec {
    /// The unit of the value axis that pane `pane` of a time chart or of small multiples is
    /// drawn on.
    pub(crate) fn axis_unit(&self, pane: usize) -> Option<&str> {
        match self.chart_type {
            ChartType::Time => self.panes.get(pane)?.value_axis.unit.as_deref(),
            ChartType::Multiples if self.is_bar_multiples() => {
                self.panes.get(pane)?.value_axis.unit.as_deref()
            }
            _ => self.value_axis.unit.as_deref(),
        }
    }
}

/// How a value axis spaces its values.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum AxisScale {
    #[default]
    Linear,
    Log,
}

impl AxisScale {
    // serde hands this function a reference, so the signature follows serde's shape.
    #[allow(clippy::trivially_copy_pass_by_ref)]
    pub(crate) const fn is_linear(&self) -> bool {
        matches!(self, Self::Linear)
    }
}

/// A reference line across a bar chart: a value every bar is read against.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ReferenceSpec {
    pub value: f64,
    pub label: String,
}

impl ValueAxisSpec {
    /// The declared lower and upper reach of the axis.
    pub(crate) const fn bounds(&self) -> (Option<f64>, Option<f64>) {
        (self.min, self.max)
    }
}

#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ValueFormat {
    #[default]
    Number,
    Percent,
}

/// A pre-computed zoom step: shows categories `from..=to`, or on a time chart the observations
/// from `from` to `to`, as its own chart variant.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ZoomStep {
    pub label: String,
    pub from: ZoomBound,
    pub to: ZoomBound,
}

/// One end of a zoom step: a category index on a bar or line chart, a timestamp on a time chart.
/// A whole number from 0 up reads as an index first, so that a category chart keeps its
/// serialized form; on a time chart the same number is Unix seconds.
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum ZoomBound {
    Index(usize),
    Time(TimeValue),
}

impl<'de> Deserialize<'de> for ZoomBound {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        untagged::deserialize(deserializer, "ZoomBound", |shape| {
            let index = match shape {
                untagged::Shape::Unsigned(number) => usize::try_from(number).ok(),
                untagged::Shape::Signed(number) => usize::try_from(number).ok(),
                _ => None,
            };
            match index {
                Some(index) => Some(Self::Index(index)),
                None => TimeValue::from_shape(shape).map(Self::Time),
            }
        })
    }
}

impl ZoomBound {
    /// The category index, `None` for a timestamp that is not a whole number from 0.
    pub(crate) const fn index(&self) -> Option<usize> {
        match self {
            Self::Index(index) => Some(*index),
            Self::Time(_) => None,
        }
    }

    /// The bound as Unix seconds, in the forms a point's `time` accepts.
    pub(crate) fn resolve(&self, zone: crate::time::TimeZone) -> Result<i64, &'static str> {
        match self {
            Self::Index(seconds) => {
                // Anything beyond the 1700–2200 contract is refused by `resolve` anyway.
                #[allow(clippy::cast_precision_loss)]
                let seconds = *seconds as f64;
                TimeValue::Number(seconds).resolve(zone)
            }
            Self::Time(time) => time.resolve(zone),
        }
    }
}

/// A layer together with where it sits in the specification.
#[derive(Clone, Copy)]
pub(crate) struct LayerRef<'a> {
    /// Index among all layers of all panes; keys a declared color and a hatch pattern.
    pub global: usize,
    pub pane: usize,
    /// Index within its pane, as the specification path names it.
    pub local: usize,
    pub layer: &'a LayerSpec,
}

/// Categories × series: the single shape that layout, description and data table work with.
pub(crate) struct Dataset {
    pub categories: Vec<String>,
    pub series: Vec<Series>,
}

pub(crate) struct Series {
    /// `None` when the chart was given as a single `data` list.
    pub name: Option<String>,
    pub values: Vec<Option<f64>>,
    /// How this column is written when it is not written like the chart's values: every pane of a time
    /// chart has its own value axis.
    pub style: Option<NumberStyle>,
}

impl Dataset {
    pub(crate) fn values(&self) -> impl Iterator<Item = f64> + '_ {
        self.series
            .iter()
            .flat_map(|series| series.values.iter().flatten().copied())
    }

    /// JSON pointer to a category label in the specification.
    pub(crate) fn category_path(&self, index: usize) -> String {
        if self.series[0].name.is_none() {
            format!("/data/{index}/label")
        } else {
            format!("/categories/{index}")
        }
    }
}

impl ChartSpec {
    /// Parses a chart specification from JSON.
    ///
    /// # Errors
    ///
    /// Returns `invalid_json` for malformed JSON and `invalid_spec` for JSON that does not match
    /// the versioned specification. Like every other error, both carry a JSON Pointer path; a
    /// syntax error points at the document root and names line and column in its message.
    pub fn from_json(input: &str) -> Result<Self, ChartError> {
        if input.len() > MAX_SPEC_BYTES {
            return Err(ChartError::new(
                "spec_too_large",
                "/",
                format!(
                    "the specification is {} bytes; at most {MAX_SPEC_BYTES} (4 MiB) are read. The largest figure at the declared limits is far smaller; remove padding, or split the data over several charts",
                    input.len()
                ),
            ));
        }
        let mut spec: Self = serde_json::from_str(input).map_err(|error: serde_json::Error| {
            let (code, (path, message)) = match error.classify() {
                serde_json::error::Category::Syntax | serde_json::error::Category::Eof => {
                    ("invalid_json", ("/".to_owned(), error.to_string()))
                }
                serde_json::error::Category::Data | serde_json::error::Category::Io => {
                    ("invalid_spec", json_pointer(input, &error))
                }
            };
            ChartError::new(code, path, message)
        })?;
        if let Some(size) = spec.size {
            // The input parsed as an object, so a second read only checks which sizes it names.
            let given: serde_json::Value = serde_json::from_str(input).unwrap_or_default();
            let (width, height) = size.dimensions();
            if given.get("width").is_none() {
                spec.width = width;
            }
            if given.get("height").is_none() {
                spec.height = height;
            }
        }
        Ok(spec)
    }

    pub(crate) fn validate(&self) -> Result<Vec<ChartWarning>, ChartError> {
        self.validate_sized(true)
    }

    /// The chart laid out at the size of its mobile variant, or `None` without one.
    pub(crate) fn mobile_variant(&self) -> Option<ChartSpec> {
        let mobile = self.mobile.as_ref()?;
        let mut spec = self.clone();
        spec.width = mobile.width;
        spec.height = mobile.height;
        if mobile.columns.is_some() {
            spec.columns = mobile.columns;
        }
        spec.mobile = None;
        spec.size = None;
        Some(spec)
    }

    /// Validates a mobile variant. Its size was already checked against the limits of `mobile`,
    /// which admit narrower charts than `width`; the checks that depend on the size, such as
    /// observations per plot pixel, run at that size.
    pub(crate) fn validate_mobile_variant(&self) -> Result<Vec<ChartWarning>, ChartError> {
        self.validate_sized(false)
    }

    fn validate_sized(&self, check_size: bool) -> Result<Vec<ChartWarning>, ChartError> {
        self.validate_metadata(check_size)?;
        self.reject_foreign_blocks()?;
        self.validate_theme()?;
        self.validate_value_axes()?;
        let mut warnings = match self.chart_type {
            ChartType::Time => self.validate_time(),
            ChartType::Multiples => self.validate_multiples(),
            ChartType::Stripes => self.validate_stripes(),
            ChartType::Calendar => self.validate_calendar(),
            ChartType::Rangebar => self.validate_rangebar(),
            ChartType::Sequence => self.validate_sequence(),
            ChartType::Flow => self.validate_flow(),
            ChartType::State => self.validate_state(),
            ChartType::Architecture => self.validate_architecture(),
            ChartType::Tree => self.validate_tree(),
            ChartType::Boxplot => self.validate_boxplot(),
            ChartType::Timeline => self.validate_timeline(),
            ChartType::Classes => self.validate_classes(),
            ChartType::Scatter => self.validate_scatter(),
            ChartType::Survival => self.validate_survival(),
            ChartType::Sankey => self.validate_sankey(),
            ChartType::Treemap => self.validate_treemap(),
            ChartType::Parliament => self.validate_parliament(),
            ChartType::Waffle => self.validate_waffle(),
            ChartType::Funnel => self.validate_funnel(),
            ChartType::Radar => self.validate_radar(),
            ChartType::Polar => self.validate_polar(),
            ChartType::Mosaic => self.validate_mosaic(),
            ChartType::Heatmap => self.validate_heatmap(),
            ChartType::Venn => self.validate_venn(),
            ChartType::Valuemap => self.validate_valuemap(),
            ChartType::Journey => self.validate_journey(),
            ChartType::Storymap => self.validate_storymap(),
            ChartType::Kanban => self.validate_kanban(),
            ChartType::Fishbone => self.validate_fishbone(),
            ChartType::Waterfall => self.validate_waterfall(),
            ChartType::Network => self.validate_network(),
            ChartType::Cycle => self.validate_cycle(),
            ChartType::Layers => self.validate_layers(),
            ChartType::Plan => self.validate_plan(),
            ChartType::Bar | ChartType::Line => self.validate_bar_and_line(),
        }?;
        warnings.extend(crate::contrast::warnings(self));
        warnings.extend(crate::readability::warnings(self));
        Ok(warnings)
    }
}

/// The value of `type` that selects a chart type.
pub(crate) const fn type_name(chart_type: ChartType) -> &'static str {
    match chart_type {
        ChartType::Bar => "bar",
        ChartType::Line => "line",
        ChartType::Time => "time",
        ChartType::Stripes => "stripes",
        ChartType::Calendar => "calendar",
        ChartType::Rangebar => "rangebar",
        ChartType::Multiples => "multiples",
        ChartType::Sequence => "sequence",
        ChartType::Flow => "flow",
        ChartType::State => "state",
        ChartType::Architecture => "architecture",
        ChartType::Tree => "tree",
        ChartType::Boxplot => "boxplot",
        ChartType::Timeline => "timeline",
        ChartType::Classes => "classes",
        ChartType::Scatter => "scatter",
        ChartType::Survival => "survival",
        ChartType::Sankey => "sankey",
        ChartType::Treemap => "treemap",
        ChartType::Parliament => "parliament",
        ChartType::Waffle => "waffle",
        ChartType::Funnel => "funnel",
        ChartType::Radar => "radar",
        ChartType::Polar => "polar",
        ChartType::Mosaic => "mosaic",
        ChartType::Heatmap => "heatmap",
        ChartType::Venn => "venn",
        ChartType::Valuemap => "valuemap",
        ChartType::Journey => "journey",
        ChartType::Storymap => "storymap",
        ChartType::Kanban => "kanban",
        ChartType::Fishbone => "fishbone",
        ChartType::Waterfall => "waterfall",
        ChartType::Network => "network",
        ChartType::Cycle => "cycle",
        ChartType::Layers => "layers",
        ChartType::Plan => "plan",
    }
}

const fn default_width() -> u32 {
    800
}

const fn default_height() -> u32 {
    450
}

const fn default_mobile_height() -> u32 {
    360
}

const fn default_breakpoint() -> u32 {
    640
}

const fn default_show_values() -> bool {
    true
}

const fn default_true() -> bool {
    true
}

// serde hands this function a reference, so the signature follows serde's shape.
#[allow(clippy::trivially_copy_pass_by_ref)]
const fn is_false(value: &bool) -> bool {
    !*value
}

// serde hands this function a reference, so the signature follows serde's shape.
#[allow(clippy::trivially_copy_pass_by_ref)]
const fn is_true(value: &bool) -> bool {
    *value
}