merman-render 0.4.1

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
use crate::json::from_value_ref;
use crate::model::{Bounds, LayoutEdge, LayoutNode, LayoutPoint, MindmapDiagramLayout};
use crate::text::WrapMode;
use crate::text::{TextMeasurer, TextStyle};
use crate::{Error, Result};
use merman_core::MAX_DIAGRAM_NESTING_DEPTH;
use serde_json::Value;

fn config_f64(cfg: &Value, path: &[&str]) -> Option<f64> {
    let mut v = cfg;
    for p in path {
        v = v.get(*p)?;
    }
    v.as_f64()
        .or_else(|| v.as_i64().map(|n| n as f64))
        .or_else(|| v.as_u64().map(|n| n as f64))
}

fn config_string(cfg: &Value, path: &[&str]) -> Option<String> {
    let mut v = cfg;
    for p in path {
        v = v.get(*p)?;
    }
    v.as_str().map(|s| s.to_string())
}

fn parse_css_px_to_f64(text: &str) -> Option<f64> {
    let trimmed = text.trim();
    let raw = trimmed.strip_suffix("px").unwrap_or(trimmed).trim();
    raw.parse::<f64>().ok().filter(|value| value.is_finite())
}

pub(crate) fn mindmap_max_node_width_px(effective_config: &Value) -> f64 {
    config_f64(effective_config, &["mindmap", "maxNodeWidth"])
        .or_else(|| {
            config_string(effective_config, &["mindmap", "maxNodeWidth"])
                .and_then(|value| parse_css_px_to_f64(&value))
        })
        .unwrap_or(200.0)
        .max(1.0)
}

type MindmapModel = merman_core::diagrams::mindmap::MindmapDiagramRenderModel;
type MindmapNodeModel = merman_core::diagrams::mindmap::MindmapDiagramRenderNode;

fn mindmap_text_style(effective_config: &Value) -> TextStyle {
    // Mermaid mindmap labels are rendered via HTML `<foreignObject>` and inherit the global font.
    let font_family = config_string(effective_config, &["fontFamily"])
        .or_else(|| config_string(effective_config, &["themeVariables", "fontFamily"]))
        .or_else(|| Some("\"trebuchet ms\", verdana, arial, sans-serif".to_string()));
    // Mermaid mindmap uses HTML `<foreignObject>` labels. Mermaid CLI baselines show that the
    // HTML label contents do not reliably inherit SVG-root `font-size` rules; measurement matches
    // a 16px default even when users override `themeVariables.fontSize`.
    let font_size = 16.0;
    TextStyle {
        font_family,
        font_size,
        font_weight: None,
    }
}

fn is_simple_markdown_label(text: &str) -> bool {
    // Conservative: only fast-path labels that would render as plain text inside a `<p>...</p>`
    // when passed through Mermaid's Markdown + sanitizer pipeline.
    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 markdown path.
    if text.contains('<') || text.contains('>') || text.contains('&') {
        return false;
    }
    true
}

