graphs-tui 0.2.0

Terminal renderer for Mermaid and D2 diagrams - flowcharts, state diagrams, pie charts in Unicode/ASCII
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
//! Sequence diagram parser and renderer for Mermaid syntax
//!
//! Supports basic mermaid sequence diagram syntax

use crate::error::MermaidError;
use crate::types::RenderOptions;

/// A participant in the sequence diagram
#[derive(Debug, Clone)]
pub struct Participant {
    pub id: String,
    pub label: String,
}

/// Message arrow style
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArrowStyle {
    /// Solid arrow ->>
    Solid,
    /// Dotted arrow -->>
    Dotted,
    /// Solid line ->
    SolidLine,
    /// Dotted line -->
    DottedLine,
    /// Async arrow -)
    Async,
}

/// A message between participants
#[derive(Debug, Clone)]
pub struct Message {
    pub from: String,
    pub to: String,
    pub label: String,
    pub style: ArrowStyle,
}

/// Note position relative to participant
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NotePosition {
    Left,
    Right,
    Over,
}

/// A note attached to participant(s)
#[derive(Debug, Clone)]
pub struct Note {
    pub position: NotePosition,
    pub participants: Vec<String>,
    pub text: String,
}

/// Items that can appear in a sequence diagram
#[derive(Debug, Clone)]
pub enum SequenceItem {
    Message(Message),
    Note(Note),
    Activate(String),
    Deactivate(String),
    Loop {
        condition: String,
        items: Vec<SequenceItem>,
    },
    Alt {
        condition: String,
        items: Vec<SequenceItem>,
        else_items: Option<Vec<SequenceItem>>,
    },
    Opt {
        condition: String,
        items: Vec<SequenceItem>,
    },
}

/// Sequence diagram data
#[derive(Debug, Clone)]
pub struct SequenceDiagram {
    pub title: Option<String>,
    pub participants: Vec<Participant>,
    pub items: Vec<SequenceItem>,
    /// Legacy field for backwards compatibility
    pub messages: Vec<Message>,
}

/// Parse sequence diagram syntax
pub fn parse_sequence_diagram(input: &str) -> Result<SequenceDiagram, MermaidError> {
    let lines: Vec<&str> = input
        .lines()
        .map(|l| l.trim())
        .filter(|l| !l.is_empty() && !l.starts_with("%%"))
        .collect();

    if lines.is_empty() {
        return Err(MermaidError::EmptyInput);
    }

    // Validate header
    let first_line = lines[0].to_lowercase();
    if !first_line.starts_with("sequencediagram") {
        return Err(MermaidError::ParseError {
            line: 1,
            message: "Expected 'sequenceDiagram'".to_string(),
            suggestion: Some("Start with 'sequenceDiagram'".to_string()),
        });
    }

    let mut diagram = SequenceDiagram {
        title: None,
        participants: Vec::new(),
        items: Vec::new(),
        messages: Vec::new(),
    };

    let mut seen_participants: std::collections::HashSet<String> = std::collections::HashSet::new();

    let content_lines: Vec<&str> = lines.iter().skip(1).copied().collect();
    let (items, _) = parse_items(&content_lines, &mut seen_participants, &mut diagram, 0);
    diagram.items = items;

    // Also populate messages for backwards compatibility
    collect_messages(&diagram.items, &mut diagram.messages);

    if diagram.participants.is_empty() && diagram.items.is_empty() {
        return Err(MermaidError::ParseError {
            line: 1,
            message: "No sequence diagram content found".to_string(),
            suggestion: Some("Add messages like 'Alice->>Bob: Hello'".to_string()),
        });
    }

    Ok(diagram)
}

