merman-render 0.7.0-alpha.2

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
//! Flowchart CSS generation.

use super::*;

pub(in crate::svg::parity) fn flowchart_css(
    diagram_id: &str,
    effective_config: &serde_json::Value,
    font_family: &str,
    font_size: f64,
    class_defs: &IndexMap<String, Vec<String>>,
) -> String {
    let id = escape_xml(diagram_id);
    let theme = PresentationTheme::new(effective_config).node_diagram();
    let stroke = theme.common.line_color.as_str();
    let arrowhead_color = theme.arrowhead_color.as_str();
    let node_border = theme.node_border.as_str();
    let main_bkg = theme.main_bkg.as_str();
    let text_color = theme.common.text_color.as_str();
    let node_text_color = theme.node_text_color.as_str();
    let title_color = theme.title_color.as_str();
    let stroke_width = theme.stroke_width.as_str();
    let error_bkg = theme.common.error_bkg.as_str();
    let error_text = theme.common.error_text.as_str();
    let edge_label_background = theme.edge_label_background.as_str();
    let tertiary = theme.tertiary.as_str();
    let cluster_bkg = theme.cluster_bkg.as_str();
    let cluster_border = theme.cluster_border.as_str();

    fn flowchart_label_bkg_from_edge_label_background(edge_label_background: &str) -> String {
        fn parse_hex_channel(hex: &str) -> Option<u8> {
            u8::from_str_radix(hex, 16).ok()
        }

        fn parse_hex_rgb(s: &str) -> Option<(f64, f64, f64)> {
            let s = s.trim();
            let hex = s.strip_prefix('#')?;
            match hex.len() {
                3 => {
                    let r = parse_hex_channel(&hex[0..1].repeat(2))? as f64;
                    let g = parse_hex_channel(&hex[1..2].repeat(2))? as f64;
                    let b = parse_hex_channel(&hex[2..3].repeat(2))? as f64;
                    Some((r, g, b))
                }
                6 => {
                    let r = parse_hex_channel(&hex[0..2])? as f64;
                    let g = parse_hex_channel(&hex[2..4])? as f64;
                    let b = parse_hex_channel(&hex[4..6])? as f64;
                    Some((r, g, b))
                }
                _ => None,
            }
        }

        fn parse_csv_f64(s: &str) -> Option<Vec<f64>> {
            let mut out = Vec::new();
            for p in s.split(',') {
                let p = p.trim();
                if p.is_empty() {
                    return None;
                }
                out.push(p.parse::<f64>().ok()?);
            }
            Some(out)
        }

        fn parse_rgb_like(s: &str, prefix: &str) -> Option<(f64, f64, f64)> {
            let inner = s.trim().strip_prefix(prefix)?.strip_suffix(')')?;
            let parts = parse_csv_f64(inner)?;
            if parts.len() < 3 {
                return None;
            }
            Some((parts[0], parts[1], parts[2]))
        }

        fn parse_named_color(s: &str) -> Option<(f64, f64, f64)> {
            match s.trim().to_ascii_lowercase().as_str() {
                "black" => Some((0.0, 0.0, 0.0)),
                "white" => Some((255.0, 255.0, 255.0)),
                _ => None,
            }
        }

        fn parse_hsl_to_rgb(s: &str) -> Option<(f64, f64, f64)> {
            let inner = s.trim().strip_prefix("hsl(")?.strip_suffix(')')?;
            let mut parts = inner.split(',').map(|p| p.trim());
            let h = parts.next()?.parse::<f64>().ok()?;
            let s = parts
                .next()?
                .strip_suffix('%')?
                .trim()
                .parse::<f64>()
                .ok()?;
            let l = parts
                .next()?
                .strip_suffix('%')?
                .trim()
                .parse::<f64>()
                .ok()?;

            let h = (h / 360.0) % 1.0;
            let s = (s / 100.0).clamp(0.0, 1.0);
            let l = (l / 100.0).clamp(0.0, 1.0);

            if s == 0.0 {
                let v = (l * 255.0).round();
                return Some((v, v, v));
            }

            fn hue_to_rgb(p: f64, q: f64, mut t: f64) -> f64 {
                if t < 0.0 {
                    t += 1.0;
                }
                if t > 1.0 {
                    t -= 1.0;
                }
                if t < 1.0 / 6.0 {
                    return p + (q - p) * 6.0 * t;
                }
                if t < 1.0 / 2.0 {
                    return q;
                }
                if t < 2.0 / 3.0 {
                    return p + (q - p) * (2.0 / 3.0 - t) * 6.0;
                }
                p
            }

            let q = if l < 0.5 {
                l * (1.0 + s)
            } else {
                l + s - l * s
            };
            let p = 2.0 * l - q;
            let r = hue_to_rgb(p, q, h + 1.0 / 3.0) * 255.0;
            let g = hue_to_rgb(p, q, h) * 255.0;
            let b = hue_to_rgb(p, q, h - 1.0 / 3.0) * 255.0;
            Some((r, g, b))
        }

        let rgb = parse_hex_rgb(edge_label_background)
            .or_else(|| parse_rgb_like(edge_label_background, "rgb("))
            .or_else(|| parse_rgb_like(edge_label_background, "rgba("))
            .or_else(|| parse_hsl_to_rgb(edge_label_background))
            .or_else(|| parse_named_color(edge_label_background));

        let (r, g, b) = rgb.unwrap_or((232.0, 232.0, 232.0));
        let r = r.round().clamp(0.0, 255.0) as i64;
        let g = g.round().clamp(0.0, 255.0) as i64;
        let b = b.round().clamp(0.0, 255.0) as i64;
        format!("rgba({r}, {g}, {b}, 0.5)")
    }

    let label_bkg = flowchart_label_bkg_from_edge_label_background(&edge_label_background);

    let mut out = String::new();
    let _ = write!(
        &mut out,
        r#"#{}{{font-family:{};font-size:{}px;fill:{};}}"#,
        id.as_str(),
        font_family,
        fmt(font_size),
        text_color
    );
    out.push_str(
        r#"@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}"#,
    );
    let _ = write!(
        &mut out,
        r#"#{} .edge-animation-slow{{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}}#{} .edge-animation-fast{{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}}"#,
        id.as_str(),
        id.as_str()
    );
    let _ = write!(
        &mut out,
        r#"#{} .error-icon{{fill:{};}}#{} .error-text{{fill:{};stroke:{};}}"#,
        id.as_str(),
        error_bkg,
        id.as_str(),
        error_text,
        error_text
    );
    let _ = write!(
        &mut out,
        r#"#{} .edge-thickness-normal{{stroke-width:{}px;}}#{} .edge-thickness-thick{{stroke-width:3.5px;}}#{} .edge-pattern-solid{{stroke-dasharray:0;}}#{} .edge-thickness-invisible{{stroke-width:0;fill:none;}}#{} .edge-pattern-dashed{{stroke-dasharray:3;}}#{} .edge-pattern-dotted{{stroke-dasharray:2;}}"#,
        id.as_str(),
        stroke_width,
        id.as_str(),
        id.as_str(),
        id.as_str(),
        id.as_str(),
        id.as_str()
    );
    let _ = write!(
        &mut out,
        r#"#{} .marker{{fill:{};stroke:{};}}#{} .marker.cross{{stroke:{};}}"#,
        id.as_str(),
        stroke,
        stroke,
        id.as_str(),
        stroke
    );
    let _ = write!(
        &mut out,
        r#"#{} svg{{font-family:{};font-size:{}px;}}#{} p{{margin:0;}}#{} .label{{font-family:{};color:{};}}"#,
        id.as_str(),
        font_family,
        fmt(font_size),
        id.as_str(),
        id.as_str(),
        font_family,
        node_text_color
    );
    let _ = write!(
        &mut out,
        r#"#{} .cluster-label text{{fill:{};}}#{} .cluster-label span{{color:{};}}#{} .cluster-label span p{{background-color:transparent;}}#{} .label text,#{} span{{fill:{};color:{};}}"#,
        id.as_str(),
        title_color,
        id.as_str(),
        title_color,
        id.as_str(),
        id.as_str(),
        id.as_str(),
        node_text_color,
        node_text_color
    );
    let _ = write!(
        &mut out,
        r#"#{id} .node rect,#{id} .node circle,#{id} .node ellipse,#{id} .node polygon,#{id} .node path{{fill:{main_bkg};stroke:{node_border};stroke-width:{stroke_width}px;}}#{id} .rough-node .label text,#{id} .node .label text,#{id} .image-shape .label,#{id} .icon-shape .label{{text-anchor:middle;}}#{id} .node .katex path{{fill:#000;stroke:#000;stroke-width:1px;}}#{id} .rough-node .label,#{id} .node .label,#{id} .image-shape .label,#{id} .icon-shape .label{{text-align:center;}}#{id} .node.clickable{{cursor:pointer;}}"#
    );
    let _ = write!(
        &mut out,
        r#"#{} .root .anchor path{{fill:{}!important;stroke-width:0;stroke:{};}}#{} .arrowheadPath{{fill:{};}}#{} .edgePath .path{{stroke:{};stroke-width:{}px;}}#{} .flowchart-link{{stroke:{};fill:none;}}"#,
        id.as_str(),
        stroke,
        stroke,
        id.as_str(),
        arrowhead_color,
        id.as_str(),
        stroke,
        stroke_width,
        id.as_str(),
        stroke
    );
    let _ = write!(
        &mut out,
        r#"#{} .edgeLabel{{background-color:{};text-align:center;}}#{} .edgeLabel p{{background-color:{};}}#{} .edgeLabel rect{{opacity:0.5;background-color:{};fill:{};}}#{} .labelBkg{{background-color:{};}}"#,
        id.as_str(),
        edge_label_background,
        id.as_str(),
        edge_label_background,
        id.as_str(),
        edge_label_background,
        edge_label_background,
        id.as_str(),
        label_bkg
    );
    let _ = write!(
        &mut out,
        r#"#{} .cluster rect{{fill:{};stroke:{};stroke-width:1px;}}#{} .cluster text{{fill:{};}}#{} .cluster span{{color:{};}}#{} div.mermaidTooltip{{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:{};font-size:12px;background:{};border:1px solid {};border-radius:2px;pointer-events:none;z-index:100;}}#{} .flowchartTitleText{{text-anchor:middle;font-size:18px;fill:{};}}#{} rect.text{{fill:none;stroke-width:0;}}"#,
        escape_xml(diagram_id),
        cluster_bkg,
        cluster_border,
        escape_xml(diagram_id),
        title_color,
        escape_xml(diagram_id),
        title_color,
        escape_xml(diagram_id),
        font_family,
        tertiary,
        cluster_border,
        escape_xml(diagram_id),
        text_color,
        escape_xml(diagram_id)
    );
    let _ = write!(
        &mut out,
        r#"#{} .icon-shape,#{} .image-shape{{background-color:{};text-align:center;}}#{} .icon-shape p,#{} .image-shape p{{background-color:{};padding:2px;}}#{} .icon-shape .label rect,#{} .image-shape .label rect{{opacity:0.5;background-color:{};fill:{};}}#{} .label-icon{{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}}#{} .node .label-icon path{{fill:currentColor;stroke:revert;stroke-width:revert;}}#{} :root{{--mermaid-font-family:{};}}"#,
        id.as_str(),
        id.as_str(),
        edge_label_background,
        id.as_str(),
        id.as_str(),
        edge_label_background,
        id.as_str(),
        id.as_str(),
        edge_label_background,
        edge_label_background,
        id.as_str(),
        id.as_str(),
        id.as_str(),
        font_family
    );

    // Mermaid `createCssStyles(...)` chooses different selectors based on `htmlLabels`.
    // - HTML labels: `.classDef > *` + `.classDef span`
    // - SVG labels: `.classDef rect|polygon|ellipse|circle|path`
    let html_labels = crate::flowchart::flowchart_effective_html_labels(effective_config);
    let shape_elements: &[&str] = &["rect", "polygon", "ellipse", "circle", "path"];

    for (class, decls) in class_defs {
        if decls.is_empty() {
            continue;
        }
        let mut style = String::new();
        let mut text_color: Option<String> = None;
        for d in decls {
            let Some((k, v)) = parse_style_decl(d) else {
                continue;
            };
            let _ = write!(&mut style, "{}:{}!important;", k, v);
            if k == "color" {
                text_color = Some(v.to_string());
            }
        }
        if style.is_empty() {
            continue;
        }
        if html_labels {
            // Mermaid (via Stylis) ends up serializing the `>` combinator inside `<style>` as
            // `&gt;` in the final SVG string (see upstream baselines).
            let _ = write!(
                &mut out,
                r#"#{} .{}&gt;*{{{}}}#{} .{} span{{{}}}"#,
                id.as_str(),
                escape_xml(class),
                style,
                id.as_str(),
                escape_xml(class),
                style
            );
        } else {
            for css_element in shape_elements {
                let _ = write!(
                    &mut out,
                    r#"#{} .{} {}{{{}}}"#,
                    id.as_str(),
                    escape_xml(class),
                    css_element,
                    style
                );
            }
        }
        if let Some(c) = text_color.as_deref() {
            let _ = write!(
                &mut out,
                r#"#{} .{} tspan{{fill:{}!important;}}"#,
                id.as_str(),
                escape_xml(class),
                escape_xml(c)
            );
        }
    }

    out
}

