figgy-model 0.10.0

figgy chart model — option SSoT, interaction contracts, preset policies.
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
//! Legend model — the whole legend is **one rich inline document**
//! ([`Legend::content`]).
//!
//! Design points:
//! - **Symbols are fixed-width rich segments.** A line sample is a drawn
//!   horizontal rule whose em dash text is only a fallback, while a scatter
//!   sample is a geometric-shape glyph (`●`, `■`, …) centered in its field.
//!   Each symbol form occupies the same 2 em total advance and carries a
//!   per-segment `RichSegment.color` override, so marks line up and use the
//!   same layout path on screen and in PNG export.
//! - **Everything is explicit in the SSoT.** Line breaks are `'\n'` segments,
//!   and symbols remain inline segment sequences, so a one-line legend,
//!   mid-text symbols, and any custom arrangement are all explicit.
//! - **Font and font size are live.** `content.font` / `content.font_size`
//!   (and per-segment overrides) are consumed at draw time, so SSoT edits
//!   after composition still apply.
//!
//! Composition helpers cover the common cases: [`symbol_segments`] /
//! [`series_symbol_segments`] build a colored symbol, [`append_legend_entry`]
//! appends "fixed-width symbol + space + tab + label" as a new line. Fully
//! custom layouts edit `content.segments` directly.

use crate::color::Color;
use crate::data_config::{DataRenderType, ScatterShape, SeriesConfig};
use crate::line::LineStylePreset;
use crate::text::{RichSegment, RichText, rich_segments_from_text};
use std::ops::Range;

#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum LegendCorner {
    TopLeft,
    TopRight,
    BottomLeft,
    BottomRight,
}

/// Sample kinds for the convenience builders (mirrors what a series draws).
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum LegendEntryKind {
    /// Line sample only.
    Line,
    /// Point sample only.
    Scatter,
    /// Line + point sample.
    LineScatter,
}

/// The compact legend character for a [`ScatterShape`]. Exact geometric
/// glyphs are used only when the bundled Liberation Sans face covers them;
/// pentagon/hexagon/octagon fall back to familiar marker-code letters.
pub fn scatter_shape_char(shape: &ScatterShape) -> char {
    match shape {
        ScatterShape::Circle => '○',
        ScatterShape::CircleFilled => '●',
        ScatterShape::Square => '□',
        ScatterShape::SquareFilled => '■',
        ScatterShape::Triangle => '▲',
        ScatterShape::TriangleFilled => '▲',
        ScatterShape::TriangleDown => '▼',
        ScatterShape::TriangleDownFilled => '▼',
        ScatterShape::TriangleLeft => '◄',
        ScatterShape::TriangleLeftFilled => '◄',
        ScatterShape::TriangleRight => '►',
        ScatterShape::TriangleRightFilled => '►',
        ScatterShape::Diamond => '◊',
        ScatterShape::DiamondFilled => '♦',
        ScatterShape::Cross => '×',
        ScatterShape::CrossFilled => '×',
        ScatterShape::Plus => '+',
        ScatterShape::PlusFilled => '+',
        ScatterShape::Pentagon => 'p',
        ScatterShape::PentagonFilled => 'p',
        ScatterShape::Hexagon => 'h',
        ScatterShape::HexagonFilled => 'h',
        ScatterShape::Octagon => '8',
        ScatterShape::OctagonFilled => '8',
        ScatterShape::Star => '*',
        ScatterShape::StarFilled => '*',
    }
}

/// Every symbol form spans exactly this many em (× legend font size), so
/// marks line up regardless of shape: a lone line, a lone glyph, and a
/// line-through-glyph all advance the pen by the same fixed field.
pub const SYMBOL_FIELD_EM: f32 = 2.0;
const LEGEND_DASH_NOMINAL_FONT_PX: f32 = 14.0;

fn rule_dash_em(style: LineStylePreset) -> Option<Vec<f32>> {
    let pattern = style.pattern();
    if pattern.is_empty() {
        None
    } else {
        Some(
            pattern
                .iter()
                .map(|v| v / LEGEND_DASH_NOMINAL_FONT_PX)
                .collect(),
        )
    }
}

