katex-rs 0.2.4

A Rust implementation of KaTeX - Fast math typesetting for anywhere, more than just the web.
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
//! DOM tree node definitions for HTML rendering
//!
//! These objects store the data about the DOM nodes we create, as well as some
//! extra data. They can then be transformed into real DOM nodes with the
//! `to_node` function or HTML markup using `to_markup`.

use core::fmt::{self, Write as _};

use crate::ParseError;
use crate::namespace::KeyMap;
use crate::types::ParseErrorKind;
#[cfg(feature = "wasm")]
use crate::web_context::WebContext;
use bon::bon;
use phf::phf_map;
#[cfg(feature = "wasm")]
use wasm_bindgen::UnwrapThrowExt as _;
#[cfg(feature = "wasm")]
use web_sys;

use crate::mathml_tree::MathNode;
use crate::options::Options;
use crate::svg_geometry::PATH_MAP;
use crate::tree::{DocumentFragment, VirtualNode};
use crate::types::ClassList;
use crate::types::{CssProperty, CssStyle};
use crate::unicode::script_from_codepoint;
use crate::units::make_em;
use crate::utils::escape_into;

const EMPTY_CLASS_LIST: ClassList = ClassList::Empty;

/// Span wrapping other DOM nodes with generic child type
#[derive(Debug, Clone, PartialEq)]
pub struct Span<T> {
    /// Child nodes contained within this span
    pub children: Vec<T>,
    /// HTML attributes for this span element
    pub attributes: KeyMap<String, String>,
    /// CSS classes applied to this span
    pub classes: ClassList,
    /// Height of this span element
    pub height: f64,
    /// Depth of this span element
    pub depth: f64,
    /// Optional width of this span element
    pub width: Option<f64>,
    /// Maximum font size used in this span
    pub max_font_size: f64,
    /// Inline CSS style object
    pub style: CssStyle,

    /// For `src/functions/delimsizing.rs` only
    pub is_middle: Option<(String, Options)>,
    /// For `src/functions/op.rs` and `src/functions/supsub.rs` only
    pub italic: Option<f64>,
}

#[bon]
/// Builder for creating a new Span
impl<T> Span<T> {
    #[builder]
    /// Create a new Span with builder
    #[expect(clippy::option_option)]
    pub fn new(
        /// Options for building the span
        #[builder(finish_fn)]
        options: Option<&Options>,
        /// Child nodes contained within this span
        children: Vec<T>,
        /// Attributes for this span element
        attributes: Option<KeyMap<String, String>>,
        /// Classes applied to this span
        classes: Option<ClassList>,
        /// Height of this span element
        height: Option<f64>,
        /// Depth of this span element
        depth: Option<f64>,
        /// Optional width of this span element
        width: Option<Option<f64>>,
        /// Maximum font size used in this span
        max_font_size: Option<f64>,
        /// Inline CSS style object
        style: Option<CssStyle>,
        /// `is_middle` tuple
        is_middle: Option<(String, Options)>,
    ) -> Self {
        let mut span = Self {
            children,
            attributes: attributes.unwrap_or_default(),
            classes: classes.unwrap_or_default(),
            height: height.unwrap_or_default(),
            depth: depth.unwrap_or_default(),
            width: width.unwrap_or(None),
            max_font_size: max_font_size.unwrap_or_default(),
            style: style.unwrap_or_default(),
            is_middle,
            italic: None,
        };

        if let Some(options) = options {
            init_node(&mut span.classes, &mut span.style, options);
        }

        span
    }

    /// Fast path constructor for callers that already have the common pieces
    /// available and would otherwise go through the builder for every node.
    pub(crate) fn from_parts(
        children: Vec<T>,
        classes: ClassList,
        style: Option<CssStyle>,
        options: Option<&Options>,
    ) -> Self {
        let mut span = Self {
            children,
            attributes: KeyMap::default(),
            classes,
            height: 0.0,
            depth: 0.0,
            width: None,
            max_font_size: 0.0,
            style: style.unwrap_or_default(),
            is_middle: None,
            italic: None,
        };

        if let Some(options) = options {
            init_node(&mut span.classes, &mut span.style, options);
        }

        span
    }
}

/// Anchor element with hyperlink
#[derive(Debug, Clone)]
pub struct Anchor {
    /// Child nodes contained within this anchor
    pub children: Vec<HtmlDomNode>,
    /// HTML attributes for this anchor element
    pub attributes: KeyMap<String, String>,
    /// CSS classes applied to this anchor
    pub classes: ClassList,
    /// Height of this anchor element
    pub height: f64,
    /// Depth of this anchor element
    pub depth: f64,
    /// Maximum font size used in this anchor
    pub max_font_size: f64,
    /// Inline CSS style object
    pub style: CssStyle,
}

