chartlet 0.20.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
mod architecture;
mod atlas;
mod boxplot;
mod calendar;
mod categorical;
mod classes;
mod dataset;
mod deployment;
mod flow;
mod network;
mod parliament;
mod rangebar;
mod sankey;
mod scatter;
mod sequence;
mod state;
mod stripes;
mod survival;
mod timechart;
mod timeline;
mod topicmap;
mod tree;
mod treemap;
pub(crate) mod untagged;
mod validate;
mod view;
mod waffle;
mod waterfall;

use serde::{Deserialize, Serialize};

use crate::{
    error::{ChartError, ChartWarning},
    time::TimeValue,
};
pub use architecture::{
    ArchitectureSpec, BoundarySpec, CategorySpec, ComponentKind, ComponentSpec,
    ConnectionDirection, ConnectionSpec, InterfaceSpec, PerspectiveSpec,
};
pub use atlas::{AtlasSpec, PlaceSpec, RegionSpec};
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 flow::{
    DiagramRole, DiagramSpacing, FlowEdgeSpec, FlowNodeSpec, FlowSpec, GroupSpec, LaneSpec,
    MainPath, NodeKind, NoteSpec, PartSpec, PortSide,
};
pub use network::{NetworkEdgeSpec, NetworkLayout, NetworkNodeSpec, NetworkOrder, NetworkSpec};
pub use parliament::{ParliamentSpec, PartySpec};
pub use rangebar::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(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 topicmap::{CartoucheSpec, Corner, TopicLinkSpec, TopicMapSpec, TopicSpec};
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 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;
/// 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,
    /// 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,
    /// 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,
    /// 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,
    #[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,
    /// 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 topics of a `type: "topicmap"` 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 topicmap: Option<TopicMapSpec>,
    /// The landscape of a `type: "atlas"` chart. Skipped while absent, for the same reason as
    /// `topicmap`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub atlas: Option<AtlasSpec>,
    /// The yearly values of a `type: "stripes"` chart. Skipped while absent, like `topicmap`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stripes: Option<StripesSpec>,
    /// The daily values of a `type: "calendar"` chart. Skipped while absent, like `topicmap`.
    #[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
    /// `topicmap`.
    #[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 `topicmap`.
    #[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
    /// `topicmap`.
    #[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 `topicmap`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub architecture: Option<ArchitectureSpec>,
    /// The nodes of a `type: "tree"` diagram. Skipped while absent, like `topicmap`.
    #[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 `topicmap`.
    #[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 `topicmap`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub waffle: Option<WaffleSpec>,
    /// A parliament: seats as dots in a semicircle, in blocks by party. Skipped while absent, like `topicmap`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parliament: Option<ParliamentSpec>,
    /// A treemap: rectangles whose areas follow the values. Skipped while absent, like `topicmap`.
    #[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 `topicmap`.
    #[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 `topicmap`.
    #[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 `topicmap`.
    #[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 `topicmap`.
    #[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 `topicmap`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub network: Option<NetworkSpec>,
    /// The items of a `type: "timeline"` chart. Skipped while absent, like `topicmap`.
    #[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 `topicmap`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mobile: Option<MobileSpec>,
}

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

/// 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,
    /// Topic areas as a landmass map; area proportional to each topic's value.
    Topicmap,
    /// A knowledge landscape: realms of adjacent regions, holding places. Where `topicmap` packs
    /// separate landmasses and lets size carry the whole statement, an `atlas` tiles one
    /// continuous land, so that *where* something lies says as much as how large it is.
    Atlas,
    /// 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 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,
}

impl ChartType {
    /// Every chart type, in the order of the specification's documentation.
    pub const ALL: [Self; 25] = [
        Self::Bar,
        Self::Line,
        Self::Time,
        Self::Topicmap,
        Self::Atlas,
        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::Parliament,
        Self::Treemap,
        Self::Sankey,
        Self::Survival,
        Self::Scatter,
        Self::Classes,
        Self::Network,
    ];

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

#[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: a topic map's
    /// share column is a percentage while the counts beside it are plain numbers, and 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> {
        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)
        })
    }

    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;
        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()?;
        match self.chart_type {
            ChartType::Time => self.validate_time(),
            ChartType::Multiples => self.validate_multiples(),
            ChartType::Topicmap => self.validate_topicmap(),
            ChartType::Atlas => self.validate_atlas(),
            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::Waterfall => self.validate_waterfall(),
            ChartType::Network => self.validate_network(),
            ChartType::Bar | ChartType::Line => self.validate_bar_and_line(),
        }
    }
}

/// 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::Topicmap => "topicmap",
        ChartType::Atlas => "atlas",
        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::Waterfall => "waterfall",
        ChartType::Network => "network",
    }
}

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 one() -> f64 {
    1.0
}

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
}