#[cfg(test)]
mod legend_update_tests {
    use super::*;
    use crate::data_config::DataLineStyleConfig;
    use crate::line::LineStylePreset;

    fn line_cfg(color: Color, line_style: LineStylePreset) -> SeriesConfig {
        SeriesConfig {
            series_id: "s".into(),
            source_id: None,
            label: None,
            x_column: "x".into(),
            y_column: "y".into(),
            render_type: DataRenderType::Line {
                line: DataLineStyleConfig {
                    line_style,
                    line_color: color,
                    line_width: 1.0,
                },
            },
        }
    }

    fn empty_content() -> RichText {
        RichText {
            segments: Vec::new(),
            color: Color::BLACK,
            font_size: 14.0,
            font: String::new(),
        }
    }

    #[test]
    fn dashed_series_symbol_carries_rule_dash() {
        let red = Color::new(1.0, 0.0, 0.0, 1.0);
        let segs = series_symbol_segments(&line_cfg(red, LineStylePreset::Dash));
        assert_eq!(segs.len(), 1);
        assert!(segs[0].rule);
        assert_eq!(segs[0].color, Some(red));
        assert_eq!(
            segs[0].rule_dash.as_deref(),
            Some(&[8.0 / 14.0, 4.0 / 14.0][..])
        );
    }

    #[test]
    fn symbol_update_preserves_user_text_and_label_newlines() {
        let red = Color::new(1.0, 0.0, 0.0, 1.0);
        let blue = Color::new(0.0, 0.0, 1.0, 1.0);
        let green = Color::new(0.0, 0.8, 0.0, 1.0);
        let mut content = empty_content();
        append_legend_entry(
            &mut content,
            series_symbol_segments(&line_cfg(red, LineStylePreset::Solid)),
            "line 1\nline 2",
        );
        append_legend_entry(
            &mut content,
            series_symbol_segments(&line_cfg(blue, LineStylePreset::Solid)),
            "beta",
        );

        let series = [
            line_cfg(green, LineStylePreset::Dash),
            line_cfg(red, LineStylePreset::Dot),
        ];
        assert_eq!(
            update_legend_symbols_preserving_text(&mut content, &series),
            2
        );
        let text: String = content.segments.iter().map(|s| s.text).collect();

        assert_eq!(legend_entry_count(&content), 2);
        assert!(text.contains("line 1\nline 2"));
        assert!(text.contains("beta"));
        assert_eq!(content.segments[0].color, Some(green));
        assert!(content.segments[0].rule_dash.is_some());
    }

    #[test]
    fn label_update_and_remove_touch_only_target_entry() {
        let mut content = empty_content();
        append_legend_entry(
            &mut content,
            series_symbol_segments(&line_cfg(Color::BLACK, LineStylePreset::Solid)),
            "alpha",
        );
        append_legend_entry(
            &mut content,
            series_symbol_segments(&line_cfg(Color::BLACK, LineStylePreset::Solid)),
            "beta",
        );

        set_legend_entry_label(
            &mut content,
            1,
            series_symbol_segments(&line_cfg(Color::BLACK, LineStylePreset::Solid)),
            rich_segments_from_text("gamma"),
        );
        let text: String = content.segments.iter().map(|s| s.text).collect();
        assert!(text.contains("alpha"));
        assert!(text.contains("gamma"));
        assert!(!text.contains("beta"));

        assert!(remove_legend_entry(&mut content, 0));
        let text: String = content.segments.iter().map(|s| s.text).collect();
        assert!(!text.contains("alpha"));
        assert!(text.contains("gamma"));
        assert_eq!(legend_entry_count(&content), 1);
    }

    #[test]
    fn custom_legend_without_auto_entry_shape_is_left_untouched() {
        let mut content = RichText::plain("custom legend text", Color::BLACK, 14.0, "");
        let before = content.clone();
        assert_eq!(
            update_legend_symbols_preserving_text(
                &mut content,
                &[line_cfg(Color::BLACK, LineStylePreset::Solid)]
            ),
            0
        );
        assert_eq!(content, before);
        assert!(!remove_legend_entry(&mut content, 0));
    }
}

