markdown-ratatui 0.2.0

Backend-independent, width-aware Markdown widgets for ratatui
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
//! Bounded, terminal-only Mermaid rendering. No browser, script, or I/O.
//!
//! Graphs use one connected pair of boxes per edge. Repeating node IDs makes
//! branches and cycles unambiguous without a large, crossing-prone canvas.
//! Sequence diagrams use shared lifelines when they fit the available width.
use crate::sanitize_terminal_text;
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;

const MAX_SOURCE: usize = 65_536;
const MAX_NODES: usize = 128;
const MAX_EDGES: usize = 512;
const MAX_EXPANDED_LABEL_BYTES: usize = 262_144;

#[derive(Default)]
struct Graph {
    nodes: Vec<(String, String)>,
    edges: Vec<Edge>,
    reverse: bool,
    horizontal: bool,
}
struct Edge {
    from: usize,
    to: usize,
    label: String,
    arrow: &'static str,
}
impl Graph {
    fn node(&mut self, id: &str, label: Option<String>) -> Result<usize, &'static str> {
        if let Some(i) = self.nodes.iter().position(|(key, _)| key == id) {
            if let Some(label) = label {
                self.nodes[i].1 = label;
            }
            return Ok(i);
        }
        if self.nodes.len() == MAX_NODES {
            return Err("too many nodes");
        }
        self.nodes
            .push((id.into(), label.unwrap_or_else(|| id.into())));
        Ok(self.nodes.len() - 1)
    }
    fn edge(
        &mut self,
        from: usize,
        to: usize,
        label: String,
        arrow: &'static str,
    ) -> Result<(), &'static str> {
        if self.edges.len() == MAX_EDGES {
            return Err("too many connections");
        }
        self.edges.push(Edge {
            from,
            to,
            label,
            arrow,
        });
        Ok(())
    }
    fn check_budget(&self) -> Result<(), &'static str> {
        let size = |i: usize| self.nodes[i].0.len() + self.nodes[i].1.len() + 2;
        let expanded: usize = self
            .edges
            .iter()
            .map(|e| size(e.from) + size(e.to) + e.label.len())
            .sum::<usize>()
            + (0..self.nodes.len()).map(size).sum::<usize>();
        if expanded > MAX_EXPANDED_LABEL_BYTES {
            Err("expanded diagram is too large")
        } else {
            Ok(())
        }
    }
    fn label(&self, i: usize) -> String {
        let (id, label) = &self.nodes[i];
        if id == label {
            label.clone()
        } else {
            format!("{id}: {label}")
        }
    }
}

/// Failure is intentionally visible: the caller displays the complete source.
pub(super) fn render(source: &str, width: usize) -> Result<Vec<String>, &'static str> {
    if source.len() > MAX_SOURCE {
        return Err("diagram exceeds 64 KiB");
    }
    if width < 8 {
        return Err("diagram needs at least 8 columns");
    }
    let source = sanitize_terminal_text(source);
    let statements = statements(&source)?;
    let (header, body) = statements.split_first().ok_or("empty diagram")?;
    let width = width.min(240);
    if *header == "sequenceDiagram" {
        return sequence(body, width);
    }
    let state = matches!(*header, "stateDiagram-v2" | "stateDiagram");
    let mut graph = Graph::default();
    if state {
        graph.horizontal = false;
    } else {
        let mut words = header.split_whitespace();
        if !matches!(words.next(), Some("graph" | "flowchart")) {
            return Err("unsupported diagram type");
        }
        direction(&mut graph, words.next().ok_or("missing graph direction")?)?;
        if words.next().is_some() {
            return Err("invalid graph header");
        }
    }
    for statement in body {
        if metadata(statement) {
            continue;
        }
        if let Some(dir) = statement.strip_prefix("direction ") {
            direction(&mut graph, dir)?;
            continue;
        }
        if state && statement.starts_with("state ") {
            let (label, id) = statement[6..]
                .rsplit_once(" as ")
                .ok_or("unsupported state declaration")?;
            graph.node(id.trim(), Some(clean_label(label)))?;
            continue;
        }
        let (statement, state_label) = if state {
            statement
                .split_once(':')
                .map_or((*statement, ""), |(s, l)| (s.trim(), l.trim()))
        } else {
            (*statement, "")
        };
        let (mut from, mut tail) = node(statement, &mut graph, state)?;
        if state && tail.trim().is_empty() && !state_label.is_empty() {
            graph.nodes[from].1 = clean_label(state_label);
        }
        while !tail.trim().is_empty() {
            let (arrow, label, rest) = connection(tail)?;
            let (to, rest) = node(rest, &mut graph, state)?;
            graph.edge(
                from,
                to,
                if state_label.is_empty() {
                    label
                } else {
                    clean_label(state_label)
                },
                arrow,
            )?;
            from = to;
            tail = rest;
        }
    }
    if graph.nodes.is_empty() {
        return Err("no nodes");
    }
    graph.check_budget()?;
    Ok(render_graph(&graph, width))
}

