merman-render 0.5.0

Headless layout + SVG renderer for Mermaid (parity-focused; upstream SVG goldens).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
use super::*;

// Mindmap diagram SVG renderer implementation (split from parity.rs).

use crate::svg::parity::roughjs46::roughjs46_solid_fill_paths_for_closed_polyline_path;

fn arc_points(
    x1: f64,
    y1: f64,
    x2: f64,
    y2: f64,
    rx: f64,
    ry: f64,
    clockwise: bool,
) -> Vec<(f64, f64)> {
    // Port of Mermaid `@11.12.2` `generateArcPoints(...)` in
    // `packages/mermaid/src/rendering-util/rendering-elements/shapes/roundedRect.ts`.
    let num_points: usize = 20;

    let mid_x = (x1 + x2) / 2.0;
    let mid_y = (y1 + y2) / 2.0;
    let angle = (y2 - y1).atan2(x2 - x1);

    let dx = (x2 - x1) / 2.0;
    let dy = (y2 - y1) / 2.0;
    let transformed_x = dx / rx;
    let transformed_y = dy / ry;
    let distance = (transformed_x * transformed_x + transformed_y * transformed_y).sqrt();
    if distance > 1.0 {
        return vec![(x1, y1), (x2, y2)];
    }

    let scaled_center_distance = (1.0 - distance * distance).sqrt();
    let sign = if clockwise { -1.0 } else { 1.0 };
    let center_x = mid_x + scaled_center_distance * ry * angle.sin() * sign;
    let center_y = mid_y - scaled_center_distance * rx * angle.cos() * sign;

    let start_angle = ((y1 - center_y) / ry).atan2((x1 - center_x) / rx);
    let end_angle = ((y2 - center_y) / ry).atan2((x2 - center_x) / rx);

    let mut angle_range = end_angle - start_angle;
    if clockwise && angle_range < 0.0 {
        angle_range += 2.0 * std::f64::consts::PI;
    }
    if !clockwise && angle_range > 0.0 {
        angle_range -= 2.0 * std::f64::consts::PI;
    }

    let mut points: Vec<(f64, f64)> = Vec::with_capacity(num_points);
    for i in 0..num_points {
        let t = i as f64 / (num_points - 1) as f64;
        let a = start_angle + t * angle_range;
        let x = center_x + rx * a.cos();
        let y = center_y + ry * a.sin();
        points.push((x, y));
    }
    points
}

fn rounded_rect_points(w: f64, h: f64) -> Vec<(f64, f64)> {
    // Mermaid mindmapRenderer overrides rounded nodes with `radius=15` and `taper=15` before
    // rendering (`diagrams/mindmap/mindmapRenderer.ts`).
    let radius = 15.0;
    let taper = 15.0;

    let mut pts: Vec<(f64, f64)> = Vec::new();
    pts.push((-w / 2.0 + taper, -h / 2.0));
    pts.push((w / 2.0 - taper, -h / 2.0));
    pts.extend(arc_points(
        w / 2.0 - taper,
        -h / 2.0,
        w / 2.0,
        -h / 2.0 + taper,
        radius,
        radius,
        true,
    ));
    pts.push((w / 2.0, -h / 2.0 + taper));
    pts.push((w / 2.0, h / 2.0 - taper));
    pts.extend(arc_points(
        w / 2.0,
        h / 2.0 - taper,
        w / 2.0 - taper,
        h / 2.0,
        radius,
        radius,
        true,
    ));
    pts.push((w / 2.0 - taper, h / 2.0));
    pts.push((-w / 2.0 + taper, h / 2.0));
    pts.extend(arc_points(
        -w / 2.0 + taper,
        h / 2.0,
        -w / 2.0,
        h / 2.0 - taper,
        radius,
        radius,
        true,
    ));
    pts.push((-w / 2.0, h / 2.0 - taper));
    pts.push((-w / 2.0, -h / 2.0 + taper));
    pts.extend(arc_points(
        -w / 2.0,
        -h / 2.0 + taper,
        -w / 2.0 + taper,
        -h / 2.0,
        radius,
        radius,
        true,
    ));
    pts
}

#[derive(Debug, Clone, Copy)]
enum MindmapPathNumberFormat {
    D3Path,
    JsNumber,
}

fn mindmap_path_number(v: f64, number_format: MindmapPathNumberFormat) -> String {
    match number_format {
        MindmapPathNumberFormat::D3Path => fmt_path(v),
        MindmapPathNumberFormat::JsNumber => fmt_string(v),
    }
}

fn mindmap_cloud_path_d(w: f64, h: f64, number_format: MindmapPathNumberFormat) -> String {
    let r1 = 0.15 * w;
    let r2 = 0.25 * w;
    let r3 = 0.35 * w;
    let r4 = 0.2 * w;
    let n = |v| mindmap_path_number(v, number_format);

    format!(
        "M0 0 a{r1},{r1} 0 0,1 {w25},{wn10} a{r3},{r3} 1 0,1 {w40},{wn10} a{r2},{r2} 1 0,1 {w35},{w20} a{r1},{r1} 1 0,1 {w15},{h35} a{r4},{r4} 1 0,1 {wn15},{h65} a{r2},{r1} 1 0,1 {wn25},{w15} a{r3},{r3} 1 0,1 {wn50},0 a{r1},{r1} 1 0,1 {wn25},{wn15} a{r1},{r1} 1 0,1 {wn10},{hn35} a{r4},{r4} 1 0,1 {w10},{hn65} H0 V0 Z",
        r1 = n(r1),
        r2 = n(r2),
        r3 = n(r3),
        r4 = n(r4),
        w25 = n(w * 0.25),
        w40 = n(w * 0.4),
        w35 = n(w * 0.35),
        w20 = n(w * 0.2),
        w15 = n(w * 0.15),
        w10 = n(w * 0.1),
        wn10 = n(-w * 0.1),
        wn15 = n(-w * 0.15),
        wn25 = n(-w * 0.25),
        wn50 = n(-w * 0.5),
        h35 = n(h * 0.35),
        h65 = n(h * 0.65),
        hn35 = n(-h * 0.35),
        hn65 = n(-h * 0.65),
    )
}

pub(super) fn mindmap_cloud_rendered_bbox_size_px(w: f64, h: f64) -> Option<(f64, f64)> {
    let d = mindmap_cloud_path_d(w, h, MindmapPathNumberFormat::JsNumber);
    let pb = svg_path_bounds_from_d(&d)?;
    Some((pb.max_x - pb.min_x, pb.max_y - pb.min_y))
}

