meraid 0.2.0

Render Mermaid diagrams in your terminal — a pure-Rust CLI and library
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
//! Meraid - Render Mermaid diagrams in your terminal
//!
//! A Rust implementation for rendering Mermaid diagrams in the terminal.

pub mod diagram;
pub mod layout;
pub mod parser;
pub mod render;
pub mod theme;

pub use diagram::{Diagram, DiagramType, Edge, EdgeStyle, Node, NodeShape};
pub use layout::Layout;
pub use parser::parse_mermaid;
pub use render::Renderer;
pub use theme::{Theme, ThemeType};

use anyhow::Result;

/// Render Mermaid diagram to terminal string
pub fn render(source: &str, theme_type: ThemeType) -> Result<String> {
    let diagram = parse_mermaid(source)?;
    let layout = Layout::new(&diagram).layout();
    let theme = Theme::get(theme_type);
    let renderer = Renderer::new(theme);
    Ok(renderer.render(&diagram, &layout))
}

/// Render Mermaid diagram with custom theme
pub fn render_with_theme(source: &str, theme: Theme) -> Result<String> {
    let diagram = parse_mermaid(source)?;
    let layout = Layout::new(&diagram).layout();
    let renderer = Renderer::new(theme);
    Ok(renderer.render(&diagram, &layout))
}

// ==================== Tests ====================

#[cfg(test)]
mod tests {
    use crate::{parse_mermaid, DiagramType, Layout, Renderer, Theme, ThemeType};

    // ==================== Parser Tests ====================

    #[test]
    fn test_parse_flowchart_basic() {
        let source = r#"
graph LR
A --> B
"#;
        let diagram = parse_mermaid(source).unwrap();
        assert_eq!(diagram.diagram_type, DiagramType::Flowchart);
        assert_eq!(diagram.direction, "LR");
    }

    #[test]
    fn test_parse_flowchart_multiple_edges() {
        let source = r#"
graph LR
A --> B --> C
A --> D
"#;
        let diagram = parse_mermaid(source).unwrap();
        assert_eq!(diagram.nodes.len(), 4);
        assert_eq!(diagram.edges.len(), 3);
    }

    #[test]
    fn test_parse_flowchart_chained() {
        let source = "graph LR\nA --> B --> C --> D";
        let diagram = parse_mermaid(source).unwrap();
        assert_eq!(diagram.edges.len(), 3);
    }

    #[test]
    fn test_parse_flowchart_thick_arrow() {
        let source = "graph LR\nA ==> B";
        let diagram = parse_mermaid(source).unwrap();
        assert_eq!(diagram.edges.len(), 1);
    }

    #[test]
    fn test_parse_flowchart_dotted_arrow() {
        let source = "graph LR\nA -.-> B";
        let diagram = parse_mermaid(source).unwrap();
        assert_eq!(diagram.edges.len(), 1);
    }

    #[test]
    fn test_parse_sequence_diagram() {
        let source = r#"
sequenceDiagram
Alice->>Bob: Hello
Bob-->>Alice: Hi
Alice->>Bob: How are you?
"#;
        let diagram = parse_mermaid(source).unwrap();
        assert_eq!(diagram.diagram_type, DiagramType::Sequence);
        assert!(diagram.participants.contains(&"Alice".to_string()));
        assert!(diagram.participants.contains(&"Bob".to_string()));
        assert_eq!(diagram.edges.len(), 3);
    }

    #[test]
    fn test_parse_sequence_participants() {
        let source = r#"
sequenceDiagram
participant Alice
participant Bob
participant Charlie
Alice->>Bob: Hello
"#;
        let diagram = parse_mermaid(source).unwrap();
        assert_eq!(diagram.participants.len(), 3);
    }

    #[test]
    fn test_parse_class_diagram() {
        let source = r#"
classDiagram
class Animal {
    +String name
    +int age
}
class Dog {
    +String breed
}
Animal <|-- Dog
"#;
        let diagram = parse_mermaid(source).unwrap();
        assert_eq!(diagram.diagram_type, DiagramType::Class);
    }

    #[test]
    fn test_parse_state_diagram() {
        let source = r#"
stateDiagram-v2
[*] --> Idle
Idle --> Processing: start
Processing --> Done: complete
Done --> [*]
"#;
        let diagram = parse_mermaid(source).unwrap();
        assert_eq!(diagram.diagram_type, DiagramType::State);
    }

    #[test]
    fn test_parse_pie_chart() {
        let source = r#"
pie title Pets
"Dogs" : 386
"Cats" : 85
"Rats" : 15
"#;
        let diagram = parse_mermaid(source).unwrap();
        assert_eq!(diagram.diagram_type, DiagramType::Pie);
        assert_eq!(diagram.nodes.len(), 3);
    }

