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
use std::fmt::Write as _;

use crate::architecture::{
    ARCHITECTURE_CREATE_TEXT_DEFAULT_WRAP_WIDTH_PX, ARCHITECTURE_SERVICE_LABEL_BOTTOM_EXTENSION_PX,
    architecture_create_text_bbox_height_px,
};
use crate::model::Bounds;
use crate::text::{TextMeasurer, VendoredFontMetricsTextMeasurer};

use super::super::{escape_xml, fmt};
use super::geometry::{
    arrow_points, arrow_shift, bounds_from_rect, edge_id, extend_bounds, is_arch_dir_x,
    is_arch_dir_y,
};
use super::labels::{svg_line_plain_text, wrap_svg_words_to_lines, write_svg_text_lines};
use super::model::ArchitectureModelAccess;
use super::settings::ArchitectureRenderSettings;
use crate::model::ArchitectureDiagramLayout;

pub(super) struct ArchitectureEdgeRenderContext<'a, M: ArchitectureModelAccess> {
    pub(super) out: &'a mut String,
    pub(super) layout: &'a ArchitectureDiagramLayout,
    pub(super) model: &'a M,
    pub(super) node_xy: &'a rustc_hash::FxHashMap<&'a str, (f64, f64)>,
    pub(super) settings: &'a ArchitectureRenderSettings,
    pub(super) text_measurer: &'a VendoredFontMetricsTextMeasurer,
    pub(super) content_bounds: &'a mut Option<Bounds>,
    pub(super) junction_bounds: &'a rustc_hash::FxHashMap<&'a str, Bounds>,
}

struct ArchitectureEdgeLabelPlan {
    lines: Vec<super::labels::SvgLine>,
    aabb_w: f64,
    aabb_h: f64,
    dominant_baseline: &'static str,
    transform: String,
}

#[derive(Clone, Copy)]
struct ArchitectureEdgePoints {
    start_x: f64,
    start_y: f64,
    mid_x: f64,
    mid_y: f64,
    end_x: f64,
    end_y: f64,
}