fn mindmap_bang_path_d(
    w_base: f64,
    effective_w: f64,
    effective_h: f64,
    number_format: MindmapPathNumberFormat,
) -> String {
    let r = 0.15 * w_base;
    let n = |v| mindmap_path_number(v, number_format);

    format!(
        "M0 0 a{r},{r} 1 0,0 {w25},{hn10} a{r},{r} 1 0,0 {w25},0 a{r},{r} 1 0,0 {w25},0 a{r},{r} 1 0,0 {w25},{h10} a{r},{r} 1 0,0 {w15},{h33} a{r08},{r08} 1 0,0 0,{h34} a{r},{r} 1 0,0 {wn15},{h33} a{r},{r} 1 0,0 {wn25},{h15} a{r},{r} 1 0,0 {wn25},0 a{r},{r} 1 0,0 {wn25},0 a{r},{r} 1 0,0 {wn25},{hn15} a{r},{r} 1 0,0 {wn10},{hn33} a{r08},{r08} 1 0,0 0,{hn34} a{r},{r} 1 0,0 {w10},{hn33} H0 V0 Z",
        r = n(r),
        r08 = n(r * 0.8),
        w25 = n(effective_w * 0.25),
        w15 = n(effective_w * 0.15),
        w10 = n(effective_w * 0.1),
        wn10 = n(-effective_w * 0.1),
        wn15 = n(-effective_w * 0.15),
        wn25 = n(-effective_w * 0.25),
        h10 = n(effective_h * 0.1),
        hn10 = n(-effective_h * 0.1),
        h15 = n(effective_h * 0.15),
        hn15 = n(-effective_h * 0.15),
        h33 = n(effective_h * 0.33),
        hn33 = n(-effective_h * 0.33),
        h34 = n(effective_h * 0.34),
        hn34 = n(-effective_h * 0.34),
    )
}

fn include_mindmap_rect_bounds(
    bounds: &mut Option<Bounds>,
    min_x: f64,
    min_y: f64,
    max_x: f64,
    max_y: f64,
) {
    if let Some(cur) = bounds.as_mut() {
        cur.min_x = cur.min_x.min(min_x);
        cur.min_y = cur.min_y.min(min_y);
        cur.max_x = cur.max_x.max(max_x);
        cur.max_y = cur.max_y.max(max_y);
    } else {
        *bounds = Some(Bounds {
            min_x,
            min_y,
            max_x,
            max_y,
        });
    }
}

fn include_mindmap_node_rect_bounds(bounds: &mut Option<Bounds>, n: &LayoutNode) {
    include_mindmap_rect_bounds(
        bounds,
        n.x - n.width / 2.0,
        n.y - n.height / 2.0,
        n.x + n.width / 2.0,
        n.y + n.height / 2.0,
    );
}

fn include_mindmap_path_bounds(
    bounds: &mut Option<Bounds>,
    d: &str,
    translate_x: f64,
    translate_y: f64,
) -> bool {
    let Some(pb) = svg_path_bounds_from_d(d) else {
        return false;
    };
    include_mindmap_rect_bounds(
        bounds,
        pb.min_x + translate_x,
        pb.min_y + translate_y,
        pb.max_x + translate_x,
        pb.max_y + translate_y,
    );
    true
}

fn mindmap_viewport_bounds_from_layout(
    layout: &MindmapDiagramLayout,
    model: &merman_core::diagrams::mindmap::MindmapDiagramRenderModel,
) -> Option<Bounds> {
    let mut layout_nodes: std::collections::BTreeMap<&str, &LayoutNode> =
        std::collections::BTreeMap::new();
    for n in &layout.nodes {
        layout_nodes.insert(n.id.as_str(), n);
    }

    let mut bounds: Option<Bounds> = None;
    for n in &model.nodes {
        let Some(ln) = layout_nodes.get(n.id.as_str()) else {
            continue;
        };

        let padding = n.padding.max(0.0);
        let half_padding = padding / 2.0;
        match n.shape.as_str() {
            "cloud" => {
                let bbox_w = ln
                    .label_width
                    .unwrap_or_else(|| (ln.width - 2.0 * half_padding).max(1.0));
                let bbox_h = ln
                    .label_height
                    .unwrap_or_else(|| (ln.height - 2.0 * half_padding).max(1.0));
                let w = (bbox_w + 2.0 * half_padding).max(1.0);
                let h = (bbox_h + 2.0 * half_padding).max(1.0);
                let d = mindmap_cloud_path_d(w, h, MindmapPathNumberFormat::JsNumber);
                if !include_mindmap_path_bounds(&mut bounds, &d, ln.x - w / 2.0, ln.y - h / 2.0) {
                    include_mindmap_node_rect_bounds(&mut bounds, ln);
                }
                include_mindmap_rect_bounds(
                    &mut bounds,
                    ln.x - bbox_w / 2.0,
                    ln.y - bbox_h / 2.0,
                    ln.x + bbox_w / 2.0,
                    ln.y + bbox_h / 2.0,
                );
            }
            "bang" => {
                let w = ln.width.max(1.0);
                let h = ln.height.max(1.0);
                let bbox_w = ln
                    .label_width
                    .unwrap_or_else(|| (w - 10.0 * half_padding).max(1.0));
                let bbox_h = ln
                    .label_height
                    .unwrap_or_else(|| (h - 8.0 * half_padding).max(1.0));
                let w_base = bbox_w + 10.0 * half_padding;
                let d = mindmap_bang_path_d(w_base, w, h, MindmapPathNumberFormat::JsNumber);
                if !include_mindmap_path_bounds(&mut bounds, &d, ln.x - w / 2.0, ln.y - h / 2.0) {
                    include_mindmap_node_rect_bounds(&mut bounds, ln);
                }
                include_mindmap_rect_bounds(
                    &mut bounds,
                    ln.x - bbox_w / 2.0,
                    ln.y - bbox_h / 2.0,
                    ln.x + bbox_w / 2.0,
                    ln.y + bbox_h / 2.0,
                );
            }
            _ => include_mindmap_node_rect_bounds(&mut bounds, ln),
        }
    }

    for e in &layout.edges {
        for p in &e.points {
            include_mindmap_rect_bounds(&mut bounds, p.x, p.y, p.x, p.y);
        }
    }

    bounds
}

