Registry / RepositoryTypeScriptRustPython
Rollpie
ReadmeFiles
Versions
Info
Download
0.2.0528.5 KB2026-10-160.1.1542.8 KB2026-10-150.1.0541.1 KB2026-10-15
Version
0.2.0
Copyright
Rollpie, Irohabook
Publisher
math
Published
2026-10-16
Size
528.5 KB
Downloads
7
Checksum
f8871632f38084ae53dd9bf16e9ea90c80a209bf6cd234b6767630c5470dc305
Dependencies
None

svg.rs

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
use crate::font::{self, Font};
use crate::label::Placed;
use crate::layout::{Figure, PlacedAtom};
use crate::outline;
use crate::style::Style;
use crate::text::{escape, number};


#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Shape {
    Outline,
    Text,
}


pub fn render(figure: &Figure, font: &Font, style: &Style, shape: Shape, label: &str) -> String {
    let extent = figure.extent.grow(style.margin);
    let width = (extent.right - extent.left).max(style.margin * 2.0);
    let height = (extent.bottom - extent.top).max(style.margin * 2.0);
    let mut out = String::new();

    out.push_str("<svg xmlns=\"http://www.w3.org/2000/svg\"");
    out.push_str(&format!(" width=\"{}em\" height=\"{}em\"", number(width), number(height)));
    out.push_str(&format!(
        " viewBox=\"{} {} {} {}\"",
        number(extent.left),
        number(extent.top),
        number(width),
        number(height)
    ));
    // An inline SVG sits on the baseline by its bottom edge
    let baseline = font::cap_height(font) / 2.0;
    let drop = extent.bottom - baseline;
    out.push_str(&format!(" style=\"vertical-align:{}em\"", number(-drop)));
    out.push_str(&format!(" role=\"img\" aria-label=\"{}\">", escape(label)));

    push_bond(&mut out, figure, style);
    push_wedge(&mut out, figure, style);
    push_circle(&mut out, figure, style);

    match shape {
        Shape::Outline => push_outline(&mut out, figure, font, style),
        Shape::Text => push_text(&mut out, figure, font),
    }

    push_fallback(&mut out, figure);

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


fn every_atom(figure: &Figure) -> impl Iterator<Item = &PlacedAtom> {
    figure.atom.iter().chain(figure.name.iter())
}


fn push_outline(out: &mut String, figure: &Figure, font: &Font, style: &Style) {
    let unit = font::units_per_em(font);
    let mut data = String::new();

    for atom in every_atom(figure) {
        for placed in &atom.label.placed {
            let Some(glyph) = placed.glyph else {
                continue;
            };
            let drawn = font::outline_of(font, glyph);

            if drawn.segment.is_empty() {
                continue;
            }

            let scale = placed.size / unit;
            let x = atom.origin_x + placed.x;
            let y = atom.origin_y + placed.y;
            data.push_str(&outline::path_data(&drawn, scale, x, y));
        }
    }

    if data.is_empty() {
        return;
    }

    out.push_str("<path fill=\"currentColor\"");

    if style.darken > 0.0 {
        let weight = number(style.darken);
        out.push_str(&format!(
            " stroke=\"currentColor\" stroke-width=\"{weight}\" stroke-linejoin=\"round\""
        ));
    }

    out.push_str(&format!(" d=\"{data}\"/>"));
}


fn push_text(out: &mut String, figure: &Figure, font: &Font) {
    let family = escape(font::family(font));

    for atom in every_atom(figure) {
        let mut start = 0;
        let placed = &atom.label.placed;

        while start < placed.len() {
            if placed[start].glyph.is_none() {
                start += 1;

                continue;
            }

            let mut end = start + 1;

            while end < placed.len() && continues(&placed[start], &placed[end]) {
                end += 1;
            }

            push_run(out, atom, &placed[start..end], &family);
            start = end;
        }
    }
}


fn continues(first: &Placed, next: &Placed) -> bool {
    next.glyph.is_some() && next.size == first.size && next.y == first.y
}


fn push_run(out: &mut String, atom: &PlacedAtom, run: &[Placed], family: &str) {
    let mut horizontal = String::new();
    let mut body = String::new();

    for placed in run {
        if !horizontal.is_empty() {
            horizontal.push(' ');
        }

        horizontal.push_str(&number(atom.origin_x + placed.x));
        body.push(placed.character);
    }

    out.push_str(&format!(
        "<text x=\"{horizontal}\" y=\"{}\" font-size=\"{}\" font-family=\"{family}\" \
         fill=\"currentColor\">{}</text>",
        number(atom.origin_y + run[0].y),
        number(run[0].size),
        escape(&body)
    ));
}


fn push_bond(out: &mut String, figure: &Figure, style: &Style) {
    if figure.line.is_empty() {
        return;
    }

    let mut data = String::new();

    for line in &figure.line {
        data.push('M');
        data.push_str(&number(line.x1));
        data.push(' ');
        data.push_str(&number(line.y1));
        data.push('L');
        data.push_str(&number(line.x2));
        data.push(' ');
        data.push_str(&number(line.y2));
    }

    out.push_str(&format!(
        "<path fill=\"none\" stroke=\"currentColor\" stroke-width=\"{}\" \
         stroke-linecap=\"round\" d=\"{data}\"/>",
        number(style.line_width)
    ));
}


fn push_wedge(out: &mut String, figure: &Figure, style: &Style) {
    for filled in [true, false] {
        let mut data = String::new();

        for wedge in figure.wedge.iter().filter(|one| one.filled == filled) {
            data.push('M');
            data.push_str(&spot(wedge.tip));
            data.push('L');
            data.push_str(&spot(wedge.base[0]));
            data.push('L');
            data.push_str(&spot(wedge.base[1]));
            data.push('Z');
        }

        if data.is_empty() {
            continue;
        }

        if filled {
            out.push_str(&format!("<path fill=\"currentColor\" d=\"{data}\"/>"));

        } else {
            out.push_str(&format!(
                "<path fill=\"none\" stroke=\"currentColor\" stroke-width=\"{}\" \
                 stroke-linejoin=\"round\" d=\"{data}\"/>",
                number(style.line_width)
            ));
        }
    }
}


fn push_circle(out: &mut String, figure: &Figure, style: &Style) {
    for circle in &figure.circle {
        out.push_str(&format!(
            "<circle cx=\"{}\" cy=\"{}\" r=\"{}\" fill=\"none\" stroke=\"currentColor\" \
             stroke-width=\"{}\"/>",
            number(circle.x),
            number(circle.y),
            number(circle.radius),
            number(style.line_width)
        ));
    }
}


fn spot(point: (f64, f64)) -> String {
    format!("{} {}", number(point.0), number(point.1))
}


fn push_fallback(out: &mut String, figure: &Figure) {
    for atom in every_atom(figure) {
        for placed in &atom.label.placed {
            if placed.glyph.is_some() {
                continue;
            }

            let x = number(atom.origin_x + placed.x);
            let y = number(atom.origin_y + placed.y);
            let size = number(placed.size);
            let text = escape(&placed.character.to_string());
            out.push_str(&format!(
                "<text x=\"{x}\" y=\"{y}\" font-size=\"{size}\" \
                 font-family=\"{}\" fill=\"currentColor\">{text}</text>",
                font::FALLBACK
            ));
        }
    }
}


#[cfg(test)]
mod tests {
    use super::*;
    use crate::font::sample;
    use crate::layout::layout;
    use crate::parse::parse;

    fn draw(source: &str) -> String {
        let font = sample();
        let style = Style::default();
        let figure = layout(&parse(source).unwrap(), &font, &style).unwrap();

        render(&figure, &font, &style, Shape::Outline, source)
    }

    fn write(source: &str) -> String {
        let font = sample();
        let style = Style::default();
        let figure = layout(&parse(source).unwrap(), &font, &style).unwrap();

        render(&figure, &font, &style, Shape::Text, source)
    }

    #[test]
    fn writes_one_svg_element() {
        let found = draw("H-O-H");
        assert!(found.starts_with("<svg xmlns=\"http://www.w3.org/2000/svg\""));
        assert!(found.ends_with("</svg>"));
        assert_eq!(found.matches("<svg").count(), 1);
    }

    #[test]
    fn the_size_is_written_in_em() {
        let found = draw("H-O-H");
        assert!(found.contains("em\" height=\""));
        assert!(found.contains("viewBox=\""));
    }

    #[test]
    fn the_figure_sits_on_the_baseline_of_the_text_around_it() {
        let found = draw("H-O-H");
        let at = found.find("vertical-align:").expect("no vertical-align");
        let rest = &found[at + "vertical-align:".len()..];
        let value: f64 = rest[..rest.find("em").unwrap()].parse().unwrap();
        assert!(value < 0.0, "the figure is not lowered");
        assert!(value > -1.0, "lowered too far: {value}");
    }

    #[test]
    fn a_taller_figure_hangs_lower() {
        let flat = draw("H-H");
        let tall = draw("H-[:-90]H");
        let of = |markup: &str| {
            let at = markup.find("vertical-align:").unwrap() + "vertical-align:".len();
            let rest = &markup[at..];
            rest[..rest.find("em").unwrap()].parse::<f64>().unwrap()
        };
        assert!(of(&tall) < of(&flat), "a taller figure is not lowered more");
    }

    #[test]
    fn the_glyphs_come_out_as_outlines() {
        let found = draw("H-O-H");
        assert!(found.contains("<path fill=\"currentColor\""));
        assert!(found.contains("C"), "no curve command");
    }

    #[test]
    fn the_bonds_come_out_as_one_stroked_path() {
        let found = draw("H-O-H");
        assert_eq!(found.matches("stroke-linecap=\"round\"").count(), 1);
        assert_eq!(found.matches("fill=\"none\"").count(), 1);
    }

    #[test]
    fn a_molecule_with_no_bond_still_draws() {
        let found = draw("H_2O");
        assert!(found.contains("<path fill=\"currentColor\""));
        assert!(!found.contains("fill=\"none\""));
    }

    #[test]
    fn the_label_becomes_the_alternative_text() {
        assert!(draw("O=C=O").contains("aria-label=\"O=C=O\""));
    }

    #[test]
    fn markup_in_the_label_is_escaped() {
        let font = sample();
        let style = Style::default();
        let figure = layout(&parse("A-B").unwrap(), &font, &style).unwrap();
        let found = render(&figure, &font, &style, Shape::Outline, "<a>&");
        assert!(found.contains("aria-label=\"&lt;a&gt;&amp;\""));
    }

    #[test]
    fn a_filled_wedge_is_a_closed_path() {
        let found = draw("C>H");
        let at = found.find("<path fill=\"currentColor\" d=\"M").expect("no triangle");
        let data = &found[at..found[at..].find("\"/>").unwrap() + at];
        assert_eq!(data.matches('L').count(), 2);
        assert_eq!(data.matches('Z').count(), 1);
    }

    #[test]
    fn a_hollow_wedge_is_stroked_instead() {
        let found = draw("C>|H");
        assert!(found.contains("stroke-linejoin=\"round\" d=\"M"));
        assert!(found.contains('Z'));
    }

    #[test]
    fn an_aromatic_ring_writes_a_circle() {
        let found = draw("**6(------)");
        assert_eq!(found.matches("<circle").count(), 1);
        assert!(found.contains("fill=\"none\" stroke=\"currentColor\""));
    }

    #[test]
    fn a_plain_ring_writes_no_circle() {
        assert!(!draw("*6(------)").contains("<circle"));
    }

    #[test]
    fn the_bonds_are_written_before_the_letters() {
        let found = draw("H-O-H");
        let bond = found.find("fill=\"none\"").unwrap();
        let glyph = found.find("<path fill=\"currentColor\"").unwrap();
        assert!(bond < glyph, "letters are hidden under bonds");
    }

    #[test]
    fn the_text_shape_writes_letters_instead_of_outlines() {
        let found = write("H-O-H");
        assert_eq!(found.matches("<text").count(), 3);
        assert!(!found.contains("<path fill=\"currentColor\""), "outlines are left");
        assert!(found.contains("font-family=\"Latin Modern Math\""));
        assert!(found.contains("fill=\"none\""), "bonds are missing");
    }

    #[test]
    fn letters_of_the_same_size_and_height_share_one_text() {
        let found = write("CH_3");
        assert_eq!(found.matches("<text").count(), 2);
        assert!(found.contains(">CH</text>"));
        assert!(found.contains(">3</text>"));
    }

    #[test]
    fn every_letter_gets_its_own_place() {
        let found = write("CH_3");
        let at = found.find("<text x=\"").unwrap() + "<text x=\"".len();
        let list = &found[at..at + found[at..].find('"').unwrap()];
        assert_eq!(list.split(' ').count(), 2, "x is not given for each letter");
    }

    #[test]
    fn the_two_shapes_place_the_letters_alike() {
        let outline = draw("H_3C-CH_3");
        let text = write("H_3C-CH_3");
        let size = |markup: &str| {
            let at = markup.find("viewBox=\"").unwrap() + "viewBox=\"".len();
            markup[at..at + markup[at..].find('"').unwrap()].to_string()
        };
        assert_eq!(size(&outline), size(&text));
    }

    #[test]
    fn a_character_the_font_lacks_is_written_as_text() {
        let found = draw("\u{3042}-H");
        assert!(found.contains("<text"));
        assert!(found.contains("\u{3042}"));
    }

    #[test]
    fn an_empty_source_still_makes_a_box() {
        let found = draw("");
        assert!(found.starts_with("<svg"));
        assert!(found.ends_with("</svg>"));
    }
}