fn mindmap_label_bbox_px(
    text: &str,
    label_type: &str,
    measurer: &dyn TextMeasurer,
    style: &TextStyle,
    max_node_width_px: f64,
) -> (f64, f64) {
    // Mermaid mindmap labels are rendered via HTML `<foreignObject>` and respect
    // `mindmap.maxNodeWidth` (default 200px). When the raw label is wider than that, Mermaid
    // switches the label container to a fixed 200px width and allows HTML-like wrapping (e.g.
    // `white-space: break-spaces` in upstream SVG baselines).
    //
    // Mirror that by measuring with an explicit max width in HTML-like mode.
    let max_node_width_px = max_node_width_px.max(1.0);

    // Complex Markdown labels require the full DOM-like measurement path (bold/em deltas, inline
    // HTML, sanitizer edge cases). Keep the existing two-pass approach for those.
    if label_type == "markdown" && !is_simple_markdown_label(text) {
        if text.contains("![") {
            let wrapped = crate::text::measure_markdown_with_flowchart_bold_deltas(
                measurer,
                text,
                style,
                Some(max_node_width_px),
                WrapMode::HtmlLike,
            );
            let unwrapped = crate::text::measure_markdown_with_flowchart_bold_deltas(
                measurer,
                text,
                style,
                None,
                WrapMode::HtmlLike,
            );
            return (
                wrapped.width.max(unwrapped.width).max(0.0),
                wrapped.height.max(0.0),
            );
        }

        let html = crate::text::mermaid_markdown_to_xhtml_label_fragment(text, true);
        let wrapped = crate::text::measure_html_with_flowchart_bold_deltas(
            measurer,
            &html,
            style,
            Some(max_node_width_px),
            WrapMode::HtmlLike,
        );
        let unwrapped = crate::text::measure_html_with_flowchart_bold_deltas(
            measurer,
            &html,
            style,
            None,
            WrapMode::HtmlLike,
        );
        return (
            wrapped.width.max(unwrapped.width).max(0.0),
            wrapped.height.max(0.0),
        );
    }

    let (wrapped, raw_width_px) = measurer.measure_wrapped_with_raw_width(
        text,
        style,
        Some(max_node_width_px),
        WrapMode::HtmlLike,
    );

    // Mermaid mindmap labels can overflow the configured `maxNodeWidth` when they contain long
    // unbreakable tokens. Upstream measures these via DOM in a way that resembles `scrollWidth`,
    // so keep the larger of:
    // - the wrapped layout width (clamped by `max-width`), and
    // - the unwrapped overflow width (ignores `max-width`).
    let overflow_width_px = raw_width_px.unwrap_or_else(|| {
        measurer
            .measure_wrapped(text, style, None, WrapMode::HtmlLike)
            .width
    });

    (
        wrapped.width.max(overflow_width_px).max(0.0),
        wrapped.height.max(0.0),
    )
}

fn mindmap_node_dimensions_px(
    node: &MindmapNodeModel,
    measurer: &dyn TextMeasurer,
    style: &TextStyle,
    max_node_width_px: f64,
) -> (f64, f64, f64, f64) {
    let (bbox_w, bbox_h) = mindmap_label_bbox_px(
        &node.label,
        &node.label_type,
        measurer,
        style,
        max_node_width_px,
    );
    // Mermaid mindmap applies some shape-specific padding overrides during rendering (after
    // `mindmapDb.getData()`), notably for rounded nodes.
    //
    // Our semantic snapshots keep the DB padding (e.g. doubled padding for `(text)`), but layout
    // should follow the render-time effective padding so layout golden snapshots remain stable.
    let padding = match node.shape.as_str() {
        "rounded" => 15.0,
        _ => node.padding.max(0.0),
    };
    let half_padding = padding / 2.0;

    // Align with Mermaid shape sizing rules for mindmap nodes (via `labelHelper(...)` + shape
    // handlers in `rendering-elements/shapes/*`).
    let (w, h) = match node.shape.as_str() {
        // `defaultMindmapNode.ts`: w = bbox.width + 8 * halfPadding; h = bbox.height + 2 * halfPadding
        "" | "defaultMindmapNode" => (bbox_w + 8.0 * half_padding, bbox_h + 2.0 * half_padding),
        // Mindmap node shapes use the standard `labelHelper(...)` label bbox, but mindmap DB
        // adjusts `node.padding` depending on the delimiter type (e.g. `[` / `(` / `{{`).
        //
        // Upstream Mermaid@11.12.2 mindmap SVG baselines show:
        // - rect (`[text]`): w = bbox.width + 2*padding, h = bbox.height + padding
        // - rounded (`(text)`): w = bbox.width + 2*padding, h = bbox.height + 2*padding
        "rect" => (bbox_w + 2.0 * padding, bbox_h + padding),
        "rounded" => (bbox_w + 2.0 * padding, bbox_h + 2.0 * padding),
        // `mindmapCircle.ts` -> `circle.ts`: radius = bbox.width/2 + padding (mindmap passes full padding)
        "mindmapCircle" => {
            let d = bbox_w + 2.0 * padding;
            (d, d)
        }
        // `cloud.ts`: w = bbox.width + 2*halfPadding; h = bbox.height + 2*halfPadding
        "cloud" => (bbox_w + 2.0 * half_padding, bbox_h + 2.0 * half_padding),
        // `bang.ts`:
        // - w = bbox.width + 10*halfPadding; h = bbox.height + 8*halfPadding
        // - minWidth = bbox.width + 20; minHeight = bbox.height + 20
        // - effectiveWidth/Height = max(w/h, minWidth/Height)
        "bang" => {
            let w = bbox_w + 10.0 * half_padding;
            let h = bbox_h + 8.0 * half_padding;
            let min_w = bbox_w + 20.0;
            let min_h = bbox_h + 20.0;
            (w.max(min_w), h.max(min_h))
        }
        // `hexagon.ts`: h = bbox.height + padding; w = bbox.width + 2.5*padding; then expands by +w/6
        // due to `halfWidth = w/2 + m` where `m = (w/2)/6`.
        "hexagon" => {
            let w = bbox_w + 2.5 * padding;
            let h = bbox_h + padding;
            (w * (7.0 / 6.0), h)
        }
        _ => (bbox_w + 8.0 * half_padding, bbox_h + 2.0 * half_padding),
    };

    (w, h, bbox_w, bbox_h)
}