impl From<Anchor> for HtmlDomNode {
    fn from(anchor: Anchor) -> Self {
        Self::Anchor(anchor)
    }
}

#[bon]
impl Anchor {
    #[builder]
    /// Create a new Anchor element with builder
    pub fn new(
        /// Options for building the anchor
        #[builder(finish_fn)]
        options: Option<&Options>,
        /// Child nodes contained within this anchor
        children: Option<Vec<HtmlDomNode>>,
        /// HTML attributes for this anchor element
        attributes: Option<KeyMap<String, String>>,
        /// Classes applied to this anchor
        classes: Option<ClassList>,
        /// Height of this anchor element
        height: Option<f64>,
        /// Depth of this anchor element
        depth: Option<f64>,
        /// Maximum font size used in this anchor
        max_font_size: Option<f64>,
        /// Inline CSS style object
        style: Option<CssStyle>,
    ) -> Self {
        let mut anchor = Self {
            children: children.unwrap_or_default(),
            attributes: attributes.unwrap_or_default(),
            classes: classes.unwrap_or_default(),
            height: height.unwrap_or_default(),
            depth: depth.unwrap_or_default(),
            max_font_size: max_font_size.unwrap_or_default(),
            style: style.unwrap_or_default(),
        };

        if let Some(options) = options {
            init_node(&mut anchor.classes, &mut anchor.style, options);
        }

        anchor
    }
}

impl Anchor {
    /// Create a new Anchor (Going to be deprecated)
    #[must_use]
    pub const fn new(
        children: Vec<HtmlDomNode>,
        attributes: KeyMap<String, String>,
        classes: ClassList,
        height: f64,
        depth: f64,
        max_font_size: f64,
        style: CssStyle,
    ) -> Self {
        Self {
            children,
            attributes,
            classes,
            height,
            depth,
            max_font_size,
            style,
        }
    }
}

/// Image embed element
#[derive(Debug, Clone)]
pub struct Img {
    /// Source URL of the image
    pub src: String,
    /// Alternative text for the image
    pub alt: String,
    /// CSS classes applied to this image
    pub classes: ClassList,
    /// Height of this image element
    pub height: f64,
    /// Depth of this image element
    pub depth: f64,
    /// Maximum font size used in this image
    pub max_font_size: f64,
    /// Inline CSS style object
    pub style: CssStyle,
}

impl Img {
    /// Create a new Img
    #[must_use]
    pub const fn new(
        src: String,
        alt: String,
        height: f64,
        depth: f64,
        max_font_size: f64,
        style: CssStyle,
    ) -> Self {
        Self {
            src,
            alt,
            classes: ClassList::Static("mord"),
            height,
            depth,
            max_font_size,
            style,
        }
    }
}

/// Symbol node containing information about a single symbol
#[derive(Debug, Clone)]
pub struct SymbolNode {
    /// The text content of this symbol
    pub text: String,
    /// Height of this symbol
    pub height: f64,
    /// Depth of this symbol
    pub depth: f64,
    /// Italic correction value
    pub italic: f64,
    /// Skew correction value
    pub skew: f64,
    /// Width of this symbol
    pub width: f64,
    /// Maximum font size used in this symbol
    pub max_font_size: f64,
    /// CSS classes applied to this symbol
    pub classes: ClassList,
    /// Inline CSS style object
    pub style: CssStyle,
}

impl From<SymbolNode> for HtmlDomNode {
    fn from(symbol: SymbolNode) -> Self {
        Self::Symbol(symbol)
    }
}

const I_COMBINATIONS: phf::Map<&str, &str> = phf_map! {
    "\u{ee}" => "\u{0131}\u{0302}",
    "\u{ef}" => "\u{0131}\u{0308}",
    "\u{ed}" => "\u{0131}\u{0301}",
    "\u{ec}" => "\u{0131}\u{0300}",
};

