merman-render 0.8.0-alpha.3

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
use crate::Result;
use crate::entities::decode_entities_minimal;
use crate::svg::foreign_object_label_fallback_svg_text;
use std::borrow::Cow;
use std::collections::HashSet;

use super::util::{extract_quoted_attr, find_tag_end};
use crate::svg::pipeline::{SvgPostprocessContext, SvgPostprocessor};

#[derive(Debug, Clone, Copy, Default)]
pub struct ForeignObjectFallbackPostprocessor;

impl SvgPostprocessor for ForeignObjectFallbackPostprocessor {
    fn name(&self) -> &'static str {
        "foreign-object-fallback"
    }

    fn process<'a>(
        &self,
        svg: Cow<'a, str>,
        _ctx: &SvgPostprocessContext<'_>,
    ) -> Result<Cow<'a, str>> {
        if !svg.contains("<foreignObject") {
            return Ok(svg);
        }
        Ok(Cow::Owned(foreign_object_fallback_svg(&svg)))
    }
}

#[derive(Debug, Clone, Copy, Default)]
pub struct StripForeignObjectPostprocessor;

impl SvgPostprocessor for StripForeignObjectPostprocessor {
    fn name(&self) -> &'static str {
        "strip-foreign-object"
    }

    fn process<'a>(
        &self,
        svg: Cow<'a, str>,
        _ctx: &SvgPostprocessContext<'_>,
    ) -> Result<Cow<'a, str>> {
        if !svg.contains("<foreignObject") {
            return Ok(svg);
        }
        Ok(Cow::Owned(strip_foreign_objects(&svg)))
    }
}

#[derive(Debug, Clone, Copy, Default)]
pub struct DropNativeDuplicateFallbacksPostprocessor;

impl SvgPostprocessor for DropNativeDuplicateFallbacksPostprocessor {
    fn name(&self) -> &'static str {
        "drop-native-duplicate-fallbacks"
    }

    fn process<'a>(
        &self,
        svg: Cow<'a, str>,
        _ctx: &SvgPostprocessContext<'_>,
    ) -> Result<Cow<'a, str>> {
        if !svg.contains(r#"data-merman-foreignobject="fallback""#) {
            return Ok(svg);
        }
        Ok(Cow::Owned(drop_native_duplicate_fallbacks(&svg)))
    }
}

pub(crate) fn drop_switch_native_fallbacks(svg: &str) -> String {
    if !svg.contains(r#"data-merman-foreignobject-source="switch-native-fallback""#) {
        return svg.to_string();
    }
    let marker = r#"data-merman-foreignobject-source="switch-native-fallback""#;
    let mut out = String::with_capacity(svg.len());
    let mut cursor = 0;

    while let Some(rel_start) = svg[cursor..].find(marker) {
        let attr_start = cursor + rel_start;
        let Some(group_start) = svg[..attr_start].rfind("<g") else {
            out.push_str(&svg[cursor..attr_start]);
            cursor = attr_start + marker.len();
            continue;
        };
        if group_start < cursor {
            out.push_str(&svg[cursor..attr_start]);
            cursor = attr_start + marker.len();
            continue;
        }
        let Some((_, group_end)) = find_matching_g_end(svg, group_start) else {
            out.push_str(&svg[cursor..attr_start]);
            cursor = attr_start + marker.len();
            continue;
        };
        out.push_str(&svg[cursor..group_start]);
        cursor = group_end;
    }

    out.push_str(&svg[cursor..]);
    out
}

pub(crate) fn foreign_object_fallback_svg(svg: &str) -> String {
    foreign_object_label_fallback_svg_text(svg)
}