fn compute_bounds(nodes: &[LayoutNode], edges: &[LayoutEdge]) -> Option<Bounds> {
    let mut pts: Vec<(f64, f64)> = Vec::new();
    for n in nodes {
        let x0 = n.x - n.width / 2.0;
        let y0 = n.y - n.height / 2.0;
        let x1 = n.x + n.width / 2.0;
        let y1 = n.y + n.height / 2.0;
        pts.push((x0, y0));
        pts.push((x1, y1));
    }
    for e in edges {
        for p in &e.points {
            pts.push((p.x, p.y));
        }
    }
    Bounds::from_points(pts)
}

fn shift_nodes_to_positive_bounds(nodes: &mut [LayoutNode], content_min: f64) {
    if nodes.is_empty() {
        return;
    }
    let mut min_x = f64::INFINITY;
    let mut min_y = f64::INFINITY;
    for n in nodes.iter() {
        min_x = min_x.min(n.x - n.width / 2.0);
        min_y = min_y.min(n.y - n.height / 2.0);
    }
    if !(min_x.is_finite() && min_y.is_finite()) {
        return;
    }
    let dx = content_min - min_x;
    let dy = content_min - min_y;
    for n in nodes.iter_mut() {
        n.x += dx;
        n.y += dy;
    }
}

pub fn layout_mindmap_diagram(
    model: &Value,
    effective_config: &Value,
    text_measurer: &dyn TextMeasurer,
    use_manatee_layout: bool,
) -> Result<MindmapDiagramLayout> {
    let model: MindmapModel = from_value_ref(model)?;
    layout_mindmap_diagram_model(&model, effective_config, text_measurer, use_manatee_layout)
}

pub fn layout_mindmap_diagram_typed(
    model: &MindmapModel,
    effective_config: &Value,
    text_measurer: &dyn TextMeasurer,
    use_manatee_layout: bool,
) -> Result<MindmapDiagramLayout> {
    layout_mindmap_diagram_model(model, effective_config, text_measurer, use_manatee_layout)
}

