Skip to main content

pax_std/drawing/
handwriter.rs

1use pax_engine::api::LocalProperty;
2use std::collections::HashMap;
3
4use pax_engine::api::{
5    Color, Numeric, PathElement, PathSmoothing, Property, Size, Stroke, StrokeCap, StrokeJoin,
6    UnitValue,
7};
8use pax_engine::*;
9use pax_runtime::api::NodeContext;
10
11/// Renders text as single-stroke vector paths suitable for handwriting effects.
12///
13/// `Handwriter` uses bundled SVG stroke fonts and translates text into
14/// `PathElement` data for an inner `Path`. Use `draw_start` and `draw_end` to
15/// animate the visible writing range.
16#[pax]
17#[engine_import_path("pax_engine")]
18#[custom(Default)]
19#[file("drawing/handwriter.pax")]
20pub struct Handwriter {
21    /// Text to render. Newline characters create additional baselines.
22    pub text: Property<String>,
23    /// Bundled stroke font used to draw `text`.
24    pub font: Property<HandwriterFont>,
25    /// Stroke used for the generated path.
26    pub stroke: Property<Vec<Stroke>>,
27    /// Optional curve smoothing applied to generated path geometry.
28    pub smoothing: Property<PathSmoothing>,
29    /// Accessible text label. When empty, `text` is used.
30    pub alt_text: Property<String>,
31    /// Whether the invisible native text layer can be selected.
32    pub selectable: Property<bool>,
33    /// Start position of the visible handwriting range.
34    pub draw_start: Property<UnitValue>,
35    /// End position of the visible handwriting range.
36    pub draw_end: Property<UnitValue>,
37    /// Baseline-to-baseline multiplier relative to the font's em size.
38    pub line_height: Property<f64>,
39    // Generated path elements consumed by the internal `Path`.
40    pub _elements: Property<Vec<PathElement>>,
41    // Native text content used for accessibility and selection.
42    pub _accessibility_text: Property<String>,
43    // Approximate native font size used by the invisible selectable text.
44    pub _accessibility_font_size: Property<Size>,
45}
46
47impl Default for Handwriter {
48    fn default() -> Self {
49        Self {
50            text: Property::new(
51                "The silver apples of the moon,\nThe golden apples of the sun.".into(),
52            ),
53            font: Property::new(HandwriterFont::EMSAllure),
54            stroke: Property::new(vec![Stroke {
55                paint: Property::new(Color::BLACK.into()),
56                width: Property::new(Size::Pixels(Numeric::F64(3.0))),
57                cap: Property::new(StrokeCap::Round),
58                join: Property::new(StrokeJoin::Round),
59
60                ..Stroke::default()
61            }]),
62            smoothing: Property::new(PathSmoothing::None),
63            alt_text: Property::new(String::new()),
64            selectable: Property::new(true),
65            draw_start: Property::new(UnitValue::Unitless(Numeric::F64(0.0))),
66            draw_end: Property::new(UnitValue::Unitless(Numeric::F64(1.0))),
67            line_height: Property::new(1.2),
68            _elements: Property::new(Vec::new()),
69            _accessibility_text: Property::new(String::new()),
70            _accessibility_font_size: Property::new(Size::Pixels(Numeric::F64(100.0))),
71        }
72    }
73}
74
75/// Bundled single-stroke fonts available to `Handwriter`.
76#[pax]
77#[engine_import_path("pax_engine")]
78pub enum HandwriterFont {
79    /// Cursive, airy script.
80    #[default]
81    EMSAllure,
82    /// Friendly rounded print hand.
83    EMSDelight,
84    /// Tall invitation script.
85    EMSInvite,
86    /// Flowing connected script.
87    EMSLeague,
88    /// Casual narrow script.
89    EMSNeato,
90    /// Rectilinear plotter hand.
91    EMSOsmotron,
92    /// Highly readable manuscript hand.
93    EMSReadability,
94    /// Technical drafting hand.
95    EMSTech,
96    /// Classic Hershey sans stroke font.
97    HersheySans1,
98    /// Classic Hershey connected script.
99    HersheyScript1,
100}
101
102impl Handwriter {
103    // Wires generated path data reactively from text/font settings.
104    pub fn on_mount(&mut self, _ctx: &NodeContext) {
105        let text = self.text.local();
106        let text_for_accessibility = self.text.local();
107        let alt_text = self.alt_text.local();
108        let font = self.font.local();
109        let line_height = self.line_height.local();
110        let deps = [text.untyped(), font.untyped(), line_height.untyped()];
111        self._elements.replace_with(LocalProperty::computed(
112            move || render_handwriter_text(&text.get(), font.get(), line_height.get()),
113            &deps,
114        ));
115        let accessibility_deps = [text_for_accessibility.untyped(), alt_text.untyped()];
116        self._accessibility_text
117            .replace_with(LocalProperty::computed(
118                move || {
119                    let alt = alt_text.get();
120                    if alt.trim().is_empty() {
121                        normalize_text_newlines(&text_for_accessibility.get())
122                    } else {
123                        normalize_text_newlines(&alt)
124                    }
125                },
126                &accessibility_deps,
127            ));
128        let accessibility_text = self._accessibility_text.local();
129        let accessibility_size_deps = [accessibility_text.untyped()];
130        self._accessibility_font_size
131            .replace_with(LocalProperty::computed(
132                move || accessibility_font_size(&accessibility_text.get()),
133                &accessibility_size_deps,
134            ));
135    }
136}
137
138fn render_handwriter_text(
139    text: &str,
140    font: HandwriterFont,
141    line_height_multiplier: f64,
142) -> Vec<PathElement> {
143    let Some(svg_font) = parse_svg_font(font_source(font)) else {
144        return Vec::new();
145    };
146    let line_height = svg_font.units_per_em * line_height_multiplier.max(0.1);
147    let fallback_advance = svg_font.default_advance.max(svg_font.units_per_em * 0.35);
148    let mut raw = Vec::new();
149    let mut pen_x = 0.0;
150    let mut line_index = 0.0;
151
152    let mut chars = text.chars().peekable();
153    while let Some(ch) = chars.next() {
154        match ch {
155            '\n' => {
156                line_index += 1.0;
157                pen_x = 0.0;
158            }
159            '\\' if chars.peek() == Some(&'n') => {
160                chars.next();
161                line_index += 1.0;
162                pen_x = 0.0;
163            }
164            '\r' => {}
165            '\t' => {
166                pen_x += fallback_advance * 4.0;
167            }
168            _ => {
169                let baseline = line_index * line_height + svg_font.ascent;
170                if let Some(glyph) = svg_font.glyphs.get(&ch) {
171                    push_glyph(&mut raw, glyph, pen_x, baseline);
172                    pen_x += glyph.advance;
173                } else {
174                    pen_x += fallback_advance;
175                }
176            }
177        }
178    }
179
180    let bounds = compute_bounds(&raw);
181    if raw.is_empty() || !bounds.is_valid() {
182        return Vec::new();
183    }
184
185    let width = (bounds.max_x - bounds.min_x).max(1.0);
186    let height = (bounds.max_y - bounds.min_y).max(1.0);
187    let mut elements = Vec::new();
188    for element in raw {
189        push_path_element(&mut elements, element, &bounds, width, height);
190    }
191    elements
192}
193
194fn push_glyph(raw: &mut Vec<RawElement>, glyph: &Glyph, pen_x: f64, baseline: f64) {
195    for element in &glyph.elements {
196        match *element {
197            GlyphElement::Move(point) => {
198                let point = transform_glyph_point(point, pen_x, baseline);
199                raw.push(RawElement::Move(point));
200            }
201            GlyphElement::Line(point) => {
202                let point = transform_glyph_point(point, pen_x, baseline);
203                raw.push(RawElement::Line(point));
204            }
205            GlyphElement::Quadratic(control, point) => {
206                let control = transform_glyph_point(control, pen_x, baseline);
207                let point = transform_glyph_point(point, pen_x, baseline);
208                raw.push(RawElement::Quadratic(control, point));
209            }
210            GlyphElement::Cubic(control_1, control_2, point) => {
211                let control_1 = transform_glyph_point(control_1, pen_x, baseline);
212                let control_2 = transform_glyph_point(control_2, pen_x, baseline);
213                let point = transform_glyph_point(point, pen_x, baseline);
214                raw.push(RawElement::Cubic(control_1, control_2, point));
215            }
216            GlyphElement::Close => raw.push(RawElement::Close),
217        }
218    }
219}
220
221fn transform_glyph_point(point: RawPoint, pen_x: f64, baseline: f64) -> RawPoint {
222    RawPoint {
223        x: pen_x + point.x,
224        y: baseline - point.y,
225    }
226}
227
228fn normalize_text_newlines(text: &str) -> String {
229    text.replace("\\n", "\n")
230}
231
232fn accessibility_font_size(text: &str) -> Size {
233    let normalized = normalize_text_newlines(text);
234    let line_count = normalized.lines().count().max(1) as f64;
235    Size::Pixels(Numeric::F64((104.0 / line_count).clamp(18.0, 112.0)))
236}
237
238fn compute_bounds(raw: &[RawElement]) -> Bounds {
239    let mut bounds = Bounds::default();
240    for element in raw {
241        match *element {
242            RawElement::Move(point) | RawElement::Line(point) => bounds.include(point),
243            RawElement::Quadratic(control, point) => {
244                bounds.include(control);
245                bounds.include(point);
246            }
247            RawElement::Cubic(control_1, control_2, point) => {
248                bounds.include(control_1);
249                bounds.include(control_2);
250                bounds.include(point);
251            }
252            RawElement::Close => {}
253        }
254    }
255    bounds
256}
257
258#[derive(Default)]
259struct Bounds {
260    min_x: f64,
261    min_y: f64,
262    max_x: f64,
263    max_y: f64,
264    initialized: bool,
265}
266
267impl Bounds {
268    fn include(&mut self, point: RawPoint) {
269        if self.initialized {
270            self.min_x = self.min_x.min(point.x);
271            self.min_y = self.min_y.min(point.y);
272            self.max_x = self.max_x.max(point.x);
273            self.max_y = self.max_y.max(point.y);
274        } else {
275            self.min_x = point.x;
276            self.min_y = point.y;
277            self.max_x = point.x;
278            self.max_y = point.y;
279            self.initialized = true;
280        }
281    }
282
283    fn is_valid(&self) -> bool {
284        self.initialized
285    }
286}
287
288#[derive(Clone)]
289struct SvgFont {
290    units_per_em: f64,
291    ascent: f64,
292    default_advance: f64,
293    glyphs: HashMap<char, Glyph>,
294}
295
296#[derive(Clone)]
297struct Glyph {
298    advance: f64,
299    elements: Vec<GlyphElement>,
300}
301
302#[derive(Clone, Copy)]
303enum GlyphElement {
304    Move(RawPoint),
305    Line(RawPoint),
306    Quadratic(RawPoint, RawPoint),
307    Cubic(RawPoint, RawPoint, RawPoint),
308    Close,
309}
310
311#[derive(Clone, Copy)]
312enum RawElement {
313    Move(RawPoint),
314    Line(RawPoint),
315    Quadratic(RawPoint, RawPoint),
316    Cubic(RawPoint, RawPoint, RawPoint),
317    Close,
318}
319
320fn push_path_element(
321    elements: &mut Vec<PathElement>,
322    element: RawElement,
323    bounds: &Bounds,
324    width: f64,
325    height: f64,
326) {
327    match element {
328        RawElement::Move(point) => elements.push(path_point(point, bounds, width, height)),
329        RawElement::Line(point) => {
330            elements.push(PathElement::Line);
331            elements.push(path_point(point, bounds, width, height));
332        }
333        RawElement::Quadratic(control, point) => {
334            elements.push(PathElement::Quadratic(
335                percent_x(control, bounds, width),
336                percent_y(control, bounds, height),
337            ));
338            elements.push(path_point(point, bounds, width, height));
339        }
340        RawElement::Cubic(control_1, control_2, point) => {
341            elements.push(PathElement::Cubic(
342                percent_x(control_1, bounds, width),
343                percent_y(control_1, bounds, height),
344                percent_x(control_2, bounds, width),
345                percent_y(control_2, bounds, height),
346            ));
347            elements.push(path_point(point, bounds, width, height));
348        }
349        RawElement::Close => elements.push(PathElement::Close),
350    }
351}
352
353#[derive(Clone, Copy, Default)]
354struct RawPoint {
355    x: f64,
356    y: f64,
357}
358
359fn percent_x(point: RawPoint, bounds: &Bounds, width: f64) -> Size {
360    percent(((point.x - bounds.min_x) / width) * 94.0 + 3.0)
361}
362
363fn percent_y(point: RawPoint, bounds: &Bounds, height: f64) -> Size {
364    percent(((point.y - bounds.min_y) / height) * 94.0 + 3.0)
365}
366
367fn path_point(point: RawPoint, bounds: &Bounds, width: f64, height: f64) -> PathElement {
368    PathElement::Point(
369        percent_x(point, bounds, width),
370        percent_y(point, bounds, height),
371    )
372}
373
374fn percent(value: f64) -> Size {
375    Size::Percent(Numeric::F64(value))
376}
377
378fn parse_svg_font(svg: &'static str) -> Option<SvgFont> {
379    let font_tag = find_tag(svg, "font")?;
380    let default_advance = parse_attr_f64(font_tag, "horiz-adv-x").unwrap_or(1000.0);
381    let font_face_tag = find_tag(svg, "font-face");
382    let units_per_em = font_face_tag
383        .and_then(|tag| parse_attr_f64(tag, "units-per-em"))
384        .unwrap_or(1000.0);
385    let ascent = font_face_tag
386        .and_then(|tag| parse_attr_f64(tag, "ascent"))
387        .unwrap_or(units_per_em * 0.8);
388
389    let mut glyphs = HashMap::new();
390    for glyph_tag in find_tags(svg, "glyph") {
391        let Some(unicode) = attr_value(glyph_tag, "unicode") else {
392            continue;
393        };
394        let mut chars = unicode.chars();
395        let Some(ch) = chars.next() else {
396            continue;
397        };
398        if chars.next().is_some() {
399            continue;
400        }
401        let advance = parse_attr_f64(glyph_tag, "horiz-adv-x").unwrap_or(default_advance);
402        let elements = attr_value(glyph_tag, "d")
403            .map(|data| parse_path_data(&data))
404            .unwrap_or_default();
405        glyphs.insert(ch, Glyph { advance, elements });
406    }
407
408    Some(SvgFont {
409        units_per_em,
410        ascent,
411        default_advance,
412        glyphs,
413    })
414}
415
416fn parse_path_data(data: &str) -> Vec<GlyphElement> {
417    let tokens = tokenize_path_data(data);
418    let mut parser = PathDataParser {
419        tokens: &tokens,
420        index: 0,
421        command: None,
422        current: RawPoint::default(),
423        contour_start: RawPoint::default(),
424        last_cubic_control: None,
425        last_quadratic_control: None,
426        elements: Vec::new(),
427    };
428    parser.parse();
429    parser.elements
430}
431
432struct PathDataParser<'a> {
433    tokens: &'a [PathToken],
434    index: usize,
435    command: Option<char>,
436    current: RawPoint,
437    contour_start: RawPoint,
438    last_cubic_control: Option<RawPoint>,
439    last_quadratic_control: Option<RawPoint>,
440    elements: Vec<GlyphElement>,
441}
442
443impl PathDataParser<'_> {
444    fn parse(&mut self) {
445        while self.index < self.tokens.len() {
446            if let Some(command) = self.take_command() {
447                self.command = Some(command);
448            }
449
450            let Some(command) = self.command else {
451                break;
452            };
453            let relative = command.is_ascii_lowercase();
454            match command.to_ascii_uppercase() {
455                'M' => self.parse_move(relative),
456                'L' => self.parse_line(relative),
457                'H' => self.parse_horizontal(relative),
458                'V' => self.parse_vertical(relative),
459                'C' => self.parse_cubic(relative),
460                'S' => self.parse_smooth_cubic(relative),
461                'Q' => self.parse_quadratic(relative),
462                'T' => self.parse_smooth_quadratic(relative),
463                'Z' => self.close_contour(),
464                _ => break,
465            }
466        }
467    }
468
469    fn parse_move(&mut self, relative: bool) {
470        let Some(point) = self.take_point(relative) else {
471            return;
472        };
473        self.current = point;
474        self.contour_start = point;
475        self.elements.push(GlyphElement::Move(point));
476        self.clear_controls();
477
478        while let Some(point) = self.take_point(relative) {
479            self.current = point;
480            self.elements.push(GlyphElement::Line(point));
481        }
482    }
483
484    fn parse_line(&mut self, relative: bool) {
485        while let Some(point) = self.take_point(relative) {
486            self.current = point;
487            self.elements.push(GlyphElement::Line(point));
488            self.clear_controls();
489        }
490    }
491
492    fn parse_horizontal(&mut self, relative: bool) {
493        while let Some(x) = self.take_number() {
494            let point = RawPoint {
495                x: if relative { self.current.x + x } else { x },
496                y: self.current.y,
497            };
498            self.current = point;
499            self.elements.push(GlyphElement::Line(point));
500            self.clear_controls();
501        }
502    }
503
504    fn parse_vertical(&mut self, relative: bool) {
505        while let Some(y) = self.take_number() {
506            let point = RawPoint {
507                x: self.current.x,
508                y: if relative { self.current.y + y } else { y },
509            };
510            self.current = point;
511            self.elements.push(GlyphElement::Line(point));
512            self.clear_controls();
513        }
514    }
515
516    fn parse_cubic(&mut self, relative: bool) {
517        while let (Some(control_1), Some(control_2), Some(point)) = (
518            self.take_point(relative),
519            self.take_point(relative),
520            self.take_point(relative),
521        ) {
522            self.current = point;
523            self.last_cubic_control = Some(control_2);
524            self.last_quadratic_control = None;
525            self.elements
526                .push(GlyphElement::Cubic(control_1, control_2, point));
527        }
528    }
529
530    fn parse_smooth_cubic(&mut self, relative: bool) {
531        while let (Some(control_2), Some(point)) =
532            (self.take_point(relative), self.take_point(relative))
533        {
534            let control_1 = self
535                .last_cubic_control
536                .map(|control| reflect(control, self.current))
537                .unwrap_or(self.current);
538            self.current = point;
539            self.last_cubic_control = Some(control_2);
540            self.last_quadratic_control = None;
541            self.elements
542                .push(GlyphElement::Cubic(control_1, control_2, point));
543        }
544    }
545
546    fn parse_quadratic(&mut self, relative: bool) {
547        while let (Some(control), Some(point)) =
548            (self.take_point(relative), self.take_point(relative))
549        {
550            self.current = point;
551            self.last_quadratic_control = Some(control);
552            self.last_cubic_control = None;
553            self.elements.push(GlyphElement::Quadratic(control, point));
554        }
555    }
556
557    fn parse_smooth_quadratic(&mut self, relative: bool) {
558        while let Some(point) = self.take_point(relative) {
559            let control = self
560                .last_quadratic_control
561                .map(|control| reflect(control, self.current))
562                .unwrap_or(self.current);
563            self.current = point;
564            self.last_quadratic_control = Some(control);
565            self.last_cubic_control = None;
566            self.elements.push(GlyphElement::Quadratic(control, point));
567        }
568    }
569
570    fn close_contour(&mut self) {
571        self.elements.push(GlyphElement::Close);
572        self.current = self.contour_start;
573        self.clear_controls();
574        self.command = None;
575    }
576
577    fn take_command(&mut self) -> Option<char> {
578        match self.tokens.get(self.index) {
579            Some(PathToken::Command(command)) => {
580                self.index += 1;
581                Some(*command)
582            }
583            _ => None,
584        }
585    }
586
587    fn take_point(&mut self, relative: bool) -> Option<RawPoint> {
588        let index = self.index;
589        let Some(x) = self.take_number() else {
590            return None;
591        };
592        let Some(y) = self.take_number() else {
593            self.index = index;
594            return None;
595        };
596        Some(if relative {
597            RawPoint {
598                x: self.current.x + x,
599                y: self.current.y + y,
600            }
601        } else {
602            RawPoint { x, y }
603        })
604    }
605
606    fn take_number(&mut self) -> Option<f64> {
607        match self.tokens.get(self.index) {
608            Some(PathToken::Number(value)) => {
609                self.index += 1;
610                Some(*value)
611            }
612            _ => None,
613        }
614    }
615
616    fn clear_controls(&mut self) {
617        self.last_cubic_control = None;
618        self.last_quadratic_control = None;
619    }
620}
621
622fn reflect(point: RawPoint, around: RawPoint) -> RawPoint {
623    RawPoint {
624        x: around.x * 2.0 - point.x,
625        y: around.y * 2.0 - point.y,
626    }
627}
628
629#[derive(Clone, Copy)]
630enum PathToken {
631    Command(char),
632    Number(f64),
633}
634
635fn tokenize_path_data(data: &str) -> Vec<PathToken> {
636    let chars: Vec<char> = data.chars().collect();
637    let mut tokens = Vec::new();
638    let mut index = 0;
639    while index < chars.len() {
640        let ch = chars[index];
641        if ch.is_ascii_whitespace() || ch == ',' {
642            index += 1;
643        } else if is_path_command(ch) {
644            tokens.push(PathToken::Command(ch));
645            index += 1;
646        } else if is_number_start(ch) {
647            let start = index;
648            index += 1;
649            while index < chars.len() {
650                let next = chars[index];
651                if next.is_ascii_digit() || next == '.' {
652                    index += 1;
653                } else if next == 'e' || next == 'E' {
654                    index += 1;
655                    if matches!(chars.get(index), Some('+') | Some('-')) {
656                        index += 1;
657                    }
658                } else {
659                    break;
660                }
661            }
662            let value = chars[start..index]
663                .iter()
664                .collect::<String>()
665                .parse::<f64>();
666            if let Ok(value) = value {
667                tokens.push(PathToken::Number(value));
668            }
669        } else {
670            index += 1;
671        }
672    }
673    tokens
674}
675
676fn is_path_command(ch: char) -> bool {
677    matches!(
678        ch,
679        'M' | 'm'
680            | 'L'
681            | 'l'
682            | 'H'
683            | 'h'
684            | 'V'
685            | 'v'
686            | 'C'
687            | 'c'
688            | 'S'
689            | 's'
690            | 'Q'
691            | 'q'
692            | 'T'
693            | 't'
694            | 'Z'
695            | 'z'
696    )
697}
698
699fn is_number_start(ch: char) -> bool {
700    ch.is_ascii_digit() || ch == '-' || ch == '+' || ch == '.'
701}
702
703fn parse_attr_f64(tag: &str, name: &str) -> Option<f64> {
704    attr_value(tag, name)?.parse().ok()
705}
706
707fn find_tag<'a>(source: &'a str, tag_name: &str) -> Option<&'a str> {
708    find_tags(source, tag_name).into_iter().next()
709}
710
711fn find_tags<'a>(source: &'a str, tag_name: &str) -> Vec<&'a str> {
712    let mut tags = Vec::new();
713    let mut search_start = 0;
714    let needle = format!("<{tag_name}");
715    while let Some(relative_start) = source[search_start..].find(&needle) {
716        let start = search_start + relative_start;
717        let after_name = start + needle.len();
718        let Some(next) = source.as_bytes().get(after_name) else {
719            break;
720        };
721        if !next.is_ascii_whitespace() && *next != b'>' && *next != b'/' {
722            search_start = after_name;
723            continue;
724        }
725        let Some(relative_end) = source[start..].find('>') else {
726            break;
727        };
728        let end = start + relative_end + 1;
729        tags.push(&source[start..end]);
730        search_start = end;
731    }
732    tags
733}
734
735fn attr_value(tag: &str, name: &str) -> Option<String> {
736    let bytes = tag.as_bytes();
737    let mut index = 0;
738    while index < bytes.len() {
739        while index < bytes.len() && !is_attr_name_start(bytes[index]) {
740            index += 1;
741        }
742        let name_start = index;
743        while index < bytes.len() && is_attr_name_char(bytes[index]) {
744            index += 1;
745        }
746        if name_start == index {
747            break;
748        }
749        let key = &tag[name_start..index];
750        while index < bytes.len() && bytes[index].is_ascii_whitespace() {
751            index += 1;
752        }
753        if bytes.get(index) != Some(&b'=') {
754            continue;
755        }
756        index += 1;
757        while index < bytes.len() && bytes[index].is_ascii_whitespace() {
758            index += 1;
759        }
760        let Some(quote) = bytes.get(index).copied() else {
761            break;
762        };
763        if quote != b'"' && quote != b'\'' {
764            index += 1;
765            continue;
766        }
767        index += 1;
768        let value_start = index;
769        while index < bytes.len() && bytes[index] != quote {
770            index += 1;
771        }
772        let value = &tag[value_start..index];
773        if key == name {
774            return Some(decode_xml_entities(value));
775        }
776        index += 1;
777    }
778    None
779}
780
781fn is_attr_name_start(byte: u8) -> bool {
782    byte.is_ascii_alphabetic() || byte == b'_'
783}
784
785fn is_attr_name_char(byte: u8) -> bool {
786    byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b':')
787}
788
789fn decode_xml_entities(value: &str) -> String {
790    let mut output = String::new();
791    let mut rest = value;
792    while let Some(start) = rest.find('&') {
793        output.push_str(&rest[..start]);
794        let entity_rest = &rest[start + 1..];
795        let Some(end) = entity_rest.find(';') else {
796            output.push('&');
797            rest = entity_rest;
798            continue;
799        };
800        let entity = &entity_rest[..end];
801        match decode_xml_entity(entity) {
802            Some(ch) => output.push(ch),
803            None => {
804                output.push('&');
805                output.push_str(entity);
806                output.push(';');
807            }
808        }
809        rest = &entity_rest[end + 1..];
810    }
811    output.push_str(rest);
812    output
813}
814
815fn decode_xml_entity(entity: &str) -> Option<char> {
816    match entity {
817        "amp" => Some('&'),
818        "apos" => Some('\''),
819        "gt" => Some('>'),
820        "lt" => Some('<'),
821        "quot" => Some('"'),
822        _ if entity.starts_with("#x") => u32::from_str_radix(&entity[2..], 16)
823            .ok()
824            .and_then(char::from_u32),
825        _ if entity.starts_with('#') => entity[1..].parse::<u32>().ok().and_then(char::from_u32),
826        _ => None,
827    }
828}
829
830fn font_source(font: HandwriterFont) -> &'static str {
831    match font {
832        HandwriterFont::EMSAllure => include_str!("handwriter_fonts/EMSAllure.svg"),
833        HandwriterFont::EMSDelight => include_str!("handwriter_fonts/EMSDelight.svg"),
834        HandwriterFont::EMSInvite => include_str!("handwriter_fonts/EMSInvite.svg"),
835        HandwriterFont::EMSLeague => include_str!("handwriter_fonts/EMSLeague.svg"),
836        HandwriterFont::EMSNeato => include_str!("handwriter_fonts/EMSNeato.svg"),
837        HandwriterFont::EMSOsmotron => include_str!("handwriter_fonts/EMSOsmotron.svg"),
838        HandwriterFont::EMSReadability => include_str!("handwriter_fonts/EMSReadability.svg"),
839        HandwriterFont::EMSTech => include_str!("handwriter_fonts/EMSTech.svg"),
840        HandwriterFont::HersheySans1 => include_str!("handwriter_fonts/HersheySans1.svg"),
841        HandwriterFont::HersheyScript1 => include_str!("handwriter_fonts/HersheyScript1.svg"),
842    }
843}
844
845#[cfg(test)]
846mod tests {
847    use super::*;
848
849    #[test]
850    fn parses_selected_font_glyphs() {
851        let elements = render_handwriter_text("Yeats", HandwriterFont::HersheyScript1, 1.2);
852        assert!(elements.len() > 10);
853        assert!(matches!(elements.first(), Some(PathElement::Point(_, _))));
854    }
855
856    #[test]
857    fn attr_parser_does_not_confuse_id_with_d() {
858        let tag = r#"<font id="HersheyScript1" horiz-adv-x="378">"#;
859        assert_eq!(attr_value(tag, "id").as_deref(), Some("HersheyScript1"));
860        assert_eq!(attr_value(tag, "d"), None);
861    }
862
863    #[test]
864    fn decodes_numeric_xml_entities() {
865        assert_eq!(decode_xml_entities("&#x22;&amp;&#62;"), "\"&>");
866    }
867
868    #[test]
869    fn accessibility_text_normalizes_template_newline_escape() {
870        assert_eq!(
871            normalize_text_newlines("one\\ntwo\nthree"),
872            "one\ntwo\nthree"
873        );
874    }
875
876    #[test]
877    fn accessibility_font_size_scales_with_line_count() {
878        assert_eq!(
879            accessibility_font_size("one line"),
880            Size::Pixels(Numeric::F64(104.0))
881        );
882        assert_eq!(
883            accessibility_font_size("one\ntwo"),
884            Size::Pixels(Numeric::F64(52.0))
885        );
886    }
887}