fn architecture_edge_label_plan(
    edge: super::model::ArchitectureEdgeRef<'_>,
    points: ArchitectureEdgePoints,
    settings: &ArchitectureRenderSettings,
    text_measurer: &VendoredFontMetricsTextMeasurer,
) -> Option<ArchitectureEdgeLabelPlan> {
    let label = edge.title.map(str::trim).filter(|t| !t.is_empty())?;
    let axis = match (is_arch_dir_x(edge.lhs_dir), is_arch_dir_x(edge.rhs_dir)) {
        (true, true) => "X",
        (false, false) => "Y",
        _ => "XY",
    };

    let wrap_width = match axis {
        "X" => (points.start_x - points.end_x).abs(),
        "Y" => (points.start_y - points.end_y).abs() / 1.5,
        _ => (points.start_x - points.end_x).abs() / 2.0,
    };
    let wrap_width = if wrap_width.is_finite() && wrap_width > 0.0 {
        wrap_width
    } else {
        ARCHITECTURE_CREATE_TEXT_DEFAULT_WRAP_WIDTH_PX
    };
    let lines = wrap_svg_words_to_lines(label, wrap_width, text_measurer, &settings.text_style);

    let mut bbox_w = 0.0f64;
    for line in &lines {
        let s = svg_line_plain_text(line);
        let m = text_measurer.measure_wrapped(
            s.as_str(),
            &settings.text_style,
            None,
            crate::text::WrapMode::SvgLike,
        );
        bbox_w = bbox_w.max(m.width);
    }
    let line_count = lines.len().max(1);
    let bbox_h = architecture_create_text_bbox_height_px(settings.svg_font_size_px, line_count);
    let half_bbox_h = bbox_h / 2.0;

    let (dominant_baseline, transform) = match axis {
        "Y" => (
            "middle",
            format!(
                r#"translate({}, {}) rotate(-90)"#,
                fmt(points.mid_x),
                fmt(points.mid_y)
            ),
        ),
        "XY" => {
            let pair = format!("{}{}", edge.lhs_dir, edge.rhs_dir);
            let (xf, yf): (f64, f64) = match pair.as_str() {
                "LT" | "TL" => (1.0, 1.0),
                "BL" | "LB" => (1.0, -1.0),
                "BR" | "RB" => (-1.0, -1.0),
                _ => (-1.0, 1.0),
            };
            let angle = (-xf * yf * 45.0f64).round() as i64;

            // Rotated bbox at 45° (w' == h' == (w+h)*sqrt(2)/2).
            let diag = (bbox_w + bbox_h) * std::f64::consts::FRAC_1_SQRT_2;
            let t2x = xf * diag / 2.0;
            let t2y = yf * diag / 2.0;
            // Mermaid CLI serializes newline characters inside attribute values as XML entities
            // (`&#10;`). Emit those explicitly so our SVG matches the upstream baselines.
            let sep = "&#10;";

            (
                "auto",
                format!(
                    "translate({}, {}){sep}                translate({}, {}){sep}                rotate({}, 0, {})",
                    fmt(points.mid_x),
                    fmt(points.mid_y - half_bbox_h),
                    fmt(t2x),
                    fmt(t2y),
                    angle,
                    fmt(half_bbox_h),
                    sep = sep
                ),
            )
        }
        _ => (
            "middle",
            format!(r#"translate({}, {})"#, fmt(points.mid_x), fmt(points.mid_y)),
        ),
    };

    let (aabb_w, aabb_h) = match axis {
        "X" => (bbox_w, bbox_h),
        "Y" => (bbox_h, bbox_w),
        _ => {
            // |cos(45°)| == |sin(45°)| == sqrt(1/2)
            let a = (bbox_w + bbox_h) * std::f64::consts::FRAC_1_SQRT_2;
            (a, a)
        }
    };

    Some(ArchitectureEdgeLabelPlan {
        lines,
        aabb_w: aabb_w.max(1.0),
        aabb_h: aabb_h.max(1.0),
        dominant_baseline,
        transform,
    })
}

pub(super) fn push_architecture_edges<M: ArchitectureModelAccess>(
    ctx: &mut ArchitectureEdgeRenderContext<'_, M>,
) {
    let out = &mut *ctx.out;
    let layout = ctx.layout;
    let model = ctx.model;
    let node_xy = ctx.node_xy;
    let settings = ctx.settings;
    let text_measurer = ctx.text_measurer;
    let content_bounds = &mut *ctx.content_bounds;
    let junction_bounds = ctx.junction_bounds;

    let group_edge_shift = settings.padding_px + 4.0;
    let group_edge_label_bottom_px = ARCHITECTURE_SERVICE_LABEL_BOTTOM_EXTENSION_PX;
    let is_junction = |id: &str| junction_bounds.contains_key(id);

    let layout_edge_points: Vec<(f64, f64, f64, f64, f64, f64)> = layout
        .edges
        .iter()
        .map(|e| {
            // Architecture layout edges are expected to be 3-point polylines.
            // Be defensive and fall back to zeros if the snapshot is malformed.
            let p0 = e.points.first().map(|p| (p.x, p.y)).unwrap_or((0.0, 0.0));
            let pm = e.points.get(1).map(|p| (p.x, p.y)).unwrap_or((0.0, 0.0));
            let p2 = e.points.last().map(|p| (p.x, p.y)).unwrap_or((0.0, 0.0));
            (p0.0, p0.1, pm.0, pm.1, p2.0, p2.1)
        })
        .collect();

    let edge_points =
        |edge_idx: usize, edge: super::model::ArchitectureEdgeRef<'_>| -> ArchitectureEdgePoints {
            // Prefer layout-provided points: this is where we model Mermaid/Cytoscape edge routing.
            //
            // The layout points represent raw Cytoscape endpoints; Mermaid applies group/junction
            // endpoint shifts later, during SVG emission.
            let (raw_start_x, raw_start_y, mid_x, mid_y, raw_end_x, raw_end_y) = layout_edge_points
                .get(edge_idx)
                .copied()
                .unwrap_or_else(|| {
                    let (sx, sy) = node_xy.get(edge.lhs_id).copied().unwrap_or((0.0, 0.0));
                    let (tx, ty) = node_xy.get(edge.rhs_id).copied().unwrap_or((0.0, 0.0));

                    let (sx, sy) = match edge.lhs_dir {
                        'L' => (sx, sy + settings.half_icon),
                        'R' => (sx + settings.icon_size_px, sy + settings.half_icon),
                        'T' => (sx + settings.half_icon, sy),
                        'B' => (sx + settings.half_icon, sy + settings.icon_size_px),
                        _ => (sx + settings.half_icon, sy + settings.half_icon),
                    };
                    let (tx, ty) = match edge.rhs_dir {
                        'L' => (tx, ty + settings.half_icon),
                        'R' => (tx + settings.icon_size_px, ty + settings.half_icon),
                        'T' => (tx + settings.half_icon, ty),
                        'B' => (tx + settings.half_icon, ty + settings.icon_size_px),
                        _ => (tx + settings.half_icon, ty + settings.half_icon),
                    };

                    let (mx, my) = if (sx - tx).abs() > 1e-6 && (sy - ty).abs() > 1e-6 {
                        // Match upstream Mermaid: choose the bend based on the *source* dir.
                        if is_arch_dir_y(edge.lhs_dir) {
                            (sx, ty)
                        } else {
                            (tx, sy)
                        }
                    } else {
                        ((sx + tx) / 2.0, (sy + ty) / 2.0)
                    };
                    (sx, sy, mx, my, tx, ty)
                });

            let mut start_x = raw_start_x;
            let mut start_y = raw_start_y;
            let mut end_x = raw_end_x;
            let mut end_y = raw_end_y;

            let lhs_group = edge.lhs_group.unwrap_or(false);
            if lhs_group {
                if is_arch_dir_x(edge.lhs_dir) {
                    start_x += if edge.lhs_dir == 'L' {
                        -group_edge_shift
                    } else {
                        group_edge_shift
                    };
                } else {
                    start_y += if edge.lhs_dir == 'T' {
                        -group_edge_shift
                    } else {
                        group_edge_shift + group_edge_label_bottom_px
                    };
                }
            }
            if !lhs_group && is_junction(edge.lhs_id) {
                if is_arch_dir_x(edge.lhs_dir) {
                    start_x += if edge.lhs_dir == 'L' {
                        settings.half_icon
                    } else {
                        -settings.half_icon
                    };
                } else {
                    start_y += if edge.lhs_dir == 'T' {
                        settings.half_icon
                    } else {
                        -settings.half_icon
                    };
                }
            }

            let rhs_group = edge.rhs_group.unwrap_or(false);
            if rhs_group {
                if is_arch_dir_x(edge.rhs_dir) {
                    end_x += if edge.rhs_dir == 'L' {
                        -group_edge_shift
                    } else {
                        group_edge_shift
                    };
                } else {
                    end_y += if edge.rhs_dir == 'T' {
                        -group_edge_shift
                    } else {
                        group_edge_shift + group_edge_label_bottom_px
                    };
                }
            }
            if !rhs_group && is_junction(edge.rhs_id) {
                if is_arch_dir_x(edge.rhs_dir) {
                    end_x += if edge.rhs_dir == 'L' {
                        settings.half_icon
                    } else {
                        -settings.half_icon
                    };
                } else {
                    end_y += if edge.rhs_dir == 'T' {
                        settings.half_icon
                    } else {
                        -settings.half_icon
                    };
                }
            }

            ArchitectureEdgePoints {
                start_x,
                start_y,
                mid_x,
                mid_y,
                end_x,
                end_y,
            }
        };

    // Edges (including conservative label bounds).
    if model.edges_len() != 0 {
        let arrow_size = settings.icon_size_px / 6.0;
        let half_arrow_size = arrow_size / 2.0;
        for (edge_idx, edge) in model.edges().enumerate() {
            let points = edge_points(edge_idx, edge);

            extend_bounds(
                content_bounds,
                Bounds::from_points(vec![
                    (points.start_x, points.start_y),
                    (points.mid_x, points.mid_y),
                    (points.end_x, points.end_y),
                ])
                .unwrap_or(Bounds {
                    min_x: points.start_x,
                    min_y: points.start_y,
                    max_x: points.end_x,
                    max_y: points.end_y,
                }),
            );

            if edge.lhs_into == Some(true) {
                let x_shift = if is_arch_dir_x(edge.lhs_dir) {
                    arrow_shift(edge.lhs_dir, points.start_x, arrow_size)
                } else {
                    points.start_x - half_arrow_size
                };
                let y_shift = if is_arch_dir_y(edge.lhs_dir) {
                    arrow_shift(edge.lhs_dir, points.start_y, arrow_size)
                } else {
                    points.start_y - half_arrow_size
                };
                extend_bounds(
                    content_bounds,
                    bounds_from_rect(x_shift, y_shift, arrow_size, arrow_size),
                );
            }

            if edge.rhs_into == Some(true) {
                let x_shift = if is_arch_dir_x(edge.rhs_dir) {
                    arrow_shift(edge.rhs_dir, points.end_x, arrow_size)
                } else {
                    points.end_x - half_arrow_size
                };
                let y_shift = if is_arch_dir_y(edge.rhs_dir) {
                    arrow_shift(edge.rhs_dir, points.end_y, arrow_size)
                } else {
                    points.end_y - half_arrow_size
                };
                extend_bounds(
                    content_bounds,
                    bounds_from_rect(x_shift, y_shift, arrow_size, arrow_size),
                );
            }

            let label_plan = architecture_edge_label_plan(edge, points, settings, text_measurer);
            if let Some(label_plan) = label_plan.as_ref() {
                extend_bounds(
                    content_bounds,
                    bounds_from_rect(
                        points.mid_x - label_plan.aabb_w / 2.0,
                        points.mid_y - label_plan.aabb_h / 2.0,
                        label_plan.aabb_w,
                        label_plan.aabb_h,
                    ),
                );
            }

            out.push_str("<g>");
            let id = edge_id("L", edge.lhs_id, edge.rhs_id, 0);
            let _ = write!(
                out,
                r#"<path d="M {sx},{sy} L {mx},{my} L{ex},{ey} " class="edge" id="{id}"/>"#,
                sx = fmt(points.start_x),
                sy = fmt(points.start_y),
                mx = fmt(points.mid_x),
                my = fmt(points.mid_y),
                ex = fmt(points.end_x),
                ey = fmt(points.end_y),
                id = escape_xml(&id)
            );

            if edge.lhs_into == Some(true) {
                let x_shift = if is_arch_dir_x(edge.lhs_dir) {
                    arrow_shift(edge.lhs_dir, points.start_x, arrow_size)
                } else {
                    points.start_x - half_arrow_size
                };
                let y_shift = if is_arch_dir_y(edge.lhs_dir) {
                    arrow_shift(edge.lhs_dir, points.start_y, arrow_size)
                } else {
                    points.start_y - half_arrow_size
                };
                let _ = write!(
                    out,
                    r#"<polygon points="{pts}" transform="translate({x},{y})" class="arrow"/>"#,
                    pts = arrow_points(edge.lhs_dir, arrow_size),
                    x = fmt(x_shift),
                    y = fmt(y_shift)
                );
            }

            if edge.rhs_into == Some(true) {
                let x_shift = if is_arch_dir_x(edge.rhs_dir) {
                    arrow_shift(edge.rhs_dir, points.end_x, arrow_size)
                } else {
                    points.end_x - half_arrow_size
                };
                let y_shift = if is_arch_dir_y(edge.rhs_dir) {
                    arrow_shift(edge.rhs_dir, points.end_y, arrow_size)
                } else {
                    points.end_y - half_arrow_size
                };
                let _ = write!(
                    out,
                    r#"<polygon points="{pts}" transform="translate({x},{y})" class="arrow"/>"#,
                    pts = arrow_points(edge.rhs_dir, arrow_size),
                    x = fmt(x_shift),
                    y = fmt(y_shift)
                );
            }

            if let Some(label_plan) = label_plan {
                let _ = write!(
                    out,
                    r#"<g dy="1em" alignment-baseline="middle" dominant-baseline="{baseline}" text-anchor="middle" transform="{transform}">"#,
                    baseline = label_plan.dominant_baseline,
                    transform = label_plan.transform.as_str()
                );
                out.push_str(r#"<g><rect class="background" style="stroke: none"/>"#);
                write_svg_text_lines(out, &label_plan.lines);
                out.push_str("</g></g>");
            }

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