#[bon]
impl SymbolNode {
    /// Create a new Symbol
    #[builder]
    pub fn new(
        /// Symbol text for the node
        text: &str,
        /// Height of the symbol
        height: Option<f64>,
        /// Depth of the symbol
        depth: Option<f64>,
        /// Italic correction value
        italic: Option<f64>,
        /// Skew correction value
        skew: Option<f64>,
        /// Width of the symbol
        width: Option<f64>,
        /// Maximum font size used in this symbol
        max_font_size: Option<f64>,
        /// Classes applied to this symbol
        classes: Option<ClassList>,
        /// Inline CSS style object
        style: Option<CssStyle>,
    ) -> Self {
        let mut classes = classes.unwrap_or_default();

        // Mark text from non-Latin scripts with specific classes so that we
        // can specify which fonts to use. This allows us to render these
        // characters with a serif font in situations where the browser would
        // either default to a sans serif or render a placeholder character.
        // We use CSS class names like cjk_fallback, hangul_fallback and
        // brahmic_fallback. See ./unicodeScripts.js for the set of possible
        // script names
        if let Some(first_ch) = text.chars().next()
            && let Some(script) = script_from_codepoint(first_ch as u32)
        {
            classes.push(format!("{script}_fallback"));
        }

        // Handle iCombinations for special characters
        let text = I_COMBINATIONS
            .get(text)
            .map_or_else(|| text.to_owned(), ToString::to_string);

        Self {
            text,
            height: height.unwrap_or_default(),
            depth: depth.unwrap_or_default(),
            italic: italic.unwrap_or_default(),
            skew: skew.unwrap_or_default(),
            width: width.unwrap_or_default(),
            max_font_size: max_font_size.unwrap_or_default(),
            classes,
            style: style.unwrap_or_default(),
        }
    }
}

/// Span wrapping other DOM nodes
pub type DomSpan = Span<HtmlDomNode>;

/// Recursive HTML DOM node enum with tuple variants
#[derive(Debug, Clone)]
pub enum HtmlDomNode {
    /// Span wrapping other DOM nodes
    DomSpan(Span<HtmlDomNode>),
    /// Anchor (`<a>`) element with hyperlink
    Anchor(Anchor),
    /// Image embed (`<img>`) element
    Img(Img),
    /// Symbol node containing information about a single symbol
    Symbol(SymbolNode),
    /// SVG node for rendering stretchy wide elements
    SvgNode(SvgNode),
    /// MathML node for mathematical expressions
    MathML(MathNode),
    /// Document fragment containing HTML DOM nodes
    Fragment(HtmlDomFragment),
}

impl From<Span<Self>> for HtmlDomNode {
    fn from(span: Span<Self>) -> Self {
        Self::DomSpan(span)
    }
}

/// SVG child node types
#[derive(Debug, Clone)]
pub enum SvgChildNode {
    /// Path element
    Path(PathNode),
    /// Line element
    Line(LineNode),
}

impl SvgChildNode {
    /// Convert this SVG child node into HTML markup string
    pub fn to_markup(&self) -> Result<String, ParseError> {
        match self {
            Self::Path(path_node) => path_node.to_markup(),
            Self::Line(line_node) => line_node.to_markup(),
        }
    }

    /// Convert this SVG child node into a DOM node representation
    #[cfg(feature = "wasm")]
    #[must_use]
    pub fn to_node(&self, ctx: &WebContext) -> web_sys::Node {
        match self {
            Self::Path(path_node) => path_node.to_node(ctx),
            Self::Line(line_node) => line_node.to_node(ctx),
        }
    }
}

/// Document fragment containing HTML DOM nodes
pub type HtmlDomFragment = DocumentFragment<HtmlDomNode>;

impl From<HtmlDomFragment> for HtmlDomNode {
    fn from(fragment: HtmlDomFragment) -> Self {
        Self::Fragment(fragment)
    }
}

/// SVG node for rendering stretchy wide elements
#[derive(Debug, Clone)]
pub struct SvgNode {
    /// Child nodes contained within this SVG
    pub children: Vec<SvgChildNode>,
    /// HTML attributes for this SVG element
    pub attributes: KeyMap<String, String>,
}

#[bon]
impl SvgNode {
    /// Create a new SvgNode
    #[builder]
    pub fn new(
        /// Children for the SVG node
        children: Vec<SvgChildNode>,
        /// Attributes for the SVG node
        attributes: Option<KeyMap<String, String>>,
    ) -> Self {
        Self {
            children,
            attributes: attributes.unwrap_or_default(),
        }
    }
}

/// Create an HTML className based on a list of classes. In addition to joining
/// with spaces, we also remove empty classes.
#[must_use]
pub fn create_class(classes: &ClassList) -> String {
    let mut result = String::new();
    let mut first = true;

    for class in classes {
        if class.is_empty() {
            continue;
        }
        if first {
            first = false;
        } else {
            result.push(' ');
        }
        result.push_str(class);
    }

    result
}

/// Initialize a DOM node with common properties according to KaTeX.js initNode
/// implementation
#[inline]
fn init_node(classes: &mut ClassList, style: &mut CssStyle, options: &Options) {
    if options.style.is_tight() {
        classes.push("mtight");
    }
    if let Some(color) = options.get_color() {
        style.insert(CssProperty::Color, color);
    }
}