pub(crate) fn strip_foreign_objects(svg: &str) -> String {
    let mut out = String::with_capacity(svg.len());
    let mut cursor = 0;

    while let Some(rel_start) = svg[cursor..].find("<foreignObject") {
        let start = cursor + rel_start;

        let Some(open_end) = find_tag_end(svg, start) else {
            out.push_str(&svg[cursor..]);
            return out;
        };
        let fo_tag = &svg[start..=open_end];
        let switch_wrapper = find_wrapping_switch(svg, cursor, start, open_end);

        if let Some((switch_start, switch_close_start, switch_close_end)) = switch_wrapper {
            // This foreignObject is part of a <switch> element with native SVG fallback text.
            // Unwrap the <switch>: remove <switch> + <foreignObject>, keep sibling <text>
            // fallback elements.
            out.push_str(&svg[cursor..switch_start]);
            if !fo_tag.trim_end().ends_with("/>") {
                let fo_close_start = open_end + 1;
                if let Some(fo_close_rel) = svg[fo_close_start..].find("</foreignObject>") {
                    let after_fo = fo_close_start + fo_close_rel + "</foreignObject>".len();
                    out.push_str(&svg[after_fo..switch_close_start]);
                }
            }
            cursor = switch_close_end;
            continue;
        }

        out.push_str(&svg[cursor..start]);

        if fo_tag.trim_end().ends_with("/>") {
            cursor = open_end + 1;
            continue;
        }

        let close_start = open_end + 1;
        let Some(rel_close) = svg[close_start..].find("</foreignObject>") else {
            cursor = open_end + 1;
            continue;
        };
        cursor = close_start + rel_close + "</foreignObject>".len();
    }

    out.push_str(&svg[cursor..]);
    out
}

fn find_wrapping_switch(
    svg: &str,
    cursor: usize,
    foreign_object_start: usize,
    foreign_object_open_end: usize,
) -> Option<(usize, usize, usize)> {
    let switch_start = find_wrapping_switch_start(svg, cursor, foreign_object_start)?;
    if svg[switch_start..foreign_object_start]
        .find("</switch>")
        .is_some()
    {
        return None;
    }

    let foreign_object_end = if svg[foreign_object_start..=foreign_object_open_end]
        .trim_end()
        .ends_with("/>")
    {
        foreign_object_open_end + 1
    } else {
        let close_search_start = foreign_object_open_end + 1;
        close_search_start
            + svg[close_search_start..].find("</foreignObject>")?
            + "</foreignObject>".len()
    };

    let switch_close_start = foreign_object_end + svg[foreign_object_end..].find("</switch>")?;
    if !svg[foreign_object_end..switch_close_start].contains("<text") {
        return None;
    }

    Some((
        switch_start,
        switch_close_start,
        switch_close_start + "</switch>".len(),
    ))
}

fn find_wrapping_switch_start(svg: &str, cursor: usize, before: usize) -> Option<usize> {
    let mut search_end = before;
    while search_end > cursor {
        let rel_start = svg[cursor..search_end].rfind("<switch")?;
        let start = cursor + rel_start;
        let open_end = find_tag_end(svg, start)?;
        if open_end >= before {
            search_end = start;
            continue;
        }

        let tag = &svg[start..=open_end];
        if is_start_switch_tag(tag) {
            return Some(start);
        }

        search_end = start;
    }
    None
}

pub fn drop_native_duplicate_fallbacks(svg: &str) -> String {
    let native_text = collect_native_text_contents(svg);
    if native_text.is_empty() {
        return svg.to_string();
    }

    let mut out = String::with_capacity(svg.len());
    let mut cursor = 0;
    while let Some(rel_start) = svg[cursor..].find(r#"data-merman-foreignobject="fallback""#) {
        let attr_start = cursor + rel_start;
        let Some(group_start) = svg[..attr_start].rfind("<g") else {
            out.push_str(&svg[cursor..attr_start]);
            cursor = attr_start;
            continue;
        };
        if group_start < cursor {
            out.push_str(&svg[cursor..attr_start]);
            cursor = attr_start;
            continue;
        }
        let Some((close_start, group_end)) = find_matching_g_end(svg, group_start) else {
            out.push_str(&svg[cursor..attr_start]);
            cursor = attr_start;
            continue;
        };
        let Some(open_end) = find_tag_end(svg, group_start) else {
            out.push_str(&svg[cursor..attr_start]);
            cursor = attr_start;
            continue;
        };

        let fallback_text = normalize_text_content(&svg[open_end + 1..close_start]);
        if native_text.contains(fallback_text.trim()) {
            out.push_str(&svg[cursor..group_start]);
        } else {
            out.push_str(&svg[cursor..group_end]);
        }
        cursor = group_end;
    }

    out.push_str(&svg[cursor..]);
    out
}