// Split only outside quoted labels and node shapes; semicolons inside labels
// and %% inside a quoted URL remain text. Reject unbalanced input as a whole.
fn statements(source: &str) -> Result<Vec<&str>, &'static str> {
    let mut result = Vec::new();
    let mut start = 0;
    let mut quote = false;
    let mut stack = Vec::new();
    let mut comment = false;
    for (i, c) in source.char_indices() {
        if comment {
            if c == '\n' {
                comment = false;
                start = i + 1;
            }
            continue;
        }
        if c == '"' {
            quote = !quote;
        }
        if quote {
            continue;
        }
        if stack.is_empty() && source[i..].starts_with("%%") {
            let s = source[start..i].trim();
            if !s.is_empty() {
                result.push(s);
            }
            comment = true;
            continue;
        }
        match c {
            '[' | '(' | '{' => stack.push(c),
            ']' | ')' | '}' => {
                let expected = match c {
                    ']' => '[',
                    ')' => '(',
                    _ => '{',
                };
                if stack.pop() != Some(expected) {
                    return Err("unbalanced node shape");
                }
            }
            '\n' | ';' if stack.is_empty() => {
                let s = source[start..i].trim();
                if !s.is_empty() {
                    result.push(s);
                }
                start = i + 1;
            }
            _ => {}
        }
    }
    if quote || !stack.is_empty() {
        return Err("unclosed label or shape");
    }
    if !comment {
        let s = source[start..].trim();
        if !s.is_empty() {
            result.push(s);
        }
    }
    Ok(result)
}
fn metadata(s: &str) -> bool {
    [
        "accTitle:",
        "accDescr:",
        "classDef ",
        "class ",
        "style ",
        "linkStyle ",
    ]
    .iter()
    .any(|p| s.starts_with(p))
}
fn direction(graph: &mut Graph, dir: &str) -> Result<(), &'static str> {
    match dir.trim() {
        "LR" | "RL" | "TD" | "TB" | "BT" => {
            graph.horizontal = matches!(dir.trim(), "LR" | "RL");
            graph.reverse = matches!(dir.trim(), "RL" | "BT");
            Ok(())
        }
        _ => Err("unsupported direction"),
    }
}
fn clean_label(s: &str) -> String {
    s.trim()
        .trim_matches('"')
        .trim_matches('`')
        .replace("<br/>", "\n")
        .replace("<br />", "\n")
        .replace("<br>", "\n")
}
fn node<'a>(s: &'a str, graph: &mut Graph, state: bool) -> Result<(usize, &'a str), &'static str> {
    let s = s.trim_start();
    if state && let Some(tail) = s.strip_prefix("[*]") {
        return Ok((graph.node("(*)", None)?, tail));
    }
    let end = s
        .char_indices()
        .find(|(_, c)| !c.is_alphanumeric() && !matches!(c, '_' | '-'))
        .map_or(s.len(), |(i, _)| i);
    // A compact A-->B must not consume the arrow's hyphens as part of A.
    let end = ["--", "-."]
        .iter()
        .filter_map(|arrow| s.find(arrow))
        .min()
        .unwrap_or(end)
        .min(end);
    let id = &s[..end];
    if id.is_empty() {
        return Err("expected node identifier");
    }
    let mut tail = s[end..].trim_start();
    let mut label = None;
    // Longest delimiters first; retain meaning in labels, normalize shapes to boxes.
    for (open, close) in [
        ("((", "))"),
        ("[[", "]]"),
        ("([", "])"),
        ("[(", ")]"),
        ("{{", "}}"),
        ("[", "]"),
        ("(", ")"),
        ("{", "}"),
    ] {
        if let Some(rest) = tail.strip_prefix(open) {
            let mut quoted = false;
            let end = rest
                .char_indices()
                .find_map(|(i, c)| {
                    if c == '"' {
                        quoted = !quoted;
                    }
                    (!quoted && rest[i..].starts_with(close)).then_some(i)
                })
                .ok_or("unclosed node label")?;
            label = Some(clean_label(&rest[..end]));
            tail = &rest[end + close.len()..];
            break;
        }
    }
    if let Some(rest) = tail.strip_prefix(":::") {
        let end = rest
            .find(|c: char| !c.is_alphanumeric() && c != '_')
            .unwrap_or(rest.len());
        if end == 0 {
            return Err("missing class name");
        }
        tail = &rest[end..];
    }
    Ok((graph.node(id, label)?, tail))
}
fn connection(s: &str) -> Result<(&'static str, String, &str), &'static str> {
    let s = s.trim_start();
    let (arrow, mut tail) = [
        ("<-->", "<-->"),
        ("-.->", "..>"),
        ("==>", "==>"),
        ("-->", "-->"),
        ("---", "---"),
    ]
    .into_iter()
    .find_map(|(token, arrow)| s.strip_prefix(token).map(|rest| (arrow, rest)))
    .or_else(|| {
        s.strip_prefix("-- ")
            .and_then(|rest| rest.split_once(" -->").map(|(_, tail)| ("-->", tail)))
    })
    .ok_or("unsupported connection syntax")?;
    let mut label = if let Some(rest) = s.strip_prefix("-- ") {
        clean_label(rest.split_once(" -->").ok_or("invalid edge label")?.0)
    } else {
        String::new()
    };
    tail = tail.trim_start();
    if let Some(rest) = tail.strip_prefix('|') {
        let (text, rest) = rest.split_once('|').ok_or("unclosed edge label")?;
        label = clean_label(text);
        tail = rest;
    }
    Ok((arrow, label, tail))
}
fn wrap(text: &str, width: usize) -> Vec<String> {
    let mut result = Vec::new();
    for line in text.split('\n') {
        let mut row = String::new();
        let mut used = 0;
        for g in line.graphemes(true) {
            let size = g.width();
            if used + size > width && !row.is_empty() {
                result.push(std::mem::take(&mut row));
                used = 0;
            }
            if size > width {
                row.push('?');
                used += 1;
            } else {
                row.push_str(g);
                used += size;
            }
        }
        result.push(row);
    }
    result
}
fn boxed(label: &str, width: usize) -> Vec<String> {
    let lines = wrap(label, width.saturating_sub(4).max(1));
    let inner = lines.iter().map(|s| s.width()).max().unwrap_or(0);
    let border = format!("+{}+", "-".repeat(inner + 2));
    let mut rows = vec![border.clone()];
    rows.extend(
        lines
            .into_iter()
            .map(|s| format!("| {s}{} |", " ".repeat(inner - s.width()))),
    );
    rows.push(border);
    rows
}
fn render_graph(graph: &Graph, width: usize) -> Vec<String> {
    let mut out = Vec::new();
    for edge in &graph.edges {
        render_edge(graph, edge, width, &mut out);
    }
    for i in 0..graph.nodes.len() {
        if !graph.edges.iter().any(|e| e.from == i || e.to == i) {
            out.extend(boxed(&graph.label(i), width));
        }
    }
    out
}

fn render_edge(graph: &Graph, edge: &Edge, width: usize, out: &mut Vec<String>) {
    let (a, b) = if graph.reverse {
        (edge.to, edge.from)
    } else {
        (edge.from, edge.to)
    };
    let label_a = graph.label(a);
    let label_b = graph.label(b);
    let horizontal = graph.horizontal && width >= 25;
    if !edge.label.is_empty() {
        out.extend(wrap(&format!("[{}]", edge.label), width));
    }
    if horizontal {
        let box_width = (width - 5) / 2;
        let left = boxed(&label_a, box_width);
        let right = boxed(&label_b, box_width);
        let left_width = left[0].width();
        for i in 0..left.len().max(right.len()) {
            let a = left.get(i).map_or("", String::as_str);
            let b = right.get(i).map_or("", String::as_str);
            let arrow = if i == 1 {
                if graph.reverse {
                    match edge.arrow {
                        "..>" => "<..",
                        "==>" => "<==",
                        "---" | "<-->" => edge.arrow,
                        _ => "<--",
                    }
                } else {
                    edge.arrow
                }
            } else {
                ""
            };
            out.push(format!(
                "{a}{} {arrow:4}{b}",
                " ".repeat(left_width - a.width())
            ));
        }
    } else {
        out.extend(boxed(&label_a, width));
        let directed = edge.arrow != "---";
        let both = edge.arrow == "<-->";
        let shaft = if edge.arrow == "..>" { "  :" } else { "  |" };
        out.push(
            if (graph.reverse && directed) || both {
                "  ^"
            } else {
                shaft
            }
            .into(),
        );
        out.push(
            if (!graph.reverse && directed) || both {
                "  v"
            } else {
                shaft
            }
            .into(),
        );
        out.extend(boxed(&label_b, width));
    }
    out.push(String::new());
}

/// Preserve the order of messages, annotations and control boundaries. A
/// stack validates nesting before rendering so invalid input never produces a
/// plausible but incomplete diagram.
enum SequenceEvent {
    Message(usize),
    Annotation(String),
    Begin { kind: Fragment, label: String },
    Else(String),
    End(Fragment),
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Fragment {
    Alt,
    Opt,
    Loop,
}
impl Fragment {
    fn name(self) -> &'static str {
        match self {
            Self::Alt => "alt",
            Self::Opt => "opt",
            Self::Loop => "loop",
        }
    }
}
const MAX_SEQUENCE_DEPTH: usize = 16;

fn sequence(body: &[&str], width: usize) -> Result<Vec<String>, &'static str> {
    let mut graph = Graph {
        horizontal: true,
        ..Graph::default()
    };
    let mut events = Vec::new();
    let mut stack = Vec::new();
    let mut max_depth = 0;
    for s in body {
        if metadata(s) {
            continue;
        }
        if let Some(rest) = s
            .strip_prefix("participant ")
            .or_else(|| s.strip_prefix("actor "))
        {
            let (id, label) = rest
                .split_once(" as ")
                .map_or((rest, None), |(id, label)| (id, Some(clean_label(label))));
            if id.trim().is_empty() {
                return Err("missing participant");
            }
            graph.node(id.trim(), label)?;
            continue;
        }
        let (keyword, label) = s.split_once(char::is_whitespace).unwrap_or((s, ""));
        let fragment = match keyword {
            "alt" => Some(Fragment::Alt),
            "opt" => Some(Fragment::Opt),
            "loop" => Some(Fragment::Loop),
            _ => None,
        };
        if let Some(kind) = fragment {
            if stack.len() == MAX_SEQUENCE_DEPTH {
                return Err("sequence blocks are nested too deeply");
            }
            stack.push(kind);
            max_depth = max_depth.max(stack.len());
            events.push(SequenceEvent::Begin {
                kind,
                label: clean_label(label),
            });
            continue;
        }
        if keyword == "else" {
            if stack.last() != Some(&Fragment::Alt) {
                return Err("else must belong to an alt block");
            }
            events.push(SequenceEvent::Else(clean_label(label)));
            continue;
        }
        if *s == "end" {
            events.push(SequenceEvent::End(
                stack.pop().ok_or("end without a sequence block")?,
            ));
            continue;
        }
        if s.starts_with("Note ")
            || s.starts_with("note ")
            || s.starts_with("activate ")
            || s.starts_with("deactivate ")
        {
            events.push(SequenceEvent::Annotation((*s).into()));
            continue;
        }
        let (route, label) = s.split_once(':').ok_or("unsupported sequence statement")?;
        let (from, to, arrow) = [
            ("-->>", "..>"),
            ("->>", "-->"),
            ("-->", "..>"),
            ("->", "-->"),
            ("--x", "--x"),
            ("-x", "--x"),
        ]
        .into_iter()
        .find_map(|(token, arrow)| route.split_once(token).map(|(a, b)| (a, b, arrow)))
        .ok_or("unsupported sequence arrow")?;
        let to = to.trim().trim_start_matches(['+', '-']);
        if from.trim().is_empty() || to.is_empty() {
            return Err("missing message participant");
        }
        let a = graph.node(from.trim(), None)?;
        let b = graph.node(to, None)?;
        graph.edge(a, b, clean_label(label), arrow)?;
        events.push(SequenceEvent::Message(graph.edges.len() - 1));
    }
    if !stack.is_empty() {
        return Err("unclosed sequence block (missing end)");
    }
    if graph.nodes.is_empty() {
        return Err("no participants");
    }
    graph.check_budget()?;
    // Reserve a fixed gutter for every possible frame depth. Participant
    // lifelines never move horizontally when a nested branch starts or ends.
    let content_width = width.saturating_sub(4 * max_depth);
    if content_width < 8 {
        return Err("sequence frames need more columns");
    }
    let columns: Vec<_> = graph
        .nodes
        .iter()
        .map(|(_, label)| label.width().max(12) + 4)
        .collect();
    let total = columns.iter().sum::<usize>();
    let strips = total > content_width;
    let mut out = Vec::new();
    let mut positions = Vec::new();
    let mut heading = String::new();
    for ((_, label), &column) in graph.nodes.iter().zip(&columns) {
        positions.push(heading.width() + column / 2);
        heading.push_str(label);
        heading.push_str(&" ".repeat(column - label.width()));
    }
    let lifeline = || {
        let mut row = vec![' '; total];
        for &p in &positions {
            row[p] = '|';
        }
        row
    };
    if !strips {
        out.push(sequence_row(&heading, content_width, 0, max_depth));
        out.push(sequence_row(
            &lifeline().into_iter().collect::<String>(),
            content_width,
            0,
            max_depth,
        ));
    } else if graph.edges.is_empty() {
        for row in render_graph(&graph, content_width) {
            out.push(sequence_row(&row, content_width, 0, max_depth));
        }
    }
    let mut depth = 0;
    for event in events {
        let mut rows = Vec::new();
        match event {
            SequenceEvent::Begin { kind, label } => {
                sequence_bar(&mut out, &format!("{} {label}", kind.name()), width, depth);
                depth += 1;
            }
            SequenceEvent::Else(label) => {
                sequence_bar(&mut out, &format!("else {label}"), width, depth - 1)
            }
            SequenceEvent::End(kind) => {
                depth -= 1;
                sequence_bar(&mut out, &format!("end {}", kind.name()), width, depth);
            }
            SequenceEvent::Annotation(note) => rows.extend(wrap(&note, content_width)),
            SequenceEvent::Message(i) => {
                let edge = &graph.edges[i];
                if strips {
                    render_edge(&graph, edge, content_width, &mut rows);
                } else {
                    rows.extend(wrap(&edge.label, content_width));
                    let mut row = lifeline();
                    let a = positions[edge.from];
                    let b = positions[edge.to];
                    if a == b {
                        row[a + 1] = '-';
                        row[a + 2] = '+';
                        rows.push(row.into_iter().collect());
                        row = lifeline();
                        row[a] = '<';
                        row[a + 1] = '-';
                        row[a + 2] = '+';
                    } else {
                        for c in &mut row[a.min(b) + 1..a.max(b)] {
                            *c = if edge.arrow == "..>" { '.' } else { '-' };
                        }
                        row[b] = if edge.arrow == "--x" {
                            'x'
                        } else if b > a {
                            '>'
                        } else {
                            '<'
                        };
                    }
                    rows.push(row.into_iter().collect());
                    rows.push(lifeline().into_iter().collect());
                }
            }
        }
        for row in rows {
            out.push(sequence_row(&row, content_width, depth, max_depth));
        }
    }
    Ok(out)
}

fn sequence_row(row: &str, content_width: usize, depth: usize, max_depth: usize) -> String {
    let prefix = format!("{}{}", "| ".repeat(depth), "  ".repeat(max_depth - depth));
    if depth == 0 {
        return format!("{prefix}{row}");
    }
    format!(
        "{prefix}{row}{}{}{}",
        " ".repeat(content_width - row.width()),
        "  ".repeat(max_depth - depth),
        " |".repeat(depth)
    )
}
fn sequence_bar(out: &mut Vec<String>, label: &str, width: usize, outer_depth: usize) {
    let inner = width - 4 * outer_depth - 4;
    let prefix = "| ".repeat(outer_depth);
    let suffix = " |".repeat(outer_depth);
    for line in wrap(label.trim_end(), inner) {
        out.push(format!(
            "{prefix}+-{line}{}-+{suffix}",
            "-".repeat(inner - line.width())
        ));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn chains_branches_cycles_labels_and_directions() {
        let source = "flowchart LR; A[Start] --> B{Ready?}; B -->|Yes| C((Done)); B -->|No| A; D[孤立]; classDef custom fill:#fff";
        let rows = render(source, 70).unwrap();
        let text = rows.join("\n");
        for label in [
            "A: Start",
            "B: Ready?",
            "C: Done",
            "D: 孤立",
            "[Yes]",
            "[No]",
        ] {
            assert!(text.contains(label), "{text}");
        }
        assert_eq!(text.matches("-->").count(), 3);
        let chain = render("graph TD; A-->B-->C", 30).unwrap().join("\n");
        assert_eq!(chain.matches("  v").count(), 2);
        let dotted = render("graph LR; A-.->B", 30).unwrap().join("\n");
        assert!(dotted.contains("| A | ..> | B |"));
        let both = render("graph TD; A<-->B", 30).unwrap().join("\n");
        assert!(both.contains('^') && both.contains('v'));
        let reverse = render("graph RL; A-->B", 30).unwrap().join("\n");
        assert!(reverse.contains("| B | <-- | A |"), "{reverse}");
        let reverse = render("graph BT; A-->B", 12).unwrap().join("\n");
        assert!(reverse.find("| B |").unwrap() < reverse.find("| A |").unwrap());
        assert!(reverse.contains('^'));
    }
    #[test]
    fn sequence_lifelines_preserve_messages_aliases_notes_and_order() {
        let source = "sequenceDiagram\nparticipant A as 地球\nparticipant B as Mira\nA->>B: Observe\nactivate B\nNote over A,B: Window\nB-->>A: Images\nB->>B: Process\ndeactivate B";
        let text = render(source, 80).unwrap().join("\n");
        assert!(text.contains("地球"));
        assert!(text.contains("Mira"));
        assert!(text.contains("--------------->"), "{text}");
        assert!(text.contains("<..............."), "{text}");
        assert!(text.find("Observe").unwrap() < text.find("Images").unwrap());
        assert!(text.find("Window").unwrap() < text.find("Images").unwrap());
        assert!(text.contains("<-+"));
        for width in [8, 12, 24, 40, 80] {
            for line in render(source, width).unwrap() {
                assert!(line.width() <= width, "{width}: {line}");
            }
        }
    }
    #[test]
    fn tcp_forwarding_alternatives_preserve_every_branch_message_and_note() {
        let source = include_str!("../tests/fixtures/tcp-forwarding.mmd");
        for width in [16, 40, 80, 116, 160, 240] {
            let rows = render(source, width).unwrap();
            assert!(rows.iter().all(|row| row.width() <= width));
            let text = rows.join("\n");
            assert!(!text.contains("sequenceDiagram"));
            assert_eq!(
                rows.iter().filter(|row| row.starts_with("+-alt ")).count(),
                1
            );
            assert_eq!(
                rows.iter().filter(|row| row.starts_with("+-else ")).count(),
                2
            );
            assert_eq!(
                rows.iter()
                    .filter(|row| row.starts_with("+-end alt"))
                    .count(),
                1
            );
            if width >= 80 {
                let mut previous = 0;
                for label in source.lines().filter_map(|line| {
                    let line = line.trim();
                    if line.contains("->") || line.starts_with("Note ") {
                        Some(line.split_once(':').unwrap().1.trim())
                    } else if line.starts_with("alt ") || line.starts_with("else ") {
                        Some(line.split_once(' ').unwrap().1)
                    } else {
                        None
                    }
                }) {
                    let offset = text[previous..].find(label).unwrap_or_else(|| {
                        panic!("missing/out-of-order {label:?} at width {width}:\n{text}")
                    });
                    previous += offset + label.len();
                }
            }
        }
        let text = render(source, 116).unwrap().join("\n");
        for participant in [
            "操作者のアプリ/OS",
            "TUN + gVisor",
            "proxy HandlePacket",
            "agent HandleConn",
            "接続先サービス",
        ] {
            assert!(text.contains(participant), "{text}");
        }
    }
    #[test]
    fn nested_fragments_keep_lifelines_aligned_and_empty_branches_visible() {
        let source = "sequenceDiagram\nparticipant A\nparticipant B\nalt outer\nA->>B: first\nloop retry\nopt cache\nA->>B: nested\nend\nend\nelse second\nNote over A,B: no message\nelse third\nend\nA->>B: after";
        let rows = render(source, 80).unwrap();
        let positions = rows
            .iter()
            .filter(|line| line.contains("--------------->"))
            .map(|line| line.find("--------------->").unwrap())
            .collect::<Vec<_>>();
        assert_eq!(positions.len(), 3);
        assert!(positions.iter().all(|p| *p == positions[0]));
        let text = rows.join("\n");
        assert!(text.contains("| +-loop retry"));
        assert!(text.contains("| | +-opt cache"));
        assert!(text.contains("| | | nested"));
        assert!(text.find("else second").unwrap() < text.find("no message").unwrap());
        assert!(text.find("end alt").unwrap() < text.find("after").unwrap());
        let only_note = render("sequenceDiagram\nparticipant A as A very long participant name that wraps\nalt empty\nelse annotated\nNote over A: Still visible\nend", 32).unwrap().join("\n");
        assert!(only_note.contains("Still visible"), "{only_note}");
        assert!(only_note.contains("end alt"));
    }
    #[test]
    fn malformed_and_excessively_nested_sequence_blocks_fall_back() {
        for body in [
            "else orphan",
            "end",
            "alt missing end\nA->>B: hi",
            "loop retry\nelse invalid\nend",
            "opt optional\nelse invalid\nend",
            "alt outer\nloop inner\nend",
            "alt ok\nend\nend",
        ] {
            assert!(
                render(&format!("sequenceDiagram\nparticipant A\n{body}"), 80).is_err(),
                "{body}"
            );
        }
        let deep = format!(
            "sequenceDiagram\nparticipant A\n{}{}",
            "alt nested\n".repeat(MAX_SEQUENCE_DEPTH + 1),
            "end\n".repeat(MAX_SEQUENCE_DEPTH + 1)
        );
        assert_eq!(
            render(&deep, 240).unwrap_err(),
            "sequence blocks are nested too deeply"
        );
        assert_eq!(
            render("sequenceDiagram\nA->>B: hi\nalt one\nend", 8).unwrap_err(),
            "sequence frames need more columns"
        );
    }
    #[test]
    fn states_unicode_and_quoted_punctuation_are_bounded() {
        let source =
            "stateDiagram-v2\n[*] --> Cruise\nCruise --> Orbit: 到着\nOrbit --> [*]: Complete";
        let text = render(source, 30).unwrap().join("\n");
        assert!(text.contains("(*)"));
        assert!(text.contains("[到着]"));
        let source = "flowchart LR\nA[\"日本語; %% label [quoted]\"] -->|Next| B[\"é 👩‍💻<br/>Done\"] %% comment";
        for width in [8, 10, 25, 80] {
            for line in render(source, width).unwrap() {
                assert!(line.width() <= width, "{width}: {line}");
            }
        }
    }
    #[test]
    fn unsupported_malformed_and_excessive_input_fail_as_a_whole() {
        for source in [
            "pie\n\"A\": 1",
            "graph LR; A -->",
            "graph LR; A[Oops",
            "graph LR; A --> B; invalid syntax",
        ] {
            assert!(render(source, 80).is_err(), "{source}");
        }
        assert!(render(&"x".repeat(MAX_SOURCE + 1), 80).is_err());
        let nodes = (0..MAX_NODES + 1)
            .map(|n| format!("N{n};"))
            .collect::<String>();
        assert!(render(&format!("graph LR; {nodes}"), 80).is_err());
        assert!(render("graph LR; A-->B", 1).is_err());
        let expanded = format!(
            "graph LR; A[{}]; {}",
            "x".repeat(2000),
            "A-->B;".repeat(150)
        );
        assert_eq!(
            render(&expanded, 8).unwrap_err(),
            "expanded diagram is too large"
        );
    }
}