/// Convert into an HTML node
#[cfg(feature = "wasm")]
#[must_use]
pub fn to_node(node: &HtmlDomNode, ctx: &WebContext) -> web_sys::Node {
    node.to_node(ctx)
}

/// Convert into an HTML markup string
pub fn to_markup(node: &HtmlDomNode) -> Result<String, ParseError> {
    node.to_markup()
}

fn map_fmt(result: fmt::Result) -> Result<(), ParseError> {
    result.map_err(ParseError::from)
}

fn write_node_class<W: fmt::Write>(writer: &mut W, classes: &ClassList) -> fmt::Result {
    let mut iter = classes.into_iter();
    if let Some(first) = iter.next() {
        writer.write_str(" class=\"")?;
        escape_into(writer, first)?;
        for class in iter {
            writer.write_char(' ')?;
            escape_into(writer, class)?;
        }
        writer.write_char('"')?;
    }

    Ok(())
}

fn write_node_style<W: fmt::Write>(writer: &mut W, style: &CssStyle) -> fmt::Result {
    if style.is_empty() {
        return Ok(());
    }

    writer.write_str(" style=\"")?;
    style.write_to(writer)?;
    writer.write_char('"')
}

#[cfg(feature = "wasm")]
fn class_to_node(element: &web_sys::Element, classes: &ClassList) {
    if !classes.is_empty() {
        let class_attr = create_class(classes);
        set_attribute(element, "class", &class_attr);
    }
}

#[cfg(feature = "wasm")]
fn style_to_node(element: &web_sys::Element, style: &CssStyle) {
    if !style.is_empty() {
        let mut styles = String::new();
        let _ = write!(styles, "{style}");
        set_attribute(element, "style", &styles);
    }
}

#[cfg(feature = "wasm")]
fn set_attribute(element: &web_sys::Element, name: &str, value: &str) {
    element.set_attribute(name, value).unwrap_throw();
}

#[cfg(feature = "wasm")]
fn append_child(parent: &web_sys::Element, child: &web_sys::Node) {
    parent.append_child(child).unwrap_throw();
}

#[cfg(feature = "wasm")]
fn create_element(ctx: &WebContext, name: &str) -> web_sys::Element {
    ctx.document.create_element(name).unwrap_throw()
}

#[cfg(feature = "wasm")]
fn create_element_ns(ctx: &WebContext, ns: &str, name: &str) -> web_sys::Element {
    ctx.document
        .create_element_ns(Some(ns), name)
        .unwrap_throw()
}

/// Implement VirtualNode for `Span<T>`
impl<T: VirtualNode> VirtualNode for Span<T> {
    fn write_markup(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), ParseError> {
        map_fmt(fmt.write_str("<span"))?;
        map_fmt(write_node_class(fmt, &self.classes))?;
        map_fmt(write_node_style(fmt, &self.style))?;
        node_attributes_to_markup(fmt, &self.attributes)?;
        map_fmt(fmt.write_char('>'))?;

        for child in &self.children {
            child.write_markup(fmt)?;
        }

        map_fmt(fmt.write_str("</span>"))?;
        Ok(())
    }

    #[cfg(feature = "wasm")]
    fn to_node(&self, ctx: &WebContext) -> web_sys::Node {
        use wasm_bindgen::JsCast as _;

        let element = create_element(ctx, "span");

        // Add classes
        class_to_node(&element, &self.classes);

        // Add styles
        style_to_node(&element, &self.style);

        // Add attributes
        node_attributes_to_node(&element, &self.attributes);

        // Add children
        for child in &self.children {
            let child_node = child.to_node(ctx);
            append_child(&element, &child_node);
        }

        element.unchecked_into::<web_sys::Node>()
    }
}

/// Implement VirtualNode for Anchor
impl VirtualNode for Anchor {
    fn write_markup(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), ParseError> {
        map_fmt(fmt.write_str("<a"))?;
        map_fmt(write_node_class(fmt, &self.classes))?;
        map_fmt(write_node_style(fmt, &self.style))?;
        node_attributes_to_markup(fmt, &self.attributes)?;
        map_fmt(fmt.write_char('>'))?;

        for child in &self.children {
            child.write_markup(fmt)?;
        }

        map_fmt(fmt.write_str("</a>"))?;
        Ok(())
    }

    #[cfg(feature = "wasm")]
    fn to_node(&self, ctx: &WebContext) -> web_sys::Node {
        use wasm_bindgen::JsCast as _;

        let element = create_element(ctx, "a");

        // Add classes
        class_to_node(&element, &self.classes);

        // Add styles
        style_to_node(&element, &self.style);

        // Add attributes
        node_attributes_to_node(&element, &self.attributes);

        // Add children
        for child in &self.children {
            let child_node = child.to_node(ctx);
            append_child(&element, &child_node);
        }

        element.unchecked_into::<web_sys::Node>()
    }
}