#[inline]
pub(super) fn write_flowchart_edge_class_attr(out: &mut String, edge: &crate::flowchart::FlowEdge) {
    // Mermaid includes a 2-part class tuple (thickness/pattern) for flowchart edge paths. The
    // second tuple is `edge-thickness-normal edge-pattern-solid` in Mermaid@11.12.2 baselines,
    // even for dotted/thick strokes.
    let (thickness_1, pattern_1) = match edge.stroke.as_deref() {
        Some("thick") => ("edge-thickness-thick", "edge-pattern-solid"),
        Some("invisible") => ("edge-thickness-invisible", "edge-pattern-solid"),
        Some("dotted") => ("edge-thickness-normal", "edge-pattern-dotted"),
        _ => ("edge-thickness-normal", "edge-pattern-solid"),
    };

    if thickness_1 == "edge-thickness-invisible" {
        // Mermaid@11.12.2 does *not* include the second tuple nor `flowchart-link` for invisible
        // edges.
        out.push_str(thickness_1);
        out.push(' ');
        out.push_str(pattern_1);
        return;
    }

    out.push_str(thickness_1);
    out.push(' ');
    out.push_str(pattern_1);
    out.push_str(" edge-thickness-normal edge-pattern-solid flowchart-link");

    // Mermaid attaches animation classes directly on the edge path element when enabled via
    // edge-id `@{ ... }` blocks (e.g. `e1@{ animate: true }` or `e1@{ animation: fast }`).
    if edge.animate == Some(false) {
        return;
    }
    let animation_class = match edge.animation.as_deref() {
        Some("slow") => Some("edge-animation-slow"),
        Some(_) => Some("edge-animation-fast"),
        None => match edge.animate {
            Some(true) => Some("edge-animation-fast"),
            _ => None,
        },
    };
    if let Some(cls) = animation_class {
        out.push(' ');
        out.push_str(cls);
    }
}

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

    #[test]
    fn neutral_named_white_edge_label_background_fades_to_white() {
        let css = flowchart_css(
            "theme_neutral",
            &json!({
                "themeVariables": {
                    "edgeLabelBackground": "white"
                }
            }),
            "\"trebuchet ms\",verdana,arial,sans-serif",
            16.0,
            &IndexMap::new(),
        );

        assert!(
            css.contains("#theme_neutral .labelBkg{background-color:rgba(255, 255, 255, 0.5);}")
        );
    }

    #[test]
    fn unknown_edge_label_background_keeps_mermaid_default_fade() {
        let css = flowchart_css(
            "theme_unknown_color",
            &json!({
                "themeVariables": {
                    "edgeLabelBackground": "not-a-css-color"
                }
            }),
            "\"trebuchet ms\",verdana,arial,sans-serif",
            16.0,
            &IndexMap::new(),
        );

        assert!(css.contains(
            "#theme_unknown_color .labelBkg{background-color:rgba(232, 232, 232, 0.5);}"
        ));
    }
}