graphs-tui 0.4.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
//! Tests for GitHub issues
use graphs_tui::{
    check, is_supported, render, render_d2_to_tui, render_mermaid_to_tui, DiagramWarning,
    RenderOptions, SUPPORTED_LANGUAGES,
};

/// Issue #7: Warnings returned in RenderResult instead of eprintln
#[test]
fn test_issue_7_cycle_warning_in_result() {
    // Cyclical graph: A -> B -> C -> A
    let input = r#"flowchart LR
A --> B
B --> C
C --> A"#;
    let result = render_mermaid_to_tui(input, RenderOptions::default()).unwrap();
    assert!(
        !result.warnings.is_empty(),
        "Cycle should produce a warning"
    );
    assert!(
        result.warnings[0].to_string().contains("Cycle"),
        "Warning should mention cycle"
    );
    insta::assert_snapshot!(result.output);
}

/// Issue #7: Non-cyclic graphs produce no warnings
#[test]
fn test_issue_7_no_warning_without_cycle() {
    let input = "flowchart LR\nA --> B --> C";
    let result = render_mermaid_to_tui(input, RenderOptions::default()).unwrap();
    assert!(result.warnings.is_empty(), "No cycle means no warnings");
    insta::assert_snapshot!(result.output);
}

/// Issue #7: D2 cyclic graph also produces warning
#[test]
fn test_issue_7_d2_cycle_warning() {
    let input = r#"
A -> B
B -> C
C -> A
"#;
    let result = render_d2_to_tui(input, RenderOptions::default()).unwrap();
    assert!(
        !result.warnings.is_empty(),
        "D2 cycle should produce a warning"
    );
    insta::assert_snapshot!(result.output);
}

/// Issue #7: Pie chart has no warnings
#[test]
fn test_issue_7_pie_no_warnings() {
    let input = r#"pie
    "A" : 50
    "B" : 50
"#;
    let result = graphs_tui::render_pie_chart(input, RenderOptions::default()).unwrap();
    assert!(result.warnings.is_empty());
    insta::assert_snapshot!(result.output);
}

// ── Issue #8: Rendering artifacts ──────────────────────────────────────

/// Issue #8: Cylinder renders 5 rows with ├───┤ separators
#[test]
fn test_issue_8_cylinder_5_rows() {
    let input = "flowchart LR\nDB[(Database)]";
    let result = render_mermaid_to_tui(input, RenderOptions::default()).unwrap();
    let output = &result.output;
    assert!(output.contains(''), "Cylinder should have ├ T-junction");
    assert!(output.contains(''), "Cylinder should have ┤ T-junction");
    assert!(output.contains(''), "Cylinder should have ╭ top-left");
    assert!(output.contains(''), "Cylinder should have ╰ bottom-left");
    assert!(output.contains("Database"), "Label should be present");

    // Verify 5-row structure: find the cylinder lines
    let lines: Vec<&str> = output.lines().collect();
    // Find the line with ╭ (top of cylinder)
    let top = lines.iter().position(|l| l.contains('')).unwrap();
    let bot = lines.iter().position(|l| l.contains('')).unwrap();
    assert_eq!(bot - top, 4, "Cylinder should span exactly 5 rows (0..4)");
    // Row 1 and 3 should have ├ separators
    assert!(lines[top + 1].contains(''), "Row 1 should have ├");
    assert!(lines[top + 3].contains(''), "Row 3 should have ├");
    insta::assert_snapshot!(result.output);
}

/// Issue #8: Edge connects to cylinder midpoint (height/2), not y+1
#[test]
fn test_issue_8_edge_connects_cylinder_midpoint() {
    let input = "flowchart LR\nA[Start] --> DB[(Database)]";
    let result = render_mermaid_to_tui(input, RenderOptions::default()).unwrap();
    let output = &result.output;

    // The arrow should be on the same row as the label (midpoint)
    let lines: Vec<&str> = output.lines().collect();
    let arrow_line = lines
        .iter()
        .position(|l| l.contains(''))
        .expect("Should have arrow");
    let label_line = lines
        .iter()
        .position(|l| l.contains("Database"))
        .expect("Should have Database label");
    assert_eq!(
        arrow_line, label_line,
        "Arrow should connect at cylinder midpoint (same row as label)"
    );
    insta::assert_snapshot!(result.output);
}