/// Collect all messages from items recursively (for backwards compatibility)
fn collect_messages(items: &[SequenceItem], messages: &mut Vec<Message>) {
    for item in items {
        match item {
            SequenceItem::Message(msg) => messages.push(msg.clone()),
            SequenceItem::Loop { items, .. }
            | SequenceItem::Alt { items, .. }
            | SequenceItem::Opt { items, .. } => {
                collect_messages(items, messages);
                if let SequenceItem::Alt {
                    else_items: Some(else_items),
                    ..
                } = item
                {
                    collect_messages(else_items, messages);
                }
            }
            _ => {}
        }
    }
}

/// Parse items from lines, handling nested blocks
fn parse_items(
    lines: &[&str],
    seen_participants: &mut std::collections::HashSet<String>,
    diagram: &mut SequenceDiagram,
    mut idx: usize,
) -> (Vec<SequenceItem>, usize) {
    let mut items = Vec::new();

    while idx < lines.len() {
        let line = lines[idx];
        let lower = line.to_lowercase();

        // Check for block end
        if lower == "end" {
            return (items, idx + 1);
        }

        // Check for else (in alt blocks)
        if lower == "else" || lower.starts_with("else ") {
            return (items, idx);
        }

        // Parse title
        if lower.starts_with("title") {
            let title_text = line
                .strip_prefix("title")
                .or_else(|| line.strip_prefix("Title"))
                .unwrap_or(line);
            diagram.title = Some(title_text.trim().to_string());
            idx += 1;
            continue;
        }

        // Parse participant declaration
        if lower.starts_with("participant") {
            if let Some(p) = parse_participant(line) {
                if !seen_participants.contains(&p.id) {
                    seen_participants.insert(p.id.clone());
                    diagram.participants.push(p);
                }
            }
            idx += 1;
            continue;
        }

        // Parse actor declaration
        if lower.starts_with("actor") {
            if let Some(p) = parse_actor(line) {
                if !seen_participants.contains(&p.id) {
                    seen_participants.insert(p.id.clone());
                    diagram.participants.push(p);
                }
            }
            idx += 1;
            continue;
        }

        // Parse activate
        if lower.starts_with("activate ") {
            let participant = line[9..].trim().to_string();
            auto_add_participant(&participant, seen_participants, diagram);
            items.push(SequenceItem::Activate(participant));
            idx += 1;
            continue;
        }

        // Parse deactivate
        if lower.starts_with("deactivate ") {
            let participant = line[11..].trim().to_string();
            items.push(SequenceItem::Deactivate(participant));
            idx += 1;
            continue;
        }

        // Parse Note
        if lower.starts_with("note ") {
            if let Some(note) = parse_note(line) {
                for p in &note.participants {
                    auto_add_participant(p, seen_participants, diagram);
                }
                items.push(SequenceItem::Note(note));
            }
            idx += 1;
            continue;
        }

        // Parse loop block
        if lower.starts_with("loop ") || lower == "loop" {
            let condition = if lower.len() > 5 {
                line[5..].trim().to_string()
            } else {
                String::new()
            };
            let (loop_items, next_idx) = parse_items(lines, seen_participants, diagram, idx + 1);
            items.push(SequenceItem::Loop {
                condition,
                items: loop_items,
            });
            idx = next_idx;
            continue;
        }

        // Parse alt block
        if lower.starts_with("alt ") || lower == "alt" {
            let condition = if lower.len() > 4 {
                line[4..].trim().to_string()
            } else {
                String::new()
            };
            let (alt_items, next_idx) = parse_items(lines, seen_participants, diagram, idx + 1);

            // Check for else
            let (else_items, final_idx) = if next_idx < lines.len() {
                let else_line = lines[next_idx].to_lowercase();
                if else_line == "else" || else_line.starts_with("else ") {
                    let (else_parsed, end_idx) = parse_items(lines, seen_participants, diagram, next_idx + 1);
                    (Some(else_parsed), end_idx)
                } else {
                    (None, next_idx)
                }
            } else {
                (None, next_idx)
            };

            items.push(SequenceItem::Alt {
                condition,
                items: alt_items,
                else_items,
            });
            idx = final_idx;
            continue;
        }

        // Parse opt block
        if lower.starts_with("opt ") || lower == "opt" {
            let condition = if lower.len() > 4 {
                line[4..].trim().to_string()
            } else {
                String::new()
            };
            let (opt_items, next_idx) = parse_items(lines, seen_participants, diagram, idx + 1);
            items.push(SequenceItem::Opt {
                condition,
                items: opt_items,
            });
            idx = next_idx;
            continue;
        }

        // Parse message
        if let Some(msg) = parse_message(line) {
            auto_add_participant(&msg.from, seen_participants, diagram);
            auto_add_participant(&msg.to, seen_participants, diagram);
            items.push(SequenceItem::Message(msg));
            idx += 1;
            continue;
        }

        idx += 1;
    }

    (items, idx)
}

