unicode-plot 0.1.0

unicode-plot-rs: Unicode terminal plotting library for Rust
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
use std::io::{Result as IoResult, Write};

use crate::color::{CanvasColor, NamedColor, TermColor};
use crate::graphics::{GraphicsArea, RowBuffer};
use crate::plot::Plot;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct StyledCell {
    pub glyph: char,
    pub color: Option<TermColor>,
    pub bold: bool,
}

impl StyledCell {
    #[must_use]
    pub(crate) const fn plain(glyph: char) -> Self {
        Self {
            glyph,
            color: None,
            bold: false,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub(crate) struct RenderedPlot {
    rows: Vec<Vec<StyledCell>>,
}

impl RenderedPlot {
    #[must_use]
    pub(crate) fn rows(&self) -> &[Vec<StyledCell>] {
        &self.rows
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct LayoutMetrics {
    pub border_length: usize,
    pub max_left_label_width: usize,
    pub max_right_label_width: usize,
    pub ylabel_row: usize,
    pub total_width: usize,
}

impl LayoutMetrics {
    #[must_use]
    pub(crate) fn for_plot<G: GraphicsArea>(plot: &Plot<G>) -> Self {
        let border_length = plot.graphics().ncols() + 2;
        let show_labels = plot.show_labels();
        let max_left_label_width = if show_labels {
            plot.annotations()
                .left()
                .values()
                .map(|label| label.text().chars().count())
                .max()
                .unwrap_or(0)
        } else {
            0
        };
        let max_right_label_width = if show_labels {
            plot.annotations()
                .right()
                .values()
                .map(|label| label.text().chars().count())
                .max()
                .unwrap_or(0)
        } else {
            0
        };
        let ylabel_row = plot.graphics().nrows() / 2;
        let ylabel_width = plot.ylabel().map_or(0, |text| text.chars().count());
        let margin = usize::from(plot.margin());
        let padding = usize::from(plot.padding());

        let total_width = margin
            + ylabel_width
            + padding
            + max_left_label_width
            + padding
            + border_length
            + padding
            + max_right_label_width;

        Self {
            border_length,
            max_left_label_width,
            max_right_label_width,
            ylabel_row,
            total_width,
        }
    }
}

#[must_use]
pub(crate) fn build_rendered_plot<G: GraphicsArea>(plot: &Plot<G>) -> RenderedPlot {
    let layout = LayoutMetrics::for_plot(plot);
    let border_chars = plot.border().chars();
    let mut rows = Vec::new();

    if let Some(title) = plot.title() {
        rows.push(centered_row(title, layout.total_width, None, true));
    }

    if has_any_decoration(plot) {
        rows.push(decoration_row(plot, layout, true));
    }

    rows.push(border_row(
        plot,
        layout,
        border_chars.tl,
        border_chars.t,
        border_chars.tr,
    ));

    let mut graphics_row = RowBuffer::new();
    for row_index in 0..plot.graphics().nrows() {
        plot.graphics().render_row(row_index, &mut graphics_row);
        rows.push(body_row(plot, layout, row_index, &graphics_row));
    }

    rows.push(border_row(
        plot,
        layout,
        border_chars.bl,
        border_chars.b,
        border_chars.br,
    ));

    if has_any_bottom_decoration(plot) {
        rows.push(decoration_row(plot, layout, false));
    }

    if let Some(xlabel) = plot.xlabel() {
        rows.push(centered_row(xlabel, layout.total_width, None, false));
    }

    RenderedPlot { rows }
}

pub(crate) fn write_plain(rendered: &RenderedPlot, writer: &mut impl Write) -> IoResult<()> {
    for row in rendered.rows() {
        let mut line = String::with_capacity(row.len());
        for cell in &row[..trimmed_render_len(row)] {
            line.push(cell.glyph);
        }
        writer.write_all(line.as_bytes())?;
        writer.write_all(b"\n")?;
    }
    Ok(())
}

pub(crate) fn write_ansi(rendered: &RenderedPlot, writer: &mut impl Write) -> IoResult<()> {
    for row in rendered.rows() {
        let mut active_style = CellStyle::default();
        for cell in &row[..trimmed_render_len(row)] {
            let style = CellStyle::from(*cell);
            if style != active_style {
                emit_style_transition(writer, active_style, style)?;
                active_style = style;
            }

            let mut glyph = [0_u8; 4];
            writer.write_all(cell.glyph.encode_utf8(&mut glyph).as_bytes())?;
        }

        if active_style != CellStyle::default() {
            emit_style_transition(writer, active_style, CellStyle::default())?;
        }

        writer.write_all(b"\n")?;
    }

    Ok(())
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
struct CellStyle {
    color: Option<TermColor>,
    bold: bool,
}

impl From<StyledCell> for CellStyle {
    fn from(value: StyledCell) -> Self {
        Self {
            color: value.color,
            bold: value.bold,
        }
    }
}

fn trimmed_render_len(row: &[StyledCell]) -> usize {
    row.iter()
        .rposition(|cell| cell.glyph != ' ')
        .map_or(0, |index| index + 1)
}

fn emit_style_transition(writer: &mut impl Write, from: CellStyle, to: CellStyle) -> IoResult<()> {
    if from.bold != to.bold {
        if to.bold {
            writer.write_all(b"\x1b[1m")?;
        } else {
            writer.write_all(b"\x1b[22m")?;
        }
    }

    if from.color != to.color {
        if let Some(color) = to.color {
            emit_fg_color(writer, color)?;
        } else if from.color.is_some() {
            writer.write_all(b"\x1b[39m")?;
        }
    }

    Ok(())
}

fn emit_fg_color(writer: &mut impl Write, color: TermColor) -> IoResult<()> {
    match color {
        TermColor::Named(named) => write!(writer, "\x1b[{}m", named_color_fg_code(named)),
        TermColor::Ansi256(index) => write!(writer, "\x1b[38;5;{index}m"),
        TermColor::Rgb(red, green, blue) => write!(writer, "\x1b[38;2;{red};{green};{blue}m"),
    }
}

const fn named_color_fg_code(color: NamedColor) -> u8 {
    match color {
        NamedColor::Black => 30,
        NamedColor::Red => 31,
        NamedColor::Green => 32,
        NamedColor::Yellow => 33,
        NamedColor::Blue => 34,
        NamedColor::Magenta => 35,
        NamedColor::Cyan => 36,
        NamedColor::White => 37,
        NamedColor::LightBlack | NamedColor::Gray => 90,
        NamedColor::LightRed => 91,
        NamedColor::LightGreen => 92,
        NamedColor::LightYellow => 93,
        NamedColor::LightBlue => 94,
        NamedColor::LightMagenta => 95,
        NamedColor::LightCyan => 96,
    }
}

fn centered_row(
    text: &str,
    total_width: usize,
    color: Option<TermColor>,
    bold: bool,
) -> Vec<StyledCell> {
    let mut row = vec![StyledCell::plain(' '); total_width];
    let width = text.chars().count();
    let start = total_width.saturating_sub(width) / 2;
    for (offset, glyph) in text.chars().enumerate() {
        if let Some(cell) = row.get_mut(start + offset) {
            *cell = StyledCell { glyph, color, bold };
        } else {
            break;
        }
    }
    row
}

fn has_any_decoration<G: GraphicsArea>(plot: &Plot<G>) -> bool {
    let deco = plot.annotations().decorations();
    deco.tl().is_some() || deco.t().is_some() || deco.tr().is_some()
}

fn has_any_bottom_decoration<G: GraphicsArea>(plot: &Plot<G>) -> bool {
    let deco = plot.annotations().decorations();
    deco.bl().is_some() || deco.b().is_some() || deco.br().is_some()
}

fn border_row<G: GraphicsArea>(
    plot: &Plot<G>,
    layout: LayoutMetrics,
    left_corner: char,
    fill: char,
    right_corner: char,
) -> Vec<StyledCell> {
    let mut row = make_row_prefix(plot, None);
    row.extend((0..layout.max_left_label_width).map(|_| StyledCell::plain(' ')));
    row.extend((0..usize::from(plot.padding())).map(|_| StyledCell::plain(' ')));
    row.push(border_cell(left_corner));
    row.extend((0..plot.graphics().ncols()).map(|_| border_cell(fill)));
    row.push(border_cell(right_corner));
    row.extend((0..usize::from(plot.padding())).map(|_| StyledCell::plain(' ')));
    row.extend((0..layout.max_right_label_width).map(|_| StyledCell::plain(' ')));
    row
}

fn decoration_row<G: GraphicsArea>(
    plot: &Plot<G>,
    layout: LayoutMetrics,
    top: bool,
) -> Vec<StyledCell> {
    let mut row = make_row_prefix(plot, None);
    row.extend((0..layout.max_left_label_width).map(|_| StyledCell::plain(' ')));
    row.extend((0..usize::from(plot.padding())).map(|_| StyledCell::plain(' ')));
    let mut border_area = vec![StyledCell::plain(' '); layout.border_length];
    let deco = plot.annotations().decorations();

    let (left, center, right) = if top {
        (deco.tl(), deco.t(), deco.tr())
    } else {
        (deco.bl(), deco.b(), deco.br())
    };

    if let Some(text) = left {
        overlay_text(
            &mut border_area,
            0,
            text,
            Some(TermColor::Named(NamedColor::White)),
        );
    }
    if let Some(text) = center {
        let text_width = text.chars().count();
        let start = layout.border_length.saturating_sub(text_width) / 2;
        overlay_text(
            &mut border_area,
            start,
            text,
            Some(TermColor::Named(NamedColor::White)),
        );
    }
    if let Some(text) = right {
        let text_width = text.chars().count();
        let start = layout.border_length.saturating_sub(text_width);
        overlay_text(
            &mut border_area,
            start,
            text,
            Some(TermColor::Named(NamedColor::White)),
        );
    }

    row.extend(border_area);
    row.extend((0..usize::from(plot.padding())).map(|_| StyledCell::plain(' ')));
    row.extend((0..layout.max_right_label_width).map(|_| StyledCell::plain(' ')));
    row
}

fn body_row<G: GraphicsArea>(
    plot: &Plot<G>,
    layout: LayoutMetrics,
    row_index: usize,
    graphics_row: &RowBuffer,
) -> Vec<StyledCell> {
    let ylabel_text = if row_index == layout.ylabel_row {
        plot.ylabel()
    } else {
        None
    };
    let mut row = make_row_prefix(plot, ylabel_text);
    let border = plot.border().chars();

    let left_annotation = if plot.show_labels() {
        plot.annotations().left().get(&row_index)
    } else {
        None
    };

    if let Some(annotation) = left_annotation {
        append_right_aligned(
            &mut row,
            annotation.text(),
            layout.max_left_label_width,
            annotation.color(),
        );
    } else {
        row.extend((0..layout.max_left_label_width).map(|_| StyledCell::plain(' ')));
    }

    row.extend((0..usize::from(plot.padding())).map(|_| StyledCell::plain(' ')));
    row.push(border_cell(border.l));
    for cell in graphics_row {
        row.push(StyledCell {
            glyph: cell.glyph,
            color: term_color_from_canvas_color(cell.color),
            bold: false,
        });
    }
    row.push(border_cell(border.r));
    row.extend((0..usize::from(plot.padding())).map(|_| StyledCell::plain(' ')));

    let right_annotation = if plot.show_labels() {
        plot.annotations().right().get(&row_index)
    } else {
        None
    };

    if let Some(annotation) = right_annotation {
        append_left_aligned(
            &mut row,
            annotation.text(),
            layout.max_right_label_width,
            annotation.color(),
        );
    } else {
        row.extend((0..layout.max_right_label_width).map(|_| StyledCell::plain(' ')));
    }

    row
}

fn term_color_from_canvas_color(color: CanvasColor) -> Option<TermColor> {
    match color {
        CanvasColor::BLUE => Some(TermColor::Named(NamedColor::Blue)),
        CanvasColor::RED => Some(TermColor::Named(NamedColor::Red)),
        CanvasColor::MAGENTA => Some(TermColor::Named(NamedColor::Magenta)),
        CanvasColor::GREEN => Some(TermColor::Named(NamedColor::Green)),
        CanvasColor::CYAN => Some(TermColor::Named(NamedColor::Cyan)),
        CanvasColor::YELLOW => Some(TermColor::Named(NamedColor::Yellow)),
        CanvasColor::WHITE => Some(TermColor::Named(NamedColor::White)),
        _ => None,
    }
}

fn border_cell(glyph: char) -> StyledCell {
    StyledCell {
        glyph,
        color: Some(TermColor::Named(NamedColor::LightBlack)),
        bold: false,
    }
}

fn make_row_prefix<G: GraphicsArea>(plot: &Plot<G>, ylabel_text: Option<&str>) -> Vec<StyledCell> {
    let margin = usize::from(plot.margin());
    let padding = usize::from(plot.padding());
    let ylabel_width = plot.ylabel().map_or(0, |text| text.chars().count());
    let mut row = Vec::new();
    row.extend((0..margin).map(|_| StyledCell::plain(' ')));

    if let Some(text) = ylabel_text {
        append_left_aligned(
            &mut row,
            text,
            ylabel_width,
            Some(TermColor::Named(NamedColor::White)),
        );
    } else {
        row.extend((0..ylabel_width).map(|_| StyledCell::plain(' ')));
    }

    row.extend((0..padding).map(|_| StyledCell::plain(' ')));
    row
}

fn append_right_aligned(
    out: &mut Vec<StyledCell>,
    text: &str,
    width: usize,
    color: Option<TermColor>,
) {
    let text_width = text.chars().count();
    let left_pad = width.saturating_sub(text_width);
    out.extend((0..left_pad).map(|_| StyledCell::plain(' ')));
    out.extend(text.chars().map(|glyph| StyledCell {
        glyph,
        color,
        bold: false,
    }));
}

fn append_left_aligned(
    out: &mut Vec<StyledCell>,
    text: &str,
    width: usize,
    color: Option<TermColor>,
) {
    let text_width = text.chars().count();
    out.extend(text.chars().map(|glyph| StyledCell {
        glyph,
        color,
        bold: false,
    }));
    let right_pad = width.saturating_sub(text_width);
    out.extend((0..right_pad).map(|_| StyledCell::plain(' ')));
}

fn overlay_text(out: &mut [StyledCell], start: usize, text: &str, color: Option<TermColor>) {
    for (offset, glyph) in text.chars().enumerate() {
        if let Some(slot) = out.get_mut(start + offset) {
            *slot = StyledCell {
                glyph,
                color,
                bold: false,
            };
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        LayoutMetrics, RenderedPlot, StyledCell, build_rendered_plot, write_ansi, write_plain,
    };
    use crate::border::BorderType;
    use crate::canvas::{CanvasType, canvas_types};
    use crate::color::{CanvasColor, NamedColor, TermColor};
    use crate::graphics::{GraphicsArea, RowBuffer, RowCell};
    use crate::lineplot::{LineplotOptions, lineplot};
    use crate::plot::{DecorationPosition, Plot};
    use crate::test_util::{assert_fixture_eq, render_plot_text};

    #[derive(Debug)]
    struct TinyGraphics {
        rows: Vec<Vec<(char, CanvasColor)>>,
    }

    impl TinyGraphics {
        fn new() -> Self {
            Self {
                rows: vec![
                    vec![
                        ('a', CanvasColor::BLUE),
                        ('b', CanvasColor::RED),
                        ('c', CanvasColor::NORMAL),
                    ],
                    vec![
                        ('d', CanvasColor::GREEN),
                        ('e', CanvasColor::CYAN),
                        ('f', CanvasColor::YELLOW),
                    ],
                ],
            }
        }
    }

    impl GraphicsArea for TinyGraphics {
        fn nrows(&self) -> usize {
            self.rows.len()
        }

        fn ncols(&self) -> usize {
            self.rows.first().map_or(0, Vec::len)
        }

        fn render_row(&self, row: usize, out: &mut RowBuffer) {
            out.clear();
            out.extend(
                self.rows[row]
                    .iter()
                    .map(|&(glyph, color)| RowCell { glyph, color }),
            );
        }
    }

    fn strip_ansi(text: &str) -> String {
        let mut out = String::with_capacity(text.len());
        let mut chars = text.chars().peekable();
        while let Some(ch) = chars.next() {
            if ch == '\x1b' && chars.peek().copied() == Some('[') {
                let _ = chars.next();
                for c in chars.by_ref() {
                    if c == 'm' {
                        break;
                    }
                }
                continue;
            }
            out.push(ch);
        }
        out
    }

    #[test]
    fn canvas_types_returns_sorted_public_variants() {
        assert_eq!(
            canvas_types(),
            &[
                CanvasType::Ascii,
                CanvasType::Block,
                CanvasType::Braille,
                CanvasType::Density,
                CanvasType::Dot,
            ]
        );
    }

    #[test]
    fn layout_metrics_match_expected_simple_plot_dimensions() {
        let mut plot = Plot::new(TinyGraphics::new());
        plot.ylabel = Some(String::from("Y"));
        plot.annotate_left(0, "L0", Some(TermColor::Named(NamedColor::Green)));
        plot.annotate_right(0, "R", Some(TermColor::Named(NamedColor::Blue)));

        let layout = LayoutMetrics::for_plot(&plot);
        assert_eq!(layout.border_length, 5);
        assert_eq!(layout.max_left_label_width, 2);
        assert_eq!(layout.max_right_label_width, 1);
        assert_eq!(layout.ylabel_row, 1);
        assert_eq!(layout.total_width, 15);
    }

    #[test]
    fn render_plain_text_has_title_borders_and_aligned_labels() {
        let mut plot = Plot::new(TinyGraphics::new());
        plot.title = Some(String::from("T"));
        plot.xlabel = Some(String::from("X"));
        plot.ylabel = Some(String::from("Y"));
        plot.border = BorderType::Solid;
        plot.margin = 1;
        plot.padding = 1;
        plot.annotate_left(0, "L0", Some(TermColor::Named(NamedColor::Green)));
        plot.annotate_right(1, "R1", Some(TermColor::Named(NamedColor::Magenta)));
        plot.set_decoration(DecorationPosition::T, "top");
        plot.set_decoration(DecorationPosition::B, "bot");

        let rendered = build_rendered_plot(&plot);
        let mut output = Vec::new();
        write_plain(&rendered, &mut output).unwrap_or_else(|error| {
            panic!("failed to write plain rendered output: {error}");
        });

        let rendered_text = String::from_utf8(output)
            .unwrap_or_else(|error| panic!("rendered output must be utf-8: {error}"));

        assert_eq!(
            rendered_text,
            "      T\n       top\n      ┌───┐\n   L0 │abc│\n Y    │def│ R1\n      └───┘\n       bot\n      X\n"
        );
    }

    #[test]
    fn rendered_ir_marks_title_cells_bold_and_preserves_graphics_color() {
        let mut plot = Plot::new(TinyGraphics::new());
        plot.title = Some(String::from("LONG TITLE"));

        let rendered = build_rendered_plot(&plot);
        let title_row = &rendered.rows()[0];
        assert!(title_row.iter().any(|cell| cell.bold));

        let body_row = &rendered.rows()[2];
        let graphics_start = body_row
            .iter()
            .position(|cell| cell.glyph == '')
            .unwrap_or_else(|| panic!("expected left border in body row"));
        assert_eq!(
            body_row[graphics_start + 1].color,
            Some(TermColor::Named(NamedColor::Blue))
        );
    }

    #[test]
    fn write_plain_trims_trailing_spaces_only() {
        let rendered = RenderedPlot {
            rows: vec![
                vec![
                    StyledCell::plain(' '),
                    StyledCell::plain('x'),
                    StyledCell::plain(' '),
                    StyledCell::plain(' '),
                ],
                vec![
                    StyledCell::plain('a'),
                    StyledCell::plain(' '),
                    StyledCell::plain('b'),
                    StyledCell::plain(' '),
                ],
                vec![StyledCell::plain(' '), StyledCell::plain(' ')],
            ],
        };

        let mut output = Vec::new();
        write_plain(&rendered, &mut output)
            .unwrap_or_else(|error| panic!("failed to write plain rows: {error}"));

        let text = String::from_utf8(output)
            .unwrap_or_else(|error| panic!("output must be utf-8: {error}"));
        assert_eq!(text, " x\na b\n\n");
    }

    #[test]
    fn plot_render_writes_ansi_when_color_enabled() {
        let mut plot = Plot::new(TinyGraphics::new());
        plot.title = Some(String::from("T"));

        let mut plain = Vec::new();
        plot.render(&mut plain, false)
            .unwrap_or_else(|error| panic!("render with color=false failed: {error}"));

        let mut ansi = Vec::new();
        plot.render(&mut ansi, true)
            .unwrap_or_else(|error| panic!("render with color=true failed: {error}"));

        let plain_text = String::from_utf8(plain)
            .unwrap_or_else(|error| panic!("plain output must be utf-8: {error}"));
        let ansi_text = String::from_utf8(ansi)
            .unwrap_or_else(|error| panic!("ansi output must be utf-8: {error}"));

        assert!(!plain_text.contains("\u{1b}["));
        assert!(ansi_text.contains("\u{1b}["));
    }

    #[test]
    fn write_ansi_batches_contiguous_style_runs() {
        let rendered = RenderedPlot {
            rows: vec![vec![
                StyledCell {
                    glyph: 'a',
                    color: Some(TermColor::Named(NamedColor::Red)),
                    bold: false,
                },
                StyledCell {
                    glyph: 'b',
                    color: Some(TermColor::Named(NamedColor::Red)),
                    bold: false,
                },
                StyledCell::plain('c'),
            ]],
        };

        let mut output = Vec::new();
        write_ansi(&rendered, &mut output)
            .unwrap_or_else(|error| panic!("failed to write ansi rows: {error}"));

        let text = String::from_utf8(output)
            .unwrap_or_else(|error| panic!("output must be utf-8: {error}"));

        assert_eq!(text.matches("\u{1b}[").count(), 2);
        assert!(text.contains("ab"));
        assert!(text.ends_with("c\n"));
    }

    #[test]
    fn write_ansi_emits_selective_sgr_when_switching_off_bold_in_same_color() {
        let rendered = RenderedPlot {
            rows: vec![vec![
                StyledCell {
                    glyph: 'A',
                    color: Some(TermColor::Named(NamedColor::Red)),
                    bold: true,
                },
                StyledCell {
                    glyph: 'B',
                    color: Some(TermColor::Named(NamedColor::Red)),
                    bold: false,
                },
            ]],
        };

        let mut output = Vec::new();
        write_ansi(&rendered, &mut output)
            .unwrap_or_else(|error| panic!("failed to write ansi rows: {error}"));

        let text = String::from_utf8(output)
            .unwrap_or_else(|error| panic!("output must be utf-8: {error}"));

        assert!(text.starts_with("\u{1b}[1m\u{1b}[31mA"));
        assert!(text.contains("A\u{1b}[22mB"));
        assert!(text.ends_with("\u{1b}[39m\n"));
        assert!(!text.contains("\u{1b}[0m"));
    }

    #[test]
    fn write_ansi_switches_between_foreground_colors_without_full_reset() {
        let rendered = RenderedPlot {
            rows: vec![vec![
                StyledCell {
                    glyph: 'A',
                    color: Some(TermColor::Named(NamedColor::Red)),
                    bold: false,
                },
                StyledCell {
                    glyph: 'B',
                    color: Some(TermColor::Named(NamedColor::Green)),
                    bold: false,
                },
                StyledCell::plain('C'),
            ]],
        };

        let mut output = Vec::new();
        write_ansi(&rendered, &mut output)
            .unwrap_or_else(|error| panic!("failed to write ansi rows: {error}"));

        let text = String::from_utf8(output)
            .unwrap_or_else(|error| panic!("output must be utf-8: {error}"));

        assert_eq!(text, "\u{1b}[31mA\u{1b}[32mB\u{1b}[39mC\n");
        assert!(!text.contains("\u{1b}[0m"));
    }

    #[test]
    fn write_ansi_resets_style_at_row_boundary() {
        let rendered = RenderedPlot {
            rows: vec![
                vec![StyledCell {
                    glyph: 'A',
                    color: Some(TermColor::Named(NamedColor::Red)),
                    bold: false,
                }],
                vec![StyledCell::plain('B')],
            ],
        };

        let mut output = Vec::new();
        write_ansi(&rendered, &mut output)
            .unwrap_or_else(|error| panic!("failed to write ansi rows: {error}"));

        let text = String::from_utf8(output)
            .unwrap_or_else(|error| panic!("output must be utf-8: {error}"));

        assert_eq!(text, "\u{1b}[31mA\u{1b}[39m\nB\n");
    }

    #[test]
    fn production_lineplot_ansi_matches_existing_fixture() {
        let x = [-1, 1, 3, 3, -1];
        let y = [2, 0, -5, 2, -5];
        let plot = lineplot(&x, &y, LineplotOptions::default())
            .unwrap_or_else(|error| panic!("lineplot construction should succeed: {error}"));

        let ansi_rendered = render_plot_text(&plot, true);
        assert_fixture_eq(&ansi_rendered, "tests/fixtures/lineplot/default.txt");

        let plain_rendered = render_plot_text(&plot, false);
        assert_eq!(plain_rendered, strip_ansi(&ansi_rendered));
    }
}