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
use crate::Result;
use crate::model::{Bounds, PieDiagramLayout, PieLegendItemLayout, PieSliceLayout};
use crate::text::{TextMeasurer, TextStyle};
use merman_core::diagrams::pie::{PieDiagramRenderModel, PieRenderSection};
use ryu_js::Buffer;
use std::cmp::Ordering;

pub(crate) const PIE_LEGEND_RECT_SIZE_PX: f64 = 18.0;
pub(crate) const PIE_LEGEND_SPACING_PX: f64 = 4.0;

#[derive(Debug, Clone)]
struct ColorScale {
    palette: Vec<String>,
    mapping: std::collections::HashMap<String, usize>,
    next: usize,
}

#[derive(Debug, Clone, Copy)]
struct Rgb01 {
    r: f64,
    g: f64,
    b: f64,
}

#[derive(Debug, Clone, Copy)]
struct Hsl {
    h_deg: f64,
    s_pct: f64,
    l_pct: f64,
}

fn round_1e10(v: f64) -> f64 {
    let v = (v * 1e10).round() / 1e10;
    if v == -0.0 { 0.0 } else { v }
}

fn fmt_js_1e10(v: f64) -> String {
    let v = round_1e10(v);
    let mut b = Buffer::new();
    b.format_finite(v).to_string()
}

fn round_hsl_1e10(mut hsl: Hsl) -> Hsl {
    // Match Mermaid's base theme output: wrap using remainder without forcing positive hue.
    // (JS `%` keeps the sign, so negative hues remain negative.)
    hsl.h_deg = round_1e10(hsl.h_deg) % 360.0;
    hsl.s_pct = round_1e10(hsl.s_pct).clamp(0.0, 100.0);
    hsl.l_pct = round_1e10(hsl.l_pct).clamp(0.0, 100.0);
    hsl
}

fn parse_hex_rgb01(s: &str) -> Option<Rgb01> {
    let s = s.trim();
    let s = s.strip_prefix('#')?;
    if s.len() != 6 {
        return None;
    }
    let r = u8::from_str_radix(&s[0..2], 16).ok()? as f64 / 255.0;
    let g = u8::from_str_radix(&s[2..4], 16).ok()? as f64 / 255.0;
    let b = u8::from_str_radix(&s[4..6], 16).ok()? as f64 / 255.0;
    Some(Rgb01 { r, g, b })
}

fn rgb01_to_hsl(rgb: Rgb01) -> Hsl {
    let r = rgb.r;
    let g = rgb.g;
    let b = rgb.b;

    let max = r.max(g.max(b));
    let min = r.min(g.min(b));
    let mut h = 0.0;
    let mut s = 0.0;
    let l = (max + min) / 2.0;

    if max != min {
        let d = max - min;
        s = if l > 0.5 {
            d / (2.0 - max - min)
        } else {
            d / (max + min)
        };

        h = if max == r {
            (g - b) / d + if g < b { 6.0 } else { 0.0 }
        } else if max == g {
            (b - r) / d + 2.0
        } else {
            (r - g) / d + 4.0
        };
        h /= 6.0;
    }

    round_hsl_1e10(Hsl {
        h_deg: h * 360.0,
        s_pct: s * 100.0,
        l_pct: l * 100.0,
    })
}

fn parse_hsl(s: &str) -> Option<Hsl> {
    let s = s.trim();
    let inner = s.strip_prefix("hsl(")?.strip_suffix(')')?;
    let parts: Vec<&str> = inner.split(',').map(|p| p.trim()).collect();
    if parts.len() != 3 {
        return None;
    }
    let h = parts[0].parse::<f64>().ok()?;
    let s_pct = parts[1].trim_end_matches('%').parse::<f64>().ok()?;
    let l_pct = parts[2].trim_end_matches('%').parse::<f64>().ok()?;
    Some(round_hsl_1e10(Hsl {
        h_deg: h,
        s_pct,
        l_pct,
    }))
}

