d2-rs-math 0.1.7

Rust port of D2's d2latex package and mathjax-go: LaTeX layout and SVG.
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
// Copyright 2017-2022 The MathJax Consortium
// SPDX-License-Identifier: Apache-2.0
// Translated from pinned mathjax-go v0.1.0 tex/commands.go and svg/mpadded.go,mphantom.go.
use super::*;
#[derive(Clone, Debug, Default)]
pub(super) struct Padding {
    pub aligned_width: Option<(String, &'static str, f64)>,
    pub mathsize: Option<f64>,
    pub position: Option<[String; 2]>,
    pub voffset: Option<String>,
    pub root: Option<[Option<String>; 2]>,
    pub width_zero: bool,
    pub width_absolute: Option<f64>,
    pub height_zero: bool,
    pub depth_zero: bool,
    pub lspace_width: f64,
    pub width_add: f64,
    pub height_add: f64,
    pub depth_add: f64,
    pub lspace_em: f64,
    pub voffset_em: f64,
}
fn group(
    body: Layout,
    kind: &'static str,
    x: f64,
    baseline: f64,
    scale: f64,
    before_glyph: usize,
) -> LayoutGroup {
    LayoutGroup {
        x_frame: None,
        data_cramped: None,
        own_translate: None,
        accent_offset: None,
        box_border: None,
        reference: None,
        tagged: None,
        percentage: None,
        table_line: None,
        mathsize: None,
        tex_class: 0,
        body: Box::new(body),
        kind,
        x,
        baseline,
        scale,
        before_glyph,
        color: None,
        background: None,
        delimiter: None,
        arrow: None,
        lines: Vec::new(),
    }
}
pub(super) fn layout_node(
    body: &Atom,
    padding: Option<&Padding>,
    hidden: bool,
    x: f64,
    baseline: f64,
    scale: f64,
    out: &mut Layout,
    display: bool,
    prime: bool,
) -> Option<f64> {
    let mut local = Layout {
        bounds_em: None,
        width_em: None,
        intrinsic_width_em: None,
        width: 0.0,
        ascent: 0.0,
        depth: 0.0,
        glyphs: Vec::new(),
        rules: Vec::new(),
        groups: Vec::new(),
    };
    local.width = layout_at_with_style(body, 0.0, 0.0, scale, &mut local, display, prime)?;
    retain_negative_glyph_depth(&mut local);
    if hidden {
        local.glyphs.clear();
        local.rules.clear();
        local.groups.clear();
    }
    if let Some(p) = padding {
        let dimension_scale = scale * p.mathsize.unwrap_or(1.);
        if let Some((raw, align, mathsize)) = &p.aligned_width {
            let unit = 1000. * scale;
            let (h, d) = styles::em_bounds(&local);
            let size = if raw.contains("height") {
                h / scale
            } else if raw.contains("depth") {
                d / scale
            } else {
                local.width / unit
            };
            let mut width = length::dimension(raw).em(size, scale * mathsize);
            if raw.starts_with(['+', '-']) {
                width += size;
            }
            let width = width.max(0.);
            let delta = (width - local.width / unit) * unit;
            // mpadded.paddedToSVG cancels negative alignment displacement.
            let dx = match *align {
                "left" => 0.,
                "right" => delta.max(0.),
                _ => delta.max(0.) / 2.,
            };
            if dx != 0. {
                let mut frame = Layout {
                    bounds_em: None,
                    width_em: None,
                    intrinsic_width_em: None,
                    width: 0.,
                    ascent: 0.,
                    depth: 0.,
                    glyphs: vec![],
                    rules: vec![],
                    groups: vec![],
                };
                frame.width = local.width;
                frame.ascent = local.ascent;
                frame.depth = local.depth;
                frame.groups.push(group(local, "", dx, 0., scale, 0));
                local = frame;
            }
            local.width = width * unit;
            local.width_em = Some(width * scale);
        }
        // mpadded resolves named dimensions against the content box. An
        // explicit rule offset is independent of its height adjustment.
        let dimension = |raw: &str, default_size: f64, adjust: bool| {
            let unit = 1000. * scale;
            let size = if raw.contains("width") {
                local.width / unit
            } else if raw.contains("height") {
                local.ascent / unit
            } else if raw.contains("depth") {
                local.depth / unit
            } else {
                default_size
            };
            let value = length::dimension(raw).em(size, dimension_scale);
            if adjust && raw.starts_with(['+', '-']) {
                value + size
            } else {
                value
            }
        };
        let position = p.voffset.as_ref().map_or_else(
            || {
                p.position
                    .as_ref()
                    .map_or(0., |d| dimension(&d[0], 0., false))
            },
            |raw| dimension(raw, 0., false),
        );
        let adjusted_bounds = p.position.as_ref().map(|dimensions| {
            let unit = 1000. * scale;
            let h = local.ascent / unit;
            let d = local.depth / unit;
            (
                dimension(&dimensions[0], h, true).max(0.) * unit,
                dimension(&dimensions[1], d, true).max(0.) * unit,
            )
        });
        let dx = p.lspace_width * local.width + p.lspace_em * 1000.0 * scale;
        let root_dy = p
            .root
            .as_ref()
            .and_then(|r| r[1].as_ref())
            .map_or(0., |raw| length::dimension(raw).em(0., dimension_scale));
        let dy = (p.voffset_em + position + root_dy) * 1000.0 * scale;
        if dx != 0.0 || dy != 0.0 {
            // Original mpadded puts lspace in a separate, independently rounded g.
            let mut frame = Layout {
                bounds_em: None,
                width_em: None,
                intrinsic_width_em: None,
                width: local.width,
                ascent: local.ascent,
                depth: local.depth,
                glyphs: Vec::new(),
                rules: Vec::new(),
                groups: Vec::new(),
            };
            frame.groups.push(group(local, "", dx, dy, scale, 0));
            local = frame;
        }
        if let Some(root) = &p.root {
            let unit = 1000. * scale;
            if let Some(raw) = &root[0] {
                let w = local.width / unit;
                local.width = (w + length::dimension(raw).em(w, dimension_scale)).max(0.) * unit;
            }
            if let Some(raw) = &root[1] {
                let h = local.ascent / unit;
                local.ascent = (h + length::dimension(raw).em(h, dimension_scale)).max(0.) * unit;
            }
        }
        if p.width_add != 0.0 {
            local.width = (local.width + p.width_add * 1000.0 * scale).max(0.0);
        }
        if p.height_add != 0.0 {
            local.ascent = (local.ascent + p.height_add * 1000.0 * scale).max(0.0);
        }
        if let Some((height, depth)) = adjusted_bounds {
            local.ascent = height;
            local.depth = depth;
            local.bounds_em = None;
        }
        if p.depth_add != 0.0 {
            local.depth = (local.depth + p.depth_add * 1000.0 * scale).max(0.0);
        }
        if p.width_zero {
            local.width = 0.0;
        }
        if let Some(width) = p.width_absolute {
            local.width = width * 1000.0 * scale;
        }
        if p.height_zero {
            local.ascent = 0.0;
        }
        if p.depth_zero {
            local.depth = 0.0;
        }
    }
    let width = local.width;
    out.ascent = out.ascent.max(baseline + local.ascent);
    out.depth = out.depth.max(local.depth - baseline);
    out.groups.push(group(
        local,
        if hidden {
            "mphantom"
        } else if let Some((_, align, _)) = padding.and_then(|p| p.aligned_width.as_ref()) {
            match *align {
                "left" => "#padded-left",
                "right" => "#padded-right",
                _ => "#padded-center",
            }
        } else {
            "mpadded"
        },
        x,
        baseline,
        scale,
        out.glyphs.len(),
    ));
    Some(width)
}
impl Parser {
    pub(super) fn padded_command(&mut self, name: &str) -> Option<Atom> {
        let mut padding = Padding::default();
        let body = match name {
            "phantom" | "hphantom" | "vphantom" => {
                let phantom = Atom::Phantom(Box::new(self.padded_argument(name)?));
                if name == "phantom" {
                    return Some(Atom::Ord(Box::new(phantom)));
                }
                padding.width_zero = name == "vphantom";
                padding.height_zero = name == "hphantom";
                padding.depth_zero = name == "hphantom";
                phantom
            }
            "smash" => {
                let option = match self.padded_brackets() {
                    Ok(s) => s,
                    Err(s) => return Some(Atom::ErrorDisplay(s)),
                };
                padding.height_zero = option.is_empty() || option == "t";
                padding.depth_zero = option.is_empty() || option == "b";
                self.padded_argument(name)?
            }
            _ => {
                padding.width_zero = true;
                padding.lspace_width = if name.contains("llap") {
                    -1.0
                } else if name.contains("clap") {
                    -0.5
                } else {
                    0.0
                };
                if name == "clap" {
                    let raw = match self.padded_raw_argument(name) {
                        Ok(raw) => raw,
                        Err(message) => return Some(Atom::ErrorDisplay(message)),
                    };
                    let body = self.internal_math(&raw, None, true)?;
                    return Some(Atom::Padded {
                        body: Box::new(body),
                        padding,
                    });
                }
                self.padded_argument(name)?
            }
        };
        let mut atom = Atom::Padded {
            body: Box::new(body),
            padding,
        };
        if name.starts_with("math") || name.starts_with("cramped") {
            atom = Atom::CrampedStyle(Box::new(atom), name.starts_with("cramped"));
        }
        Some(Atom::Ord(Box::new(atom)))
    }
    pub(super) fn padded_raw_argument(&mut self, name: &str) -> Result<String, String> {
        while self
            .chars
            .get(self.index)
            .is_some_and(|c| c.is_whitespace())
        {
            self.index += 1;
        }
        let Some(c) = self.chars.get(self.index).copied() else {
            return Err(format!("Missing argument for \\{name}"));
        };
        if c == '}' {
            return Err("Extra close brace or missing open brace".into());
        }
        if c == '{' {
            return self
                .braced_text()
                .ok_or_else(|| "Missing close brace".into());
        }
        let start = self.index;
        self.index += 1;
        if c == '\\' {
            if self
                .chars
                .get(self.index)
                .is_some_and(char::is_ascii_alphabetic)
            {
                while self
                    .chars
                    .get(self.index)
                    .is_some_and(char::is_ascii_alphabetic)
                {
                    self.index += 1;
                }
                if self.chars.get(self.index) == Some(&' ') {
                    self.index += 1;
                }
            } else if self.index < self.chars.len() {
                self.index += 1;
            }
        }
        Ok(self.chars[start..self.index].iter().collect())
    }
    pub(super) fn padded_argument(&mut self, name: &str) -> Option<Atom> {
        let raw = match self.padded_raw_argument(name) {
            Ok(raw) => raw,
            Err(message) => return Some(Atom::ErrorDisplay(message)),
        };
        self.padded_parse_string(&raw)
    }
    pub(super) fn bounded_font_argument(&mut self, name: &str) -> Option<Atom> {
        let raw = match self.padded_raw_argument(name) {
            Ok(v) => v,
            Err(e) => return Some(Atom::ErrorDisplay(e)),
        };
        let mut parser = Parser {
            in_root: self.in_root,
            root_moves: Default::default(),
            physics_after: None,
            physics_auto: None,
            command_position: None,
            pending_cell: None,
            pending_infix: None,
            row_delimiter: None,
            active_color: self.active_color.clone(),
            equation_seen: Default::default(),
            array_cell: None,
            vector_alias: self.vector_alias,
            vector_font: self.vector_font,
            ams: self.ams.clone(),
            splice_inferred: false,
            chars: raw.chars().collect(),
            index: 0,
            active_font: Some(declaration_fonts::font_name(name)?),
            normal_font: false,
            calligraphic_font: false,
            multi_letter_font: !declaration_fonts::font_name(name)?.is_empty(),
            operator_letters: self.operator_letters,
            operator_pattern: false,
            no_auto_operator: true,
        };
        let saved_count = self.ams.borrow().paired_macro_count;
        self.ams.borrow_mut().paired_macro_count = 0;
        let result = parser.sequence(None);
        self.ams.borrow_mut().paired_macro_count = saved_count;
        result
    }
    pub(super) fn padded_parse_string(&self, raw: &str) -> Option<Atom> {
        let mut sub = Parser {
            in_root: self.in_root,
            root_moves: Default::default(),
            physics_after: None,
            physics_auto: None,
            command_position: None,
            pending_cell: None,
            pending_infix: None,
            row_delimiter: None,
            active_color: self.active_color.clone(),
            equation_seen: Default::default(),
            array_cell: None,
            vector_alias: self.vector_alias,
            vector_font: self.vector_font,
            ams: self.ams.clone(),
            splice_inferred: false,
            chars: raw.chars().collect(),
            index: 0,
            active_font: self.active_font,
            normal_font: self.normal_font,
            calligraphic_font: self.calligraphic_font,
            multi_letter_font: self.vector_alias && self.multi_letter_font,
            operator_letters: self.operator_letters,
            operator_pattern: self.operator_pattern,
            no_auto_operator: self.no_auto_operator,
        };
        sub.sequence(None)
    }
    pub(super) fn padded_brackets(&mut self) -> Result<String, String> {
        while self
            .chars
            .get(self.index)
            .is_some_and(|c| c.is_whitespace())
        {
            self.index += 1;
        }
        if self.chars.get(self.index) != Some(&'[') {
            return Ok(String::new());
        }
        let start = self.index + 1;
        let mut i = start;
        let mut depth = 0;
        while let Some(c) = self.chars.get(i) {
            match c {
                '\\' => {
                    i += 1;
                }
                '{' => depth += 1,
                '}' => {
                    if depth == 0 {
                        return Err("Extra close brace while looking for ']'".into());
                    }
                    depth -= 1;
                }
                ']' if depth == 0 => {
                    let s = self.chars[start..i].iter().collect();
                    self.index = i + 1;
                    return Ok(s);
                }
                _ => {}
            }
            i += 1;
        }
        Err("Could not find closing ']' for argument".into())
    }
}
#[cfg(all(test, feature = "oracle-fixtures"))]
mod tests {
    use super::*;
    #[test]
    fn original_padding_phantom_smash_lap_boxes() {
        let rows: Vec<serde_json::Value> = serde_json::from_str(d2_rs_testdata::oracle_fixture!(
            "tests/fixtures/padded-source-v090.json"
        ))
        .unwrap();
        assert_eq!(rows.len(), 304);
        for row in rows {
            let expression = row["expression"].as_str().unwrap();
            let source = roxmltree::Document::parse(row["svg"].as_str().unwrap()).unwrap();
            let svg = render(expression).unwrap();
            let doc = roxmltree::Document::parse(&svg).unwrap();
            let root = doc.root_element();
            // The root box of the Go render: width, height, viewBox and style.
            for k in ["width", "height", "viewBox", "style"] {
                assert_eq!(
                    root.attribute(k),
                    source.root_element().attribute(k),
                    "{expression} {k}"
                );
            }
            let size = measure(expression).unwrap();
            assert_eq!(
                (size.width, size.height),
                (
                    row["width"].as_f64().unwrap(),
                    row["height"].as_f64().unwrap()
                ),
                "{expression}"
            );
        }
    }
}