fn mindmap_css(diagram_id: &str, effective_config: &serde_json::Value) -> String {
    // Mirrors Mermaid@11.12.2 `diagrams/mindmap/styles.ts` + shared base stylesheet ordering.
    //
    // Keep `:root` last (matches upstream fixtures).
    let id = escape_xml(diagram_id);
    let parts = info_css_parts_with_config(diagram_id, effective_config);
    let mut out = parts.css_prefix;

    let _ = write!(&mut out, r#"#{} .edge{{stroke-width:3;}}"#, id);

    // Mermaid default theme resolves `cScale0..11` into this fixed palette for mindmap/kanban/timeline.
    // The first generated section is `section--1` (i=0).
    let fills = [
        "hsl(240, 100%, 76.2745098039%)",
        "hsl(60, 100%, 73.5294117647%)",
        "hsl(80, 100%, 76.2745098039%)",
        "hsl(270, 100%, 76.2745098039%)",
        "hsl(300, 100%, 76.2745098039%)",
        "hsl(330, 100%, 76.2745098039%)",
        "hsl(0, 100%, 76.2745098039%)",
        "hsl(30, 100%, 76.2745098039%)",
        "hsl(90, 100%, 76.2745098039%)",
        "hsl(150, 100%, 76.2745098039%)",
        "hsl(180, 100%, 76.2745098039%)",
        "hsl(210, 100%, 76.2745098039%)",
    ];
    let inv_fills = [
        "hsl(60, 100%, 86.2745098039%)",
        "hsl(240, 100%, 83.5294117647%)",
        "hsl(260, 100%, 86.2745098039%)",
        "hsl(90, 100%, 86.2745098039%)",
        "hsl(120, 100%, 86.2745098039%)",
        "hsl(150, 100%, 86.2745098039%)",
        "hsl(180, 100%, 86.2745098039%)",
        "hsl(210, 100%, 86.2745098039%)",
        "hsl(270, 100%, 86.2745098039%)",
        "hsl(330, 100%, 86.2745098039%)",
        "hsl(0, 100%, 86.2745098039%)",
        "hsl(30, 100%, 86.2745098039%)",
    ];

    for (i, (fill, inv)) in fills.iter().zip(inv_fills.iter()).enumerate() {
        let section = i as i64 - 1;
        let label = if i == 0 || i == 3 { "#ffffff" } else { "black" };
        let sw = 17_i64 - 3_i64 * (i as i64);
        let _ = write!(
            &mut out,
            r#"#{} .section-{} rect,#{} .section-{} path,#{} .section-{} circle,#{} .section-{} polygon,#{} .section-{} path{{fill:{};}}"#,
            id, section, id, section, id, section, id, section, id, section, fill
        );
        let _ = write!(
            &mut out,
            r#"#{} .section-{} text{{fill:{};}}"#,
            id, section, label
        );
        let _ = write!(
            &mut out,
            r#"#{} .node-icon-{}{{font-size:40px;color:{};}}"#,
            id, section, label
        );
        let _ = write!(
            &mut out,
            r#"#{} .section-edge-{}{{stroke:{};}}"#,
            id, section, fill
        );
        let _ = write!(
            &mut out,
            r#"#{} .edge-depth-{}{{stroke-width:{};}}"#,
            id, section, sw
        );
        let _ = write!(
            &mut out,
            r#"#{} .section-{} line{{stroke:{};stroke-width:3;}}"#,
            id, section, inv
        );
        let _ = write!(
            &mut out,
            r#"#{} .disabled,#{} .disabled circle,#{} .disabled text{{fill:lightgray;}}#{} .disabled text{{fill:#efefef;}}"#,
            id, id, id, id
        );
    }

    // Root section overrides.
    let _ = write!(
        &mut out,
        r#"#{} .section-root rect,#{} .section-root path,#{} .section-root circle,#{} .section-root polygon{{fill:hsl(240, 100%, 46.2745098039%);}}"#,
        id, id, id, id
    );
    let _ = write!(&mut out, r#"#{} .section-root text{{fill:#ffffff;}}"#, id);
    let _ = write!(&mut out, r#"#{} .section-root span{{color:#ffffff;}}"#, id);
    let _ = write!(&mut out, r#"#{} .section-2 span{{color:#ffffff;}}"#, id);
    let _ = write!(
        &mut out,
        r#"#{} .icon-container{{height:100%;display:flex;justify-content:center;align-items:center;}}"#,
        id
    );
    let _ = write!(&mut out, r#"#{} .edge{{fill:none;}}"#, id);
    let _ = write!(
        &mut out,
        r#"#{} .mindmap-node-label{{dy:1em;alignment-baseline:middle;text-anchor:middle;dominant-baseline:middle;text-align:center;}}"#,
        id
    );

    out.push_str(&parts.root_rule);
    out
}

pub(super) fn render_mindmap_diagram_svg(
    layout: &MindmapDiagramLayout,
    semantic: &serde_json::Value,
    _effective_config: &serde_json::Value,
    options: &SvgRenderOptions,
) -> Result<String> {
    let model: merman_core::diagrams::mindmap::MindmapDiagramRenderModel =
        crate::json::from_value_ref(semantic)?;
    render_mindmap_diagram_svg_model(layout, &model, _effective_config, options)
}

pub(super) fn render_mindmap_diagram_svg_with_config(
    layout: &MindmapDiagramLayout,
    semantic: &serde_json::Value,
    effective_config: &merman_core::MermaidConfig,
    options: &SvgRenderOptions,
) -> Result<String> {
    let model: merman_core::diagrams::mindmap::MindmapDiagramRenderModel =
        { crate::json::from_value_ref(semantic)? };
    render_mindmap_diagram_svg_model_with_config(layout, &model, effective_config, options)
}

pub(super) fn render_mindmap_diagram_svg_model(
    layout: &MindmapDiagramLayout,
    model: &merman_core::diagrams::mindmap::MindmapDiagramRenderModel,
    _effective_config: &serde_json::Value,
    options: &SvgRenderOptions,
) -> Result<String> {
    let config = merman_core::MermaidConfig::from_value(_effective_config.clone());
    render_mindmap_diagram_svg_model_with_config(layout, model, &config, options)
}

pub(super) fn render_mindmap_diagram_svg_model_with_config(
    layout: &MindmapDiagramLayout,
    model: &merman_core::diagrams::mindmap::MindmapDiagramRenderModel,
    config: &merman_core::MermaidConfig,
    options: &SvgRenderOptions,
) -> Result<String> {
    let timing_enabled = super::timing::render_timing_enabled();
    let mut timings = super::timing::RenderTimings::default();
    let total_start = std::time::Instant::now();
    fn section<'a>(
        enabled: bool,
        dst: &'a mut std::time::Duration,
    ) -> Option<super::timing::TimingGuard<'a>> {
        enabled.then(|| super::timing::TimingGuard::new(dst))
    }

    #[derive(Debug, Clone, serde::Serialize)]
    struct Pt {
        x: f64,
        y: f64,
    }

    let hand_drawn_seed = config
        .as_value()
        .get("handDrawnSeed")
        .and_then(|v| v.as_u64())
        .unwrap_or(0);

    let max_node_width_px = crate::mindmap::mindmap_max_node_width_px(config.as_value());

    struct MindmapLabelSpec<'a> {
        text: &'a str,
        label_type: &'a str,
        label_bkg: bool,
        width: f64,
        height: f64,
        tx: f64,
        ty: f64,
        max_node_width_px: f64,
    }

    fn mk_label(out: &mut String, spec: MindmapLabelSpec<'_>, config: &merman_core::MermaidConfig) {
        let MindmapLabelSpec {
            text,
            label_type,
            label_bkg,
            width,
            height,
            tx,
            ty,
            max_node_width_px,
        } = spec;

        fn is_simple_markdown(text: &str) -> bool {
            // Conservative: only fast-path labels that would render as a plain `<p>text</p>`.
            if text.contains('\n') || text.contains('\r') {
                return false;
            }
            let trimmed = text.trim_start();
            let bytes = trimmed.as_bytes();
            // Line-leading markdown constructs that can change the HTML shape even without newlines.
            if bytes.first().is_some_and(|b| matches!(b, b'#' | b'>')) {
                return false;
            }
            if bytes.starts_with(b"- ") || bytes.starts_with(b"+ ") || bytes.starts_with(b"---") {
                return false;
            }
            // Ordered list: `1. item` / `1) item`
            let mut i = 0usize;
            while i < bytes.len() && bytes[i].is_ascii_digit() {
                i += 1;
            }
            if i > 0
                && i + 1 < bytes.len()
                && (bytes[i] == b'.' || bytes[i] == b')')
                && bytes[i + 1] == b' '
            {
                return false;
            }
            // Block/inline markdown triggers we don't want to replicate here.
            if text.contains('*')
                || text.contains('_')
                || text.contains('`')
                || text.contains('~')
                || text.contains('[')
                || text.contains(']')
                || text.contains('!')
                || text.contains('\\')
            {
                return false;
            }
            // HTML passthrough / entity patterns: keep the full pulldown + sanitize path.
            if text.contains('<') || text.contains('>') || text.contains('&') {
                return false;
            }
            true
        }

        fn push_br_normalized_text_into(out: &mut String, text: &str) {
            // Mirror the existing `replace("<br>", "<br />").replace("<br/>", "<br />")` behavior,
            // but avoid allocating intermediate strings for the common case (no `<br>` tokens).
            let bytes = text.as_bytes();
            let mut i = 0usize;
            let mut start = 0usize;
            while i + 3 < bytes.len() {
                if bytes[i] == b'<' && bytes[i + 1] == b'b' && bytes[i + 2] == b'r' {
                    // "<br>"
                    if bytes[i + 3] == b'>' {
                        if start < i {
                            out.push_str(&text[start..i]);
                        }
                        out.push_str("<br />");
                        i += 4;
                        start = i;
                        continue;
                    }
                    // "<br/>"
                    if i + 4 < bytes.len() && bytes[i + 3] == b'/' && bytes[i + 4] == b'>' {
                        if start < i {
                            out.push_str(&text[start..i]);
                        }
                        out.push_str("<br />");
                        i += 5;
                        start = i;
                        continue;
                    }
                }
                i += 1;
            }
            if start < text.len() {
                out.push_str(&text[start..]);
            }
        }

        let div_class = if label_bkg {
            r#" class="labelBkg""#
        } else {
            ""
        };

        let max_node_width_px = if max_node_width_px.is_finite() && max_node_width_px > 0.0 {
            max_node_width_px
        } else {
            200.0
        };

        // Mermaid flips the `<div>` to a fixed-width wrapping container when the measured label
        // reaches/exceeds the configured max width (default 200px), even if the emitted
        // `<foreignObject width="...">` reflects the overflow width.
        let wrap_container = width >= max_node_width_px - 1e-3;
        out.push_str(r#"<g class="label" style="" transform="translate("#);
        fmt_into(out, tx);
        out.push_str(", ");
        fmt_into(out, ty);
        out.push_str(r#")"><rect/><foreignObject width=""#);
        fmt_into(out, width.max(1.0));
        out.push_str(r#"" height=""#);
        fmt_into(out, height.max(1.0));
        out.push_str(r#""><div xmlns="http://www.w3.org/1999/xhtml""#);
        out.push_str(div_class);
        out.push_str(r#" style=""#);
        if wrap_container {
            out.push_str(
                "display: table; white-space: break-spaces; line-height: 1.5; max-width: ",
            );
            fmt_into(out, max_node_width_px);
            out.push_str("px; text-align: center; width: ");
            fmt_into(out, max_node_width_px);
            out.push_str("px;");
        } else {
            out.push_str("display: table-cell; white-space: nowrap; line-height: 1.5; max-width: ");
            fmt_into(out, max_node_width_px);
            out.push_str("px; text-align: center;");
        }
        out.push_str(r#""><span class="nodeLabel">"#);
        fn markdown_to_sanitized_xhtml(text: &str, config: &merman_core::MermaidConfig) -> String {
            let html_out = crate::text::mermaid_markdown_to_xhtml_label_fragment(text, true);
            let html_out = crate::text::replace_fontawesome_icons(&html_out);
            let html_out = merman_core::sanitize::sanitize_text(&html_out, config);
            html_out
                .replace("<br>", "<br />")
                .replace("<br/>", "<br />")
                .trim()
                .to_string()
        }

        fn is_single_img_fragment(html: &str) -> bool {
            // Mermaid does not wrap a single <img> label inside a <p> node for mindmap labels.
            let t = html.trim();
            let lower = t.to_ascii_lowercase();
            if lower.starts_with("<p>") && lower.ends_with("</p>") {
                let inner = t.strip_prefix("<p>").unwrap_or(t);
                let inner = inner.strip_suffix("</p>").unwrap_or(inner);
                return is_single_img_fragment(inner);
            }
            if !lower.starts_with("<img") {
                return false;
            }
            let Some(end) = t.find('>') else {
                return false;
            };
            t[end + 1..].trim().is_empty()
        }

        fn unwrap_single_img_p(html: &str) -> String {
            let t = html.trim();
            if !t.to_ascii_lowercase().starts_with("<p>")
                || !t.to_ascii_lowercase().ends_with("</p>")
            {
                return t.to_string();
            }
            let inner = t.strip_prefix("<p>").unwrap_or(t);
            let inner = inner.strip_suffix("</p>").unwrap_or(inner);
            inner.trim().to_string()
        }

        fn escape_amp_preserving_entities(raw: &str) -> String {
            fn is_valid_entity(entity: &str) -> bool {
                if entity.is_empty() {
                    return false;
                }
                if let Some(hex) = entity
                    .strip_prefix("#x")
                    .or_else(|| entity.strip_prefix("#X"))
                {
                    return !hex.is_empty() && hex.chars().all(|c| c.is_ascii_hexdigit());
                }
                if let Some(dec) = entity.strip_prefix('#') {
                    return !dec.is_empty() && dec.chars().all(|c| c.is_ascii_digit());
                }
                let mut it = entity.chars();
                let Some(first) = it.next() else {
                    return false;
                };
                if !first.is_ascii_alphabetic() {
                    return false;
                }
                it.all(|c| c.is_ascii_alphanumeric())
            }

            let mut out = String::with_capacity(raw.len());
            let mut i = 0usize;
            while let Some(rel) = raw[i..].find('&') {
                let amp = i + rel;
                out.push_str(&raw[i..amp]);
                let tail = &raw[amp + 1..];
                if let Some(semi_rel) = tail.find(';') {
                    let semi = amp + 1 + semi_rel;
                    let entity = &raw[amp + 1..semi];
                    if is_valid_entity(entity) {
                        out.push_str(&raw[amp..=semi]);
                        i = semi + 1;
                        continue;
                    }
                }
                out.push_str("&amp;");
                i = amp + 1;
            }
            out.push_str(&raw[i..]);
            out
        }

        if label_type == "markdown" {
            if is_simple_markdown(text) {
                let mut html_out = String::with_capacity(text.len() + 7);
                html_out.push_str("<p>");
                html_out.push_str(text);
                html_out.push_str("</p>");
                let html_out = crate::text::replace_fontawesome_icons(&html_out);
                let html_out = decode_mermaid_entities_for_render_text(&html_out);
                out.push_str(&escape_amp_preserving_entities(html_out.as_ref()));
            } else {
                let html = markdown_to_sanitized_xhtml(text, config);
                let html = decode_mermaid_entities_for_render_text(&html);
                out.push_str(&escape_amp_preserving_entities(html.as_ref()));
            }
        } else if text.contains('\n') || text.contains('\r') {
            // Mermaid's Cypress mindmap fixtures include multi-line labels inside node delimiters
            // (e.g. `root((\n  The root\n))`). Upstream preserves the raw whitespace/newlines as
            // a text node (no `<p>...</p>` wrapper) unless the label intentionally includes a
            // backtick snippet (which upstream keeps inside a `<p>` node).
            if text.contains('`') {
                let mut normalized;
                let normalized = if text.contains("<br>") || text.contains("<br/>") {
                    normalized = String::with_capacity(text.len() + 8);
                    push_br_normalized_text_into(&mut normalized, text);
                    normalized.as_str()
                } else {
                    text
                };
                out.push_str("<p>");
                out.push_str(&escape_xml(normalized));
                out.push_str("</p>");
            } else {
                out.push_str(&escape_xml(text));
            }
        } else {
            // Mermaid applies Markdown parsing semantics even for regular, single-line mindmap
            // labels. This matters for emphasis markers like `__proto__` (renders as `<strong>`).
            // Keep output XHTML-compatible and sanitizer-aligned.
            let mut normalized;
            let text = if text.contains("<br>") || text.contains("<br/>") {
                normalized = String::with_capacity(text.len() + 8);
                push_br_normalized_text_into(&mut normalized, text);
                normalized.as_str()
            } else {
                text
            };
            // Mindmap fixtures use *wrapping* backticks to denote "verbatim" labels. Mermaid keeps
            // those backticks as literal text (no Markdown evaluation) in that mode.
            //
            // Do not treat the presence of any backtick as verbatim. Upstream Mermaid's
            // `encodeEntities(...)` pass can introduce `&`-prefixed backticks (e.g. `&#96;` ->
            // `&fl°°96¶ß` -> `&\``), and those should still participate in Markdown parsing.
            let trimmed = text.trim();
            let is_verbatim =
                trimmed.len() >= 2 && trimmed.starts_with('`') && trimmed.ends_with('`');
            if is_verbatim {
                out.push_str("<p>");
                out.push_str(&escape_xml(text));
                out.push_str("</p>");
            } else if is_simple_markdown(text) {
                let mut html_out = String::with_capacity(text.len() + 7);
                html_out.push_str("<p>");
                html_out.push_str(text);
                html_out.push_str("</p>");
                let html_out = crate::text::replace_fontawesome_icons(&html_out);
                let html_out = decode_mermaid_entities_for_render_text(&html_out);
                out.push_str(&escape_amp_preserving_entities(html_out.as_ref()));
            } else {
                let html = markdown_to_sanitized_xhtml(text, config);
                if is_single_img_fragment(&html) {
                    let html = unwrap_single_img_p(&html);
                    let html = decode_mermaid_entities_for_render_text(&html);
                    out.push_str(&escape_amp_preserving_entities(html.as_ref()));
                } else {
                    let html = decode_mermaid_entities_for_render_text(&html);
                    out.push_str(&escape_amp_preserving_entities(html.as_ref()));
                }
            }
        }

        out.push_str("</span></div></foreignObject></g>");
    }

    fn mk_edge_label(out: &mut String, edge_id: &str) {
        let _ = write!(
            out,
            r#"<g class="edgeLabel"><g class="label" data-id="{id}" transform="translate(0, 0)"><foreignObject width="0" height="0"><div xmlns="http://www.w3.org/1999/xhtml" class="labelBkg" style="display: table-cell; white-space: nowrap; line-height: 1.5; max-width: 200px; text-align: center;"><span class="edgeLabel"></span></div></foreignObject></g></g>"#,
            id = escape_xml(edge_id),
        );
    }

    let _g_build_ctx = section(timing_enabled, &mut timings.build_ctx);

    let diagram_id = options.diagram_id.as_deref().unwrap_or("mindmap");
    let diagram_id_esc = escape_xml(diagram_id);

    let mut node_by_id: std::collections::BTreeMap<String, &crate::model::LayoutNode> =
        std::collections::BTreeMap::new();
    for n in &layout.nodes {
        node_by_id.insert(n.id.clone(), n);
    }

    drop(_g_build_ctx);

    let _g_viewbox = section(timing_enabled, &mut timings.viewbox);

    let padding = 10.0;
    let viewport_bounds =
        mindmap_viewport_bounds_from_layout(layout, model).or_else(|| layout.bounds.clone());
    let (vx, vy, vw, vh) = viewport_bounds
        .as_ref()
        .map(|b| {
            let w = (b.max_x - b.min_x).max(0.0);
            let h = (b.max_y - b.min_y).max(0.0);
            (
                b.min_x - padding,
                b.min_y - padding,
                w + 2.0 * padding,
                h + 2.0 * padding,
            )
        })
        .unwrap_or((0.0, 0.0, 100.0, 100.0));

    let mut view_box_attr = format!("{} {} {} {}", fmt(vx), fmt(vy), fmt(vw), fmt(vh));
    let mut max_w_attr = fmt_max_width_px(vw);
    let mut w_attr = fmt_string(vw);
    let mut h_attr = fmt_string(vh);
    apply_root_viewport_override(
        diagram_id,
        &mut view_box_attr,
        &mut w_attr,
        &mut h_attr,
        &mut max_w_attr,
        crate::generated::mindmap_root_overrides_11_12_2::lookup_mindmap_root_viewport_override,
    );

    drop(_g_viewbox);

    let _g_render_svg = section(timing_enabled, &mut timings.render_svg);

    let mut out = String::new();
    let style_attr = format!("max-width: {max_w_attr}px; background-color: white;");
    root_svg::push_svg_root_open(
        &mut out,
        root_svg::SvgRootAttrs {
            class: Some("mindmapDiagram"),
            width: root_svg::SvgRootWidth::Percent100,
            style_attr: Some(style_attr.as_str()),
            viewbox_attr: Some(view_box_attr.as_str()),
            trailing_newline: false,
            ..root_svg::SvgRootAttrs::new(diagram_id, "mindmap")
        },
    );
    let css = mindmap_css(diagram_id, config.as_value());
    let _ = write!(&mut out, "<style>{}</style>", css);
    out.push_str("<g>");

    let _ = write!(
        &mut out,
        r#"<marker id="{id}_mindmap-pointEnd" class="marker mindmap" viewBox="0 0 10 10" refX="5" refY="5" markerUnits="userSpaceOnUse" markerWidth="8" markerHeight="8" orient="auto"><path d="M 0 0 L 10 5 L 0 10 z" class="arrowMarkerPath" style="stroke-width: 1; stroke-dasharray: 1, 0;"/></marker>"#,
        id = diagram_id_esc
    );
    let _ = write!(
        &mut out,
        r#"<marker id="{id}_mindmap-pointStart" class="marker mindmap" viewBox="0 0 10 10" refX="4.5" refY="5" markerUnits="userSpaceOnUse" markerWidth="8" markerHeight="8" orient="auto"><path d="M 0 5 L 10 10 L 10 0 z" class="arrowMarkerPath" style="stroke-width: 1; stroke-dasharray: 1, 0;"/></marker>"#,
        id = diagram_id_esc
    );

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

    out.push_str(r#"<g class="edgePaths">"#);
    for e in &model.edges {
        let (sx, sy, tx, ty) = match (node_by_id.get(&e.start), node_by_id.get(&e.end)) {
            (Some(a), Some(b)) => (a.x, a.y, b.x, b.y),
            _ => (0.0, 0.0, 0.0, 0.0),
        };

        // Mermaid mindmap edges use `curveBasis` and offset endpoints from node centers
        // along the direction of the edge.
        let (vx, vy) = (tx - sx, ty - sy);
        let v_len = (vx * vx + vy * vy).sqrt();
        let (ux, uy) = if v_len == 0.0 {
            (0.0, 0.0)
        } else {
            (vx / v_len, vy / v_len)
        };
        let endpoint_offset = 15.0;
        let start_x = sx + endpoint_offset * ux;
        let start_y = sy + endpoint_offset * uy;
        let end_x = tx - endpoint_offset * ux;
        let end_y = ty - endpoint_offset * uy;
        let mid_x = (start_x + end_x) / 2.0;
        let mid_y = (start_y + end_y) / 2.0;

        let points = [
            Pt {
                x: start_x,
                y: start_y,
            },
            Pt { x: mid_x, y: mid_y },
            Pt { x: end_x, y: end_y },
        ];
        let points_for_data_points = points
            .iter()
            .map(|p| crate::model::LayoutPoint { x: p.x, y: p.y })
            .collect::<Vec<_>>();
        let data_points = base64::engine::general_purpose::STANDARD
            .encode(json_stringify_points(&points_for_data_points));

        let d = if e.curve.trim() == "basis" {
            curve::curve_basis_path_d(&points_for_data_points)
        } else {
            curve::curve_linear_path_d(&points_for_data_points)
        };
        let class = format!(
            "edge-thickness-{} edge-pattern-solid {}",
            e.thickness.trim(),
            e.classes.trim()
        );
        let _ = write!(
            &mut out,
            r#"<path d="{d}" id="{id}" class="{class}" style="undefined;;;undefined" data-edge="true" data-et="edge" data-id="{id}" data-points="{pts}"/>"#,
            d = escape_attr(&d),
            id = escape_xml(&e.id),
            class = escape_xml(&class),
            pts = escape_xml(&data_points),
        );
    }
    out.push_str("</g>");

    out.push_str(r#"<g class="edgeLabels">"#);
    for e in &model.edges {
        mk_edge_label(&mut out, &e.id);
    }
    out.push_str("</g>");

    out.push_str(r#"<g class="nodes">"#);
    for n in &model.nodes {
        let (x, y, w, h, label_w, label_h) = node_by_id
            .get(&n.id)
            .map(|ln| {
                (
                    ln.x,
                    ln.y,
                    ln.width,
                    ln.height,
                    ln.label_width,
                    ln.label_height,
                )
            })
            .unwrap_or((0.0, 0.0, 80.0, 44.0, None, None));
        let padding = n.padding.max(0.0);
        let half_padding = padding / 2.0;
        let class = format!("node {}", n.css_classes.trim());
        let _ = write!(
            &mut out,
            r#"<g class="{class}" id="{dom_id}" transform="translate({x}, {y})">"#,
            class = escape_xml(&class),
            dom_id = escape_xml(&n.dom_id),
            x = fmt(x),
            y = fmt(y),
        );

        match n.shape.as_str() {
            "defaultMindmapNode" => {
                let rd = 5.0;
                let rect_path = format!(
                    "\n    M{} {}\n    v{}\n    q0,-{} {},-{}\n    h{}\n    q{},0 {},{}\n    v{}\n    q0,{} -{},{}\n    h{}\n    q-{},0 -{},-{}\n    Z\n  ",
                    fmt_path(-(w / 2.0)),
                    fmt_path(h / 2.0 - rd),
                    fmt_path(-h + 2.0 * rd),
                    fmt_path(rd),
                    fmt_path(rd),
                    fmt_path(rd),
                    fmt_path(w - 2.0 * rd),
                    fmt_path(rd),
                    fmt_path(rd),
                    fmt_path(rd),
                    fmt_path(h - 2.0 * rd),
                    fmt_path(rd),
                    fmt_path(rd),
                    fmt_path(rd),
                    fmt_path(-w + 2.0 * rd),
                    fmt_path(rd),
                    fmt_path(rd),
                    fmt_path(rd),
                );

                // Recover label bbox dimensions from the rendered node size + padding rules.
                let bbox_w = (w - 8.0 * half_padding).max(1.0);
                let bbox_h = (h - 2.0 * half_padding).max(1.0);
                let _ = write!(
                    &mut out,
                    r#"<path id="node-{id}" class="node-bkg node-0" style="" d="{d}"/>"#,
                    id = escape_xml(&n.id),
                    d = escape_attr(&rect_path),
                );
                let _ = write!(
                    &mut out,
                    r#"<line class="node-line-" x1="{x1}" y1="{y}" x2="{x2}" y2="{y}"/>"#,
                    x1 = fmt(-(w / 2.0)),
                    x2 = fmt(w / 2.0),
                    y = fmt(h / 2.0),
                );
                mk_label(
                    &mut out,
                    MindmapLabelSpec {
                        text: &n.label,
                        label_type: &n.label_type,
                        label_bkg: n.icon.is_some(),
                        width: bbox_w,
                        height: bbox_h,
                        tx: -bbox_w / 2.0,
                        ty: -bbox_h / 2.0,
                        max_node_width_px,
                    },
                    config,
                );
            }
            "rect" => {
                // `rect` mindmap nodes use: w = bbox_w + 2*padding, h = bbox_h + padding.
                let bbox_w = (w - 2.0 * padding).max(1.0);
                let bbox_h = (h - padding).max(1.0);
                let _ = write!(
                    &mut out,
                    r#"<rect class="basic label-container" style="" x="{x}" y="{y}" width="{w}" height="{h}"/>"#,
                    x = fmt(-(w / 2.0)),
                    y = fmt(-(h / 2.0)),
                    w = fmt(w.max(1.0)),
                    h = fmt(h.max(1.0)),
                );
                mk_label(
                    &mut out,
                    MindmapLabelSpec {
                        text: &n.label,
                        label_type: &n.label_type,
                        label_bkg: n.icon.is_some(),
                        width: bbox_w,
                        height: bbox_h,
                        tx: -bbox_w / 2.0,
                        ty: -bbox_h / 2.0,
                        max_node_width_px,
                    },
                    config,
                );
            }
            "rounded" => {
                let w = w.max(1.0);
                let h = h.max(1.0);
                let pts = rounded_rect_points(w, h);
                let (fill_d, _stroke_d) = roughjs46_solid_fill_paths_for_closed_polyline_path(
                    &pts,
                    hand_drawn_seed,
                    false,
                );

                out.push_str(r#"<g class="basic label-container outer-path">"#);
                let _ = write!(
                    &mut out,
                    r##"<path d="{d}" stroke="none" stroke-width="0" fill="#ECECFF" style=""/>"##,
                    d = escape_attr(&fill_d),
                );
                out.push_str("</g>");

                let bbox_w = label_w.unwrap_or_else(|| (w - 2.0 * padding).max(1.0));
                let bbox_h = label_h.unwrap_or_else(|| (h - 2.0 * padding).max(1.0));
                mk_label(
                    &mut out,
                    MindmapLabelSpec {
                        text: &n.label,
                        label_type: &n.label_type,
                        label_bkg: n.icon.is_some(),
                        width: bbox_w,
                        height: bbox_h,
                        tx: -bbox_w / 2.0,
                        ty: -bbox_h / 2.0,
                        max_node_width_px,
                    },
                    config,
                );
            }
            "mindmapCircle" => {
                let r = (w.max(h) / 2.0).max(1.0);
                let _ = write!(
                    &mut out,
                    r#"<circle class="basic label-container" style="" r="{r}" cx="0" cy="0"/>"#,
                    r = fmt(r),
                );
                // Mermaid sizes the circle diameter using `bbox.width`, but label placement still
                // uses the true label bbox height (not a square).
                let bbox_w = label_w.unwrap_or_else(|| (w - 2.0 * padding).max(1.0));
                let bbox_h = label_h.unwrap_or_else(|| (h - 2.0 * padding).max(1.0));
                mk_label(
                    &mut out,
                    MindmapLabelSpec {
                        text: &n.label,
                        label_type: &n.label_type,
                        label_bkg: n.icon.is_some(),
                        width: bbox_w,
                        height: bbox_h,
                        tx: -bbox_w / 2.0,
                        ty: -bbox_h / 2.0,
                        max_node_width_px,
                    },
                    config,
                );
            }
            "cloud" => {
                let bbox_w = label_w.unwrap_or_else(|| (w - 2.0 * half_padding).max(1.0));
                let bbox_h = label_h.unwrap_or_else(|| (h - 2.0 * half_padding).max(1.0));
                let w = (bbox_w + 2.0 * half_padding).max(1.0);
                let h = (bbox_h + 2.0 * half_padding).max(1.0);

                let cloud_path = mindmap_cloud_path_d(w, h, MindmapPathNumberFormat::D3Path);

                let _ = write!(
                    &mut out,
                    r#"<path class="basic label-container" style="" d="{d}" transform="translate({tx}, {ty})"/>"#,
                    d = escape_attr(&cloud_path),
                    tx = fmt(-(w / 2.0)),
                    ty = fmt(-(h / 2.0)),
                );
                mk_label(
                    &mut out,
                    MindmapLabelSpec {
                        text: &n.label,
                        label_type: &n.label_type,
                        label_bkg: n.icon.is_some(),
                        width: bbox_w,
                        height: bbox_h,
                        tx: -bbox_w / 2.0,
                        ty: -bbox_h / 2.0,
                        max_node_width_px,
                    },
                    config,
                );
            }
            "hexagon" => {
                let w = w.max(1.0);
                let h = h.max(1.0);

                let half_width = w / 2.0;
                let half_height = h / 2.0;
                let fixed_length = half_height / 2.0;
                let deduced_width = half_width - fixed_length;
                let pts: [(f64, f64); 8] = [
                    (-deduced_width, -half_height),
                    (0.0, -half_height),
                    (deduced_width, -half_height),
                    (half_width, 0.0),
                    (deduced_width, half_height),
                    (0.0, half_height),
                    (-deduced_width, half_height),
                    (-half_width, 0.0),
                ];
                let (fill_d, stroke_d) = roughjs46_solid_fill_paths_for_closed_polyline_path(
                    &pts,
                    hand_drawn_seed,
                    true,
                );

                out.push_str(r#"<g class="basic label-container">"#);
                let _ = write!(
                    &mut out,
                    r##"<path d="{d}" stroke="none" stroke-width="0" fill="#ECECFF" style=""/>"##,
                    d = escape_attr(&fill_d),
                );
                if let Some(stroke_d) = stroke_d {
                    let _ = write!(
                        &mut out,
                        r##"<path d="{d}" stroke="#9370DB" stroke-width="1.3" fill="none" stroke-dasharray="0 0" style=""/>"##,
                        d = escape_attr(&stroke_d),
                    );
                }
                out.push_str("</g>");
                let label_width = label_w.unwrap_or_else(|| w.max(1.0));
                let label_height = label_h.unwrap_or_else(|| h.max(1.0));
                mk_label(
                    &mut out,
                    MindmapLabelSpec {
                        text: &n.label,
                        label_type: &n.label_type,
                        label_bkg: n.icon.is_some(),
                        width: label_width,
                        height: label_height,
                        tx: -label_width / 2.0,
                        ty: -label_height / 2.0,
                        max_node_width_px,
                    },
                    config,
                );
            }
            "bang" => {
                let bbox_w = label_w.unwrap_or_else(|| (w - 10.0 * half_padding).max(1.0));
                let bbox_h = label_h.unwrap_or_else(|| (h - 8.0 * half_padding).max(1.0));

                let w_base = bbox_w + 10.0 * half_padding;
                let effective_w = w.max(1.0);
                let effective_h = h.max(1.0);

                let bang_path = mindmap_bang_path_d(
                    w_base,
                    effective_w,
                    effective_h,
                    MindmapPathNumberFormat::D3Path,
                );

                let _ = write!(
                    &mut out,
                    r#"<path class="basic label-container" style="" d="{d}" transform="translate({tx}, {ty})"/>"#,
                    d = escape_attr(&bang_path),
                    tx = fmt(-(effective_w / 2.0)),
                    ty = fmt(-(effective_h / 2.0)),
                );
                mk_label(
                    &mut out,
                    MindmapLabelSpec {
                        text: &n.label,
                        label_type: &n.label_type,
                        label_bkg: n.icon.is_some(),
                        width: bbox_w,
                        height: bbox_h,
                        tx: -bbox_w / 2.0,
                        ty: -bbox_h / 2.0,
                        max_node_width_px,
                    },
                    config,
                );
            }
            _ => {
                let _ = write!(
                    &mut out,
                    r#"<rect class="basic label-container" style="" x="{x}" y="{y}" width="{w}" height="{h}"/>"#,
                    x = fmt(-(w / 2.0)),
                    y = fmt(-(h / 2.0)),
                    w = fmt(w.max(1.0)),
                    h = fmt(h.max(1.0)),
                );
                mk_label(
                    &mut out,
                    MindmapLabelSpec {
                        text: &n.label,
                        label_type: &n.label_type,
                        label_bkg: n.icon.is_some(),
                        width: w.max(1.0),
                        height: h.max(1.0),
                        tx: -w / 2.0,
                        ty: -h / 2.0,
                        max_node_width_px,
                    },
                    config,
                );
            }
        }

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

    out.push_str("</g></svg>\n");

    drop(_g_render_svg);

    timings.total = total_start.elapsed();
    if timing_enabled {
        eprintln!(
            "[render-timing] diagram=mindmap total={:?} deserialize={:?} build_ctx={:?} viewbox={:?} render_svg={:?} finalize={:?} nodes={} edges={}",
            timings.total,
            timings.deserialize_model,
            timings.build_ctx,
            timings.viewbox,
            timings.render_svg,
            timings.finalize_svg,
            model.nodes.len(),
            model.edges.len(),
        );
    }

    Ok(out)
}

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

    #[test]
    fn viewport_bounds_include_cloud_path_bbox() {
        let layout = MindmapDiagramLayout {
            nodes: vec![LayoutNode {
                id: "0".to_string(),
                x: 63.953125,
                y: 32.0,
                width: 97.90625,
                height: 34.0,
                is_cluster: false,
                label_width: Some(87.90625),
                label_height: Some(24.0),
            }],
            edges: Vec::new(),
            bounds: Some(Bounds {
                min_x: 15.0,
                min_y: 15.0,
                max_x: 112.90625,
                max_y: 49.0,
            }),
        };
        let model = merman_core::diagrams::mindmap::MindmapDiagramRenderModel {
            nodes: vec![merman_core::diagrams::mindmap::MindmapDiagramRenderNode {
                id: "0".to_string(),
                dom_id: "node_0".to_string(),
                label: "I am a cloud".to_string(),
                label_type: String::new(),
                is_group: false,
                shape: "cloud".to_string(),
                width: 0.0,
                height: 0.0,
                padding: 10.0,
                css_classes: "mindmap-node section-root section--1".to_string(),
                css_styles: Vec::new(),
                look: String::new(),
                icon: None,
                x: None,
                y: None,
                level: 0,
                node_id: "id".to_string(),
                node_type: -1,
                section: Some(-1),
            }],
            edges: Vec::new(),
        };

        let bounds = mindmap_viewport_bounds_from_layout(&layout, &model).expect("bounds");

        assert!(bounds.min_x < 15.0);
        assert!(bounds.min_y < 15.0);
        assert!(bounds.max_x > 112.90625);
        assert!(bounds.max_y > 49.0);
    }
}