fn adjust_hsl(mut hsl: Hsl, h_delta: f64, s_delta: f64, l_delta: f64) -> Hsl {
    hsl.h_deg = (hsl.h_deg + h_delta) % 360.0;
    hsl.s_pct = (hsl.s_pct + s_delta).clamp(0.0, 100.0);
    hsl.l_pct = (hsl.l_pct + l_delta).clamp(0.0, 100.0);
    round_hsl_1e10(hsl)
}

fn fmt_hsl(hsl: Hsl) -> String {
    format!(
        "hsl({}, {}%, {}%)",
        fmt_js_1e10(hsl.h_deg),
        fmt_js_1e10(hsl.s_pct),
        fmt_js_1e10(hsl.l_pct)
    )
}

fn adjust_color_to_hsl_string(
    color: &str,
    h_delta: f64,
    s_delta: f64,
    l_delta: f64,
) -> Option<String> {
    let base = if let Some(rgb) = parse_hex_rgb01(color) {
        rgb01_to_hsl(rgb)
    } else if let Some(hsl) = parse_hsl(color) {
        hsl
    } else {
        return None;
    };
    Some(fmt_hsl(adjust_hsl(base, h_delta, s_delta, l_delta)))
}

impl ColorScale {
    fn new_default() -> Self {
        // Default theme colors as emitted by Mermaid 11.12.2 in SVG.
        //
        // Mermaid derives this palette from `theme-default.js` `pie1..pie12` (using `adjust()`),
        // where the base colors are:
        // - primaryColor = "#ECECFF"
        // - secondaryColor = "#ffffde"
        // - tertiaryColor = "hsl(80, 100%, 96.2745098039%)"
        //
        // Note: `adjust(...)` serializes as `hsl(...)` (not hex), so the palette contains a mix.
        const PRIMARY: &str = "#ECECFF";
        const SECONDARY: &str = "#ffffde";
        const TERTIARY: &str = "hsl(80, 100%, 96.2745098039%)";

        let pie3 = adjust_color_to_hsl_string(TERTIARY, 0.0, 0.0, -40.0)
            .unwrap_or_else(|| "hsl(80, 100%, 56.2745098039%)".to_string());
        let pie4 = adjust_color_to_hsl_string(PRIMARY, 0.0, 0.0, -10.0)
            .unwrap_or_else(|| "hsl(240, 100%, 86.2745098039%)".to_string());
        let pie5 = adjust_color_to_hsl_string(SECONDARY, 0.0, 0.0, -30.0)
            .unwrap_or_else(|| "hsl(60, 100%, 57.0588235294%)".to_string());
        let pie6 = adjust_color_to_hsl_string(TERTIARY, 0.0, 0.0, -20.0)
            .unwrap_or_else(|| "hsl(80, 100%, 76.2745098039%)".to_string());
        let pie7 = adjust_color_to_hsl_string(PRIMARY, 60.0, 0.0, -20.0)
            .unwrap_or_else(|| "hsl(300, 100%, 76.2745098039%)".to_string());
        let pie8 = adjust_color_to_hsl_string(PRIMARY, -60.0, 0.0, -40.0)
            .unwrap_or_else(|| "hsl(180, 100%, 56.2745098039%)".to_string());
        let pie9 = adjust_color_to_hsl_string(PRIMARY, 120.0, 0.0, -40.0)
            .unwrap_or_else(|| "hsl(0, 100%, 56.2745098039%)".to_string());
        let pie10 = adjust_color_to_hsl_string(PRIMARY, 60.0, 0.0, -40.0)
            .unwrap_or_else(|| "hsl(300, 100%, 56.2745098039%)".to_string());
        let pie11 = adjust_color_to_hsl_string(PRIMARY, -90.0, 0.0, -40.0)
            .unwrap_or_else(|| "hsl(150, 100%, 56.2745098039%)".to_string());
        let pie12 = adjust_color_to_hsl_string(PRIMARY, 120.0, 0.0, -30.0)
            .unwrap_or_else(|| "hsl(0, 100%, 66.2745098039%)".to_string());

        Self {
            palette: vec![
                PRIMARY.to_string(),
                SECONDARY.to_string(),
                pie3,
                pie4,
                pie5,
                pie6,
                pie7,
                pie8,
                pie9,
                pie10,
                pie11,
                pie12,
            ],
            mapping: std::collections::HashMap::new(),
            next: 0,
        }
    }