/// Auto-add participant if not seen
fn auto_add_participant(
    id: &str,
    seen_participants: &mut std::collections::HashSet<String>,
    diagram: &mut SequenceDiagram,
) {
    if !seen_participants.contains(id) {
        let id_owned = id.to_string();
        seen_participants.insert(id_owned.clone());
        diagram.participants.push(Participant {
            label: id_owned.clone(),
            id: id_owned,
        });
    }
}

/// Parse a Note: Note left/right/over participant: text
fn parse_note(line: &str) -> Option<Note> {
    let lower = line.to_lowercase();
    let rest = line.strip_prefix("note").or_else(|| line.strip_prefix("Note"))?.trim();

    let (position, after_pos) = if lower.contains(" left of ") {
        (NotePosition::Left, rest.strip_prefix("left of").or_else(|| rest.strip_prefix("Left of"))?)
    } else if lower.contains(" right of ") {
        (NotePosition::Right, rest.strip_prefix("right of").or_else(|| rest.strip_prefix("Right of"))?)
    } else if lower.contains(" over ") {
        (NotePosition::Over, rest.strip_prefix("over").or_else(|| rest.strip_prefix("Over"))?)
    } else {
        return None;
    };

    let after_pos = after_pos.trim();

    // Find colon separator
    let (participants_str, text) = if let Some(colon_idx) = after_pos.find(':') {
        let p = after_pos[..colon_idx].trim();
        let t = after_pos[colon_idx + 1..].trim();
        (p, t.to_string())
    } else {
        (after_pos, String::new())
    };

    // Parse participants (can be comma-separated for "over")
    let participants: Vec<String> = participants_str
        .split(',')
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect();

    if participants.is_empty() {
        return None;
    }

    Some(Note {
        position,
        participants,
        text,
    })
}

/// Parse participant declaration: participant Alice or participant A as Alice
fn parse_participant(line: &str) -> Option<Participant> {
    let rest = line
        .strip_prefix("participant")
        .or_else(|| line.strip_prefix("Participant"))?
        .trim();

    if rest.contains(" as ") {
        let parts: Vec<&str> = rest.splitn(2, " as ").collect();
        if parts.len() == 2 {
            return Some(Participant {
                id: parts[0].trim().to_string(),
                label: parts[1].trim().to_string(),
            });
        }
    }

    Some(Participant {
        id: rest.to_string(),
        label: rest.to_string(),
    })
}

/// Parse actor declaration: actor Alice or actor A as Alice
fn parse_actor(line: &str) -> Option<Participant> {
    let rest = line
        .strip_prefix("actor")
        .or_else(|| line.strip_prefix("Actor"))?
        .trim();

    if rest.contains(" as ") {
        let parts: Vec<&str> = rest.splitn(2, " as ").collect();
        if parts.len() == 2 {
            return Some(Participant {
                id: parts[0].trim().to_string(),
                label: parts[1].trim().to_string(),
            });
        }
    }

    Some(Participant {
        id: rest.to_string(),
        label: rest.to_string(),
    })
}

