ariel-rs 0.2.0

A faithful Rust port of Mermaid JS — headless SVG diagram rendering without a browser
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
// Mermaid class diagram renderer — faithful port of classRenderer-v3.ts
// Uses dagre for layout; SVG structure mirrors reference output.

use super::constants::*;
use super::parser::{ClassDiagram, ClassNode, ClassRelation, EndType, LineStyle};
use super::templates::{
    self as tmpl, build_css, build_markers, drop_shadow_filter, drop_shadow_filter_small,
    edge_label_empty, edge_label_fo, edge_label_text, esc, fmt, svg_root, terminal_label_fo,
};
use crate::text::measure;
use crate::theme::{Theme, ThemeVars};
use dagre_dgl_rs::graph::{EdgeLabel, Graph, GraphLabel, NodeLabel, Point};
use dagre_dgl_rs::layout::layout;

// ─── Public entry points ──────────────────────────────────────────────────────

pub fn render(diag: &ClassDiagram, theme: Theme, use_foreign_object: bool) -> String {
    let vars = theme.resolve();
    render_inner(diag, &vars, use_foreign_object)
}

fn render_inner(diag: &ClassDiagram, vars: &ThemeVars, use_foreign_object: bool) -> String {
    let mut g = Graph::with_options(false, true, true);
    g.set_graph(GraphLabel {
        rankdir: Some(diag.direction.clone()),
        nodesep: Some(50.0),
        ranksep: Some(50.0),
        marginx: Some(8.0),
        marginy: Some(8.0),
        ..Default::default()
    });

    // Compute node sizes and add to graph
    let node_sizes: Vec<(String, f64, f64)> = diag
        .class_order
        .iter()
        .filter_map(|id| {
            let cls = diag.classes.get(id)?;
            let (w, h) = class_box_size(cls);
            Some((id.clone(), w, h))
        })
        .collect();

    for (id, w, h) in &node_sizes {
        g.set_node(
            id,
            NodeLabel {
                width: *w,
                height: *h,
                ..Default::default()
            },
        );
    }

    // Add edges — include label dimensions so dagre expands ranksep for labeled edges.
    // Edge labels in class diagrams are 24 px tall (one line); width is measured text.
    // Apply CONTENT_SCALE so dagre reserves the same space as the browser-rendered label.
    for (i, rel) in diag.relations.iter().enumerate() {
        let key = Some(format!("e{}", i));
        let (lbl_w, lbl_h) = if !rel.title.is_empty() {
            let (tw, _) = measure(&rel.title, FONT_SIZE);
            (tw * CONTENT_SCALE, 24.0)
        } else {
            (0.0, 0.0)
        };
        g.set_edge(
            &rel.id1,
            &rel.id2,
            EdgeLabel {
                minlen: Some(1),
                weight: Some(1.0),
                width: Some(lbl_w),
                height: Some(lbl_h),
                labelpos: Some("c".to_string()),
                ..Default::default()
            },
            key.as_deref(),
        );
    }

    layout(&mut g);

    let graph_w_dagre = g.graph().width.unwrap_or(200.0);
    let graph_h = g.graph().height.unwrap_or(200.0);

    // Mermaid's setupViewPortForSVG uses getBBox() on the full SVG, which includes cardinality
    // (edgeTerminal) labels.  In Mermaid's DOM structure, the terminal label foreignObject is a
    // direct child of the edgeTerminals group (no centering offset), so its CSS-styled width
    // (text.len() * 9 px) adds to the right edge of the bounding box.  We replicate that here
    // so our viewBox width matches the reference.
    //
    // Formula (mirrors Mermaid/browser getBBox result):
    //   content_right = max over all terminal labels of (terminal_cx + style_w_px)
    //   content_left  = marginx (leftmost node left edge ≈ marginx after dagre translate)
    //   viewBox_width = max(graph_w_dagre, content_right + marginx)
    let margin_x = 8.0_f64;
    let mut max_terminal_right: f64 = 0.0;
    if use_foreign_object {
        let terminal_marker_size: f64 = 10.0;
        for (i, rel) in diag.relations.iter().enumerate() {
            let edge_key = format!("e{}", i);
            let e = dagre_dgl_rs::graph::Edge::named(&rel.id1, &rel.id2, &edge_key);
            if let Some(lbl_data) = g.edge(&e) {
                let pts = lbl_data.points.clone().unwrap_or_default();
                if pts.len() >= 2 {
                    if !rel.title1.is_empty() {
                        let (cx, _) = calc_terminal_label_position(
                            terminal_marker_size,
                            TerminalPos::StartRight,
                            &pts,
                        );
                        let style_w = (rel.title1.len() * 9) as f64;
                        max_terminal_right = max_terminal_right.max(cx + style_w);
                    }
                    if !rel.title2.is_empty() {
                        let (cx, _) = calc_terminal_label_position(
                            terminal_marker_size,
                            TerminalPos::EndLeft,
                            &pts,
                        );
                        let style_w = (rel.title2.len() * 9) as f64;
                        max_terminal_right = max_terminal_right.max(cx + style_w);
                    }
                }
            }
        }
    }
    let graph_w = f64::max(graph_w_dagre, max_terminal_right + margin_x);

    let svg_id = "mermaid-svg";
    let css = build_css(svg_id, vars);

    let mut out = String::new();

    out.push_str(&svg_root(svg_id, &fmt(graph_w), &fmt(graph_h)));

    out.push_str("<style>");
    out.push_str(&css);
    out.push_str("</style>");

    out.push_str("<g>");
    out.push_str(&build_markers(svg_id));
    out.push_str("</g>");

    out.push_str(r#"<g class="root">"#);

    // clusters (none for basic class diagrams)
    out.push_str(r#"<g class="clusters"></g>"#);

    // edgePaths
    out.push_str(r#"<g class="edgePaths">"#);
    for (i, rel) in diag.relations.iter().enumerate() {
        let edge_key = format!("e{}", i);
        let e = dagre_dgl_rs::graph::Edge::named(&rel.id1, &rel.id2, &edge_key);
        if let Some(lbl) = g.edge(&e) {
            let pts = lbl.points.clone().unwrap_or_default();
            if pts.len() >= 2 {
                let edge_id = format!("{}-id_{}_{}_{}", svg_id, rel.id1, rel.id2, i + 1);
                let pts = trim_end(
                    &trim_start(&pts, start_trim(&rel.start)),
                    end_trim(&rel.end),
                );
                let path_d = edge_path(&pts);
                let is_dashed = rel.line_style == LineStyle::Dashed;
                let classes = if is_dashed {
                    " edge-thickness-normal edge-pattern-dashed relation"
                } else {
                    " edge-thickness-normal edge-pattern-solid relation"
                };
                let marker_start = marker_start_attr(svg_id, rel);
                let marker_end = marker_end_attr(svg_id, rel);
                out.push_str(&tmpl::edge_path(
                    &path_d,
                    &edge_id,
                    classes,
                    &marker_start,
                    &marker_end,
                ));
            }
        }
    }
    out.push_str("</g>");

    // edgeLabels
    out.push_str(r#"<g class="edgeLabels">"#);
    for (i, rel) in diag.relations.iter().enumerate() {
        let edge_key = format!("e{}", i);
        let e = dagre_dgl_rs::graph::Edge::named(&rel.id1, &rel.id2, &edge_key);
        if let Some(lbl_data) = g.edge(&e) {
            let pts = lbl_data.points.clone().unwrap_or_default();
            let edge_id = format!("{}-id_{}_{}_{}", svg_id, rel.id1, rel.id2, i + 1);
            if !rel.title.is_empty() {
                let mid = midpoint(&pts);
                let (raw_fo_w, _) = measure(&rel.title, TITLE_FONT_SIZE);
                let fo_w = raw_fo_w * CONTENT_SCALE;
                if use_foreign_object {
                    out.push_str(&edge_label_fo(
                        &fmt(mid.0),
                        &fmt(mid.1),
                        &edge_id,
                        &fmt(-fo_w / 2.0),
                        &fmt(fo_w),
                        &esc(&rel.title),
                    ));
                } else {
                    out.push_str(&edge_label_text(
                        &fmt(mid.0),
                        &fmt(mid.1),
                        &fmt(-fo_w / 2.0),
                        &fmt(fo_w),
                        vars.primary_color,
                        vars.font_family,
                        &esc(&rel.title),
                    ));
                }
            } else {
                out.push_str(&edge_label_empty(&edge_id));
            }

            // Render start/end cardinality labels (title1 = near id1, title2 = near id2)
            // Faithfully ports Mermaid's calcTerminalLabelPosition algorithm from utils.ts
            // and positionEdgeLabel from edges.js:
            //   title1 → 'start_right' position (left of edge near source)
            //   title2 → 'end_left'   position (right of edge near target)
            if use_foreign_object {
                // terminalMarkerSize: Mermaid passes `edge.arrowTypeStart ? 10 : 0`.
                // In Mermaid class-diagram rendering the arrowType strings are always set
                // (e.g. 'none', 'dependencyEnd', etc.) so arrowTypeStart/End are always
                // truthy JS strings — both terminals always receive terminalMarkerSize = 10.
                let terminal_marker_size: f64 = 10.0;

                let render_card_label = |text: &str, cx: f64, cy: f64| -> String {
                    // CSS `.edgeTerminals{font-size:11px}` — measure at 11px with TERMINAL_SCALE
                    let (fw_raw, _) = measure(text, 11.0);
                    let fw = fw_raw * TERMINAL_SCALE;
                    let style_w = text.len() * 9;
                    terminal_label_fo(&fmt(cx), &fmt(cy), &fmt(fw), style_w, &esc(text))
                };

                if !rel.title1.is_empty() && pts.len() >= 2 {
                    // title1 near source → 'start_right' position
                    let (cx, cy) = calc_terminal_label_position(
                        terminal_marker_size,
                        TerminalPos::StartRight,
                        &pts,
                    );
                    out.push_str(&render_card_label(&rel.title1, cx, cy));
                }
                if !rel.title2.is_empty() && pts.len() >= 2 {
                    // title2 near target → 'end_left' position
                    // Apply render-time offset (+10x, +3y) so wider labels clear the edge line.
                    // This does NOT affect layout calculation (done separately above).
                    let (cx, cy) = calc_terminal_label_position(
                        terminal_marker_size,
                        TerminalPos::EndLeft,
                        &pts,
                    );
                    out.push_str(&render_card_label(&rel.title2, cx + 0.0, cy + 7.0));
                }
            }
        }
    }
    out.push_str("</g>");

    // nodes
    out.push_str(r#"<g class="nodes">"#);
    for (class_idx, id) in diag.class_order.iter().enumerate() {
        if let Some(cls) = diag.classes.get(id) {
            if let Some(n) = g.node_opt(id) {
                let cx = n.x.unwrap_or(0.0);
                let cy = n.y.unwrap_or(0.0);
                let w = n.width;
                let h = n.height;
                let dom_id = format!("{}-classId-{}-{}", svg_id, id, class_idx);
                out.push_str(&render_class_node(
                    cls,
                    cx,
                    cy,
                    w,
                    h,
                    vars,
                    &dom_id,
                    use_foreign_object,
                ));
            }
        }
    }
    out.push_str("</g>");

    out.push_str("</g>"); // root

    out.push_str(&drop_shadow_filter(svg_id));
    out.push_str(&drop_shadow_filter_small(svg_id));

    out.push_str("</svg>");
    out
}

// ─── Class box sizing ─────────────────────────────────────────────────────────

/// Returns the height of a non-empty section (n > 0 guaranteed).
/// Mermaid: (n+1)*24px per section when rows > 0.
fn section_h_nonzero(rows: usize) -> f64 {
    (rows as f64 + 1.0) * MEMBER_ROW_H
}

/// Compute the total width and height of a class box.
///
/// Width formula mirrors Mermaid's DOM-based layout (classBox.ts / textHelper):
///   • Annotation and label groups are **centred** at x=0.
///   • Member and method groups are **left-aligned** starting at x=0.
///   • After layout the shapeSvg bbox spans:
///       x_min = −max(ann_w, name_w) / 2
///       x_max = max(max(ann_w, name_w)/2, max_content_w)
///       bbox_w = x_max − x_min
///   • The enclosing rectangle adds H_PAD on each side:
///       hw = bbox_w / 2 + H_PAD   →   full_w = bbox_w + 2*H_PAD
fn class_box_size(cls: &ClassNode) -> (f64, f64) {
    // ── Centred items: class name + annotations ──────────────────────────────
    // Apply NAME_SCALE to the bold class name and CONTENT_SCALE to italic annotations,
    // matching browser foreignObject rendering widths derived from reference SVGs.
    let (raw_name_w, _) = measure(&cls.label, FONT_SIZE);
    let name_w = raw_name_w * NAME_SCALE;

    let mut max_centred_w: f64 = name_w;
    for ann in &cls.annotations {
        // Use actual guillemet characters (U+00AB, U+00BB) that Mermaid displays —
        // these are narrower than ASCII "<<>>" and match the reference foreignObject widths.
        // Measure with actual Unicode chars; render with HTML entities to avoid encoding issues.
        let (raw_w, _) = measure(&format!("\u{00AB}{}\u{00BB}", ann), FONT_SIZE);
        max_centred_w = max_centred_w.max(raw_w * CONTENT_SCALE);
    }

    // ── Left-aligned items: members + methods ────────────────────────────────
    // Apply CONTENT_SCALE to regular text (member/method display strings).
    let mut max_content_w: f64 = 0.0;
    for m in &cls.members {
        let (raw_w, _) = measure(&m.display_text(), FONT_SIZE);
        max_content_w = max_content_w.max(raw_w * CONTENT_SCALE);
    }
    for m in &cls.methods {
        let (raw_w, _) = measure(&m.display_text(), FONT_SIZE);
        max_content_w = max_content_w.max(raw_w * CONTENT_SCALE);
    }

    // ── shapeSvg bbox width ──────────────────────────────────────────────────
    let half_centred = max_centred_w / 2.0;
    let x_max = f64::max(half_centred, max_content_w);
    let bbox_w = x_max + half_centred; // x_max − (−half_centred)

    // ── Full box width = bbox_w + 2*H_PAD, with a minimum ───────────────────
    let w = (bbox_w + H_PAD * 2.0).max(MIN_BOX_W);

    // ── Height ───────────────────────────────────────────────────────────────
    //   annotations:      ann_rows * 24
    //   header:           48  (always)
    //   members section:  section_h(member_rows)  — 18 if empty, (n+1)*24 if non-empty
    //   methods section:  section_h(method_rows)
    //
    // Mermaid DOM observation: when annotations are present and the members section
    // is empty, the classBox.ts bounding-box calculation produces an extra 6px for
    // the empty members section (24 instead of 18) AND an extra 6px in the methods
    // section when methods are non-empty.  Together this adds 12px in that case.
    let ann_rows = cls.annotations.len();
    let member_rows = cls.members.len();
    let method_rows = cls.methods.len();

    // Section heights — derived from Mermaid classBox.ts DOM measurements.
    // When one section is empty and the other is not, Mermaid's GAP/2=6px floor on
    // membersGroupHeight shifts the layout, producing section sizes of 24px (not 18).
    //   (m=0, me=0): members=18, methods=18
    //   (m>0, me=0): members=(m+1)*24, methods=24       ← methods floor = 24
    //   (m=0, me>0): members=24, methods=(me+1)*24 + 6  ← members floor=24; +6 shift
    //   (m>0, me>0): members=(m+1)*24, methods=(me+1)*24
    let (members_h, methods_h) = match (member_rows, method_rows) {
        (0, 0) => (EMPTY_SECTION_H, EMPTY_SECTION_H),
        (m, 0) => (section_h_nonzero(m), MEMBER_ROW_H),
        (0, me) => (MEMBER_ROW_H, section_h_nonzero(me) + 6.0),
        (m, me) => (section_h_nonzero(m), section_h_nonzero(me)),
    };

    let h = ann_rows as f64 * ANNOTATION_H + HEADER_H + members_h + methods_h;

    (w, h)
}

// ─── Node rendering ───────────────────────────────────────────────────────────

#[allow(clippy::too_many_arguments)]
fn render_class_node(
    cls: &ClassNode,
    cx: f64,
    cy: f64,
    w: f64,
    h: f64,
    vars: &ThemeVars,
    dom_id: &str,
    use_foreign_object: bool,
) -> String {
    let hw = w / 2.0;
    let hh = h / 2.0;
    let pb = vars.primary_border;
    let pf = vars.primary_color;

    let mut s = String::new();
    s.push_str(&format!(
        r#"<g class="node default " id="{did}" data-look="classic" transform="translate({cx}, {cy})">"#,
        did = dom_id, cx = fmt(cx), cy = fmt(cy),
    ));

    // Outer rectangle (filled, no stroke for shadow layer)
    s.push_str(&format!(
        r#"<g class="basic label-container outer-path"><path d="M{x1} {y1} L{x2} {y1} L{x2} {y2} L{x1} {y2}" stroke="none" stroke-width="0" fill="{pf}" style=""></path>"#,
        x1 = fmt(-hw), y1 = fmt(-hh), x2 = fmt(hw), y2 = fmt(hh), pf = pf,
    ));
    // Sketchy border path (matches Mermaid neo-classic look)
    s.push_str(&format!(
        r#"<path d="M{x1} {y1} C{cx1} {y1},{cx2} {y1},{x2} {y1} M{x2} {y1} C{x2} {cy1},{x2} {cy2},{x2} {y2} M{x2} {y2} C{cx3} {y2},{cx4} {y2},{x1} {y2} M{x1} {y2} C{x1} {cy3},{x1} {cy4},{x1} {y1}" stroke="{pb}" stroke-width="1.3" fill="none" stroke-dasharray="0 0" style=""></path></g>"#,
        x1 = fmt(-hw), y1 = fmt(-hh), x2 = fmt(hw), y2 = fmt(hh),
        cx1 = fmt(-hw * 0.6), cx2 = fmt(hw * 0.4),
        cx3 = fmt(hw * 0.5), cx4 = fmt(-hw * 0.2),
        cy1 = fmt(-hh * 0.6), cy2 = fmt(hh * 0.5),
        cy3 = fmt(hh * 0.5), cy4 = fmt(-hh * 0.1),
        pb = pb,
    ));

    // Y layout (all positions relative to node centre = 0, box spans -hh to +hh):
    //
    //   -hh ───────────────────── box top
    //        ann_rows * 24        annotation rows
    //   div1 ──────────────────── members divider  (= -hh + ann*24 + 48)
    //        section_h(members)   member rows       (0 rows → 18, n rows → (n+1)*24)
    //   div2 ──────────────────── methods divider  (= div1 + section_h(members))
    //        section_h(methods)   method rows
    //   +hh ───────────────────── box bottom
    //
    // Group positions:
    //   annotation_group_y = -hh (box top; row i centred at -hh + i*24 + 12)
    //   label_group_y = -hh + ann*24 + HEADER_H/2 (= centre of header section)
    //   members_group_y = div1 + MEMBER_ROW_H (first row centred at group_y + 0)
    //   methods_group_y = div2 + MEMBER_ROW_H (first row centred at group_y + 0)

    let ann_rows = cls.annotations.len();
    let member_rows = cls.members.len();

    let method_rows = cls.methods.len();

    let ann_top_y = -hh;
    let div1_y = ann_top_y + ann_rows as f64 * ANNOTATION_H + HEADER_H;

    // Members section height — must match class_box_size() exactly.
    let members_section_h = match (member_rows, method_rows) {
        (0, 0) => EMPTY_SECTION_H,
        (0, _) => MEMBER_ROW_H, // floor = 24
        (m, _) => section_h_nonzero(m),
    };
    let div2_y = div1_y + members_section_h;

    // ── Annotation group ────────────────────────────────────────────────────────
    // Vertically center the annotation+class_name block within the combined region.
    // region_h = ann_rows*24 + HEADER_H; content_h = (ann_rows+1)*24 (each row 24px).
    // vert_pad = (region_h - content_h) / 2  →  offsets annotation away from box top.
    let region_h = ann_rows as f64 * ANNOTATION_H + HEADER_H;
    let content_h = (ann_rows as f64 + 1.0) * ANNOTATION_H;
    let vert_pad = (region_h - content_h) / 2.0;
    let ann_group_y = if ann_rows > 0 {
        ann_top_y + vert_pad
    } else {
        ann_top_y + ann_rows as f64 * ANNOTATION_H + HEADER_H / 2.0
    };
    s.push_str(&format!(
        r#"<g class="annotation-group text" transform="translate(0, {})">"#,
        fmt(ann_group_y),
    ));
    for (i, ann) in cls.annotations.iter().enumerate() {
        // Row i centre is at ann_top_y + i*24 + 12 (absolute).
        // Relative to ann_group_y (= ann_top_y): offset = i*24 + 12.
        let ann_text = format!("&laquo;{}&raquo;", esc(ann));
        let row_centre_rel = i as f64 * ANNOTATION_H + ANNOTATION_H / 2.0;
        let (raw_ann_w, _) = measure(&format!("\u{00AB}{}\u{00BB}", ann), FONT_SIZE);
        let ann_w = raw_ann_w * CONTENT_SCALE;
        if use_foreign_object {
            s.push_str(&format!(
                r#"<g class="label" style="font-style: italic" transform="translate({ox}, {y})"><foreignObject width="{fw}" height="24"><div xmlns="http://www.w3.org/1999/xhtml" style="display: table-cell; white-space: nowrap; line-height: 1.5; max-width: 200px; text-align: center;"><span class="nodeLabel markdown-node-label" style=""><p>{text}</p></span></div></foreignObject></g>"#,
                ox = fmt(-ann_w / 2.0),
                y  = fmt(row_centre_rel - ANNOTATION_H / 2.0),
                fw = fmt(ann_w),
                text = ann_text,
            ));
        } else {
            s.push_str(&format!(
                r#"<text x="0" y="{y}" text-anchor="middle" font-family="Arial,sans-serif" font-size="{fs}" fill="{pb}" font-style="italic">{text}</text>"#,
                y = fmt(row_centre_rel), fs = FONT_SIZE, pb = pb, text = ann_text,
            ));
        }
    }
    s.push_str("</g>");

    // ── Label group (class name) ─────────────────────────────────────────────────
    // Centred vertically in the header section.
    // header section runs from (ann_top_y + ann*24) to div1.
    // Centre of header = ann_top_y + ann*24 + HEADER_H/2.
    let header_centre_y = ann_top_y + ann_rows as f64 * ANNOTATION_H + HEADER_H / 2.0;
    let (raw_name_fo_w, _) = measure(&cls.label, TITLE_FONT_SIZE);
    let name_fo_w = raw_name_fo_w * NAME_SCALE;
    s.push_str(&format!(
        r#"<g class="label-group text" transform="translate({ox}, {gy})">"#,
        ox = fmt(-name_fo_w / 2.0),
        gy = fmt(header_centre_y),
    ));
    if use_foreign_object {
        s.push_str(&format!(
            r#"<g class="label" style="font-weight: bolder" transform="translate(0,-12)"><foreignObject width="{fw}" height="24"><div xmlns="http://www.w3.org/1999/xhtml" style="display: table-cell; white-space: nowrap; line-height: 1.5; max-width: 100px; text-align: center;"><span class="nodeLabel markdown-node-label" style=""><p>{text}</p></span></div></foreignObject></g>"#,
            fw = fmt(name_fo_w),
            text = esc(&cls.label),
        ));
    } else {
        s.push_str(&format!(
            r#"<text x="{hw}" y="5" text-anchor="middle" font-family="Arial,sans-serif" font-size="{fs}" fill="{pb}" font-weight="bold">{text}</text>"#,
            hw = fmt(name_fo_w / 2.0), fs = TITLE_FONT_SIZE, pb = pb,
            text = esc(&cls.label),
        ));
    }
    s.push_str("</g>");

    // ── Members group ────────────────────────────────────────────────────────────
    // members_group_y is the y of the group; row i centre = group_y + i*24.
    // First row centre = div1 + MEMBER_ROW_H (one full row-height below divider).
    let members_group_y = div1_y + MEMBER_ROW_H;
    s.push_str(&format!(
        r#"<g class="members-group text" transform="translate({ox}, {gy})">"#,
        ox = fmt(-hw + H_PAD),
        gy = fmt(members_group_y),
    ));
    for (i, m) in cls.members.iter().enumerate() {
        let text = m.display_text();
        let (raw_mem_w, _) = measure(&text, FONT_SIZE);
        let mem_fo_w = raw_mem_w * CONTENT_SCALE;
        // Row i centre at group_y + i*24; FO starts 12 above centre.
        let row_y = i as f64 * MEMBER_ROW_H;
        if use_foreign_object {
            s.push_str(&format!(
                r#"<g class="label" style="" transform="translate(0,{y})"><foreignObject width="{fw}" height="24"><div xmlns="http://www.w3.org/1999/xhtml" style="display: table-cell; white-space: nowrap; line-height: 1.5; max-width: 150px; text-align: center;"><span class="nodeLabel markdown-node-label" style=""><p>{text}</p></span></div></foreignObject></g>"#,
                y = fmt(row_y - 12.0),
                fw = fmt(mem_fo_w),
                text = esc(&text),
            ));
        } else {
            s.push_str(&format!(
                r#"<text x="0" y="{y}" font-family="Arial,sans-serif" font-size="{fs}" fill="{pb}">{text}</text>"#,
                y = fmt(row_y), fs = FONT_SIZE, pb = pb, text = esc(&text),
            ));
        }
    }
    s.push_str("</g>");

    // ── Methods group ─────────────────────────────────────────────────────────────
    let methods_group_y = div2_y + MEMBER_ROW_H;
    s.push_str(&format!(
        r#"<g class="methods-group text" transform="translate({ox}, {gy})">"#,
        ox = fmt(-hw + H_PAD),
        gy = fmt(methods_group_y),
    ));
    for (i, m) in cls.methods.iter().enumerate() {
        let text = m.display_text();
        let (raw_meth_w, _) = measure(&text, FONT_SIZE);
        let meth_fo_w = raw_meth_w * CONTENT_SCALE;
        let row_y = i as f64 * MEMBER_ROW_H;
        if use_foreign_object {
            s.push_str(&format!(
                r#"<g class="label" style="" transform="translate(0,{y})"><foreignObject width="{fw}" height="24"><div xmlns="http://www.w3.org/1999/xhtml" style="display: table-cell; white-space: nowrap; line-height: 1.5; max-width: 200px; text-align: center;"><span class="nodeLabel markdown-node-label" style=""><p>{text}</p></span></div></foreignObject></g>"#,
                y = fmt(row_y - 12.0),
                fw = fmt(meth_fo_w),
                text = esc(&text),
            ));
        } else {
            s.push_str(&format!(
                r#"<text x="0" y="{y}" font-family="Arial,sans-serif" font-size="{fs}" fill="{pb}">{text}</text>"#,
                y = fmt(row_y), fs = FONT_SIZE, pb = pb, text = esc(&text),
            ));
        }
    }
    s.push_str("</g>");

    // ── Dividers ──────────────────────────────────────────────────────────────────
    // div1: between header and members section
    s.push_str(&format!(
        r#"<g class="divider" style=""><path d="M{x1} {y} C{cx1} {y},{cx2} {y},{x2} {y}" stroke="{pb}" stroke-width="1.3" fill="none" stroke-dasharray="0 0" style=""></path></g>"#,
        x1 = fmt(-hw), y = fmt(div1_y),
        cx1 = fmt(-hw * 0.4), cx2 = fmt(hw * 0.4),
        x2 = fmt(hw), pb = pb,
    ));
    // div2: between members and methods section
    s.push_str(&format!(
        r#"<g class="divider" style=""><path d="M{x1} {y} C{cx1} {y},{cx2} {y},{x2} {y}" stroke="{pb}" stroke-width="1.3" fill="none" stroke-dasharray="0 0" style=""></path></g>"#,
        x1 = fmt(-hw), y = fmt(div2_y),
        cx1 = fmt(-hw * 0.4), cx2 = fmt(hw * 0.4),
        x2 = fmt(hw), pb = pb,
    ));

    s.push_str("</g>"); // node
    s
}

// ─── Marker helpers ───────────────────────────────────────────────────────────

fn marker_start_attr(svg_id: &str, rel: &ClassRelation) -> String {
    match &rel.start {
        EndType::None => String::new(),
        EndType::Extension => format!(r#" marker-start="url(#{}_class-extensionStart)""#, svg_id),
        EndType::Composition => {
            format!(r#" marker-start="url(#{}_class-compositionStart)""#, svg_id)
        }
        EndType::Aggregation => {
            format!(r#" marker-start="url(#{}_class-aggregationStart)""#, svg_id)
        }
        EndType::Arrow => format!(r#" marker-start="url(#{}_class-dependencyStart)""#, svg_id),
    }
}

fn marker_end_attr(svg_id: &str, rel: &ClassRelation) -> String {
    match &rel.end {
        EndType::None => String::new(),
        EndType::Extension => format!(r#" marker-end="url(#{}_class-extensionEnd)""#, svg_id),
        EndType::Composition => format!(r#" marker-end="url(#{}_class-compositionEnd)""#, svg_id),
        EndType::Aggregation => format!(r#" marker-end="url(#{}_class-aggregationEnd)""#, svg_id),
        EndType::Arrow => format!(r#" marker-end="url(#{}_class-dependencyEnd)""#, svg_id),
    }
}

// ─── Edge path ────────────────────────────────────────────────────────────────

/// Arrowhead overhang = (tip_x - refX) for each End marker type.
/// The dagre edge endpoint lands on the node boundary; trimming pulls it back
/// so the arrowhead tip touches the boundary instead of being buried inside.
fn end_trim(end: &EndType) -> f64 {
    match end {
        EndType::Extension | EndType::Composition | EndType::Aggregation => 17.0,
        EndType::Arrow => 8.0,
        EndType::None => 0.0,
    }
}

fn start_trim(start: &EndType) -> f64 {
    match start {
        EndType::Extension | EndType::Composition | EndType::Aggregation => 17.0,
        EndType::Arrow => 8.0,
        EndType::None => 0.0,
    }
}

/// Trim `amount` units off the END of the last segment (toward source).
fn trim_end(pts: &[Point], amount: f64) -> Vec<Point> {
    if amount <= 0.0 || pts.len() < 2 {
        return pts.to_vec();
    }
    let mut result = pts.to_vec();
    let n = result.len();
    let last = result[n - 1].clone();
    let prev = result[n - 2].clone();
    let dx = last.x - prev.x;
    let dy = last.y - prev.y;
    let len = (dx * dx + dy * dy).sqrt();
    if len <= amount {
        result.truncate(n - 1);
    } else {
        let frac = (len - amount) / len;
        result[n - 1] = Point {
            x: prev.x + dx * frac,
            y: prev.y + dy * frac,
        };
    }
    result
}

/// Trim `amount` units off the START of the first segment (toward target).
fn trim_start(pts: &[Point], amount: f64) -> Vec<Point> {
    if amount <= 0.0 || pts.len() < 2 {
        return pts.to_vec();
    }
    let mut result = pts.to_vec();
    let first = result[0].clone();
    let next = result[1].clone();
    let dx = next.x - first.x;
    let dy = next.y - first.y;
    let len = (dx * dx + dy * dy).sqrt();
    if len <= amount {
        result.remove(0);
    } else {
        let frac = amount / len;
        result[0] = Point {
            x: first.x + dx * frac,
            y: first.y + dy * frac,
        };
    }
    result
}

fn edge_path(pts: &[Point]) -> String {
    let pairs: Vec<(f64, f64)> = pts.iter().map(|p| (p.x, p.y)).collect();
    crate::svg::curve_basis_path(&pairs)
}

fn midpoint(pts: &[Point]) -> (f64, f64) {
    if pts.is_empty() {
        return (0.0, 0.0);
    }
    let mid = pts.len() / 2;
    (pts[mid].x, pts[mid].y)
}

// ─── Terminal label positioning — faithful port of Mermaid utils.ts ──────────
//
// Mermaid uses calcTerminalLabelPosition(terminalMarkerSize, position, points)
// from packages/mermaid/src/utils.ts via positionEdgeLabel in edges.js.
//
// title1 (near source) → position 'start_right'
// title2 (near target) → position 'end_left'
//
// terminalMarkerSize = 10 when an arrow marker is present, 0 otherwise.

#[derive(Clone, Copy)]
enum TerminalPos {
    StartRight,
    EndLeft,
}

/// Port of utils.calcTerminalLabelPosition.
/// Returns (x, y) for the outer group transform of the terminal label.
fn calc_terminal_label_position(
    terminal_marker_size: f64,
    position: TerminalPos,
    points: &[Point],
) -> (f64, f64) {
    // For end positions, reverse the point list so we always traverse from source.
    let fwd: Vec<(f64, f64)> = points.iter().map(|p| (p.x, p.y)).collect();
    let rev: Vec<(f64, f64)> = fwd.iter().cloned().rev().collect();
    let pts_owned: Vec<(f64, f64)> = match position {
        TerminalPos::StartRight => fwd,
        TerminalPos::EndLeft => rev,
    };
    let pts_ref: &[(f64, f64)] = &pts_owned;

    let distance_to_cardinality_point = 25.0 + terminal_marker_size;
    // We need calculatePoint over Point slices — use a helper that accepts (f64,f64) tuples.
    let center = {
        let mut prev: Option<(f64, f64)> = None;
        let mut remaining = distance_to_cardinality_point;
        let mut result = pts_ref[pts_ref.len() - 1];
        for &p in pts_ref {
            if let Some(prev_p) = prev {
                let dx = p.0 - prev_p.0;
                let dy = p.1 - prev_p.1;
                let seg_len = (dx * dx + dy * dy).sqrt();
                if seg_len == 0.0 {
                    prev = Some(p);
                    continue;
                }
                if seg_len < remaining {
                    remaining -= seg_len;
                } else {
                    let ratio = remaining / seg_len;
                    result = (
                        (1.0 - ratio) * prev_p.0 + ratio * p.0,
                        (1.0 - ratio) * prev_p.1 + ratio * p.1,
                    );
                    break;
                }
            }
            prev = Some(p);
        }
        result
    };

    let d = 10.0 + terminal_marker_size * 0.5;
    let p0 = pts_ref[0];
    let angle = f64::atan2(p0.1 - center.1, p0.0 - center.0);

    let (x, y) = match position {
        TerminalPos::StartRight => {
            // sin(angle)*d + (p0.x + center.x)/2
            // -cos(angle)*d + (p0.y + center.y)/2
            let x = angle.sin() * d + (p0.0 + center.0) / 2.0;
            let y = -angle.cos() * d + (p0.1 + center.1) / 2.0;
            (x, y)
        }
        TerminalPos::EndLeft => {
            // Mermaid source: sin(angle)*d + (p0.x+center.x)/2 - 5
            //                 -cos(angle)*d + (p0.y+center.y)/2 - 5
            let x = angle.sin() * d + (p0.0 + center.0) / 2.0 - 5.0;
            let y = -angle.cos() * d + (p0.1 + center.1) / 2.0 - 5.0;
            (x, y)
        }
    };

    (x, y)
}

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

    const CLASS_BASIC: &str = "classDiagram\n    class Animal {\n        +String name\n        +int age\n        +makeSound() void\n    }\n    class Dog {\n        +String breed\n        +fetch() void\n    }\n    Animal <|-- Dog";

    #[test]
    fn basic_render_produces_svg() {
        let diag = parser::parse(CLASS_BASIC).diagram;
        let svg = render(&diag, Theme::Default, false);
        assert!(svg.contains("<svg"), "missing <svg tag");
        assert!(svg.contains("Animal"), "missing class name");
        assert!(svg.contains("Dog"), "missing class name");
    }

    #[test]
    fn dark_theme() {
        let diag = parser::parse(CLASS_BASIC).diagram;
        let svg = render(&diag, Theme::Dark, false);
        assert!(svg.contains("<svg"), "missing <svg tag");
    }

    #[test]
    fn snapshot_default_theme() {
        let diag = parser::parse(CLASS_BASIC).diagram;
        let svg = render(&diag, crate::theme::Theme::Default, false);
        insta::assert_snapshot!(crate::svg::normalize_floats(&svg));
    }
}