fn layout_mindmap_diagram_model(
    model: &MindmapModel,
    effective_config: &Value,
    text_measurer: &dyn TextMeasurer,
    use_manatee_layout: bool,
) -> Result<MindmapDiagramLayout> {
    validate_mindmap_model_depth(model)?;
    let timing_enabled = std::env::var("MERMAN_MINDMAP_LAYOUT_TIMING")
        .ok()
        .as_deref()
        == Some("1");
    #[derive(Debug, Default, Clone)]
    struct MindmapLayoutTimings {
        total: std::time::Duration,
        measure_nodes: std::time::Duration,
        manatee: std::time::Duration,
        build_edges: std::time::Duration,
        bounds: std::time::Duration,
    }
    let mut timings = MindmapLayoutTimings::default();
    let total_start = timing_enabled.then(std::time::Instant::now);

    let text_style = mindmap_text_style(effective_config);
    let max_node_width_px = mindmap_max_node_width_px(effective_config);

    let measure_nodes_start = timing_enabled.then(std::time::Instant::now);
    let mut nodes_sorted: Vec<(i64, &MindmapNodeModel)> = model
        .nodes
        .iter()
        .map(|n| (n.id.parse::<i64>().unwrap_or(i64::MAX), n))
        .collect();
    nodes_sorted.sort_by(|(na, a), (nb, b)| na.cmp(nb).then_with(|| a.id.cmp(&b.id)));

    let mut nodes: Vec<LayoutNode> = Vec::with_capacity(model.nodes.len());
    for (_id_num, n) in nodes_sorted {
        let (width, height, label_width, label_height) =
            mindmap_node_dimensions_px(n, text_measurer, &text_style, max_node_width_px);

        nodes.push(LayoutNode {
            id: n.id.clone(),
            // Mermaid mindmap uses Cytoscape COSE-Bilkent and initializes node positions at (0,0).
            // We keep that behavior so `manatee` can reproduce upstream placements deterministically.
            x: 0.0,
            y: 0.0,
            width: width.max(1.0),
            height: height.max(1.0),
            is_cluster: false,
            label_width: Some(label_width.max(0.0)),
            label_height: Some(label_height.max(0.0)),
        });
    }
    if let Some(s) = measure_nodes_start {
        timings.measure_nodes = s.elapsed();
    }

    let mut id_to_idx: rustc_hash::FxHashMap<&str, usize> =
        rustc_hash::FxHashMap::with_capacity_and_hasher(nodes.len(), Default::default());
    for (idx, n) in nodes.iter().enumerate() {
        id_to_idx.insert(n.id.as_str(), idx);
    }

    let mut edge_indices: Vec<(usize, usize)> = Vec::with_capacity(model.edges.len());
    for e in &model.edges {
        let Some(&a) = id_to_idx.get(e.start.as_str()) else {
            return Err(Error::InvalidModel {
                message: format!("edge start node not found: {}", e.start),
            });
        };
        let Some(&b) = id_to_idx.get(e.end.as_str()) else {
            return Err(Error::InvalidModel {
                message: format!("edge end node not found: {}", e.end),
            });
        };
        edge_indices.push((a, b));
    }

    if use_manatee_layout {
        let manatee_start = timing_enabled.then(std::time::Instant::now);
        let indexed_nodes: Vec<manatee::algo::cose_bilkent::IndexedNode> = nodes
            .iter()
            .map(|n| manatee::algo::cose_bilkent::IndexedNode {
                width: n.width,
                height: n.height,
                x: n.x,
                y: n.y,
            })
            .collect();
        let mut indexed_edges: Vec<manatee::algo::cose_bilkent::IndexedEdge> =
            Vec::with_capacity(model.edges.len());
        for (edge_idx, (a, b)) in edge_indices.iter().copied().enumerate() {
            if a == b {
                continue;
            }
            indexed_edges.push(manatee::algo::cose_bilkent::IndexedEdge { a, b });

            // Keep `edge_idx` referenced so unused warnings don't obscure failures if we ever
            // enhance indexed validation error messages.
            let _ = edge_idx;
        }

        let positions = manatee::algo::cose_bilkent::layout_indexed(
            &indexed_nodes,
            &indexed_edges,
            &Default::default(),
        )
        .map_err(|e| Error::InvalidModel {
            message: format!("manatee layout failed: {e}"),
        })?;

        for (n, p) in nodes.iter_mut().zip(positions) {
            n.x = p.x;
            n.y = p.y;
        }
        if let Some(s) = manatee_start {
            timings.manatee = s.elapsed();
        }
    }

    // Mermaid's COSE-Bilkent post-layout normalizes to a positive coordinate space via
    // `transform(0,0)` (layout-base), yielding a content bbox that starts around (15,15) before
    // the 10px viewport padding is applied (viewBox starts at 5,5).
    //
    // Do this regardless of layout backend so parity-root viewport comparisons remain stable.
    shift_nodes_to_positive_bounds(&mut nodes, 15.0);

    let build_edges_start = timing_enabled.then(std::time::Instant::now);
    let mut edges: Vec<LayoutEdge> = Vec::new();
    edges.reserve(model.edges.len());
    for (e, (sidx, tidx)) in model.edges.iter().zip(edge_indices.iter().copied()) {
        let (sx, sy) = (nodes[sidx].x, nodes[sidx].y);
        let (tx, ty) = (nodes[tidx].x, nodes[tidx].y);
        let points = vec![LayoutPoint { x: sx, y: sy }, LayoutPoint { x: tx, y: ty }];
        edges.push(LayoutEdge {
            id: e.id.clone(),
            from: e.start.clone(),
            to: e.end.clone(),
            from_cluster: None,
            to_cluster: None,
            points,
            label: None,
            start_label_left: None,
            start_label_right: None,
            end_label_left: None,
            end_label_right: None,
            start_marker: None,
            end_marker: None,
            stroke_dasharray: None,
        });
    }
    if let Some(s) = build_edges_start {
        timings.build_edges = s.elapsed();
    }

    let bounds_start = timing_enabled.then(std::time::Instant::now);
    let bounds = compute_bounds(&nodes, &edges);
    if let Some(s) = bounds_start {
        timings.bounds = s.elapsed();
    }
    if let Some(s) = total_start {
        timings.total = s.elapsed();
        eprintln!(
            "[layout-timing] diagram=mindmap total={:?} measure_nodes={:?} manatee={:?} build_edges={:?} bounds={:?} nodes={} edges={}",
            timings.total,
            timings.measure_nodes,
            timings.manatee,
            timings.build_edges,
            timings.bounds,
            nodes.len(),
            edges.len(),
        );
    }
    Ok(MindmapDiagramLayout {
        nodes,
        edges,
        bounds,
    })
}

fn validate_mindmap_model_depth(model: &MindmapModel) -> Result<()> {
    for node in &model.nodes {
        if usize::try_from(node.level).is_ok_and(|depth| depth > MAX_DIAGRAM_NESTING_DEPTH) {
            return Err(Error::InvalidModel {
                message: format!(
                    "mindmap nesting depth exceeds maximum of {MAX_DIAGRAM_NESTING_DEPTH}"
                ),
            });
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    #[test]
    fn mindmap_max_node_width_accepts_number_and_px_string() {
        let numeric = serde_json::json!({
            "mindmap": {
                "maxNodeWidth": 320
            }
        });
        assert_eq!(super::mindmap_max_node_width_px(&numeric), 320.0);

        let px_string = serde_json::json!({
            "mindmap": {
                "maxNodeWidth": "280px"
            }
        });
        assert_eq!(super::mindmap_max_node_width_px(&px_string), 280.0);

        let plain_string = serde_json::json!({
            "mindmap": {
                "maxNodeWidth": "240"
            }
        });
        assert_eq!(super::mindmap_max_node_width_px(&plain_string), 240.0);

        let fallback = serde_json::json!({});
        assert_eq!(super::mindmap_max_node_width_px(&fallback), 200.0);
    }
}