/// Implement VirtualNode for Img
impl VirtualNode for Img {
    fn write_markup(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), ParseError> {
        map_fmt(fmt.write_str("<img src=\""))?;
        map_fmt(escape_into(fmt, &self.src))?;
        map_fmt(fmt.write_str("\" alt=\""))?;
        map_fmt(escape_into(fmt, &self.alt))?;
        map_fmt(fmt.write_char('"'))?;
        map_fmt(write_node_class(fmt, &self.classes))?;
        map_fmt(write_node_style(fmt, &self.style))?;
        map_fmt(fmt.write_str("/"))?;
        map_fmt(fmt.write_char('>'))?;
        Ok(())
    }

    #[cfg(feature = "wasm")]
    fn to_node(&self, ctx: &WebContext) -> web_sys::Node {
        use wasm_bindgen::JsCast as _;

        let element = create_element(ctx, "img");

        set_attribute(&element, "src", &self.src);
        set_attribute(&element, "alt", &self.alt);

        // Add classes
        class_to_node(&element, &self.classes);

        // Add styles
        style_to_node(&element, &self.style);

        element.unchecked_into::<web_sys::Node>()
    }
}

fn write_symbol_style<W: fmt::Write>(writer: &mut W, italic: f64, style: &CssStyle) -> fmt::Result {
    if italic <= 0.0 && style.is_empty() {
        return Ok(());
    }

    writer.write_str(" style=\"")?;
    if italic > 0.0 {
        writer.write_str("margin-right:")?;
        writer.write_str(&make_em(italic))?;
        writer.write_char(';')?;
    }
    style.write_to(writer)?;
    writer.write_char('"')
}

#[cfg(feature = "wasm")]
fn symbol_node_style_str(italic: f64, style: &CssStyle) -> String {
    let mut styles = String::new();
    if italic > 0.0 {
        let _ = write!(styles, "margin-right:{};", make_em(italic));
    }
    let _ = write!(styles, "{style}");

    let mut escaped = String::with_capacity(styles.len() * 9 / 8);
    let _ = escape_into(&mut escaped, &styles);
    escaped
}

/// Implement VirtualNode for Symbol
impl VirtualNode for SymbolNode {
    fn write_markup(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), ParseError> {
        let needs_span = self.italic > 0.0 || !self.classes.is_empty() || !self.style.is_empty();

        if needs_span {
            map_fmt(fmt.write_str("<span"))?;
            map_fmt(write_node_class(fmt, &self.classes))?;
            map_fmt(write_symbol_style(fmt, self.italic, &self.style))?;
            map_fmt(fmt.write_char('>'))?;
            map_fmt(escape_into(fmt, &self.text))?;
            map_fmt(fmt.write_str("</span>"))?;
        } else {
            map_fmt(escape_into(fmt, &self.text))?;
        }

        Ok(())
    }

    #[cfg(feature = "wasm")]
    fn to_node(&self, ctx: &WebContext) -> web_sys::Node {
        use wasm_bindgen::JsCast as _;

        let needs_span = self.italic > 0.0 || !self.classes.is_empty() || !self.style.is_empty();

        if needs_span {
            let element = create_element(ctx, "span");

            // Add classes
            if !self.classes.is_empty() {
                let class_attr = create_class(&self.classes);
                set_attribute(&element, "class", &class_attr);
            }

            // Add styles
            let styles = symbol_node_style_str(self.italic, &self.style);
            if !styles.is_empty() {
                set_attribute(&element, "style", &styles);
            }

            // Add text content
            let text_node = ctx.document.create_text_node(&self.text);
            append_child(&element, &text_node);

            element.unchecked_into::<web_sys::Node>()
        } else {
            // Just return a text node
            ctx.document
                .create_text_node(&self.text)
                .unchecked_into::<web_sys::Node>()
        }
    }
}

/// Implement VirtualNode for SvgNode
impl VirtualNode for SvgNode {
    fn write_markup(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), ParseError> {
        map_fmt(fmt.write_str("<svg xmlns=\"http://www.w3.org/2000/svg\""))?;
        node_attributes_to_markup(fmt, &self.attributes)?;
        map_fmt(fmt.write_char('>'))?;

        for child in &self.children {
            match child {
                SvgChildNode::Path(path) => path.write_markup(fmt)?,
                SvgChildNode::Line(line) => line.write_markup(fmt)?,
            }
        }

        map_fmt(fmt.write_str("</svg>"))?;
        Ok(())
    }