/// Line sample: a drawn rule filling the whole symbol field — exact length,
/// unlike any dash glyph.
fn line_symbol(color: Color, style: LineStylePreset) -> Vec<RichSegment> {
    let seg = match rule_dash_em(style) {
        Some(dash) => RichSegment::dashed_rule(SYMBOL_FIELD_EM, Some(color), dash),
        None => RichSegment::rule(SYMBOL_FIELD_EM, Some(color)),
    };
    vec![seg]
}

/// Point sample: the shape's glyph centered in the symbol field.
fn scatter_symbol(shape: &ScatterShape, color: Color) -> Vec<RichSegment> {
    vec![RichSegment::fielded(
        scatter_shape_char(shape),
        SYMBOL_FIELD_EM,
        Some(color),
    )]
}

/// Line + point sample: rule — glyph — rule, the three fields summing to
/// exactly [`SYMBOL_FIELD_EM`] so the combined mark is as long as a lone
/// line mark.
fn line_scatter_symbol(shape: &ScatterShape, color: Color) -> Vec<RichSegment> {
    line_scatter_symbol_with_style(shape, color, LineStylePreset::Solid)
}

fn line_scatter_symbol_with_style(
    shape: &ScatterShape,
    color: Color,
    style: LineStylePreset,
) -> Vec<RichSegment> {
    let glyph_em = 0.7;
    let rule_em = (SYMBOL_FIELD_EM - glyph_em) * 0.5;
    let rule = |width_em| match rule_dash_em(style) {
        Some(dash) => RichSegment::dashed_rule(width_em, Some(color), dash),
        None => RichSegment::rule(width_em, Some(color)),
    };
    vec![
        rule(rule_em),
        RichSegment::fielded(scatter_shape_char(shape), glyph_em, Some(color)),
        rule(rule_em),
    ]
}

/// Symbol segments for the convenience-builder [`LegendEntryKind`]: each
/// segment carries `color: Some(color)` so the mark keeps the series color
/// independent of the document-level text color.
pub fn symbol_segments(kind: &LegendEntryKind, color: Color) -> Vec<RichSegment> {
    match kind {
        LegendEntryKind::Line => line_symbol(color, LineStylePreset::Solid),
        LegendEntryKind::Scatter => scatter_symbol(&ScatterShape::CircleFilled, color),
        LegendEntryKind::LineScatter => line_scatter_symbol(&ScatterShape::CircleFilled, color),
    }
}

/// Blank mark of exactly [`SYMBOL_FIELD_EM`] — a label-only legend row.
///
/// Used for a heatmap, whose colour is the colourbar's to report and not a
/// single swatch's. It is a spacer rather than an empty vec because every series
/// must still produce exactly one entry: legend entry `i` **is** series `i`
/// (`update_legend_symbols_preserving_text` zips the two positionally, and the
/// web layer passes series indices to `set_legend_entry_label`), so a skipped
/// entry would re-point every later row's symbol at the wrong series. Full field
/// width also keeps the tab-aligned symbol column the same width on every row.
fn blank_symbol() -> Vec<RichSegment> {
    vec![RichSegment::fielded(' ', SYMBOL_FIELD_EM, None)]
}

/// Symbol segments matching a series declaration: line / scatter / combined,
/// shape and color taken from the render type's sub-styles.
pub fn series_symbol_segments(cfg: &SeriesConfig) -> Vec<RichSegment> {
    match &cfg.render_type {
        DataRenderType::Line { line } => line_symbol(line.line_color, line.line_style),
        // A bar reads as a filled swatch; the glyph is already in the shape
        // table, so no new symbol machinery.
        DataRenderType::Histogram { bar } => {
            scatter_symbol(&ScatterShape::SquareFilled, bar.fill_color)
        }
        // Contour lines are lines. When a fill is under them the line is still
        // the mark — the fill's colours belong to the colourbar.
        DataRenderType::Contour { contour, .. }
        | DataRenderType::HeatmapContour { contour, .. } => {
            line_symbol(contour.line.line_color, contour.line.line_style)
        }
        DataRenderType::Heatmap { .. } => blank_symbol(),
        DataRenderType::Scatter { scatter }
        | DataRenderType::ScatterErrorbarX { scatter, .. }
        | DataRenderType::ScatterErrorbarY { scatter, .. }
        | DataRenderType::ScatterErrorbarXY { scatter, .. } => {
            scatter_symbol(&scatter.point_shape, scatter.point_color)
        }
        DataRenderType::ScatterLine { scatter, line }
        | DataRenderType::LineScatterErrorbarX { scatter, line, .. }
        | DataRenderType::LineScatterErrorbarY { scatter, line, .. }
        | DataRenderType::LineScatterErrorbarXY { scatter, line, .. } => {
            line_scatter_symbol_with_style(&scatter.point_shape, line.line_color, line.line_style)
        }
    }
}