/// Issue #8: Subgraph ║ borders not corrupted by nodes
#[test]
fn test_issue_8_subgraph_borders_preserved() {
    let input = r#"flowchart LR
subgraph sg1 [Group]
    A[Node]
end"#;
    let result = render_mermaid_to_tui(input, RenderOptions::default()).unwrap();
    let output = &result.output;
    // Subgraph should have ║ vertical borders
    assert!(
        output.contains(''),
        "Subgraph should have ║ vertical borders"
    );
    assert!(output.contains(''), "Subgraph should have ╔ corner");
    assert!(output.contains(''), "Subgraph should have ╗ corner");
    assert!(output.contains(''), "Subgraph should have ╚ corner");
    assert!(output.contains(''), "Subgraph should have ╝ corner");
    insta::assert_snapshot!(result.output);
}

/// Issue #8: Subgraph labels not corrupted by edges
#[test]
fn test_issue_8_subgraph_labels_intact() {
    let input = r#"flowchart TB
subgraph sg1 [My Group]
    A[Node1]
    B[Node2]
end
A --> B"#;
    let result = render_mermaid_to_tui(input, RenderOptions::default()).unwrap();
    let output = &result.output;
    assert!(
        output.contains("My Group"),
        "Subgraph label should be intact"
    );
    insta::assert_snapshot!(result.output);
}

// ── Issue #9: Deterministic layout, dropped edge labels, cycle warning UX ──

/// Issue #9: Same input produces identical output across multiple runs (Mermaid)
#[test]
fn test_issue_9_deterministic_mermaid() {
    let input = r#"flowchart LR
A[Start] --> B[Middle]
A --> C[Other]
B --> D[End]
C --> D"#;
    let first = render_mermaid_to_tui(input, RenderOptions::default())
        .unwrap()
        .output;
    for i in 1..20 {
        let result = render_mermaid_to_tui(input, RenderOptions::default())
            .unwrap()
            .output;
        assert_eq!(first, result, "Mermaid run {i} differs from first run");
    }
    insta::assert_snapshot!(first);
}

/// Issue #9: Same input produces identical output across multiple runs (D2)
#[test]
fn test_issue_9_deterministic_d2() {
    let input = r#"
A -> B
A -> C
B -> D
C -> D
"#;
    let first = render_d2_to_tui(input, RenderOptions::default())
        .unwrap()
        .output;
    for i in 1..20 {
        let result = render_d2_to_tui(input, RenderOptions::default())
            .unwrap()
            .output;
        assert_eq!(first, result, "D2 run {i} differs from first run");
    }
    insta::assert_snapshot!(first);
}

/// Issue #9: D2 cycle graph determinism (original reproducer from #9)
#[test]
fn test_issue_9_deterministic_d2_with_cycle() {
    let input = r#"
users: Users
api: Production API
pgbouncer: PgBouncer { shape: cylinder }
analytics: Analytics Query
users -> api: requests
api -> pgbouncer: need conn
analytics -> pgbouncer: 60 conns held
api -> users: 503 errors
"#;
    let first = render_d2_to_tui(input, RenderOptions::default())
        .unwrap()
        .output;
    for i in 1..20 {
        let result = render_d2_to_tui(input, RenderOptions::default())
            .unwrap()
            .output;
        assert_eq!(first, result, "D2 cycle run {i} differs");
    }
    insta::assert_snapshot!(first);
}

/// Issue #9: Edge label dropped to legend when edge is too short
#[test]
fn test_issue_9_edge_label_legend() {
    // Use very short node names with a long label to force the label to not fit
    let input = "flowchart LR\nA -->|This is a very long label that will not fit| B";
    let result = render_mermaid_to_tui(input, RenderOptions::default()).unwrap();

    // Legend should appear
    assert!(
        result.output.contains("Labels:"),
        "Legend section should appear when label is dropped"
    );
    assert!(
        result
            .output
            .contains("This is a very long label that will not fit"),
        "Legend should contain the dropped label text"
    );

    // Should have a LabelDropped warning
    let has_label_warning = result
        .warnings
        .iter()
        .any(|w| matches!(w, DiagramWarning::LabelDropped { .. }));
    assert!(has_label_warning, "Should have a LabelDropped warning");
    insta::assert_snapshot!(result.output);
}

/// Issue #9: Cycle warning includes node names
#[test]
fn test_issue_9_cycle_warning_nodes() {
    let input = r#"flowchart LR
X --> Y
Y --> Z
Z --> X"#;
    let result = render_mermaid_to_tui(input, RenderOptions::default()).unwrap();
    assert_eq!(result.warnings.len(), 1);

    match &result.warnings[0] {
        DiagramWarning::CycleDetected { nodes } => {
            assert!(nodes.contains(&"X".to_string()), "Should contain X");
            assert!(nodes.contains(&"Y".to_string()), "Should contain Y");
            assert!(nodes.contains(&"Z".to_string()), "Should contain Z");
            // Nodes should be sorted
            assert_eq!(nodes, &["X", "Y", "Z"]);
        }
        other => panic!("Expected CycleDetected, got: {other:?}"),
    }
    insta::assert_snapshot!(result.output);
}