/// Parse message: From->>To: Label
fn parse_message(line: &str) -> Option<Message> {
    // Order matters - check longer patterns first
    let patterns = [
        ("-->>", ArrowStyle::Dotted),
        ("->>", ArrowStyle::Solid),
        ("-->", ArrowStyle::DottedLine),
        ("->", ArrowStyle::SolidLine),
        ("-)", ArrowStyle::Async),
    ];

    for (pattern, style) in patterns {
        if let Some(idx) = line.find(pattern) {
            let from = line[..idx].trim().to_string();
            let rest = line[idx + pattern.len()..].trim();

            // Parse label after colon
            let (to, label) = if let Some(colon_idx) = rest.find(':') {
                let to = rest[..colon_idx].trim().to_string();
                let label = rest[colon_idx + 1..].trim().to_string();
                (to, label)
            } else {
                (rest.to_string(), String::new())
            };

            if !from.is_empty() && !to.is_empty() {
                return Some(Message {
                    from,
                    to,
                    label,
                    style,
                });
            }
        }
    }

    None
}

/// Render sequence diagram to ASCII representation
#[allow(clippy::needless_range_loop)]
pub fn render_sequence_diagram(diagram: &SequenceDiagram, options: &RenderOptions) -> String {
    let mut output = String::new();

    if diagram.participants.is_empty() {
        return "No participants".to_string();
    }

    // Character set
    let (box_h, box_v, box_tl, box_tr, box_bl, box_br) = if options.ascii {
        ('-', '|', '+', '+', '+', '+')
    } else {
        ('', '', '', '', '', '')
    };

    let arrow_r = if options.ascii { '>' } else { '' };
    let arrow_l = if options.ascii { '<' } else { '' };

    // Calculate participant column widths
    let min_col_width = 12;
    let col_widths: Vec<usize> = diagram
        .participants
        .iter()
        .map(|p| (p.label.len() + 4).max(min_col_width))
        .collect();

    // Calculate participant x positions (center of each column)
    let mut positions: Vec<usize> = Vec::new();
    let mut x = 0;
    for width in &col_widths {
        positions.push(x + width / 2);
        x += width;
    }
    let total_width = x;

    // Title
    if let Some(ref title) = diagram.title {
        let padding = (total_width.saturating_sub(title.len())) / 2;
        output.push_str(&" ".repeat(padding));
        output.push_str(title);
        output.push('\n');
        output.push_str(&" ".repeat(padding));
        output.push_str(&"".repeat(title.len()));
        output.push_str("\n\n");
    }

    // Draw participant boxes at top
    // Box top line
    let mut line = vec![' '; total_width];
    for (i, p) in diagram.participants.iter().enumerate() {
        let center = positions[i];
        let box_width = p.label.len() + 2;
        let start = center.saturating_sub(box_width / 2);
        let end = start + box_width;

        if start < total_width {
            line[start] = box_tl;
        }
        for j in (start + 1)..end.min(total_width).saturating_sub(1) {
            line[j] = box_h;
        }
        if end > 0 && end - 1 < total_width {
            line[end - 1] = box_tr;
        }
    }
    output.push_str(&line.iter().collect::<String>());
    output.push('\n');

    // Box middle line (label)
    let mut line = vec![' '; total_width];
    for (i, p) in diagram.participants.iter().enumerate() {
        let center = positions[i];
        let box_width = p.label.len() + 2;
        let start = center.saturating_sub(box_width / 2);
        let end = start + box_width;

        if start < total_width {
            line[start] = box_v;
        }
        // Center label
        let label_start = start + 1;
        for (j, c) in p.label.chars().enumerate() {
            if label_start + j < total_width {
                line[label_start + j] = c;
            }
        }
        if end > 0 && end - 1 < total_width {
            line[end - 1] = box_v;
        }
    }
    output.push_str(&line.iter().collect::<String>());
    output.push('\n');

    // Box bottom line
    let mut line = vec![' '; total_width];
    for (i, p) in diagram.participants.iter().enumerate() {
        let center = positions[i];
        let box_width = p.label.len() + 2;
        let start = center.saturating_sub(box_width / 2);
        let end = start + box_width;

        if start < total_width {
            line[start] = box_bl;
        }
        for j in (start + 1)..end.min(total_width).saturating_sub(1) {
            line[j] = box_h;
        }
        if end > 0 && end - 1 < total_width {
            line[end - 1] = box_br;
        }
    }
    output.push_str(&line.iter().collect::<String>());
    output.push('\n');

    // Draw vertical lines (lifelines) and messages
    for msg in &diagram.messages {
        // Find participant indices
        let from_idx = diagram
            .participants
            .iter()
            .position(|p| p.id == msg.from || p.label == msg.from);
        let to_idx = diagram
            .participants
            .iter()
            .position(|p| p.id == msg.to || p.label == msg.to);

        if let (Some(from_i), Some(to_i)) = (from_idx, to_idx) {
            let from_x = positions[from_i];
            let to_x = positions[to_i];

            // Draw lifeline row with vertical lines at participant positions
            let mut line = vec![' '; total_width];
            for &pos in &positions {
                if pos < total_width {
                    line[pos] = if options.ascii { '|' } else { '' };
                }
            }
            output.push_str(&line.iter().collect::<String>());
            output.push('\n');

            // Draw message arrow
            let mut line = vec![' '; total_width];
            for &pos in &positions {
                if pos < total_width {
                    line[pos] = if options.ascii { '|' } else { '' };
                }
            }

            let (start_x, end_x, going_right) = if from_x < to_x {
                (from_x, to_x, true)
            } else {
                (to_x, from_x, false)
            };

            // Draw arrow line
            let arrow_char = match msg.style {
                ArrowStyle::Dotted | ArrowStyle::DottedLine => {
                    if options.ascii {
                        '-'
                    } else {
                        '·'
                    }
                }
                _ => {
                    if options.ascii {
                        '-'
                    } else {
                        ''
                    }
                }
            };

            for x in (start_x + 1)..end_x {
                if x < total_width {
                    line[x] = arrow_char;
                }
            }

            // Draw arrow head
            let has_arrow = matches!(
                msg.style,
                ArrowStyle::Solid | ArrowStyle::Dotted | ArrowStyle::Async
            );
            if has_arrow {
                if going_right && end_x > 0 && end_x - 1 < total_width {
                    line[end_x - 1] = arrow_r;
                } else if !going_right && start_x + 1 < total_width {
                    line[start_x + 1] = arrow_l;
                }
            }

            output.push_str(&line.iter().collect::<String>());

            // Add label
            if !msg.label.is_empty() {
                output.push_str("  ");
                output.push_str(&msg.label);
            }
            output.push('\n');
        }
    }

    // Final lifeline row
    let mut line = vec![' '; total_width];
    for &pos in &positions {
        if pos < total_width {
            line[pos] = if options.ascii { '|' } else { '' };
        }
    }
    output.push_str(&line.iter().collect::<String>());
    output.push('\n');

    output
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_simple_sequence() {
        let input = r#"sequenceDiagram
    Alice->>Bob: Hello
"#;
        let diagram = parse_sequence_diagram(input).unwrap();
        assert_eq!(diagram.participants.len(), 2);
        assert_eq!(diagram.messages.len(), 1);
        assert_eq!(diagram.messages[0].from, "Alice");
        assert_eq!(diagram.messages[0].to, "Bob");
        assert_eq!(diagram.messages[0].label, "Hello");
    }

    #[test]
    fn test_parse_participant_declaration() {
        let input = r#"sequenceDiagram
    participant A as Alice
    participant B as Bob
    A->>B: Hi
"#;
        let diagram = parse_sequence_diagram(input).unwrap();
        assert_eq!(diagram.participants.len(), 2);
        assert_eq!(diagram.participants[0].id, "A");
        assert_eq!(diagram.participants[0].label, "Alice");
    }

    #[test]
    fn test_parse_arrow_styles() {
        let input = r#"sequenceDiagram
    A->>B: Solid
    A-->>B: Dotted
    A->B: Line
    A-->B: DottedLine
"#;
        let diagram = parse_sequence_diagram(input).unwrap();
        assert_eq!(diagram.messages.len(), 4);
        assert_eq!(diagram.messages[0].style, ArrowStyle::Solid);
        assert_eq!(diagram.messages[1].style, ArrowStyle::Dotted);
        assert_eq!(diagram.messages[2].style, ArrowStyle::SolidLine);
        assert_eq!(diagram.messages[3].style, ArrowStyle::DottedLine);
    }

    #[test]
    fn test_render_sequence() {
        let msg = Message {
            from: "A".to_string(),
            to: "B".to_string(),
            label: "Hello".to_string(),
            style: ArrowStyle::Solid,
        };
        let diagram = SequenceDiagram {
            title: Some("Test".to_string()),
            participants: vec![
                Participant {
                    id: "A".to_string(),
                    label: "Alice".to_string(),
                },
                Participant {
                    id: "B".to_string(),
                    label: "Bob".to_string(),
                },
            ],
            items: vec![SequenceItem::Message(msg.clone())],
            messages: vec![msg],
        };
        let output = render_sequence_diagram(&diagram, &RenderOptions::default());
        assert!(output.contains("Test"));
        assert!(output.contains("Alice"));
        assert!(output.contains("Bob"));
        assert!(output.contains("Hello"));
    }

    #[test]
    fn test_seq_activate_deactivate() {
        let input = r#"sequenceDiagram
    Alice->>Bob: Hello
    activate Bob
    Bob-->>Alice: Hi
    deactivate Bob
"#;
        let diagram = parse_sequence_diagram(input).unwrap();
        assert_eq!(diagram.items.len(), 4);
        assert!(matches!(&diagram.items[1], SequenceItem::Activate(p) if p == "Bob"));
        assert!(matches!(&diagram.items[3], SequenceItem::Deactivate(p) if p == "Bob"));
    }

    #[test]
    fn test_seq_note_left_right() {
        let input = r#"sequenceDiagram
    Alice->>Bob: Hello
    Note right of Bob: Thinking
    Note left of Alice: Waiting
    Note over Alice,Bob: Both see this
"#;
        let diagram = parse_sequence_diagram(input).unwrap();
        assert_eq!(diagram.items.len(), 4);
        if let SequenceItem::Note(note) = &diagram.items[1] {
            assert_eq!(note.position, NotePosition::Right);
            assert_eq!(note.participants, vec!["Bob"]);
            assert_eq!(note.text, "Thinking");
        } else {
            panic!("Expected Note");
        }
    }

    #[test]
    fn test_seq_loop_block() {
        let input = r#"sequenceDiagram
    Alice->>Bob: Hello
    loop Every minute
        Bob->>Alice: Ping
    end
"#;
        let diagram = parse_sequence_diagram(input).unwrap();
        assert_eq!(diagram.items.len(), 2);
        if let SequenceItem::Loop { condition, items } = &diagram.items[1] {
            assert_eq!(condition, "Every minute");
            assert_eq!(items.len(), 1);
        } else {
            panic!("Expected Loop");
        }
    }

    #[test]
    fn test_seq_alt_else_block() {
        let input = r#"sequenceDiagram
    Alice->>Bob: Request
    alt Success
        Bob->>Alice: OK
    else Failure
        Bob->>Alice: Error
    end
"#;
        let diagram = parse_sequence_diagram(input).unwrap();
        assert_eq!(diagram.items.len(), 2);
        if let SequenceItem::Alt { condition, items, else_items } = &diagram.items[1] {
            assert_eq!(condition, "Success");
            assert_eq!(items.len(), 1);
            assert!(else_items.is_some());
            assert_eq!(else_items.as_ref().unwrap().len(), 1);
        } else {
            panic!("Expected Alt");
        }
    }
}