/// Append one "entry" to the legend document: a `'\n'` segment when content
/// already exists, then the symbol segments, one space, a `'\t'` column
/// separator, then the label (sub/superscript unicode and `'\n'` are
/// interpreted by the segment mapper).
///
/// The `'\t'` makes the symbol field a table column: the text engine sizes
/// each label column consistently across rows. The symbol sequence itself
/// always totals [`SYMBOL_FIELD_EM`], whether it is a rule, a centered glyph,
/// or rule + glyph + rule. Callers wanting a one-line legend can extend
/// `content.segments` themselves without the `'\n'`.
pub fn append_legend_entry(content: &mut RichText, symbol: Vec<RichSegment>, label: &str) {
    append_legend_entry_rich(content, symbol, rich_segments_from_text(label));
}

/// Append one legend entry using already-styled label segments.
pub fn append_legend_entry_rich(
    content: &mut RichText,
    symbol: Vec<RichSegment>,
    label: Vec<RichSegment>,
) {
    if !content.segments.is_empty() {
        content.segments.push(RichSegment::plain('\n'));
    }
    content.segments.extend(symbol);
    content.segments.push(RichSegment::plain(' '));
    content.segments.push(RichSegment::plain('\t'));
    content.segments.extend(label);
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct LegendEntrySpan {
    symbol: Range<usize>,
    text: Range<usize>,
    remove: Range<usize>,
}

fn is_plain_space(seg: &RichSegment) -> bool {
    seg.text == ' '
        && !seg.bold
        && !seg.italic
        && !seg.underline
        && !seg.superscript
        && !seg.subscript
        && !seg.greek
        && seg.color.is_none()
        && seg.font_size.is_none()
        && seg.field_em.is_none()
        && !seg.rule
        && seg.rule_dash.is_none()
}

fn symbol_anchor(segments: &[RichSegment], start: usize) -> Option<(usize, usize)> {
    if start >= segments.len() || segments[start].field_em.is_none() {
        return None;
    }

    let mut i = start;
    while i < segments.len() && segments[i].field_em.is_some() {
        i += 1;
    }
    let symbol_end = i;
    while i < segments.len() && is_plain_space(&segments[i]) {
        i += 1;
    }
    (i < segments.len() && segments[i].text == '\t').then_some((symbol_end, i))
}

fn legend_entry_spans(content: &RichText) -> Vec<LegendEntrySpan> {
    let segments = &content.segments;
    let mut anchors = Vec::new();
    let mut i = 0;
    while i < segments.len() {
        if let Some((symbol_end, tab)) = symbol_anchor(segments, i) {
            anchors.push((i, symbol_end, tab));
            i = tab + 1;
        } else {
            i += 1;
        }
    }

    let mut spans = Vec::with_capacity(anchors.len());
    for (idx, &(symbol_start, symbol_end, tab)) in anchors.iter().enumerate() {
        let next_start = anchors.get(idx + 1).map(|(start, _, _)| *start);
        let mut text_end = next_start.unwrap_or(segments.len());
        if next_start.is_some() && text_end > tab + 1 && segments[text_end - 1].text == '\n' {
            text_end -= 1;
        }

        let remove_start = if symbol_start > 0 && segments[symbol_start - 1].text == '\n' {
            symbol_start - 1
        } else {
            symbol_start
        };
        let remove_end = if idx == 0 {
            next_start
                .filter(|&start| start > 0 && segments[start - 1].text == '\n')
                .unwrap_or(text_end)
        } else {
            text_end
        };

        spans.push(LegendEntrySpan {
            symbol: symbol_start..symbol_end,
            text: tab + 1..text_end,
            remove: remove_start..remove_end,
        });
    }
    spans
}

/// Number of auto-format legend entries recognized in a rich legend document.
pub fn legend_entry_count(content: &RichText) -> usize {
    legend_entry_spans(content).len()
}

/// Replace recognized entry symbols in order and keep every user text segment
/// untouched. Custom layouts that do not expose the auto symbol+tab shape are
/// left unchanged.
pub fn update_legend_symbols_preserving_text(
    content: &mut RichText,
    series: &[SeriesConfig],
) -> usize {
    let spans = legend_entry_spans(content);
    let mut replaced = 0;
    for (span, cfg) in spans.into_iter().zip(series.iter()).rev() {
        content
            .segments
            .splice(span.symbol, series_symbol_segments(cfg));
        replaced += 1;
    }
    replaced
}

/// Set one recognized legend entry label while preserving the surrounding
/// document. If the entry does not exist, append a new auto-format entry.
pub fn set_legend_entry_label(
    content: &mut RichText,
    entry_index: usize,
    symbol: Vec<RichSegment>,
    label: Vec<RichSegment>,
) {
    let spans = legend_entry_spans(content);
    if let Some(span) = spans.get(entry_index) {
        content.segments.splice(span.text.clone(), label);
    } else {
        append_legend_entry_rich(content, symbol, label);
    }
}

/// Remove one recognized auto-format legend entry. Returns false when the
/// document does not expose that entry shape.
pub fn remove_legend_entry(content: &mut RichText, entry_index: usize) -> bool {
    let spans = legend_entry_spans(content);
    let Some(span) = spans.get(entry_index) else {
        return false;
    };
    content.segments.drain(span.remove.clone());
    true
}

/// Legend box rendered in one corner of the chart's data area.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Legend {
    pub visible: bool,
    /// The whole legend as one rich document. `'\n'` segments break lines;
    /// symbol fields are fixed-width inline segments with color overrides.
    /// Line symbols draw rules across their fields and retain an em dash only
    /// as fallback text; scatter glyphs are centered in their fields. Thus
    /// line breaks, symbol positions, and mid-text symbols remain explicit in
    /// the SSoT. Font + font_size of this RichText are consumed at draw time.
    pub content: RichText,
    pub corner: LegendCorner,
    /// Visual offset from the corner anchor (drag-to-move lands here).
    pub offset_x: f32,
    pub offset_y: f32,
    /// Inset from the data_area inner corner + padding inside the box.
    pub padding: f32,
    /// Box background and border.
    pub bg_color: Color,
    pub border_color: Color,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data_config::DataLineStyleConfig;
    use crate::line::LineStylePreset;

    fn line_cfg(color: Color) -> SeriesConfig {
        line_cfg_style(color, LineStylePreset::Solid)
    }

    fn line_cfg_style(color: Color, line_style: LineStylePreset) -> SeriesConfig {
        SeriesConfig {
            series_id: "s".into(),
            source_id: None,
            label: None,
            x_column: "x".into(),
            y_column: "y".into(),
            render_type: DataRenderType::Line {
                line: DataLineStyleConfig {
                    line_style,
                    line_color: color,
                    line_width: 1.0,
                },
            },
        }
    }

    fn empty_content() -> RichText {
        RichText {
            segments: Vec::new(),
            color: Color::BLACK,
            font_size: 14.0,
            font: String::new(),
        }
    }

    #[test]
    fn series_symbol_takes_series_color_as_override() {
        let red = Color::new(1.0, 0.0, 0.0, 1.0);
        let segs = series_symbol_segments(&line_cfg(red));
        assert_eq!(segs.len(), 1); // "—"
        assert_eq!(segs[0].text, '—');
        assert_eq!(segs[0].color, Some(red));
        assert_eq!(segs[0].font_size, None); // size stays live via the document
    }

    #[test]
    fn scatter_symbols_map_every_shape_to_a_glyph() {
        for shape in [
            ScatterShape::Circle,
            ScatterShape::Square,
            ScatterShape::Triangle,
            ScatterShape::TriangleDown,
            ScatterShape::TriangleLeft,
            ScatterShape::TriangleRight,
            ScatterShape::Diamond,
            ScatterShape::Cross,
            ScatterShape::Plus,
            ScatterShape::Pentagon,
            ScatterShape::Hexagon,
            ScatterShape::Octagon,
            ScatterShape::Star,
            ScatterShape::CircleFilled,
            ScatterShape::SquareFilled,
            ScatterShape::TriangleFilled,
            ScatterShape::TriangleDownFilled,
            ScatterShape::TriangleLeftFilled,
            ScatterShape::TriangleRightFilled,
            ScatterShape::DiamondFilled,
            ScatterShape::CrossFilled,
            ScatterShape::PlusFilled,
            ScatterShape::PentagonFilled,
            ScatterShape::HexagonFilled,
            ScatterShape::OctagonFilled,
            ScatterShape::StarFilled,
        ] {
            let c = scatter_shape_char(&shape);
            assert!(!c.is_control(), "{shape:?} → {c}");
        }
    }

    #[test]
    fn kind_symbols_carry_color_override_on_every_segment() {
        let blue = Color::new(0.0, 0.0, 1.0, 1.0);
        for kind in [
            LegendEntryKind::Line,
            LegendEntryKind::Scatter,
            LegendEntryKind::LineScatter,
        ] {
            let segs = symbol_segments(&kind, blue);
            assert!(!segs.is_empty());
            assert!(segs.iter().all(|s| s.color == Some(blue)), "{kind:?}");
        }
    }

    #[test]
    fn two_appends_put_explicit_newline_between_entries() {
        let mut content = empty_content();
        append_legend_entry(
            &mut content,
            symbol_segments(&LegendEntryKind::Line, Color::BLACK),
            "a",
        );
        append_legend_entry(
            &mut content,
            symbol_segments(&LegendEntryKind::Line, Color::BLACK),
            "b",
        );

        let newlines = content.segments.iter().filter(|s| s.text == '\n').count();
        assert_eq!(newlines, 1);
        // Entry shape: symbol, space, '\t' column break, label — twice.
        // The tab gives every entry the same symbol-field width at draw time.
        let texts: String = content.segments.iter().map(|s| s.text).collect();
        assert_eq!(texts, "— \ta\n— \tb");
        // Labels inherit the document color (no override).
        assert!(
            content
                .segments
                .iter()
                .filter(|s| s.text == 'a')
                .all(|s| s.color.is_none())
        );
    }

    #[test]
    fn label_newlines_stay_explicit_in_content() {
        let mut content = empty_content();
        append_legend_entry(
            &mut content,
            symbol_segments(&LegendEntryKind::Line, Color::BLACK),
            "line 1\nline 2",
        );
        let newlines = content.segments.iter().filter(|s| s.text == '\n').count();
        assert_eq!(newlines, 1);
    }

    #[test]
    fn one_line_composition_when_caller_joins_without_newline() {
        // A fully one-line legend: the caller extends the document directly
        // instead of letting `append_legend_entry` insert the '\n'.
        let red = Color::new(1.0, 0.0, 0.0, 1.0);
        let mut content = empty_content();
        append_legend_entry(
            &mut content,
            symbol_segments(&LegendEntryKind::Line, red),
            "a",
        );
        content.segments.push(RichSegment::plain(' '));
        content
            .segments
            .extend(symbol_segments(&LegendEntryKind::Scatter, red));
        content.segments.push(RichSegment::plain(' '));
        content.segments.extend(rich_segments_from_text("b"));

        assert!(content.segments.iter().all(|s| s.text != '\n'));
        let texts: String = content.segments.iter().map(|s| s.text).collect();
        assert_eq!(texts, "— \ta ● b");
    }

    fn field_series(render_type: DataRenderType) -> SeriesConfig {
        SeriesConfig {
            series_id: "f".into(),
            source_id: None,
            label: None,
            x_column: "x".into(),
            y_column: "y".into(),
            render_type,
        }
    }

    fn bar(color: Color) -> DataRenderType {
        DataRenderType::Histogram {
            bar: crate::data_config::DataBarStyleConfig {
                fill_color: color,
                border_color: Color::BLACK,
                border_width: 1.0,
                baseline: 0.0,
                gap_px: 1.0,
                width_ratio: 1.0,
                orientation: crate::data_config::BarOrientation::Vertical,
                bar_style_overrides: None,
            },
        }
    }

    fn contour(color: Color) -> crate::data_config::ContourConfig {
        crate::data_config::ContourConfig {
            levels: vec![1.0],
            line: DataLineStyleConfig {
                line_style: LineStylePreset::Dash,
                line_color: color,
                line_width: 1.0,
            },
            per_level_color: None,
            labels: None,
        }
    }

    fn matrix() -> crate::data_config::MatrixRef {
        crate::data_config::MatrixRef {
            columns: vec!["z0".into()],
            orientation: crate::data_config::MatrixOrientation::ColumnsAreX,
            grid_layout: crate::data_config::GridLayout::Centers,
        }
    }

    fn fill() -> crate::data_config::FieldFillConfig {
        crate::data_config::FieldFillConfig {
            mode: crate::data_config::FillMode::Continuous,
            shading: crate::data_config::Shading::Flat,
            opacity: 1.0,
        }
    }

    // A bar reads as a swatch, a contour as a line — in the colours those
    // primitives are actually drawn with.
    #[test]
    fn field_series_symbols_come_from_the_primitive_that_is_drawn() {
        let swatch = series_symbol_segments(&field_series(bar(Color::from_rgb8(1, 2, 3))));
        assert_eq!(swatch.len(), 1);
        assert_eq!(swatch[0].color, Some(Color::from_rgb8(1, 2, 3)));
        assert_eq!(
            swatch[0].text,
            scatter_shape_char(&crate::data_config::ScatterShape::SquareFilled)
        );

        let level_color = Color::from_rgb8(4, 5, 6);
        for render_type in [
            DataRenderType::Contour {
                matrix: matrix(),
                contour: contour(level_color),
            },
            DataRenderType::HeatmapContour {
                matrix: matrix(),
                fill: fill(),
                contour: contour(level_color),
            },
        ] {
            let mark = series_symbol_segments(&field_series(render_type));
            assert_eq!(mark.len(), 1, "a contour mark is one rule");
            assert_eq!(mark[0].color, Some(level_color));
            // Dashed, because the contour line is — the mark reports the style
            // the line is drawn with, not a generic rule.
            assert!(mark[0].rule, "a contour mark is a drawn rule");
            assert!(mark[0].rule_dash.is_some(), "dashed contour, dashed mark");
        }
    }

    // A heatmap has no swatch of its own: its colours are the colourbar's. The
    // mark is blank — but it is still exactly one full-width segment, because
    // legend entry `i` is series `i` and the symbol column is tab-aligned across
    // rows. An empty vec would re-point every later row at the wrong series.
    #[test]
    fn a_heatmap_gets_a_blank_full_width_mark_not_no_entry() {
        let heatmap = field_series(DataRenderType::Heatmap {
            matrix: matrix(),
            fill: fill(),
        });
        let mark = series_symbol_segments(&heatmap);
        assert_eq!(mark.len(), 1);
        assert_eq!(mark[0].field_em, Some(SYMBOL_FIELD_EM));
        assert_eq!(mark[0].text, ' ');

        // One entry per series, in series order, with the heatmap in the middle.
        let series = [
            line_cfg(Color::from_rgb8(10, 0, 0)),
            heatmap,
            field_series(bar(Color::from_rgb8(0, 10, 0))),
        ];
        let mut content = RichText {
            segments: Vec::new(),
            color: Color::BLACK,
            font_size: 12.0,
            font: String::new(),
        };
        for cfg in &series {
            append_legend_entry(&mut content, series_symbol_segments(cfg), "label");
        }
        assert_eq!(legend_entry_count(&content), series.len());
        assert_eq!(
            update_legend_symbols_preserving_text(&mut content, &series),
            series.len(),
            "every series must own exactly one entry, or later symbols shift"
        );
    }
}