    #[cfg(feature = "wasm")]
    fn to_node(&self, ctx: &WebContext) -> web_sys::Node {
        use wasm_bindgen::JsCast as _;

        let element = create_element_ns(ctx, "http://www.w3.org/2000/svg", "svg");

        // Add attributes
        node_attributes_to_node(&element, &self.attributes);

        // Add children
        for child in &self.children {
            let child_node = child.to_node(ctx);
            append_child(&element, &child_node);
        }

        element.unchecked_into::<web_sys::Node>()
    }
}

/// Implement VirtualNode for HtmlDomNode
impl VirtualNode for HtmlDomNode {
    fn write_markup(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), ParseError> {
        match self {
            Self::DomSpan(span) => span.write_markup(fmt),
            Self::Anchor(anchor) => anchor.write_markup(fmt),
            Self::Img(img) => img.write_markup(fmt),
            Self::Symbol(symbol) => symbol.write_markup(fmt),
            Self::SvgNode(svg_node) => svg_node.write_markup(fmt),
            Self::MathML(math_node) => math_node.write_markup(fmt),
            Self::Fragment(fragment) => fragment.write_markup(fmt),
        }
    }

    #[cfg(feature = "wasm")]
    fn to_node(&self, ctx: &WebContext) -> web_sys::Node {
        match self {
            Self::DomSpan(span) => span.to_node(ctx),
            Self::Anchor(anchor) => anchor.to_node(ctx),
            Self::Img(img) => img.to_node(ctx),
            Self::Symbol(symbol) => symbol.to_node(ctx),
            Self::SvgNode(svg_node) => svg_node.to_node(ctx),
            Self::MathML(math_node) => math_node.to_node(ctx),
            Self::Fragment(fragment) => fragment.to_node(ctx),
        }
    }
}

/// Helper methods for HtmlDomNode to maintain API compatibility
///
/// These methods provide a unified interface for accessing properties of
/// different HTML DOM node types. Not all node types support all properties -
/// for example, SVG and MathML nodes don't have traditional CSS classes or
/// dimensions.
impl HtmlDomNode {
    /// Get the CSS classes applied to this node
    ///
    /// Returns an empty class list for node types that don't support CSS
    /// classes (SvgNode, MathML). For other node types, returns their class
    /// list.
    #[must_use]
    pub const fn classes(&self) -> &ClassList {
        match self {
            Self::DomSpan(span) => &span.classes,
            Self::Anchor(anchor) => &anchor.classes,
            Self::Img(img) => &img.classes,
            Self::Symbol(symbol) => &symbol.classes,
            Self::Fragment(fragment) => &fragment.classes,
            Self::SvgNode(_) | Self::MathML { .. } => &EMPTY_CLASS_LIST,
        }
    }

    /// Try to mutate the CSS classes applied to this node
    ///
    /// Returns `Some(&mut ClassList)` for node types that support mutable CSS
    /// classes, or `None` for node types that don't support CSS classes
    /// (SvgNode, MathML).
    pub const fn classes_mut(&mut self) -> Option<&mut ClassList> {
        match self {
            Self::DomSpan(span) => Some(&mut span.classes),
            Self::Anchor(anchor) => Some(&mut anchor.classes),
            Self::Img(img) => Some(&mut img.classes),
            Self::Symbol(symbol) => Some(&mut symbol.classes),
            Self::SvgNode(_) | Self::MathML { .. } => None,
            Self::Fragment(fragment) => Some(&mut fragment.classes),
        }
    }

    /// Get the height of this node
    ///
    /// Returns the vertical height above the baseline in em units.
    /// For node types that don't have a defined height (SvgNode, MathML),
    /// returns 0.0.
    #[must_use]
    pub const fn height(&self) -> f64 {
        match self {
            Self::DomSpan(span) => span.height,
            Self::Anchor(anchor) => anchor.height,
            Self::Img(img) => img.height,
            Self::Symbol(symbol) => symbol.height,
            Self::SvgNode(_) | Self::MathML { .. } => 0.0,
            Self::Fragment(fragment) => fragment.height,
        }
    }

    /// Try to set the height of this node
    ///
    /// Returns `Some(&mut f64)` for node types that support mutable height,
    /// or `None` for node types that don't have a defined height (SvgNode,
    /// MathML).
    pub const fn height_mut(&mut self) -> Option<&mut f64> {
        match self {
            Self::DomSpan(span) => Some(&mut span.height),
            Self::Anchor(anchor) => Some(&mut anchor.height),
            Self::Img(img) => Some(&mut img.height),
            Self::Symbol(symbol) => Some(&mut symbol.height),
            Self::SvgNode(_) | Self::MathML { .. } => None,
            Self::Fragment(fragment) => Some(&mut fragment.height),
        }
    }