    #[test]
    fn test_parse_unknown_defaults_to_flowchart() {
        let source = "A --> B";
        let diagram = parse_mermaid(source).unwrap();
        assert_eq!(diagram.diagram_type, DiagramType::Flowchart);
    }

    #[test]
    fn test_parse_flowchart_vertical_direction() {
        let source = "graph TB\nA --> B";
        let diagram = parse_mermaid(source).unwrap();
        assert_eq!(diagram.direction, "TB");
    }

    #[test]
    fn test_parse_comments_ignored() {
        let source = r#"
%% This is a comment
graph LR
%% Another comment
A --> B
%% End comment
"#;
        let diagram = parse_mermaid(source).unwrap();
        assert_eq!(diagram.edges.len(), 1);
    }

    // ==================== Integration Tests ====================

    #[test]
    fn test_full_render_flowchart() {
        let source = "graph LR\nA --> B";
        let diagram = parse_mermaid(source).unwrap();
        let layout = Layout::new(&diagram).layout();
        let theme = Theme::get(ThemeType::Default);
        let renderer = Renderer::new(theme);
        let output = renderer.render(&diagram, &layout);

        assert!(!output.is_empty());
    }

    #[test]
    fn test_full_render_sequence() {
        let source = "sequenceDiagram\nAlice->>Bob: Hello";
        let diagram = parse_mermaid(source).unwrap();
        let layout = Layout::new(&diagram).layout();
        let theme = Theme::get(ThemeType::Default);
        let renderer = Renderer::new(theme);
        let output = renderer.render(&diagram, &layout);

        assert!(!output.is_empty());
    }

    #[test]
    fn test_full_render_pie() {
        let source = "pie title Test\nA : 50\nB : 50";
        let diagram = parse_mermaid(source).unwrap();
        let layout = Layout::new(&diagram).layout();
        let theme = Theme::get(ThemeType::Default);
        let renderer = Renderer::new(theme);
        let output = renderer.render(&diagram, &layout);

        assert!(!output.is_empty());
    }

    #[test]
    fn test_render_class_diagram_with_chinese_alignment() {
        let source = r#"
classDiagram
class 用户服务 {
    +获取用户
    +更新资料
}
"#;
        let diagram = parse_mermaid(source).unwrap();
        let layout = Layout::new(&diagram).layout();
        let theme = Theme::get(ThemeType::Default);
        let renderer = Renderer::new(theme);
        let output = renderer.render(&diagram, &layout);

        assert!(output.contains("│    用户服务    │"));
        assert!(output.contains("│+获取用户       │"));
        assert!(output.contains("│+更新资料       │"));
    }

    #[test]
    fn test_full_render_flowchart_with_chinese_label_keeps_borders_aligned() {
        let source = "graph LR\n开始 --> 结束";
        let diagram = parse_mermaid(source).unwrap();
        let layout = Layout::new(&diagram).layout();
        let theme = Theme::get(ThemeType::Default);
        let renderer = Renderer::new(theme);
        let output = renderer.render(&diagram, &layout);

        assert!(output.contains("┌──────────┐"));
        assert!(output.contains("│   开始   │"));
        assert!(output.contains("└──────────┘"));
    }

    #[test]
    fn test_flowchart_merge_node_does_not_overlap() {
        // Regression: a merge node reachable by two paths of different lengths
        // must land in its longest-path layer, not collide with an earlier node.
        // Previously `结束` (reachable directly and via the long branch) was
        // placed in the same column/coordinate as another node, overprinting it.
        let source = "graph LR\n\
            A --> B --> C --> D\n\
            A --> E\n\
            B --> E\n\
            E --> D";
        let diagram = parse_mermaid(source).unwrap();
        let layout = Layout::new(&diagram).layout();

        // No two nodes may share the same top-left coordinate.
        let positions: Vec<_> = diagram
            .nodes
            .iter()
            .map(|n| {
                let p = layout.positions.get(&n.id).expect("node positioned");
                (p.x, p.y)
            })
            .collect();
        for i in 0..positions.len() {
            for j in (i + 1)..positions.len() {
                assert_ne!(
                    positions[i], positions[j],
                    "nodes {} and {} overlap at {:?}",
                    diagram.nodes[i].id, diagram.nodes[j].id, positions[i]
                );
            }
        }

        // D is the sink (longest path A→B→C→D), so it must be the rightmost box.
        let max_x = layout.positions.values().map(|p| p.x).max().unwrap();
        assert_eq!(layout.positions.get("D").unwrap().x, max_x);
    }