fn collect_native_text_contents(svg: &str) -> HashSet<String> {
    let mut contents = HashSet::new();
    let mut cursor = 0;
    while let Some(rel_start) = svg[cursor..].find("<text") {
        let start = cursor + rel_start;
        let Some(open_end) = find_tag_end(svg, start) else {
            break;
        };
        let tag = &svg[start..=open_end];
        if text_tag_is_fallback(tag) || tag.trim_end().ends_with("/>") {
            cursor = open_end + 1;
            continue;
        }

        let close_start = open_end + 1;
        let Some(rel_close) = svg[close_start..].find("</text>") else {
            cursor = open_end + 1;
            continue;
        };
        let close = close_start + rel_close;
        let text = normalize_text_content(&svg[close_start..close]);
        if !text.is_empty() {
            contents.insert(text);
        }
        cursor = close + "</text>".len();
    }
    contents
}

fn text_tag_is_fallback(tag: &str) -> bool {
    extract_quoted_attr(tag, "class").is_some_and(|classes| {
        classes
            .split_whitespace()
            .any(|class| class == "merman-foreignobject-fallback-text")
    })
}

fn normalize_text_content(fragment: &str) -> String {
    decode_entities_minimal(&strip_tags(fragment))
        .trim()
        .to_string()
}

fn strip_tags(fragment: &str) -> String {
    let mut out = String::with_capacity(fragment.len());
    let mut in_tag = false;
    for ch in fragment.chars() {
        match ch {
            '<' => in_tag = true,
            '>' => in_tag = false,
            _ if !in_tag => out.push(ch),
            _ => {}
        }
    }
    out
}

fn find_matching_g_end(svg: &str, group_start: usize) -> Option<(usize, usize)> {
    let open_end = find_tag_end(svg, group_start)?;
    if svg[group_start..=open_end].trim_end().ends_with("/>") {
        return Some((group_start, open_end + 1));
    }

    let mut depth = 1usize;
    let mut cursor = open_end + 1;
    while let Some(rel_tag) = svg[cursor..].find('<') {
        let tag_start = cursor + rel_tag;
        let Some(tag_end) = find_tag_end(svg, tag_start) else {
            break;
        };
        let tag = &svg[tag_start..=tag_end];
        if is_start_g_tag(tag) {
            if !tag.trim_end().ends_with("/>") {
                depth += 1;
            }
        } else if is_end_g_tag(tag) {
            depth = depth.checked_sub(1)?;
            if depth == 0 {
                return Some((tag_start, tag_end + 1));
            }
        }
        cursor = tag_end + 1;
    }
    None
}

fn is_start_g_tag(tag: &str) -> bool {
    let bytes = tag.as_bytes();
    tag.starts_with("<g")
        && bytes
            .get(2)
            .is_some_and(|b| b.is_ascii_whitespace() || *b == b'>' || *b == b'/')
}

fn is_end_g_tag(tag: &str) -> bool {
    let bytes = tag.as_bytes();
    tag.starts_with("</g")
        && bytes
            .get(3)
            .is_some_and(|b| b.is_ascii_whitespace() || *b == b'>')
}