/// Issue #9: DiagramWarning Display impl
#[test]
fn test_issue_9_warning_display() {
    let w = DiagramWarning::CycleDetected {
        nodes: vec!["A".into(), "B".into()],
    };
    assert_eq!(w.to_string(), "Cycle detected involving nodes: A, B");

    let w2 = DiagramWarning::LabelDropped {
        marker: "[1]".into(),
        edge_from: "X".into(),
        edge_to: "Y".into(),
        label: "my label".into(),
    };
    assert_eq!(
        w2.to_string(),
        "Label 'my label' on edge X -> Y moved to legend as [1]"
    );
}

/// Issue #9: No legend when labels fit inline
#[test]
fn test_issue_9_no_legend_when_labels_fit() {
    let input = "flowchart LR\nA[Start] -->|yes| B[End]";
    let result = render_mermaid_to_tui(input, RenderOptions::default()).unwrap();
    assert!(
        !result.output.contains("Labels:"),
        "No legend when labels fit inline"
    );
    assert!(result.output.contains("yes"), "Label should appear inline");
    insta::assert_snapshot!(result.output);
}

// ── Issue #12: Expose supported languages list ───────────────────────

/// Issue #12: SUPPORTED_LANGUAGES contains mermaid and d2
#[test]
fn test_issue_12_supported_languages() {
    assert!(SUPPORTED_LANGUAGES.contains(&"mermaid"));
    assert!(SUPPORTED_LANGUAGES.contains(&"d2"));
}

/// Issue #12: is_supported works case-insensitively
#[test]
fn test_issue_12_is_supported() {
    assert!(is_supported("mermaid"));
    assert!(is_supported("Mermaid"));
    assert!(is_supported("D2"));
    assert!(is_supported("d2"));
    assert!(!is_supported("graphviz"));
    assert!(!is_supported(""));
}

// ── Issue #11: Unified render() entry point ──────────────────────────

/// Issue #11: render("d2", ...) dispatches to D2 parser
#[test]
fn test_issue_11_render_d2() {
    let result = render("d2", "A -> B", RenderOptions::default()).unwrap();
    insta::assert_snapshot!(result.output);
}

/// Issue #11: render("mermaid", ...) dispatches to Mermaid auto-detect
#[test]
fn test_issue_11_render_mermaid() {
    let result = render(
        "mermaid",
        "flowchart LR\nA[Start] --> B[End]",
        RenderOptions::default(),
    )
    .unwrap();
    insta::assert_snapshot!(result.output);
}

/// Issue #11: render("mermaid", ...) handles pie charts
#[test]
fn test_issue_11_render_mermaid_pie() {
    let result = render(
        "mermaid",
        "pie\n    \"A\" : 60\n    \"B\" : 40",
        RenderOptions::default(),
    )
    .unwrap();
    insta::assert_snapshot!(result.output);
}

/// Issue #11: render is case-insensitive on lang
#[test]
fn test_issue_11_render_case_insensitive() {
    let result = render("D2", "X -> Y", RenderOptions::default()).unwrap();
    insta::assert_snapshot!(result.output);
}

// ── Issue #13: Validate-only check() ─────────────────────────────────

/// Issue #13: check detects cycle without rendering
#[test]
fn test_issue_13_check_cycle() {
    let warnings = check("mermaid", "flowchart LR\nA --> B\nB --> A").unwrap();
    assert!(!warnings.is_empty(), "Should detect cycle");
    assert!(
        matches!(&warnings[0], DiagramWarning::CycleDetected { .. }),
        "Should be CycleDetected"
    );
}

/// Issue #13: check returns empty for valid acyclic graph
#[test]
fn test_issue_13_check_no_warnings() {
    let warnings = check("mermaid", "flowchart LR\nA --> B --> C").unwrap();
    assert!(warnings.is_empty());
}

/// Issue #13: check works with D2
#[test]
fn test_issue_13_check_d2_cycle() {
    let warnings = check("d2", "A -> B\nB -> A").unwrap();
    assert!(!warnings.is_empty());
}

/// Issue #13: check validates pie chart parse errors
#[test]
fn test_issue_13_check_pie_valid() {
    let warnings = check("mermaid", "pie\n    \"A\" : 50\n    \"B\" : 50").unwrap();
    assert!(warnings.is_empty());
}