    #[test]
    fn test_flowchart_branches_straddle_trunk() {
        // A decision node's two outcomes should sit on opposite sides of the
        // trunk (one above, one below), not stacked together.
        let source = "graph LR\nA --> B\nB --> C\nB --> D";
        let diagram = parse_mermaid(source).unwrap();
        let layout = Layout::new(&diagram).layout();

        let b = layout.positions.get("B").unwrap().y;
        let c = layout.positions.get("C").unwrap().y;
        let d = layout.positions.get("D").unwrap().y;
        // One branch above B, the other below.
        assert!(
            (c < b && d > b) || (d < b && c > b),
            "branches did not straddle the trunk: B={b}, C={c}, D={d}"
        );
    }

    #[test]
    fn test_sequence_diagram_with_chinese_and_mixed_text_alignment() {
        let source = r#"
sequenceDiagram
participant 用户A
participant API服务
用户A->>API服务: 查询 user-详情
API服务-->>用户A: 返回 成功OK
"#;
        let diagram = parse_mermaid(source).unwrap();
        let layout = Layout::new(&diagram).layout();
        let theme = Theme::get(ThemeType::Default);
        let renderer = Renderer::new(theme);
        let output = renderer.render(&diagram, &layout);

        assert!(output.contains("用户A"));
        assert!(output.contains("API服务"));
        assert!(output.contains(""));
        // Solid arrow for `->>`, dashed arrow for `-->>`.
        assert!(output.contains("├─────────────────▶ 查询 user-详情"));
        assert!(output.contains("◀┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┤ 返回 成功OK"));
    }

    #[test]
    fn test_state_diagram_with_chinese_and_mixed_text() {
        let source = r#"
stateDiagram-v2
[*] --> 待处理
待处理 --> 处理中: 开始 job-1
处理中 --> 已完成: 完成 OK
已完成 --> [*]
"#;
        let diagram = parse_mermaid(source).unwrap();
        let layout = Layout::new(&diagram).layout();
        let theme = Theme::get(ThemeType::Default);
        let renderer = Renderer::new(theme);
        let output = renderer.render(&diagram, &layout);

        assert!(output.contains("待处理 ──▶ 处理中 : 开始 job-1"));
        assert!(output.contains("处理中 ──▶ 已完成 : 完成 OK"));
    }

    #[test]
    fn test_all_themes() {
        let source = "graph LR\nA --> B";
        let diagram = parse_mermaid(source).unwrap();

        for theme_type in [
            ThemeType::Default,
            ThemeType::Terra,
            ThemeType::Neon,
            ThemeType::Mono,
            ThemeType::Amber,
            ThemeType::Phosphor,
        ] {
            let theme = Theme::get(theme_type);
            let layout = Layout::new(&diagram).layout();
            let renderer = Renderer::new(theme);
            let output = renderer.render(&diagram, &layout);
            assert!(!output.is_empty());
        }
    }

    // ==================== Layout Tests ====================

    #[test]
    fn test_flowchart_layout_has_positions() {
        let source = "graph LR\nA --> B --> C";
        let diagram = parse_mermaid(source).unwrap();
        let layout = Layout::new(&diagram).layout();

        assert!(!layout.positions.is_empty());
        assert!(layout.width > 0);
        assert!(layout.height > 0);
    }

    #[test]
    fn test_layout_with_many_nodes() {
        let source = "graph LR\nA --> B --> C --> D --> E --> F --> G --> H";
        let diagram = parse_mermaid(source).unwrap();
        let layout = Layout::new(&diagram).layout();

        assert_eq!(layout.positions.len(), 8);
    }

    // ==================== Render Tests ====================

    #[test]
    fn test_renderer_respects_ascii_only() {
        let source = "graph LR\nA --> B";
        let diagram = parse_mermaid(source).unwrap();
        let layout = Layout::new(&diagram).layout();
        let theme = Theme::get(ThemeType::Default);

        let renderer = Renderer::new(theme).ascii_only(true);
        let output = renderer.render(&diagram, &layout);

        // ASCII mode should use +, -, |
        assert!(output.contains('+') || output.contains('-') || output.contains('|'));
    }

    // ==================== Edge Cases ====================

    #[test]
    fn test_empty_source() {
        // Empty input now surfaces an error instead of a blank canvas.
        let result = parse_mermaid("");
        assert!(result.is_err());
    }

    #[test]
    fn test_only_comments() {
        // A source with only comments parses to nothing, so it errors.
        let source = "%% comment only";
        assert!(parse_mermaid(source).is_err());
    }

    #[test]
    fn test_complex_flow() {
        let source = r#"
graph TD
A[Start] --> B{Decision}
B -->|Yes| C[Process]
B -->|No| D[Skip]
C --> E[End]
D --> E
"#;
        let diagram = parse_mermaid(source).unwrap();
        // Due to how parsing works, each labeled node (A[Start], B{Decision}, etc.)
        // might create multiple entries. Just check we have nodes and edges.
        assert!(diagram.nodes.len() >= 5);
        assert!(diagram.edges.len() >= 5);
    }
}