    fn color_for(&mut self, label: &str) -> String {
        if let Some(idx) = self.mapping.get(label).copied() {
            return self.palette[idx % self.palette.len()].clone();
        }
        let idx = self.next;
        self.next += 1;
        self.mapping.insert(label.to_string(), idx);
        self.palette[idx % self.palette.len()].clone()
    }
}

fn polar_xy(radius: f64, angle: f64) -> (f64, f64) {
    // Mermaid pie charts use a "12 o'clock is zero" convention with y increasing downwards.
    let x = radius * angle.sin();
    let y = -radius * angle.cos();
    (x, y)
}

fn fmt_number(v: f64) -> String {
    if !v.is_finite() {
        return "0".to_string();
    }
    if v.abs() < 0.0005 {
        return "0".to_string();
    }
    let mut r = (v * 1000.0).round() / 1000.0;
    if r.abs() < 0.0005 {
        r = 0.0;
    }
    let mut s = format!("{r:.3}");
    if s.contains('.') {
        while s.ends_with('0') {
            s.pop();
        }
        if s.ends_with('.') {
            s.pop();
        }
    }
    if s == "-0" { "0".to_string() } else { s }
}

pub fn layout_pie_diagram(
    semantic: &serde_json::Value,
    _effective_config: &serde_json::Value,
    measurer: &dyn TextMeasurer,
) -> Result<PieDiagramLayout> {
    let model: PieDiagramRenderModel = crate::json::from_value_ref(semantic)?;
    layout_pie_diagram_typed(&model, _effective_config, measurer)
}