/// Issue #13: check validates sequence diagram parse
#[test]
fn test_issue_13_check_sequence_valid() {
    let warnings = check("mermaid", "sequenceDiagram\n    A->>B: Hi").unwrap();
    assert!(warnings.is_empty());
}

/// Issue #13: check returns Err on invalid input
#[test]
fn test_issue_13_check_invalid() {
    let result = check("mermaid", "flowchart\n");
    assert!(result.is_err(), "Should fail on invalid input");
}

// ── Issue #18: Layout quality — tiered DAG, inline labels, trailing whitespace

/// Issue #18: D2 cycle graph produces tiered layout (not all at layer 0)
#[test]
fn test_issue_18_tiered_layout() {
    let input = r#"
users: Users
api: Production API
pgbouncer: PgBouncer { shape: cylinder }
analytics: Analytics Query
users -> api: requests
api -> pgbouncer: need conn
analytics -> pgbouncer: 60 conns held
api -> users: 503 errors
"#;
    let result = render_d2_to_tui(input, RenderOptions::default()).unwrap();
    let output = &result.output;

    // With tiered layout, pgbouncer should be below api (TB direction default for D2),
    // not all on the same row. Verify nodes appear on different lines.
    let lines: Vec<&str> = output.lines().collect();

    let users_line = lines.iter().position(|l| l.contains("Users")).unwrap();
    let api_line = lines
        .iter()
        .position(|l| l.contains("Production API"))
        .unwrap();
    let pgbouncer_line = lines.iter().position(|l| l.contains("PgBouncer")).unwrap();

    // users and analytics should be at layer 0, api at layer 1, pgbouncer at layer 2
    // In TB layout this means users_line < api_line < pgbouncer_line
    assert!(
        api_line > users_line,
        "api should be below users: api={api_line} users={users_line}"
    );
    assert!(
        pgbouncer_line > api_line,
        "pgbouncer should be below api: pgbouncer={pgbouncer_line} api={api_line}"
    );
    insta::assert_snapshot!(result.output);
}

/// Issue #18: Labels render inline (no Labels: legend) for D2 cycle graph
#[test]
fn test_issue_18_inline_labels() {
    let input = r#"
users: Users
api: Production API
pgbouncer: PgBouncer { shape: cylinder }
analytics: Analytics Query
users -> api: requests
api -> pgbouncer: need conn
analytics -> pgbouncer: 60 conns held
api -> users: 503 errors
"#;
    let result = render_d2_to_tui(input, RenderOptions::default()).unwrap();
    assert!(
        !result.output.contains("Labels:"),
        "Labels should render inline, no legend section needed"
    );
    insta::assert_snapshot!(result.output);
}

/// Issue #18: Output should not end with blank lines
#[test]
fn test_issue_18_no_trailing_blank_lines() {
    let input = "flowchart LR\nA --> B";
    let result = render_mermaid_to_tui(input, RenderOptions::default()).unwrap();

    // No trailing whitespace-only lines
    let last_line = result.output.lines().last().unwrap_or("");
    assert!(
        !last_line.trim().is_empty(),
        "Output should not end with a blank line"
    );
    assert!(
        !result.output.ends_with('\n'),
        "Output should not end with newline"
    );
    insta::assert_snapshot!(result.output);
}

/// Issue #18: D2 cycle graph output has no trailing blank lines
#[test]
fn test_issue_18_no_trailing_blank_lines_d2() {
    let input = r#"
users: Users
api: Production API
pgbouncer: PgBouncer { shape: cylinder }
analytics: Analytics Query
users -> api: requests
api -> pgbouncer: need conn
analytics -> pgbouncer: 60 conns held
api -> users: 503 errors
"#;
    let result = render_d2_to_tui(input, RenderOptions::default()).unwrap();

    let last_line = result.output.lines().last().unwrap_or("");
    assert!(
        !last_line.trim().is_empty(),
        "D2 output should not end with blank line"
    );
    insta::assert_snapshot!(result.output);
}

/// Issue #18: Cycle warning still fires for graphs with back-edges
#[test]
fn test_issue_18_cycle_warning_still_fires() {
    let input = r#"
users: Users
api: Production API
users -> api: requests
api -> users: 503 errors
"#;
    let result = render_d2_to_tui(input, RenderOptions::default()).unwrap();
    assert!(
        !result.warnings.is_empty(),
        "Cycle warning should still fire"
    );
    assert!(
        result.warnings[0].to_string().contains("Cycle"),
        "Warning should mention cycle"
    );
    insta::assert_snapshot!(result.output);
}