fn is_start_switch_tag(tag: &str) -> bool {
    let bytes = tag.as_bytes();
    tag.starts_with("<switch")
        && bytes
            .get("<switch".len())
            .is_some_and(|b| b.is_ascii_whitespace() || *b == b'>' || *b == b'/')
        && !tag.trim_end().ends_with("/>")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::svg::pipeline::SvgPipeline;

    #[test]
    fn drop_native_duplicate_fallbacks_removes_only_matching_fallback_groups() {
        let svg = r##"<svg>
<text class="task">Make tea</text>
<g data-merman-foreignobject="fallback" class="dup">
  <rect/>
  <text class="merman-foreignobject-fallback-text">Make tea</text>
</g>
<g data-merman-foreignobject="fallback" class="keep">
  <text class="merman-foreignobject-fallback-text">Only fallback</text>
</g>
</svg>"##;

        let out = drop_native_duplicate_fallbacks(svg);

        assert!(out.contains(r#"<text class="task">Make tea</text>"#));
        assert!(!out.contains(r#"class="dup""#));
        assert!(out.contains(r#"class="keep""#));
        assert!(out.contains("Only fallback"));
    }

    #[test]
    fn fallback_text_class_scanner_handles_single_quoted_attrs() {
        assert!(text_tag_is_fallback(
            r#"<text class = 'label merman-foreignobject-fallback-text'>"#
        ));
        assert!(!text_tag_is_fallback(r#"<text class = 'label task'>"#));
    }

    #[test]
    fn strip_foreign_objects_unwraps_switch_with_native_text_fallback() {
        let svg = r##"<svg><switch><foreignObject x="10" y="20" width="100" height="50"><div xmlns="http://www.w3.org/1999/xhtml">Make tea</div></foreignObject><text x="60" y="45">Make tea</text></switch></svg>"##;
        let out = strip_foreign_objects(svg);

        assert!(
            !out.contains("<foreignObject"),
            "foreignObject should be stripped: {out}"
        );
        assert!(
            !out.contains("<switch>"),
            "switch wrapper should be removed: {out}"
        );
        assert!(
            !out.contains("</switch>"),
            "switch closing tag should be removed: {out}"
        );
        assert!(
            out.contains(r#"<text x="60" y="45">Make tea</text>"#),
            "text fallback should be preserved: {out}"
        );
    }

    #[test]
    fn strip_foreign_objects_unwraps_switch_with_attrs() {
        let svg = r##"<svg><switch data-renderer="future"><foreignObject x="10" y="20" width="100" height="50"><div xmlns="http://www.w3.org/1999/xhtml">Make tea</div></foreignObject><text x="60" y="45">Make tea</text></switch></svg>"##;
        let out = strip_foreign_objects(svg);

        assert!(
            !out.contains("<foreignObject"),
            "foreignObject should be stripped: {out}"
        );
        assert!(
            !out.contains("<switch"),
            "switch wrapper should be removed: {out}"
        );
        assert!(
            out.contains(r#"<text x="60" y="45">Make tea</text>"#),
            "text fallback should be preserved: {out}"
        );
    }

    #[test]
    fn strip_foreign_objects_handles_switch_with_multiple_text_elements() {
        let svg = r##"<svg><switch><foreignObject x="0" y="0" width="80" height="40"><div xmlns="http://www.w3.org/1999/xhtml">Line 1</div></foreignObject><text x="40" y="15">Line 1</text><text x="40" y="30">Line 2</text></switch></svg>"##;
        let out = strip_foreign_objects(svg);

        assert!(!out.contains("<foreignObject"), "{out}");
        assert!(!out.contains("<switch>"), "{out}");
        assert!(
            out.contains(r#"<text x="40" y="15">Line 1</text>"#),
            "{out}"
        );
        assert!(
            out.contains(r#"<text x="40" y="30">Line 2</text>"#),
            "{out}"
        );
    }

    #[test]
    fn resvg_safe_pipeline_preserves_switch_text_fallback() {
        let svg = r##"<svg xmlns="http://www.w3.org/2000/svg"><switch><foreignObject x="150" y="50" width="550" height="50"><div class="journey-section" xmlns="http://www.w3.org/1999/xhtml" style="display: table; height: 100%; width: 100%;"><div class="label" style="display: table-cell; text-align: center; vertical-align: middle;">Go to work</div></div></foreignObject><text x="425" y="75" fill="#333"><tspan x="425" dy="0">Go to work</tspan></text></switch></svg>"##;
        let out = SvgPipeline::resvg_safe().process_to_string(svg).unwrap();

        assert!(
            !out.contains("<foreignObject"),
            "foreignObject should be stripped: {out}"
        );
        assert!(!out.contains("<switch>"), "switch should be removed: {out}");
        assert!(
            out.contains("Go to work"),
            "text fallback should survive full pipeline: {out}"
        );
        assert!(
            !out.contains(r#"data-merman-foreignobject-source"#),
            "generated fallback should be dropped: {out}"
        );
    }

    #[test]
    fn strip_foreign_objects_handles_journey_switch_pattern() {
        let svg = r##"<svg><g><rect class="section-type-0"/><switch><foreignObject x="150" y="50" width="550" height="50"><div class="journey-section section-type-0" xmlns="http://www.w3.org/1999/xhtml" style="display: table; height: 100%; width: 100%;"><div class="label" style="display: table-cell; text-align: center; vertical-align: middle;">Go to work</div></div></foreignObject><text x="425" y="75" fill="#333" class="journey-section section-type-0" style="text-anchor: middle;"><tspan x="425" dy="0">Go to work</tspan></text></switch></g></svg>"##;
        let out = strip_foreign_objects(svg);

        assert!(
            !out.contains("<foreignObject"),
            "foreignObject should be stripped: {out}"
        );
        assert!(!out.contains("<switch>"), "switch should be removed: {out}");
        assert!(
            out.contains("Go to work"),
            "section text should be preserved: {out}"
        );
        assert!(
            out.contains(r#"<text x="425" y="75""#),
            "text element should be preserved: {out}"
        );
    }

    #[test]
    fn strip_foreign_objects_still_works_without_switch() {
        let svg = r#"<svg><foreignObject width="80" height="24"><div>Hello</div></foreignObject><text>World</text></svg>"#;
        let out = strip_foreign_objects(svg);

        assert!(!out.contains("<foreignObject"), "{out}");
        assert!(out.contains("<text>World</text>"), "{out}");
    }

    #[test]
    fn drop_switch_native_fallbacks_removes_tagged_groups() {
        let svg = r##"<svg><text x="60" y="45">Make tea</text><g data-merman-foreignobject="fallback" data-merman-foreignobject-source="switch-native-fallback" class="merman-foreignobject-fallback"><text class="merman-foreignobject-fallback-text">Make tea</text></g><g data-merman-foreignobject="fallback" class="merman-foreignobject-fallback"><text class="merman-foreignobject-fallback-text">Other label</text></g></svg>"##;
        let out = drop_switch_native_fallbacks(svg);

        assert!(
            !out.contains("switch-native-fallback"),
            "tagged fallback group should be removed: {out}"
        );
        assert!(
            out.contains("Other label"),
            "non-switch fallback should be kept: {out}"
        );
        assert!(
            out.contains(r#"<text x="60" y="45">Make tea</text>"#),
            "native text should remain: {out}"
        );
    }

    #[test]
    fn resvg_safe_can_optionally_drop_native_duplicate_fallbacks() {
        let svg = r##"<svg xmlns="http://www.w3.org/2000/svg">
<text class="task">Make tea</text>
<g transform="translate(0,0)">
  <foreignObject width="80" height="24"><div xmlns="http://www.w3.org/1999/xhtml"><p>Make tea</p></div></foreignObject>
</g>
<g transform="translate(0,40)">
  <foreignObject width="80" height="24"><div xmlns="http://www.w3.org/1999/xhtml"><p>Only fallback</p></div></foreignObject>
</g>
</svg>"##;

        let out = SvgPipeline::resvg_safe()
            .with_postprocessor(DropNativeDuplicateFallbacksPostprocessor)
            .process_to_string(svg)
            .unwrap();

        assert!(!out.contains("<foreignObject"));
        assert_eq!(
            out.matches(r#"data-merman-foreignobject="fallback""#)
                .count(),
            1,
            "{out}"
        );
        assert!(out.contains("Only fallback"));
        assert!(out.contains(r#"<text class="task">Make tea</text>"#));
    }
}