pub fn layout_pie_diagram_typed(
    model: &PieDiagramRenderModel,
    _effective_config: &serde_json::Value,
    measurer: &dyn TextMeasurer,
) -> Result<PieDiagramLayout> {
    let _ = (
        model.title.as_deref(),
        model.acc_title.as_deref(),
        model.acc_descr.as_deref(),
    );

    // Mermaid@11.12.2 `packages/mermaid/src/diagrams/pie/pieRenderer.ts` constants.
    let margin: f64 = 40.0;
    let legend_rect_size = PIE_LEGEND_RECT_SIZE_PX;
    let legend_spacing = PIE_LEGEND_SPACING_PX;

    let center: f64 = 225.0;
    let radius: f64 = 185.0;
    let outer_radius = radius + 1.0;
    let label_radius = radius.max(0.0) * 0.75;
    let legend_x = 12.0 * legend_rect_size;
    let legend_step_y: f64 = legend_rect_size + legend_spacing;
    let legend_start_y: f64 = -(legend_step_y * (model.sections.len().max(1) as f64)) / 2.0;

    let total: f64 = model
        .sections
        .iter()
        .filter(|s| s.value.is_finite() && s.value >= 0.0)
        .map(|s| s.value)
        .sum();

    let mut color_scale = ColorScale::new_default();

    let mut slices: Vec<PieSliceLayout> = Vec::new();
    if total.is_finite() && total > 0.0 {
        // Mermaid@11.12.2 `packages/mermaid/src/diagrams/pie/pieRenderer.ts`:
        //
        // - filter out values < 1% (based on the original total)
        // - sort remaining values by descending value before D3 pie() computes angles
        // - angles are normalized over the filtered set (so drawn slices fill the whole circle)
        // - percentage labels are still computed using the original total
        let mut pie_sections: Vec<&PieRenderSection> = model
            .sections
            .iter()
            .filter(|s| s.value.is_finite() && s.value > 0.0)
            .filter(|s| (s.value / total) * 100.0 >= 1.0)
            .collect();
        pie_sections.sort_by(|a, b| b.value.partial_cmp(&a.value).unwrap_or(Ordering::Equal));

        let pie_total: f64 = pie_sections.iter().map(|s| s.value).sum();
        if !pie_sections.is_empty() && pie_total.is_finite() && pie_total > 0.0 {
            if pie_sections.len() == 1 {
                let s = pie_sections[0];
                let fill = color_scale.color_for(&s.label);
                let (tx, ty) = polar_xy(label_radius, std::f64::consts::PI);
                let percent = ((100.0 * (s.value / total)).max(0.0)).round() as i64;
                slices.push(PieSliceLayout {
                    label: s.label.clone(),
                    value: s.value,
                    start_angle: 0.0,
                    end_angle: std::f64::consts::TAU,
                    is_full_circle: true,
                    percent,
                    text_x: tx,
                    text_y: ty,
                    fill,
                });
            } else {
                let mut start = 0.0;
                for s in pie_sections {
                    let frac = (s.value / pie_total).max(0.0);
                    let delta = (frac * std::f64::consts::TAU).max(0.0);
                    let end = start + delta;
                    let mid = (start + end) / 2.0;
                    let (tx, ty) = polar_xy(label_radius, mid);
                    let fill = color_scale.color_for(&s.label);
                    let percent = ((100.0 * (s.value / total)).max(0.0)).round() as i64;
                    if percent != 0 {
                        slices.push(PieSliceLayout {
                            label: s.label.clone(),
                            value: s.value,
                            start_angle: start,
                            end_angle: end,
                            is_full_circle: false,
                            percent,
                            text_x: tx,
                            text_y: ty,
                            fill,
                        });
                    }
                    start = end;
                }
            }
        }
    }

    // Lock the color scale domain based on the drawn slices first, then compute legend colors in
    // the original section order (this matches Mermaid's zero-slice behavior).
    let mut legend_items: Vec<PieLegendItemLayout> = Vec::new();
    for (i, sec) in model.sections.iter().enumerate() {
        let y = legend_start_y + (i as f64) * legend_step_y;
        let fill = color_scale.color_for(&sec.label);
        legend_items.push(PieLegendItemLayout {
            label: sec.label.clone(),
            value: sec.value,
            fill,
            y,
        });
    }

    let legend_style = TextStyle {
        font_family: None,
        font_size: 17.0,
        font_weight: None,
    };
    let mut max_legend_width: f64 = 0.0;
    for sec in &model.sections {
        let label = if model.show_data {
            format!("{} [{}]", sec.label, fmt_number(sec.value))
        } else {
            sec.label.clone()
        };
        let trimmed = label.trim_end();
        // Mermaid pie legend labels render as a single SVG `<text>` run and compute
        // `longestTextWidth` from each node's bounding client rect. The shared SVG bbox extents are
        // closer to that browser width than the wrapped-text width path and remove the need for
        // fixture-specific root viewport pins.
        let w = if trimmed.is_empty() {
            0.0
        } else {
            let (left, right) = measurer.measure_svg_text_bbox_x(trimmed, &legend_style);
            crate::text::round_to_1_64_px((left + right).max(0.0))
        };
        max_legend_width = max_legend_width.max(w);
    }

    let base_w: f64 = center * 2.0;
    // Mermaid computes:
    //   totalWidth = pieWidth + MARGIN + LEGEND_RECT_SIZE + LEGEND_SPACING + longestTextWidth
    // where `pieWidth == height == 450`.
    let width: f64 =
        (base_w + margin + legend_rect_size + legend_spacing + max_legend_width).max(1.0);
    let height: f64 = f64::max(center * 2.0, 1.0);

    Ok(PieDiagramLayout {
        bounds: Some(Bounds {
            min_x: 0.0,
            min_y: 0.0,
            max_x: width,
            max_y: height,
        }),
        center_x: center,
        center_y: center,
        radius,
        outer_radius,
        legend_x,
        legend_start_y,
        legend_step_y,
        slices,
        legend_items,
    })
}

#[cfg(test)]
mod tests {
    #[test]
    fn pie_legend_geometry_constants_match_mermaid() {
        assert_eq!(super::PIE_LEGEND_RECT_SIZE_PX, 18.0);
        assert_eq!(super::PIE_LEGEND_SPACING_PX, 4.0);
    }
}