Skip to main content

sdf_text/
text_builder.rs

1//! Synchronous text layout — a port of lib3's `src/sdf-text/TextBuilder.js`.
2//!
3//! Two layout functions, sharing one result type:
4//!
5//! - [`layout_text_vector`] is the real one: `unitsPerEm` scaling, advances from
6//!   `hmtx`, kerning from GPOS, ink boxes from the outline, and
7//!   ascender/descender from OS/2 or `hhea`. Everything it needs is in
8//!   [`crate::vector_font`], so it ports across exactly and is graded
9//!   bit-for-bit (after the `f32` truncation the JS does) against
10//!   `tests/golden/layout_vector.json`.
11//! - [`layout_text`] is the canvas-metrics one. Its measuring context is an
12//!   `OffscreenCanvas`, which does not exist here — and, importantly, does not
13//!   exist in node either, where `getMeasureCtx` returns `null` and the whole
14//!   function falls into a hardcoded `0.6 em` advance with a `+0.8 / -0.2 em`
15//!   box. **That null branch is what this port implements**, and it is what
16//!   `tests/golden/layout_canvas_fallback.json` was dumped from, so the grading
17//!   is honest: the same inputs give the same numbers as the JS does in the same
18//!   environment. The browser branch is in the README's skip register — it needs
19//!   a text-shaping stack, it is not what the SDF atlas path uses, and faking it
20//!   would be worse than not having it.
21//!
22//! # Quirks that are ports, not bugs
23//!
24//! Every one of these is load-bearing for matching the golden, and four of them
25//! are called out in the plan's §5.4:
26//!
27//! - **Unknown anchor keywords resolve to 0.** `resolveAnchor` has no `else`, so
28//!   `anchorX: 'start'` and `'end'` — which is what d33 passes — fall through
29//!   every branch and return `0`, i.e. left-aligned. [`Anchor::Named`] keeps
30//!   that: any string that is not one of the six recognised keywords is a no-op
31//!   offset. The `start-anchored` case in the golden exists to pin it.
32//! - **`letter_spacing` is applied asymmetrically.** The measure pass
33//!   (`vec_measure_run`) adds it only *between* glyphs, `len - 1` times; the
34//!   pen loop adds it *after* every glyph, `len` times. So a line's measured
35//!   width is one `letter_spacing` shorter than the pen actually travels, which
36//!   shifts `text_align: center` by half a spacing and `right` by a whole one.
37//! - **Lines march in −Y.** `baseline_y -= line_advance` each line while the
38//!   boxes are Y-up, so the first line is the topmost and later lines have
39//!   negative Y. Combined with the anchor being resolved from the *block*
40//!   extent, this is why `anchor_y: 'top'` produces an all-negative-Y block.
41//! - **Kerning is applied to the pen before the glyph it belongs to**, not after
42//!   the previous one, so it tucks the current glyph toward its predecessor and
43//!   is *not* included in the glyph's own advance. Net horizontal travel is the
44//!   same; the per-glyph boxes are not.
45//! - **`line_width` is zero in the fallback `layout_text`.** The JS guards the
46//!   measure with `ctx ? … : 0`, but not the `align_offset` that consumes it, so
47//!   `text_align: center` with the default `max_width: Infinity` yields an
48//!   infinite offset and infinite glyph bounds. Reproduced, not clamped.
49//! - **`f32` is the only truncation point**, and only for `glyph_bounds`.
50//!   `block_bounds`, `visible_bounds`, `line_height`, `ascender` and `descender`
51//!   stay `f64`, which is why the golden has `1.7999999999999998` in
52//!   `blockBounds` next to `1.7999999523162842` in `glyphBounds` for the same
53//!   edge.
54
55use crate::vector_font::VectorFont;
56
57/// Canvas metrics below ~6 px are unreliable, so the JS measures at this size
58/// and scales. It survives into the fallback branch as the source of the
59/// `0.6 em` advance (`MEASURE_FONT_PX * 0.6 * scale`).
60#[doc(hidden)]
61pub const MEASURE_FONT_PX: f64 = 64.0;
62
63/// `anchorX` / `anchorY`. The JS takes `number | string`; a number is negated
64/// directly and a string is matched against the keyword list.
65#[derive(Clone, Debug, PartialEq)]
66pub enum Anchor {
67    /// `typeof anchor === 'number'` → `-anchor`.
68    Offset(f64),
69    /// Anything else. Only `left`/`center`/`right` (x) and
70    /// `top`/`middle`/`center`/`bottom` (y) do anything; every other string,
71    /// `'start'` and `'end'` included, resolves to `0`.
72    Named(String),
73}
74
75impl Anchor {
76    /// An [`Anchor::Named`] keyword.
77    pub fn named(s: &str) -> Self {
78        Anchor::Named(s.to_string())
79    }
80
81    /// `resolveAnchor(anchor, extent, axis)`. `axis_x` picks the keyword set.
82    fn resolve(&self, extent: f64, axis_x: bool) -> f64 {
83        match self {
84            Anchor::Offset(n) => -n,
85            Anchor::Named(name) => {
86                let s = name.as_str();
87                if axis_x {
88                    match s {
89                        "left" => 0.0,
90                        "center" => -extent * 0.5,
91                        "right" => -extent,
92                        _ => 0.0,
93                    }
94                } else {
95                    match s {
96                        "top" => -extent,
97                        "middle" | "center" => -extent * 0.5,
98                        "bottom" => 0.0,
99                        _ => 0.0,
100                    }
101                }
102            }
103        }
104    }
105}
106
107impl Default for Anchor {
108    fn default() -> Self {
109        Anchor::Offset(0.0)
110    }
111}
112
113/// `lineHeight: 'normal' | number | string`.
114///
115/// The JS runs `parseFloat` over whatever it is given and falls back to the
116/// natural height when the result is not finite, so a string like `"1.5"` and
117/// the number `1.5` are the same input. [`LineHeight::parse`] does that
118/// conversion, which leaves only the two outcomes the JS can actually reach.
119#[derive(Clone, Copy, Debug, PartialEq)]
120pub enum LineHeight {
121    /// `'normal'`, `null`, or anything `parseFloat` cannot read.
122    Normal,
123    /// A multiple of `font_size`.
124    Factor(f64),
125}
126
127impl LineHeight {
128    /// `parseFloat(lineHeight)` plus the `Number.isFinite` guard.
129    pub fn parse(s: &str) -> Self {
130        if s == "normal" {
131            return LineHeight::Normal;
132        }
133        match parse_float(s) {
134            Some(n) if n.is_finite() => LineHeight::Factor(n),
135            _ => LineHeight::Normal,
136        }
137    }
138
139    /// `parseLineHeight(lineHeight, fontSize)` — the canvas path's version,
140    /// where "natural" is a flat `1.2 em`.
141    fn resolve_canvas(&self, font_size: f64) -> f64 {
142        match self {
143            LineHeight::Normal => font_size * 1.2,
144            LineHeight::Factor(n) => n * font_size,
145        }
146    }
147}
148
149/// JS `parseFloat`: read a leading decimal literal, ignore the rest, `NaN` if
150/// there is nothing to read.
151fn parse_float(s: &str) -> Option<f64> {
152    let t = s.trim_start();
153    let bytes = t.as_bytes();
154    let mut end = 0;
155    let mut seen_digit = false;
156    let mut seen_dot = false;
157    let mut seen_exp = false;
158    while end < bytes.len() {
159        let c = bytes[end];
160        match c {
161            b'+' | b'-' if end == 0 => {}
162            b'+' | b'-' if seen_exp && matches!(bytes[end - 1], b'e' | b'E') => {}
163            b'0'..=b'9' => seen_digit = true,
164            b'.' if !seen_dot && !seen_exp => seen_dot = true,
165            b'e' | b'E' if seen_digit && !seen_exp => seen_exp = true,
166            _ => break,
167        }
168        end += 1;
169    }
170    if !seen_digit {
171        return None;
172    }
173    // Back off a trailing exponent marker with no digits after it.
174    let mut slice = &t[..end];
175    while !slice.is_empty()
176        && matches!(slice.as_bytes()[slice.len() - 1], b'e' | b'E' | b'+' | b'-')
177    {
178        slice = &slice[..slice.len() - 1];
179    }
180    slice.parse::<f64>().ok()
181}
182
183/// `textAlign`. The JS tests for `'center'` and `'right'` and does nothing
184/// otherwise, so every other value — `'left'`, `'justify'`, a typo — is
185/// [`TextAlign::Left`].
186#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
187#[non_exhaustive]
188pub enum TextAlign {
189    /// The default, and every unrecognised value.
190    #[default]
191    Left,
192    /// Centred lines.
193    Center,
194    /// Right-aligned lines.
195    Right,
196}
197
198/// The layout parameter block. [`Default`] is lib3's `LAYOUT_DEFAULTS`
199/// (`Text.js:8-20`) verbatim, including `max_width: Infinity`.
200#[derive(Clone, Debug, PartialEq)]
201#[non_exhaustive]
202pub struct LayoutParams {
203    /// The string to lay out.
204    pub text: String,
205    /// Font size, world units.
206    pub font_size: f64,
207    /// Canvas path only; the fallback branch never reads it.
208    pub font_family: String,
209    /// Canvas path only.
210    pub font_weight: String,
211    /// Canvas path only.
212    pub font_style: String,
213    /// Extra space added per glyph. See the module's asymmetric-spacing note.
214    pub letter_spacing: f64,
215    /// Line height.
216    pub line_height: LineHeight,
217    /// Horizontal anchor.
218    pub anchor_x: Anchor,
219    /// Vertical anchor.
220    pub anchor_y: Anchor,
221    /// Multi-line alignment.
222    pub text_align: TextAlign,
223    /// Line-wrap width, world units.
224    pub max_width: f64,
225}
226
227impl Default for LayoutParams {
228    fn default() -> Self {
229        LayoutParams {
230            text: String::new(),
231            font_size: 1.0,
232            font_family: "monospace".to_string(),
233            font_weight: "normal".to_string(),
234            font_style: "normal".to_string(),
235            letter_spacing: 0.0,
236            line_height: LineHeight::Normal,
237            anchor_x: Anchor::Offset(0.0),
238            anchor_y: Anchor::Offset(0.0),
239            text_align: TextAlign::Left,
240            max_width: f64::INFINITY,
241        }
242    }
243}
244
245/// One laid-out character and its Y-up box, before the anchor offset is folded
246/// in. The JS keeps this list alongside the `Float32Array` so consumers can see
247/// which character each quad belongs to.
248#[derive(Clone, Debug, PartialEq)]
249pub struct LaidOutGlyph {
250    /// The character this glyph renders.
251    pub ch: char,
252    /// `[min_x, min_y, max_x, max_y]`, `f64`.
253    pub bounds: [f64; 4],
254}
255
256/// `TextRenderInfo` — what `BatchedText` consumes.
257#[derive(Clone, Debug, PartialEq)]
258#[non_exhaustive]
259pub struct TextRenderInfo {
260    /// The parameters this layout was produced from.
261    pub parameters: LayoutParams,
262    /// `Float32Array(glyphCount * 4)`, anchored. The one place the JS truncates.
263    pub glyph_bounds: Vec<f32>,
264    /// One entry per laid-out glyph, in text order.
265    pub glyphs: Vec<LaidOutGlyph>,
266    /// `glyphs.len()`.
267    pub glyph_count: usize,
268    /// `[min_x, min_y, max_x, max_y]`, anchored, `f64`.
269    pub block_bounds: [f64; 4],
270    /// The JS sets this to the same four numbers as `block_bounds`.
271    pub visible_bounds: [f64; 4],
272    /// Resolved line height, world units.
273    pub line_height: f64,
274    /// Ascender, world units.
275    pub ascender: f64,
276    /// Descender, world units (negative).
277    pub descender: f64,
278}
279
280/// `emptyRenderInfo(params)` — the layout a `Text` carries while its vector font
281/// is still loading.
282pub fn empty_render_info(params: LayoutParams) -> TextRenderInfo {
283    TextRenderInfo {
284        parameters: params,
285        glyph_bounds: Vec::new(),
286        glyphs: Vec::new(),
287        glyph_count: 0,
288        block_bounds: [0.0; 4],
289        visible_bounds: [0.0; 4],
290        line_height: 0.0,
291        ascender: 0.0,
292        descender: 0.0,
293    }
294}
295
296// ── Shared line handling ───────────────────────────────────────────────────
297
298/// `text.split("\n")`, which keeps empty leading and trailing fields.
299fn split_lines(text: &str) -> Vec<String> {
300    text.split('\n').map(|s| s.to_string()).collect()
301}
302
303/// `paragraph.split(/(\s+)/)` — a *capturing* split, so the whitespace runs stay
304/// in the list as their own entries, alternating word, gap, word, gap, …
305/// starting with a word that may be empty.
306fn split_words_keeping_gaps(paragraph: &str) -> Vec<String> {
307    let mut out = Vec::new();
308    let mut cur = String::new();
309    let mut in_space = false;
310    for ch in paragraph.chars() {
311        let is_space = is_js_whitespace(ch);
312        if is_space != in_space {
313            out.push(std::mem::take(&mut cur));
314            in_space = is_space;
315        }
316        cur.push(ch);
317    }
318    out.push(cur);
319    out
320}
321
322/// The character class JS's `\s` and `trimStart` use.
323fn is_js_whitespace(ch: char) -> bool {
324    matches!(
325        ch,
326        '\t' | '\n' | '\u{0b}' | '\u{0c}' | '\r' | ' ' | '\u{a0}' | '\u{1680}' | '\u{2000}'
327            ..='\u{200a}'
328                | '\u{2028}'
329                | '\u{2029}'
330                | '\u{202f}'
331                | '\u{205f}'
332                | '\u{3000}'
333                | '\u{feff}'
334    )
335}
336
337fn trim_start_js(s: &str) -> &str {
338    s.trim_start_matches(is_js_whitespace)
339}
340
341/// The shared shape of `breakLines` / `vecBreakLines`: identical control flow,
342/// different measure function. Both drop `lineWidth` bookkeeping on the floor
343/// (the JS assigns it and never reads it), so it is not modelled.
344fn break_lines(text: &str, max_width: f64, measure: &mut dyn FnMut(&str) -> f64) -> Vec<String> {
345    if !max_width.is_finite() || max_width <= 0.0 {
346        return split_lines(text);
347    }
348
349    let mut lines: Vec<String> = Vec::new();
350    for paragraph in split_lines(text) {
351        if paragraph.is_empty() {
352            lines.push(String::new());
353            continue;
354        }
355        let mut line = String::new();
356        for word in split_words_keeping_gaps(&paragraph) {
357            let test = format!("{line}{word}");
358            let w = measure(&test);
359            if !line.is_empty() && w > max_width {
360                lines.push(std::mem::take(&mut line));
361                line = trim_start_js(&word).to_string();
362            } else {
363                line = test;
364            }
365        }
366        // `paragraph === ""` cannot be true here — the `continue` above took it
367        // — so this is just "push a non-empty remainder". Kept in the JS's form.
368        if !line.is_empty() || paragraph.is_empty() {
369            lines.push(line);
370        }
371    }
372
373    if lines.is_empty() {
374        vec![String::new()]
375    } else {
376        lines
377    }
378}
379
380/// The tail both layout functions share: anchor resolution, the `f32` copy, and
381/// the result assembly.
382fn finish(
383    params: LayoutParams,
384    glyphs: Vec<LaidOutGlyph>,
385    mut block: [f64; 4],
386    line_height: f64,
387    ascender: f64,
388    descender: f64,
389) -> TextRenderInfo {
390    if glyphs.is_empty() {
391        block = [0.0; 4];
392    }
393    let [block_min_x, block_min_y, block_max_x, block_max_y] = block;
394    let block_width = block_max_x - block_min_x;
395    let block_height = block_max_y - block_min_y;
396    let offset_x = params.anchor_x.resolve(block_width, true) - block_min_x;
397    let offset_y = params.anchor_y.resolve(block_height, false) - block_min_y;
398
399    let mut glyph_bounds = Vec::with_capacity(glyphs.len() * 4);
400    for g in &glyphs {
401        glyph_bounds.push((g.bounds[0] + offset_x) as f32);
402        glyph_bounds.push((g.bounds[1] + offset_y) as f32);
403        glyph_bounds.push((g.bounds[2] + offset_x) as f32);
404        glyph_bounds.push((g.bounds[3] + offset_y) as f32);
405    }
406
407    let anchored = [
408        block_min_x + offset_x,
409        block_min_y + offset_y,
410        block_max_x + offset_x,
411        block_max_y + offset_y,
412    ];
413
414    TextRenderInfo {
415        parameters: params,
416        glyph_bounds,
417        glyph_count: glyphs.len(),
418        glyphs,
419        block_bounds: anchored,
420        visible_bounds: anchored,
421        line_height,
422        ascender,
423        descender,
424    }
425}
426
427// ── The canvas path, in its no-canvas branch ───────────────────────────────
428
429/// `measureRunWidth(null, str, …)` — `str.length * 0.6 * scale`.
430///
431/// `length` is UTF-16 code units in JS; this counts `char`s. They differ only
432/// for astral-plane text, which the JS would also mis-handle (it would measure
433/// and lay out each surrogate half separately). Recorded in the README.
434fn measure_run_width_no_ctx(s: &str, scale: f64) -> f64 {
435    if s.is_empty() {
436        return 0.0;
437    }
438    s.chars().count() as f64 * 0.6 * scale
439}
440
441/// `layoutText(params)` in the environment where `OffscreenCanvas` is absent.
442///
443/// Every glyph gets a `0.6 em` advance and a `−0.2 em … +0.8 em` box, spaces
444/// included (the `ch !== ' '` test is never reached, because `metrics` is
445/// undefined and the `metrics && …` guard short-circuits first). `line_width`
446/// is forced to `0`, which is what makes the centred and right-aligned cases
447/// infinite at the default `max_width`.
448pub fn layout_text(params: LayoutParams) -> TextRenderInfo {
449    let font_size = params.font_size;
450    let scale = font_size / MEASURE_FONT_PX;
451    let line_advance = params.line_height.resolve_canvas(font_size);
452    let lines = break_lines(&params.text, params.max_width, &mut |s| {
453        measure_run_width_no_ctx(s, scale)
454    });
455
456    let mut glyphs: Vec<LaidOutGlyph> = Vec::new();
457    let mut block = [
458        f64::INFINITY,
459        f64::INFINITY,
460        f64::NEG_INFINITY,
461        f64::NEG_INFINITY,
462    ];
463    let mut baseline_y = 0.0f64;
464
465    for line in &lines {
466        // `ctx ? measureRunWidth(…) : 0` — the measure is skipped, the consumer
467        // of it is not.
468        let line_width = 0.0f64;
469        let align_offset = match params.text_align {
470            TextAlign::Center => (params.max_width - line_width) * 0.5,
471            TextAlign::Right => params.max_width - line_width,
472            TextAlign::Left => 0.0,
473        };
474        let mut pen_x = align_offset;
475
476        for ch in line.chars() {
477            let char_width = MEASURE_FONT_PX * 0.6 * scale;
478            let advance = char_width + params.letter_spacing;
479
480            let min_x = pen_x;
481            let max_x = pen_x + char_width;
482            let min_y = baseline_y - font_size * 0.2;
483            let max_y = baseline_y + font_size * 0.8;
484
485            glyphs.push(LaidOutGlyph {
486                ch,
487                bounds: [min_x, min_y, max_x, max_y],
488            });
489            block[0] = block[0].min(min_x);
490            block[1] = block[1].min(min_y);
491            block[2] = block[2].max(max_x);
492            block[3] = block[3].max(max_y);
493
494            pen_x += advance;
495        }
496
497        baseline_y -= line_advance;
498    }
499
500    finish(
501        params,
502        glyphs,
503        block,
504        line_advance,
505        font_size * 0.8,
506        -font_size * 0.2,
507    )
508}
509
510// ── The vector path ────────────────────────────────────────────────────────
511
512/// `vecLineAdvance` — the natural height is the font's own
513/// `ascender - descender + lineGap`, not a flat `1.2 em`.
514fn vec_line_advance(line_height: LineHeight, font: &VectorFont, font_size: f64) -> f64 {
515    let scale = font_size / font.units_per_em;
516    let natural = (font.ascender - font.descender + font.line_gap) * scale;
517    match line_height {
518        LineHeight::Normal => natural,
519        LineHeight::Factor(n) if n.is_finite() => n * font_size,
520        LineHeight::Factor(_) => natural,
521    }
522}
523
524/// `vecMeasureRun` — advance plus kerning plus spacing, with the spacing (and
525/// the kerning) added only *between* glyphs. The pen loop in
526/// [`layout_text_vector`] adds the spacing after *every* glyph instead; that
527/// asymmetry is the JS's and is preserved.
528pub(crate) fn vec_measure_run(font: &VectorFont, s: &str, letter_spacing: f64, scale: f64) -> f64 {
529    let chars: Vec<char> = s.chars().collect();
530    let mut w = 0.0;
531    for i in 0..chars.len() {
532        w += font.advance_width(chars[i]) * scale;
533        if i + 1 < chars.len() {
534            w += font.kerning(chars[i], chars[i + 1]) * scale + letter_spacing;
535        }
536    }
537    w
538}
539
540/// `layoutTextVector({ font, …params })`.
541///
542/// `font` is a separate argument here rather than a field of [`LayoutParams`],
543/// because the JS only puts it in `params` to spread it into one call — and then
544/// it lands in the returned `parameters`, which nothing reads. Returns
545/// [`empty_render_info`] when there is no font, exactly as `if (!font)` does.
546pub fn layout_text_vector(params: LayoutParams, font: Option<&VectorFont>) -> TextRenderInfo {
547    let Some(font) = font else {
548        return empty_render_info(params);
549    };
550
551    let font_size = params.font_size;
552    let scale = font_size / font.units_per_em;
553    let ascender = font.ascender * scale;
554    let descender = font.descender * scale;
555    let line_advance = vec_line_advance(params.line_height, font, font_size);
556    let letter_spacing = params.letter_spacing;
557    let lines = break_lines(&params.text, params.max_width, &mut |s| {
558        vec_measure_run(font, s, letter_spacing, scale)
559    });
560
561    let mut glyphs: Vec<LaidOutGlyph> = Vec::new();
562    let mut block = [
563        f64::INFINITY,
564        f64::INFINITY,
565        f64::NEG_INFINITY,
566        f64::NEG_INFINITY,
567    ];
568    let mut baseline_y = 0.0f64;
569
570    for line in &lines {
571        let line_width = vec_measure_run(font, line, letter_spacing, scale);
572        let align_offset = match params.text_align {
573            TextAlign::Center => (params.max_width - line_width) * 0.5,
574            TextAlign::Right => params.max_width - line_width,
575            TextAlign::Left => 0.0,
576        };
577        let mut pen_x = align_offset;
578        let chars: Vec<char> = line.chars().collect();
579
580        for i in 0..chars.len() {
581            let ch = chars[i];
582
583            // Kerning tucks this glyph toward the previous one: it moves the pen
584            // *before* the box is computed and is not part of this glyph's
585            // advance.
586            if i > 0 {
587                pen_x += font.kerning(chars[i - 1], ch) * scale;
588            }
589
590            let advance = font.advance_width(ch) * scale;
591            // A space is forced to the no-ink branch even if the font gives it a
592            // box, which Roboto does not.
593            let bbox = if ch == ' ' {
594                None
595            } else {
596                font.bounding_box(ch)
597            };
598
599            let (min_x, min_y, max_x, max_y) = match bbox {
600                Some(b) => (
601                    pen_x + b.x1 * scale,
602                    baseline_y + b.y1 * scale,
603                    pen_x + b.x2 * scale,
604                    baseline_y + b.y2 * scale,
605                ),
606                None => (
607                    pen_x,
608                    baseline_y + descender,
609                    pen_x + advance,
610                    baseline_y + ascender,
611                ),
612            };
613
614            glyphs.push(LaidOutGlyph {
615                ch,
616                bounds: [min_x, min_y, max_x, max_y],
617            });
618            block[0] = block[0].min(min_x);
619            block[1] = block[1].min(min_y);
620            block[2] = block[2].max(max_x);
621            block[3] = block[3].max(max_y);
622
623            pen_x += advance + letter_spacing;
624        }
625
626        baseline_y -= line_advance;
627    }
628
629    finish(params, glyphs, block, line_advance, ascender, descender)
630}