    /// Get the depth of this node
    ///
    /// Returns the vertical depth below the baseline in em units.
    /// For node types that don't have a defined depth (SvgNode, MathML),
    /// returns 0.0.
    #[must_use]
    pub const fn depth(&self) -> f64 {
        match self {
            Self::DomSpan(span) => span.depth,
            Self::Anchor(anchor) => anchor.depth,
            Self::Img(img) => img.depth,
            Self::Symbol(symbol) => symbol.depth,
            Self::SvgNode(_) | Self::MathML { .. } => 0.0,
            Self::Fragment(fragment) => fragment.depth,
        }
    }

    /// Try to set the depth of this node
    ///
    /// Returns `Some(&mut f64)` for node types that support mutable depth,
    /// or `None` for node types that don't have a defined depth (SvgNode,
    /// MathML).
    pub const fn depth_mut(&mut self) -> Option<&mut f64> {
        match self {
            Self::DomSpan(span) => Some(&mut span.depth),
            Self::Anchor(anchor) => Some(&mut anchor.depth),
            Self::Img(img) => Some(&mut img.depth),
            Self::Symbol(symbol) => Some(&mut symbol.depth),
            Self::SvgNode(_) | Self::MathML { .. } => None,
            Self::Fragment(fragment) => Some(&mut fragment.depth),
        }
    }

    /// Get the maximum font size used in this node
    ///
    /// Returns the largest font size used within this node and its children in
    /// em units. For node types that don't have a defined max_font_size
    /// (SvgNode, MathML), returns 0.0.
    #[must_use]
    pub const fn max_font_size(&self) -> f64 {
        match self {
            Self::DomSpan(span) => span.max_font_size,
            Self::Anchor(anchor) => anchor.max_font_size,
            Self::Img(img) => img.max_font_size,
            Self::Symbol(symbol) => symbol.max_font_size,
            Self::SvgNode(_) | Self::MathML { .. } => 0.0,
            Self::Fragment(fragment) => fragment.max_font_size,
        }
    }

    /// Try to set the maximum font size of this node
    ///
    /// Returns `Some(&mut f64)` for node types that support mutable
    /// max_font_size, or `None` for node types that don't have a defined
    /// max_font_size (SvgNode, MathML).
    pub const fn max_font_size_mut(&mut self) -> Option<&mut f64> {
        match self {
            Self::DomSpan(span) => Some(&mut span.max_font_size),
            Self::Anchor(anchor) => Some(&mut anchor.max_font_size),
            Self::Img(img) => Some(&mut img.max_font_size),
            Self::Symbol(symbol) => Some(&mut symbol.max_font_size),
            Self::SvgNode(_) | Self::MathML { .. } => None,
            Self::Fragment(fragment) => Some(&mut fragment.max_font_size),
        }
    }

    /// Get the width of this node
    ///
    /// Returns the horizontal width in em units, or `None` if the node doesn't
    /// have a defined width. Most node types don't have a defined width,
    /// with Symbol being the primary exception.
    #[must_use]
    pub const fn width(&self) -> Option<f64> {
        match self {
            Self::DomSpan(span) => span.width,
            Self::Anchor(_)
            | Self::Img(_)
            | Self::SvgNode(_)
            | Self::MathML { .. }
            | Self::Fragment(_) => None,
            Self::Symbol(symbol) => Some(symbol.width),
        }
    }

    /// Get the inline CSS style object
    ///
    /// Returns a reference to the CSS style properties applied to this node.
    /// For node types that don't support inline styles (SvgNode, MathML),
    /// returns an empty style object.
    #[must_use]
    pub const fn style(&self) -> Option<&CssStyle> {
        match self {
            Self::DomSpan(span) => Some(&span.style),
            Self::Anchor(anchor) => Some(&anchor.style),
            Self::Img(img) => Some(&img.style),
            Self::Symbol(symbol) => Some(&symbol.style),
            Self::Fragment(fragment) => Some(&fragment.style),
            Self::SvgNode(_) | Self::MathML { .. } => None,
        }
    }

    /// Get a mutable reference to the inline CSS style object
    ///
    /// Returns a mutable reference to the CSS style properties applied to this
    /// node. For node types that don't support inline styles (SvgNode,
    /// MathML), returns an empty style object.
    pub const fn style_mut(&mut self) -> Option<&mut CssStyle> {
        match self {
            Self::DomSpan(span) => Some(&mut span.style),
            Self::Anchor(anchor) => Some(&mut anchor.style),
            Self::Img(img) => Some(&mut img.style),
            Self::Symbol(symbol) => Some(&mut symbol.style),
            Self::SvgNode(_) | Self::MathML { .. } => None,
            Self::Fragment(fragment) => Some(&mut fragment.style),
        }
    }

    /// Check if this node has a specific CSS class
    ///
    /// Returns `true` if the node contains the specified CSS class in its class
    /// list. For node types that don't support CSS classes (SvgNode,
    /// MathML), always returns `false`.
    #[must_use]
    pub fn has_class(&self, class_name: &str) -> bool {
        self.classes().contains(class_name)
    }

    /// Get the attributes of this node
    #[must_use]
    pub const fn attributes(&self) -> Option<&KeyMap<String, String>> {
        match self {
            Self::DomSpan(span) => Some(&span.attributes),
            Self::Anchor(anchor) => Some(&anchor.attributes),
            Self::Img(_) | Self::Symbol(_) | Self::Fragment(_) => None,
            Self::SvgNode(svg_node) => Some(&svg_node.attributes),
            Self::MathML(mathml) => Some(&mathml.attributes),
        }
    }
}

/// SVG path node
#[derive(Debug, Clone)]
pub struct PathNode {
    /// Name of the predefined path
    pub path_name: String,
    /// Optional alternate path data (used for sqrt, phase, tall delimiters)
    pub alternate: Option<String>,
}

impl VirtualNode for PathNode {
    /// Convert this path node into HTML markup string
    fn write_markup(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), ParseError> {
        let path_data = self.alternate.as_ref().map_or_else(
            || {
                PATH_MAP
                    .get(&self.path_name)
                    .map_or_else(String::new, |s| (*s).to_owned())
            },
            Clone::clone,
        );

        map_fmt(fmt.write_str("<path d=\""))?;
        map_fmt(escape_into(fmt, &path_data))?;
        map_fmt(fmt.write_str("\"/>"))?;
        Ok(())
    }

    /// Convert this path node into a DOM node representation
    #[cfg(feature = "wasm")]
    fn to_node(&self, ctx: &WebContext) -> web_sys::Node {
        use wasm_bindgen::JsCast as _;

        let element = create_element_ns(ctx, "http://www.w3.org/2000/svg", "path");

        let path_data = self.alternate.as_ref().map_or_else(
            || {
                PATH_MAP
                    .get(&self.path_name)
                    .map_or_else(String::new, |s| (*s).to_owned())
            },
            Clone::clone,
        );

        set_attribute(&element, "d", &path_data);
        element.unchecked_into::<web_sys::Node>()
    }
}

/// SVG line node
#[derive(Debug, Clone)]
pub struct LineNode {
    /// SVG attributes for this line element
    pub attributes: KeyMap<String, String>,
}

fn node_attributes_to_markup<W: fmt::Write>(
    writer: &mut W,
    attributes: &KeyMap<String, String>,
) -> Result<(), ParseError> {
    for (attr, value) in attributes {
        if !attr.is_empty() {
            if attr.contains(|c: char| {
                c.is_whitespace() || "\"'>/=".contains(c) || ('\x00'..='\x1f').contains(&c)
            }) {
                return Err(ParseErrorKind::InvalidAttributeName { attr: attr.clone() }.into());
            }
            map_fmt(write!(writer, " {attr}=\""))?;
            map_fmt(escape_into(writer, value))?;
            map_fmt(writer.write_char('"'))?;
        }
    }
    Ok(())
}

#[cfg(feature = "wasm")]
fn node_attributes_to_node(element: &web_sys::Element, attributes: &KeyMap<String, String>) {
    for (attr, value) in attributes {
        if !attr.is_empty() {
            if attr.contains(|c: char| {
                c.is_whitespace() || "\"'>/=".contains(c) || ('\x00'..='\x1f').contains(&c)
            }) {
                continue;
            }
            set_attribute(element, attr, value);
        }
    }
}

impl VirtualNode for LineNode {
    /// Convert this line node into HTML markup string
    fn write_markup(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), ParseError> {
        map_fmt(fmt.write_str("<line"))?;
        node_attributes_to_markup(fmt, &self.attributes)?;
        map_fmt(fmt.write_str("/"))?;
        map_fmt(fmt.write_char('>'))?;
        Ok(())
    }

    /// Convert this line node into a DOM node representation
    #[cfg(feature = "wasm")]
    fn to_node(&self, ctx: &WebContext) -> web_sys::Node {
        use wasm_bindgen::JsCast as _;

        let element = create_element_ns(ctx, "http://www.w3.org/2000/svg", "line");

        // Add attributes
        node_attributes_to_node(&element, &self.attributes);

        element.unchecked_into::<web_sys::Node>()
    }
}