@weasel-js/text 1.9.4 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/runs.ts","../src/runs/textTransform.ts","../src/runs/smallCaps.ts","../src/runs/resolveRuns.ts","../src/measure/verticalAlign.ts","../src/layout/textPoseLayout.ts","../src/measure/measureText.ts","../src/measure/measureTextBounds.ts","../src/measure/lineBoxes.ts","../src/markdownText.ts"],"names":["faceMetricsOf","resolveFontVariant","resolveScreenLength","width"],"mappings":";;;;;;AAmFO,SAAS,OAAO,KAAA,EAA0C;AAC/D,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,OAAO,KAAA,CAAM,WAAW,CAAA,GAAI,KAAK,CAAC,EAAE,IAAA,EAAM,KAAA,EAAO,CAAA;AAAA,EACnD;AACA,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,KAAA,CAAM,QAAQ,CAAA,EAAA,EAAK;AACrC,IAAA,MAAM,CAAA,GAAI,MAAM,CAAC,CAAA;AACjB,IAAA,IAAI,OAAO,CAAA,EAAG,IAAA,KAAS,QAAA,EAAU;AAC/B,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,qBAAA,EAAwB,CAAC,CAAA,2BAAA,CAA6B,CAAA;AAAA,IACxE;AAAA,EACF;AACA,EAAA,OAAO,KAAA;AACT;AAGO,SAAS,gBAAgB,IAAA,EAAoC;AAClE,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,KAAA,MAAW,CAAA,IAAK,IAAA,EAAM,GAAA,IAAO,CAAA,CAAE,IAAA;AAC/B,EAAA,OAAO,GAAA;AACT;AAmCO,IAAM,oBAAA,GAAmC;AAAA,EAC9C,OAAA,EAAS;AAAA,IACP,EAAE,WAAW,GAAA,EAAK,MAAA,EAAQ,GAAG,KAAA,EAAO,CAAC,MAAA,EAA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A,CAAI,MAAM,IAAA,EAAM,GAAA,CAAI,IAAA,EAAM,SAAA,EAAW,MAAM,EAAA,EAAI,EAAA,EAAI,EAAA,EAAI,EAAA,GAAK,IAAI,KAAA,EAAM;AAAA,MACpG;AAAA,IACF,CAAC,CAAA;AACD,IAAA,KAAA,EAAM;AAAA,EACR,CAAA;AAEA,EAAA,MAAM,cAAA,GAA+B,CAAC,IAAA,EAAM,KAAA,EAAO,GAAG,CAAA,KAAM;AAC1D,IAAA,IAAA,CAAK,IAAA,EAAM,CAAA,EAAG,CAAA,EAAG,CAAC,GAAA,EAAK,EAAA,EAAI,EAAA,KAAO,IAAA,CAAK,UAAA,CAAW,GAAA,CAAI,IAAA,EAAM,EAAA,EAAI,EAAE,CAAC,CAAA;AAAA,EACrE,CAAA;AAEA,EAAA,OAAO,EAAE,UAAU,cAAA,EAAgB,KAAA,EAAO,OAAO,KAAA,EAAO,MAAA,EAAQ,OAAO,MAAA,EAAO;AAChF","file":"index.js","sourcesContent":["/**\n * Canonical inline-styling primitive for text nodes. A node's text is\n * either a plain `string` (treated as a single-run, default-styled fragment)\n * or `StyledRun[]` for rich content. `toRuns` is the funnel that normalizes\n * either form into the array shape used by the renderer.\n *\n * Every field except `text` is optional; missing fields fall back to the\n * node-level `TextStyle`. `bold`/`italic` are toggles; `fontWeight` is the\n * numeric weight `bold` is a preset over.\n */\n\nimport type { FillStyle, ScreenLength, Stroke } from '@weasel-js/paint';\nimport type { TextTransform } from './runs/textTransform';\nimport type { FontVariantCaps } from './runs/smallCaps';\n\n/** A span of text with its own styling, as authored. Fields left absent\n * inherit from the node's text style — this is the difference between a run\n * and a fully resolved one. */\nexport interface StyledRun {\n text: string;\n /** Draw at weight 700. A preset over `fontWeight`, which wins when both\n * are present. */\n bold?: boolean;\n /** Numeric weight, 100–900. Overrides the node's weight and `bold`. */\n fontWeight?: number;\n italic?: boolean;\n fontFamily?: string;\n /** World units, or `{ px }` for screen pixels — resolved against the view\n * scale `resolveRuns` is given, like `TextStyle.fontSize`. */\n fontSize?: ScreenLength;\n /** This run's ink. `null` is no fill at all, leaving the glyphs to `stroke`\n * alone; absent inherits the node's. */\n fill?: FillStyle | null;\n /** Outline over this run's glyphs. Overrides the node's own `data.stroke`;\n * absent inherits it. Only painted on the outline tier. */\n stroke?: Stroke;\n /** World units, or `{ px }` for screen pixels. */\n letterSpacing?: ScreenLength;\n underline?: boolean;\n strikethrough?: boolean;\n /** Draw a rule above this run's ascent. Additive over the node style. */\n overline?: boolean;\n /**\n * Set this run as a superscript or subscript — a raised or lowered baseline\n * and a smaller size together, which is the pair `<sup>` and `<sub>` imply.\n *\n * A preset over the two primitives below, not a third mechanism: it supplies\n * a `baselineShift` and a `fontScale`, and naming either of those directly\n * overrides that half while leaving the other alone. The numbers are the\n * face's own `OS/2` script metrics, or {@link SCRIPT_METRICS} for a face\n * that states none — `scriptMetricsFor` answers which.\n */\n script?: 'super' | 'sub';\n /**\n * Raise (positive) or lower (negative) this run off the line's shared\n * baseline, in ems of the *inherited* font size — so a run's rise does not\n * shrink along with the run when `fontScale` also applies.\n */\n baselineShift?: number;\n /**\n * Multiplier on the inherited font size. The relative counterpart to\n * `fontSize`, which pins an absolute size and wins over this when both are\n * present.\n */\n fontScale?: number;\n /**\n * CSS `text-transform` for this run's display. The run's `text` stays as\n * authored — carets, selections and edits address it — and only what is\n * drawn changes. Overrides the node's own; `'none'` turns an inherited one\n * off.\n */\n textTransform?: TextTransform;\n /**\n * `'small-caps'` draws this run's lowercase letters as capitals at a\n * smaller size — synthesized, at the face's x-height over its cap height.\n * Like `textTransform`, only what is drawn changes. Overrides the node's\n * own; `'normal'` turns an inherited one off.\n */\n fontVariantCaps?: FontVariantCaps;\n}\n\n/** Normalize the two accepted spellings of text content — a plain string or\n * an array of runs — to runs. Throws on a run with no string `text`. */\nexport function toRuns(input: string | StyledRun[]): StyledRun[] {\n if (typeof input === 'string') {\n return input.length === 0 ? [] : [{ text: input }];\n }\n for (let i = 0; i < input.length; i++) {\n const r = input[i];\n if (typeof r?.text !== 'string') {\n throw new Error(`toRuns: run at index ${i} is missing string \\`text\\``);\n }\n }\n return input;\n}\n\n/** Concatenate runs, dropping all styling. */\nexport function runsToPlainText(runs: readonly StyledRun[]): string {\n let out = '';\n for (const r of runs) out += r.text;\n return out;\n}\n\n/** A run flag an inline marker can toggle. The additive style toggles on\n * `StyledRun`; the valued fields (family, size, paint, `script`) have no\n * inline spelling and are not addressable this way. */\nexport type RunFlag = 'bold' | 'italic' | 'underline' | 'strikethrough' | 'overline';\n\n/** One inline marker: a delimiter repeated `repeat` times, and the flags it\n * turns on between its opening and closing occurrence. */\nexport interface RunMarker {\n delimiter: string;\n repeat: number;\n flags: readonly RunFlag[];\n}\n\n/**\n * The inline grammar `runsToMarkdown` writes and `markdownToRuns` reads.\n *\n * Markers sharing a delimiter are matched longest-first, which is what lets\n * `***` mean something other than `**` followed by `*`. A backslash escapes\n * any delimiter character and itself, in both directions.\n */\nexport interface RunGrammar {\n markers: readonly RunMarker[];\n}\n\n/**\n * The markdown subset the kit reads and writes: `**bold**`, `*italic*`,\n * `***both***`.\n *\n * Deliberately not the whole of markdown, and deliberately silent on\n * `underline` / `strikethrough` — the two run flags with no entry here are\n * dropped by `runsToMarkdown`, as they always have been. A grammar that wants\n * `~~struck~~` adds one marker; nothing else has to change.\n */\nexport const MARKDOWN_RUN_GRAMMAR: RunGrammar = {\n markers: [\n { delimiter: '*', repeat: 3, flags: ['bold', 'italic'] },\n { delimiter: '*', repeat: 2, flags: ['bold'] },\n { delimiter: '*', repeat: 1, flags: ['italic'] },\n ],\n};\n\n/** Delimiter characters of a grammar, plus the backslash that escapes them. */\nfunction escapees(grammar: RunGrammar): Set<string> {\n const out = new Set<string>(['\\\\']);\n for (const m of grammar.markers) out.add(m.delimiter);\n return out;\n}\n\nfunction escapeFor(text: string, chars: ReadonlySet<string>): string {\n let out = '';\n for (const ch of text) out += chars.has(ch) ? `\\\\${ch}` : ch;\n return out;\n}\n\n/** The flags a run turns on, in the grammar's own marker order so two runs\n * with the same flags always serialize identically. */\nfunction flagsOf(run: StyledRun, grammar: RunGrammar): Set<RunFlag> {\n const on = new Set<RunFlag>();\n for (const m of grammar.markers) {\n for (const f of m.flags) if (run[f]) on.add(f);\n }\n return on;\n}\n\nfunction sameFlags(a: ReadonlySet<RunFlag>, b: readonly RunFlag[]): boolean {\n return a.size === b.length && b.every((f) => a.has(f));\n}\n\n/**\n * Render runs in `grammar`, defaulting to the markdown subset. The flavor\n * written to the clipboard alongside the plain-text one.\n *\n * A run whose flags exactly match one marker takes it; otherwise the markers\n * that cover them nest. Flags no marker spells are dropped — the text still\n * round-trips, without that styling.\n */\nexport function runsToMarkdown(\n runs: readonly StyledRun[],\n grammar: RunGrammar = MARKDOWN_RUN_GRAMMAR,\n): string {\n const chars = escapees(grammar);\n let out = '';\n for (const r of runs) {\n // An empty run would write its markers back to back, which read as a toggle.\n if (r.text.length === 0) continue;\n const escaped = escapeFor(r.text, chars);\n const on = flagsOf(r, grammar);\n if (on.size === 0) { out += escaped; continue; }\n\n const exact = grammar.markers.find((m) => sameFlags(on, m.flags));\n if (exact) {\n const d = exact.delimiter.repeat(exact.repeat);\n out += `${d}${escaped}${d}`;\n continue;\n }\n // No single marker says all of it: nest the ones that each say part.\n const covering = grammar.markers.filter(\n (m) => m.flags.length === 1 && on.has(m.flags[0]),\n );\n const open = covering.map((m) => m.delimiter.repeat(m.repeat)).join('');\n const close = [...covering].reverse().map((m) => m.delimiter.repeat(m.repeat)).join('');\n out += `${open}${escaped}${close}`;\n }\n return out;\n}\n\n/**\n * Parse `input` in `grammar`, defaulting to the markdown subset, into styled\n * runs. Newlines are preserved as literal characters inside a run — they are\n * not run-boundary markers in this format.\n */\nexport function markdownToRuns(\n input: string,\n grammar: RunGrammar = MARKDOWN_RUN_GRAMMAR,\n): StyledRun[] {\n const chars = escapees(grammar);\n // Longest-first per delimiter, so `***` is tried before `**` before `*`.\n const byDelimiter = new Map<string, RunMarker[]>();\n for (const m of grammar.markers) {\n const list = byDelimiter.get(m.delimiter) ?? [];\n list.push(m);\n byDelimiter.set(m.delimiter, list);\n }\n for (const list of byDelimiter.values()) list.sort((a, b) => b.repeat - a.repeat);\n\n const runs: StyledRun[] = [];\n const active = new Set<RunFlag>();\n let buf = '';\n let i = 0;\n\n function flush(): void {\n if (buf.length === 0) return;\n const run: StyledRun = { text: buf };\n for (const f of active) run[f] = true;\n runs.push(run);\n buf = '';\n }\n\n while (i < input.length) {\n const ch = input[i];\n\n if (ch === '\\\\' && i + 1 < input.length && chars.has(input[i + 1])) {\n buf += input[i + 1];\n i += 2;\n continue;\n }\n\n const markers = byDelimiter.get(ch);\n if (markers) {\n let count = 0;\n while (i + count < input.length && input[i + count] === ch) count++;\n // The longest marker the delimiter run can pay for; a run shorter than\n // every marker is text.\n const marker = markers.find((m) => m.repeat <= count);\n if (!marker) {\n buf += ch.repeat(count);\n i += count;\n continue;\n }\n flush();\n for (const f of marker.flags) {\n if (active.has(f)) active.delete(f);\n else active.add(f);\n }\n i += marker.repeat;\n continue;\n }\n\n buf += ch;\n i++;\n }\n\n flush();\n return runs;\n}\n","/**\n * CSS `text-transform` over styled runs: `uppercase`, `lowercase` and\n * `capitalize`, with the source offsets each transformed character came from.\n *\n * Case mapping is not length-preserving — `'ß'.toUpperCase()` is `'SS'` — and\n * every caret, selection and hit-test in the kit addresses the *source* text.\n * So a transform that changes a code point's length reports a\n * {@link RunSourceMap} alongside the text, and layout reads each cell's source\n * span off it instead of counting the characters it drew.\n */\n\n/** The CSS `text-transform` keywords the run model carries. `none` is an\n * explicit override: a run can turn off a transform it would inherit. */\nexport type TextTransform = 'none' | 'uppercase' | 'lowercase' | 'capitalize';\n\n/**\n * Where each UTF-16 unit of a transformed run's text came from in its source,\n * as run-relative offsets. `starts[i]` / `ends[i]` bound the source code point\n * that produced output unit `i`, so the two units `ß` uppercases to share one\n * span. `length` is the source run's own length.\n */\nexport interface RunSourceMap {\n length: number;\n starts: readonly number[];\n ends: readonly number[];\n}\n\n/** A run's text after its transform. `srcMap` is present only when some code\n * point changed length — otherwise output offsets are source offsets. */\nexport interface TransformedRunText {\n text: string;\n srcMap?: RunSourceMap;\n}\n\n/** Title-case mappings that differ from the uppercase one (UnicodeData and\n * SpecialCasing). Everything absent titlecases as it uppercases. */\nconst TITLE: ReadonlyMap<number, string> = new Map<number, string>([\n [0x00df, 'Ss'],\n [0x01c4, 'Dž'], [0x01c5, 'Dž'], [0x01c6, 'Dž'],\n [0x01c7, 'Lj'], [0x01c8, 'Lj'], [0x01c9, 'Lj'],\n [0x01ca, 'Nj'], [0x01cb, 'Nj'], [0x01cc, 'Nj'],\n [0x01f1, 'Dz'], [0x01f2, 'Dz'], [0x01f3, 'Dz'],\n [0x0587, 'Եւ'],\n [0xfb00, 'Ff'], [0xfb01, 'Fi'], [0xfb02, 'Fl'], [0xfb03, 'Ffi'], [0xfb04, 'Ffl'],\n [0xfb05, 'St'], [0xfb06, 'St'],\n [0xfb13, 'Մն'], [0xfb14, 'Մե'], [0xfb15, 'Մի'],\n [0xfb16, 'Վն'], [0xfb17, 'Մխ'],\n [0x1fb3, 'ᾼ'], [0x1fbc, 'ᾼ'],\n [0x1fc3, 'ῌ'], [0x1fcc, 'ῌ'],\n [0x1ff3, 'ῼ'], [0x1ffc, 'ῼ'],\n [0x1fb2, 'Ὰͅ'], [0x1fb4, 'Άͅ'], [0x1fb7, 'ᾼ͂'],\n [0x1fc2, 'Ὴͅ'], [0x1fc4, 'Ήͅ'], [0x1fc7, 'ῌ͂'],\n [0x1ff2, 'Ὼͅ'], [0x1ff4, 'Ώͅ'], [0x1ff7, 'ῼ͂'],\n]);\n\nfunction titlecase(ch: string): string {\n const cp = ch.codePointAt(0)!;\n // Greek with ypogegrammeni: the titlecase form keeps the iota subscript,\n // where uppercase spells it out as a capital iota.\n if (cp >= 0x1f80 && cp <= 0x1faf) return String.fromCodePoint(cp | 0x8);\n return TITLE.get(cp) ?? ch.toUpperCase();\n}\n\nconst WORD_FALLBACK = /[\\p{L}\\p{N}][\\p{L}\\p{N}\\p{M}\\p{Pc}'’]*/gu;\n\n/** Source offsets at which a word begins, by the same UAX #29 word boundaries\n * browsers use for `capitalize`. */\nfunction wordStarts(text: string): Set<number> {\n const out = new Set<number>();\n if (typeof Intl !== 'undefined' && 'Segmenter' in Intl) {\n const seg = new Intl.Segmenter(undefined, { granularity: 'word' });\n for (const s of seg.segment(text)) if (s.isWordLike) out.add(s.index);\n return out;\n }\n for (const m of text.matchAll(WORD_FALLBACK)) out.add(m.index!);\n return out;\n}\n\n/** Whether mapping `full` per code point, run by run, produces exactly the\n * units `whole` does — true unless a mapping spans a run boundary. */\nfunction alignsPerCodePoint(\n texts: readonly string[], whole: string, map: (ch: string) => string,\n): boolean {\n let n = 0;\n for (const t of texts) for (const ch of t) n += map(ch).length;\n return n === whole.length;\n}\n\nconst upper = (ch: string): string => ch.toUpperCase();\nconst lower = (ch: string): string => ch.toLowerCase();\n\n/**\n * Apply each run's transform to its text. `texts[i]` is transformed by\n * `transforms[i]`; the runs are read as one paragraph, so final sigma and\n * `capitalize`'s word starts see across run boundaries — a word split by\n * styling still gets one capital.\n *\n * Mappings are the locale-independent ones JavaScript's `toUpperCase` /\n * `toLowerCase` implement, which include `ß` → `SS` and final sigma.\n * `capitalize` titlecases the first code point of each word when it has a\n * case to change, and leaves every other character as it was.\n */\nexport function transformRunTexts(\n texts: readonly string[],\n transforms: readonly TextTransform[],\n): TransformedRunText[] {\n if (transforms.every((t) => t === 'none')) return texts.map((text) => ({ text }));\n\n const full = texts.join('');\n // Lowercasing is contextual (final sigma), so the per-code-point pieces are\n // read out of the whole paragraph's mapping wherever the two align.\n const wholeUpper = transforms.includes('uppercase') ? full.toUpperCase() : '';\n const wholeLower = transforms.includes('lowercase') ? full.toLowerCase() : '';\n const upperAligned = wholeUpper !== '' && alignsPerCodePoint(texts, wholeUpper, upper);\n const lowerAligned = wholeLower !== '' && alignsPerCodePoint(texts, wholeLower, lower);\n const starts = transforms.includes('capitalize') ? wordStarts(full) : null;\n\n const out: TransformedRunText[] = [];\n let base = 0;\n let upOff = 0;\n let lowOff = 0;\n for (let i = 0; i < texts.length; i++) {\n const source = texts[i];\n const t = transforms[i] ?? 'none';\n let text = '';\n const srcStarts: number[] = [];\n const srcEnds: number[] = [];\n let resized = false;\n let local = 0;\n for (const ch of source) {\n const up = upper(ch);\n const lo = lower(ch);\n let piece = ch;\n if (t === 'uppercase') {\n piece = upperAligned ? wholeUpper.slice(upOff, upOff + up.length) : up;\n } else if (t === 'lowercase') {\n piece = lowerAligned ? wholeLower.slice(lowOff, lowOff + lo.length) : lo;\n } else if (t === 'capitalize' && starts!.has(base + local) && up !== ch) {\n piece = titlecase(ch);\n }\n upOff += up.length;\n lowOff += lo.length;\n if (piece.length !== ch.length) resized = true;\n text += piece;\n for (let k = 0; k < piece.length; k++) {\n srcStarts.push(local);\n srcEnds.push(local + ch.length);\n }\n local += ch.length;\n }\n out.push(resized\n ? { text, srcMap: { length: source.length, starts: srcStarts, ends: srcEnds } }\n : { text });\n base += source.length;\n }\n return out;\n}\n","/**\n * Synthetic small caps: lowercase drawn as capitals at a smaller size, the\n * way a browser synthesizes `font-variant: small-caps` for a face with no\n * `smcp` feature. It is the one run style that sizes characters within a run\n * differently, so it reports a per-unit size map beside the text.\n *\n * It reads the text *after* `textTransform`, as CSS does: `uppercase` leaves\n * nothing to shrink, and `lowercase` shrinks everything.\n */\n\nimport { faceMetricsOf, resolveFontVariant, type FaceMetrics, type FontStyle } from '@weasel-js/font';\nimport type { RunSourceMap } from './textTransform';\n\n/** The CSS `font-variant-caps` keywords the run model carries. `normal` is an\n * explicit override: a run can turn off small caps it would inherit. */\nexport type FontVariantCaps = 'normal' | 'small-caps';\n\n/**\n * The small-caps size, as a fraction of the run's, for a face that states no\n * x-height and cap height. 0.7 is the factor Chromium and WebKit synthesize\n * with.\n */\nexport const SMALL_CAPS_SCALE = 0.7;\n\n/** The small-caps size for a face: its x-height over its cap height, so a\n * small capital stands as tall as its lowercase letters do, or\n * {@link SMALL_CAPS_SCALE} where the face lacks either. */\nexport function smallCapsScale(face?: FaceMetrics): number {\n const x = face?.xHeight;\n const cap = face?.capHeight;\n if (x === undefined || cap === undefined || x >= cap) return SMALL_CAPS_SCALE;\n return x / cap;\n}\n\n/** The small-caps scale a run set in `(family, weight, style)` gets —\n * resolved through the font registry exactly as layout resolves the run. */\nexport function smallCapsScaleFor(family: string, weight: number, style: FontStyle): number {\n return smallCapsScale(faceMetricsOf(resolveFontVariant(family, weight, style)));\n}\n\n/** Whether small caps draws `ch` as a smaller capital: whether it has a\n * capital other than itself. */\nexport function isSmallCapsLetter(ch: string): boolean {\n return ch.toUpperCase() !== ch;\n}\n\n/** A run's drawn text under small caps. `small[i]` says whether UTF-16 unit\n * `i` of `text` draws at the small size; absent when none does. */\nexport interface SmallCapsText {\n text: string;\n srcMap?: RunSourceMap;\n small?: readonly boolean[];\n}\n\n/**\n * Apply small caps to a run's drawn text. `srcMap` is the map `textTransform`\n * already produced for it, if any; the result's map composes the two, so\n * each drawn unit still names the source character it came from.\n */\nexport function smallCapsText(text: string, srcMap?: RunSourceMap): SmallCapsText {\n let out = '';\n const small: boolean[] = [];\n const starts: number[] = [];\n const ends: number[] = [];\n let resized = false;\n let anySmall = false;\n let at = 0;\n for (const ch of text) {\n const shrink = isSmallCapsLetter(ch);\n const piece = shrink ? ch.toUpperCase() : ch;\n if (piece.length !== ch.length) resized = true;\n anySmall ||= shrink;\n const start = srcMap ? srcMap.starts[at] : at;\n const end = srcMap ? srcMap.ends[at] : at + ch.length;\n for (let k = 0; k < piece.length; k++) {\n small.push(shrink);\n starts.push(start);\n ends.push(end);\n }\n out += piece;\n at += ch.length;\n }\n if (!anySmall) return srcMap ? { text, srcMap } : { text };\n const map = resized\n ? { length: srcMap?.length ?? text.length, starts, ends }\n : srcMap;\n return { text: out, ...(map ? { srcMap: map } : {}), small };\n}\n","/**\n * Apply node-level `ResolvedTextStyle` defaults to each `StyledRun`,\n * producing a fully-resolved run with every styling field set. Downstream\n * layout and draw never re-resolve defaults — `ResolvedRun` is the\n * canonical shape the renderer consumes.\n *\n * `bold`/`italic` toggles on a run are folded into `fontWeight`/`fontStyle`:\n * `bold: true` → fontWeight 700, `italic: true` → fontStyle 'italic'. A run's\n * own numeric `fontWeight` is the primitive `bold` is a preset over, so it\n * wins over both the flag and the node weight.\n * Explicit `fontFamily` / `fontSize` / `fill` / `letterSpacing` on the run\n * override the node-level value (`letterSpacing: 0` on a run is an override,\n * not an absence — it zeroes inherited tracking).\n *\n * `underline` / `strikethrough` / `overline` are *additive*, like\n * `bold`/`italic`: a run can turn a decoration on but never off, so they\n * resolve as `run.x || style.x` and not `run.x ?? style.x`. See the header of\n * `runs/rangeStyle.ts` for why the model collapses the tri-state.\n *\n * `script` is folded the same way the toggles are, into the two primitives it\n * is a preset over: `baselineShift` and `fontScale`. Both come out as one\n * world-unit `baselineShift` and a final `fontSize`, so layout never learns\n * that superscripts exist — it places a run against a baseline and an offset.\n *\n * `textTransform` is applied here too, so `text` is what gets drawn. When a\n * transform changes a length, `srcMap` says which source characters each\n * drawn one came from; see `textTransform.ts`.\n *\n * `fontVariantCaps: 'small-caps'` is applied after it, over the transformed\n * text: lowercase becomes capitals, and `sizeMap` gives those their smaller\n * size. See `smallCaps.ts`.\n */\n\nimport type { FillStyle, Stroke } from '@weasel-js/paint';\nimport { resolveScreenLength } from '@weasel-js/paint';\nimport { faceMetricsOf, resolveFontVariant, type FaceMetrics, type FontStyle } from '@weasel-js/font';\nimport type { StyledRun } from '../runs';\nimport type { ResolvedTextStyle } from '../textStyle';\nimport { transformRunTexts, type RunSourceMap } from './textTransform';\nimport { smallCapsScaleFor, smallCapsText } from './smallCaps';\n\n/** A run with every style resolved against the node's text style — no\n * optional inheritance left. This is what layout and painting consume. */\nexport interface ResolvedRun {\n /** The text as drawn — after `textTransform`, so not necessarily the\n * run's source text. */\n text: string;\n /** Present when `text` differs in length from the source it was\n * transformed from: where each of its UTF-16 units came from. Absent\n * means `text`'s offsets are the source's. */\n srcMap?: RunSourceMap;\n fontFamily: string;\n /** The run's size — what its line and its rules are set at, and what\n * every glyph is drawn at unless `sizeMap` says otherwise. */\n fontSize: number;\n /** Present when not every glyph is drawn at `fontSize`: the size each\n * UTF-16 unit of `text` is drawn at. Small caps is what produces one. */\n sizeMap?: readonly number[];\n fontWeight: number;\n fontStyle: 'normal' | 'italic';\n /** `null` is an explicit no-fill: the glyphs are painted by `stroke` alone,\n * which only the outline tier can do. Nothing is emitted for a run with\n * neither. */\n fill: FillStyle | null;\n /** Outline over this run's glyphs, or absent for none. Painted only on the\n * outline tier — a distance field has no geometry to stroke. */\n stroke?: Stroke;\n /** Extra advance added after each glyph of this run, in world units. */\n letterSpacing: number;\n /** Draw a rule below this run's baseline. Additive over the node style. */\n underline: boolean;\n /** Draw a rule through this run's x-height. Additive over the node style. */\n strikethrough: boolean;\n /** Draw a rule above this run's ascent. Additive over the node style. */\n overline: boolean;\n /**\n * How far this run sits off the line's shared baseline, in world units;\n * positive raises. 0 for ordinary text.\n *\n * Already multiplied out against the inherited font size, and already\n * carrying whatever `script` asked for — layout adds it to a baseline and\n * asks nothing about where it came from.\n */\n baselineShift: number;\n /**\n * The size this run holds its line open at, when a relative size shrank it\n * below the size it inherited — so a superscript alone on its line keeps the\n * line's height and baseline instead of collapsing them. Absent means\n * `fontSize`.\n */\n strutSize?: number;\n}\n\n/** What one script preset expands to. */\nexport type ScriptPreset = Readonly<{ size: number; shift: number }>;\n\n/**\n * What `script: 'super'` and `script: 'sub'` expand to for a face that states\n * no script metrics of its own, as fractions of the inherited font size:\n * `size` scales it, `shift` raises (positive) or lowers (negative) the\n * baseline.\n *\n * These are Adobe's defaults — InDesign and Illustrator ship 58.3% size and\n * 33.3% position for both. A face that carries `OS/2` script metrics uses\n * those instead; {@link scriptMetricsFor} is what a run actually gets.\n */\nexport const SCRIPT_METRICS: Readonly<Record<'super' | 'sub', ScriptPreset>> = Object.freeze({\n super: Object.freeze({ size: 0.583, shift: 0.333 }),\n sub: Object.freeze({ size: 0.583, shift: -0.333 }),\n});\n\nconst resolvedScripts = new WeakMap<FaceMetrics, Readonly<Record<'super' | 'sub', ScriptPreset>>>();\n\n/** The script presets for a face: its own `OS/2` values where it states\n * them, {@link SCRIPT_METRICS} per half where it does not. */\nexport function scriptMetrics(face?: FaceMetrics): Readonly<Record<'super' | 'sub', ScriptPreset>> {\n if (!face || (!face.superscript && !face.subscript)) return SCRIPT_METRICS;\n let out = resolvedScripts.get(face);\n if (!out) {\n out = Object.freeze({\n super: face.superscript ?? SCRIPT_METRICS.super,\n sub: face.subscript ?? SCRIPT_METRICS.sub,\n });\n resolvedScripts.set(face, out);\n }\n return out;\n}\n\n/**\n * The script presets a run set in `(family, weight, style)` gets — resolved\n * through the font registry exactly as layout resolves the run, so a\n * character panel, an SVG export and the DOM edit overlay read the numbers\n * the canvas draws with. Override either half per run with `baselineShift` /\n * `fontScale`.\n */\nexport function scriptMetricsFor(\n family: string,\n weight: number,\n style: FontStyle,\n): Readonly<Record<'super' | 'sub', ScriptPreset>> {\n return scriptMetrics(faceMetricsOf(resolveFontVariant(family, weight, style)));\n}\n\n/** A `TextStyle.fontWeight` as a number: the CSS keywords `bold` and\n * `normal` read as 700 and 400, anything unparseable as 400. */\nexport function numericWeight(w: number | string): number {\n if (typeof w === 'number') return w;\n if (w === 'bold' || w === 'bolder') return 700;\n if (w === 'normal') return 400;\n const parsed = Number(w);\n return Number.isFinite(parsed) ? parsed : 400;\n}\n\n/** Whether a weight reads as bold — 600 and up, the same line the font\n * registry draws between its regular and bold buckets. */\nexport function isBoldWeight(w: number | string): boolean {\n return numericWeight(w) >= 600;\n}\n\n/** The face a run is set in — its family, weight and style, each falling\n * back to the node's. Reads no font registry, so asking loads nothing. */\nexport function resolveRunFace(\n run: StyledRun,\n style: Pick<ResolvedTextStyle, 'fontFamily' | 'fontWeight' | 'fontStyle'>,\n): { fontFamily: string; fontWeight: number; fontStyle: FontStyle } {\n return {\n fontFamily: run.fontFamily ?? style.fontFamily,\n fontWeight: run.fontWeight ?? (run.bold ? 700 : numericWeight(style.fontWeight)),\n fontStyle: run.italic ? 'italic' : style.fontStyle,\n };\n}\n\n/** Resolve each run's styling against the node's text style, filling in\n * everything the run left inherited. `viewScale` resolves a run's own\n * `{ px }` size or spacing; the inherited ones arrived already resolved on\n * `style`. */\nexport function resolveRuns(\n runs: readonly StyledRun[],\n style: ResolvedTextStyle,\n viewScale = 1,\n): ResolvedRun[] {\n const out: ResolvedRun[] = [];\n const shown = transformRunTexts(\n runs.map((r) => r.text),\n runs.map((r) => r.textTransform ?? style.textTransform),\n );\n for (let i = 0; i < runs.length; i++) {\n const run = runs[i];\n let { text, srcMap } = shown[i];\n const scriptKey = run.script ?? style.script;\n const { fontFamily, fontWeight, fontStyle } = resolveRunFace(run, style);\n const script = scriptKey ? scriptMetricsFor(fontFamily, fontWeight, fontStyle)[scriptKey] : undefined;\n // Against the inherited size, not the run's own: a superscript that also\n // shrank its rise would climb less the smaller it got.\n const shiftEm = run.baselineShift ?? script?.shift ?? 0;\n const scale = run.fontScale ?? script?.size ?? 1;\n const relative = run.fontSize === undefined && scale !== 1;\n // An absolute size wins over a relative one; naming both is a consumer\n // saying \"this size exactly\", which a multiplier cannot improve on.\n const fontSize = run.fontSize !== undefined\n ? resolveScreenLength(run.fontSize, viewScale)\n : style.fontSize * scale;\n let sizeMap: number[] | undefined;\n if ((run.fontVariantCaps ?? style.fontVariantCaps) === 'small-caps') {\n const caps = smallCapsText(text, srcMap);\n text = caps.text;\n srcMap = caps.srcMap;\n if (caps.small) {\n const small = fontSize * smallCapsScaleFor(fontFamily, fontWeight, fontStyle);\n sizeMap = caps.small.map((s) => (s ? small : fontSize));\n }\n }\n out.push({\n text,\n ...(srcMap ? { srcMap } : {}),\n fontFamily,\n fontSize,\n ...(sizeMap ? { sizeMap } : {}),\n fontWeight,\n fontStyle,\n fill: run.fill !== undefined ? run.fill : style.fill,\n // Unlike the decorations below, a run's stroke *replaces* the node's\n // rather than adding to it — there is only one outline to paint.\n ...((run.stroke ?? style.stroke) !== undefined\n ? { stroke: run.stroke ?? style.stroke }\n : {}),\n letterSpacing: run.letterSpacing !== undefined\n ? resolveScreenLength(run.letterSpacing, viewScale)\n : style.letterSpacing,\n // `||`, not `??`: run-level decorations are additive over the node style.\n underline: run.underline || style.underline,\n strikethrough: run.strikethrough || style.strikethrough,\n overline: run.overline || style.overline,\n baselineShift: shiftEm * style.fontSize,\n ...(relative ? { strutSize: style.fontSize } : {}),\n });\n }\n return out;\n}\n","/**\n * Box vertical alignment for text draw commands. Given the command's box\n * `height` and the laid-out text block's height, returns the Y offset to\n * apply to every quad. `'top'` (or an undefined `align`, or a missing box\n * `height`) is the legacy behavior: offset 0.\n */\nexport type TextVerticalAlign = 'top' | 'center' | 'bottom';\n\n/** How far to shift laid-out text down inside a box of `boxHeight` to satisfy\n * a vertical alignment. Zero when the box height is unknown or alignment is\n * top. */\nexport function verticalAlignOffset(\n align: TextVerticalAlign | undefined,\n boxHeight: number | undefined,\n textHeight: number,\n): number {\n if (align === undefined || align === 'top' || boxHeight === undefined) return 0;\n const slack = boxHeight - textHeight;\n return align === 'center' ? slack / 2 : slack;\n}\n","/**\n * How a text pose lays out — the one decision every consumer of a text node\n * reads: the painters (`kit:text`, `createTextLayer`), picking\n * (`textLineBoxes`), the caret (`caretIndexAt`), fitting (`fitTextPose`) and\n * the DOM edit overlay.\n *\n * The pose width is always the box `align` resolves within. It is the wrap\n * width only when the style declares `wrap`; otherwise a line runs as long as\n * its text, whichever of them is asking.\n */\nimport type { LaidOutRuns, LayoutRunsOpts } from './layoutRuns';\nimport { cachedLayoutRuns } from './layoutCache';\nimport { resolveTextStyle, type ResolvedTextStyle } from '../textStyle';\nimport { resolveRuns, type ResolvedRun } from '../runs/resolveRuns';\nimport { toRuns } from '../runs';\nimport { verticalAlignOffset } from '../measure/verticalAlign';\nimport type { TextPose } from '../pose';\n\n/** What {@link layoutTextPose} hands `cachedLayoutRuns`. */\nexport interface TextPoseLayoutInput {\n style: ResolvedTextStyle;\n runs: ResolvedRun[];\n opts: LayoutRunsOpts & { justify: boolean };\n}\n\n/**\n * The resolved runs and layout options for `pose`. A text draw command built\n * from these lays out, in the renderer, into exactly the lines\n * {@link layoutTextPose} reports.\n *\n * `scale` is the view scale a `{ px }` `fontSize` or `letterSpacing` resolves\n * against. Everything past this point is world units, so a caller that\n * measures, hit-tests or paints one pose has to pass the same scale to each\n * or they disagree.\n */\nexport function textPoseLayoutInput(pose: TextPose, scale = 1): TextPoseLayoutInput {\n const style = resolveTextStyle(pose.style, { fill: pose.fill, stroke: pose.stroke }, scale);\n // Empty runs are not a styling, so they fall back to the plain string\n // rather than lay out nothing.\n const source = pose.runs && pose.runs.length > 0 ? pose.runs : pose.text;\n return {\n style,\n runs: resolveRuns(toRuns(source), style, scale),\n opts: {\n maxWidth: style.wrap ? pose.width : Infinity,\n alignWidth: pose.width,\n lineHeight: style.lineHeight,\n align: style.align,\n direction: style.direction,\n tabSize: style.tabSize,\n justify: style.align === 'justify',\n },\n };\n}\n\n/** A text pose laid out. */\nexport interface TextPoseLayout {\n /** Origin-relative, shared with the layout cache — treat as immutable. */\n laid: LaidOutRuns;\n /** World position of the layout's origin: `pose.x`, and `pose.y` shifted by\n * `verticalAlign` within the pose height. */\n x: number;\n y: number;\n}\n\n/** The lines `pose` lays out into, and where they sit in world space. */\nexport function layoutTextPose(pose: TextPose, scale = 1): TextPoseLayout {\n const { runs, opts } = textPoseLayoutInput(pose, scale);\n const laid = cachedLayoutRuns(runs, opts);\n return {\n laid,\n x: pose.x,\n y: pose.y + verticalAlignOffset(pose.verticalAlign, pose.height, laid.bounds.height),\n };\n}\n","/**\n * Wrap-aware text measurement for a 2D context. Lines end where `layoutRuns`\n * ends them — at UAX #14 break opportunities when a word would overflow\n * `maxWidth`, and at every hard break — through the same `wrapLines`, with\n * widths from `ctx.measureText` plus tracking. A word wider than `maxWidth`\n * is emitted on its own line unbroken (caller can decide to clip).\n *\n * Returns the laid-out lines, the total block height in world units\n * (`lines.length * fontSize * lineHeight`), and per-line `lineStarts` —\n * the UTF-16 offset of each line's first character in `text`, which\n * `caretIndexAt` uses to map a clicked (x, y) back to a source offset.\n * Trailing spaces and tabs hang and are not included in `lines[i]`; neither is the\n * hard break that closed it.\n *\n * The caller owns the `ctx.font` setup — pass a context whose `font`\n * already matches `style` (use `fontString(style)`).\n */\n\nimport type { ResolvedTextStyle } from '../textStyle';\nimport { graphemeCount } from './graphemes';\nimport { hangs, wrapLines } from '../layout/lineBreak/wrapLines';\n\n/**\n * Advance width of `text` in world units, tracking included.\n *\n * `letter-spacing` is not part of the CSS `font` shorthand, so a context\n * whose `font` was set from `fontString(style)` measures glyphs only. The\n * GL path (`layoutRuns`) adds `letterSpacing` after every grapheme cluster\n * including the last, matching CSS, so this does too — and every 2D-side\n * width has to go through here or the two paths disagree about where a line\n * breaks.\n */\nexport function measuredWidth(\n ctx: CanvasRenderingContext2D,\n text: string,\n style: ResolvedTextStyle,\n): number {\n return ctx.measureText(text).width\n + (style.letterSpacing === 0 ? 0 : graphemeCount(text) * style.letterSpacing);\n}\n\n/** Result of `measureText`: wrapped lines, per-line source offsets, and total block height. */\nexport interface MeasuredText {\n lines: string[];\n lineStarts: number[];\n height: number;\n}\n\n/**\n * Wrap `text` against `maxWidth` at the break opportunities `layoutRuns`\n * wraps at, measuring with `ctx`.\n */\nexport function measureText(\n ctx: CanvasRenderingContext2D,\n text: string,\n maxWidth: number,\n style: ResolvedTextStyle,\n): MeasuredText {\n const cps: number[] = [];\n /** UTF-16 offset of each code point, then `text.length`. */\n const at: number[] = [];\n let u = 0;\n for (const ch of text) {\n cps.push(ch.codePointAt(0)!);\n at.push(u);\n u += ch.length;\n }\n at.push(u);\n\n const wrapped = wrapLines(cps, maxWidth, (start, end) => measuredWidth(ctx, text.slice(at[start], at[end]), style));\n const lines = wrapped.map((l) => {\n let end = l.end;\n while (end > l.start && hangs(cps[end - 1])) end--;\n return text.slice(at[l.start], at[end]);\n });\n const lineStarts = wrapped.map((l) => at[l.start]);\n const height = lines.length * style.fontSize * style.lineHeight;\n return { lines, lineStarts, height };\n}\n","import type { TextStyle } from '../textStyle';\nimport { resolveTextStyle } from '../textStyle';\nimport { resolveRuns } from '../runs/resolveRuns';\nimport { cachedLayoutRuns } from '../layout/layoutCache';\n\n/** Options for `measureTextBounds`. */\nexport interface MeasureTextBoundsOpts {\n /** Wrap width; words exceeding it start a new line. Default `Infinity` (no wrap). */\n maxWidth?: number;\n /** Overrides `style`'s `lineHeight` multiplier for this measurement. */\n lineHeight?: number;\n /** View scale any `{ px }` size in `style` resolves against. Default 1,\n * which measures a `{ px }` size as that many world units. */\n scale?: number;\n}\n\n/**\n * Measure how the GL/MSDF renderer will lay out a single plain-text string,\n * using the registered font atlas metrics. Mirrors `textCommand` exactly\n * (`resolveTextStyle` → `resolveRuns` → `cachedLayoutRuns`), so the returned\n * bounds match what actually gets drawn — use it to size backgrounds/pills, place\n * labels, or test overlap without guessing widths.\n *\n * Pass `opts.maxWidth` to measure word-wrapped height (e.g. for a fixed-width\n * text box); omitting it measures the unwrapped single-line width. `opts.lineHeight`\n * overrides the style's multiplier without changing `style` itself.\n *\n * Returns `{ width, height }` in the same units as `style.fontSize`. The font\n * must already be registered via `registerFont`; an unregistered family falls\n * back to the atlas fallback glyph (and warns), so register fonts at app boot\n * before measuring.\n */\nexport function measureTextBounds(\n text: string,\n style?: TextStyle,\n opts?: MeasureTextBoundsOpts,\n): { width: number; height: number } {\n const resolved = resolveTextStyle(style, undefined, opts?.scale);\n const runs = resolveRuns([{ text }], resolved, opts?.scale);\n const { bounds } = cachedLayoutRuns(runs, {\n maxWidth: opts?.maxWidth ?? Infinity,\n lineHeight: opts?.lineHeight ?? resolved.lineHeight,\n align: resolved.align,\n direction: resolved.direction,\n tabSize: resolved.tabSize,\n });\n // Copied: the layout behind it is shared, and handing a caller a mutable\n // reference into a cache entry is how one measurement corrupts the next.\n return { width: bounds.width, height: bounds.height };\n}\n","/**\n * Where a text node's lines actually sit inside its pose box.\n *\n * A text pose is a layout box, not a bounding box: `\"Away\"` in a 309-unit-wide\n * box leaves most of the box empty, and anything that treats the pose as the\n * node's extent — picking, lasso, clipping, SVG export — claims that empty\n * space. `textLineBoxes` returns the per-line rectangles instead.\n *\n * The numbers come from `layoutTextPose`, the layout every painter of a text\n * pose draws, so the boxes cannot drift from what is painted — they wrap only\n * where the style declares `wrap`, and honor `align` and `verticalAlign`.\n *\n * These are line boxes, not ink boxes: each is `fontSize * lineHeight` tall\n * from the pen's line top. Ink can escape vertically at a `lineHeight` low\n * enough — see the `bounds` note at the end of `layoutRuns` — which is the\n * right trade for hit-testing, where a box that hugged the ink would make\n * an `x` harder to click than an `X`.\n */\n\nimport type { Rect } from '@weasel-js/geom';\nimport { layoutTextPose } from '../layout/textPoseLayout';\nimport type { TextPose } from '../pose';\n\n/** Options for {@link textLineBoxes}. */\nexport interface TextLineBoxesOpts {\n /** Grow every box by this much on all four sides (world units). Default 0.\n * Picking wants a little slack so a single hairline row of text is still\n * grabbable; clipping and export want none. */\n padding?: number;\n /** Keep boxes for blank lines (zero width). Default `false` — a blank line\n * covers no area, so for hit-testing and silhouettes it is noise. Pass\n * `true` when the indices have to line up with the laid-out lines. */\n includeEmpty?: boolean;\n}\n\n/** Per-line rectangles for a text pose, in world units, in layout order. */\nexport function textLineBoxes(pose: TextPose, opts: TextLineBoxesOpts = {}): Rect[] {\n const padding = opts.padding ?? 0;\n const { laid, x: dx, y: dy } = layoutTextPose(pose);\n\n const out: Rect[] = [];\n for (const line of laid.lines) {\n if (!opts.includeEmpty && line.x1 <= line.x0) continue;\n out.push({\n x: line.x0 + dx - padding,\n y: line.y0 + dy - padding,\n width: line.x1 - line.x0 + padding * 2,\n height: line.y1 - line.y0 + padding * 2,\n });\n }\n return out;\n}\n","import { resolveScreenLength } from '@weasel-js/paint';\nimport { markdownToRuns, type StyledRun } from './runs';\nimport { cssFamilyName, faceMetricsFor, type FaceMetrics } from '@weasel-js/font';\nimport { numericWeight, scriptMetrics } from './runs/resolveRuns';\nimport { DECORATION_KINDS, decorationRule, type DecorationKind } from './layout/decorationMetrics';\nimport { transformRunTexts } from './runs/textTransform';\nimport { smallCapsScale, smallCapsText } from './runs/smallCaps';\nimport { hangs, wrapLines } from './layout/lineBreak/wrapLines';\n\nexport type { StyledRun };\n\n/** Width-measurement strategy for `layoutMarkdown`; canvas-backed default supplied by `createMarkdownRenderer`. */\nexport type MeasureFn = (text: string, fontSize: number, bold: boolean, italic: boolean) => number;\n\n/** The face a run's rules and script presets come from, for `layoutMarkdown`.\n * `createMarkdownRenderer` supplies one that looks the family up in the font\n * registry, so a registered face places them as it does on the GL tier. */\nexport type FaceMetricsFn = (bold: boolean, italic: boolean) => FaceMetrics | undefined;\n\n/** A `StyledRun` with its resolved size and its position relative to the\n * start of its line: `x` along the line, `y` off its baseline. */\nexport interface PositionedRun extends StyledRun {\n x: number;\n /** Advance width, as the layout's `MeasureFn` measured it. */\n width: number;\n /** Baseline offset, positive down — a superscript's is negative. Add it to\n * the line's baseline when painting. */\n y: number;\n /** The run's font size in px, with `fontScale` and `script` already folded\n * in. Resolved once here so layout and paint cannot disagree about it. */\n size: number;\n /** The face that placed the run's script and places its rules. */\n face?: FaceMetrics;\n}\n\n/**\n * A run's size and baseline offset, resolved the way `resolveRuns` resolves\n * them for the GL path: an absolute `fontSize` wins over a multiplier, and\n * the rise is measured against the *inherited* size so it does not shrink\n * along with the run.\n */\nfunction runMetrics(run: StyledRun, fontSize: number, face: FaceMetrics | undefined): { size: number; y: number } {\n const script = run.script ? scriptMetrics(face)[run.script] : undefined;\n const scale = run.fontScale ?? script?.size ?? 1;\n const shiftEm = run.baselineShift ?? script?.shift ?? 0;\n return {\n size: run.fontSize !== undefined\n ? resolveScreenLength(run.fontSize, 1)\n : fontSize * scale,\n // Canvas y grows downward; a positive shift is a rise. Guarded so an\n // unshifted run reports 0 rather than -0.\n y: shiftEm === 0 ? 0 : -shiftEm * fontSize,\n };\n}\n\n/** A run as `layoutMarkdown` walks it: small caps has split it where its\n * size changes, and marked the pieces drawn at the small size. */\ntype Segment = StyledRun & { smallCaps?: true; source?: StyledRun };\n\n/** A single laid-out line of text: its positioned runs, total width, and computed line height. */\nexport interface LayoutLine {\n runs: PositionedRun[];\n width: number;\n height: number;\n}\n\n/** Output of `layoutMarkdown`: per-line breakdown plus overall block dimensions. */\nexport interface LayoutResult {\n lines: LayoutLine[];\n width: number;\n height: number;\n}\n\n/**\n * Word-wrap parsed runs into lines bounded by `maxWidth`, breaking at the\n * UAX #14 opportunities `layoutRuns` breaks at; pass `Infinity` for\n * single-line layout.\n */\nexport function layoutMarkdown(\n runs: StyledRun[],\n maxWidth: number,\n fontSize: number,\n measure: MeasureFn,\n lineHeightFactor: number = 1.3,\n faceOf?: FaceMetricsFn,\n): LayoutResult {\n if (runs.length === 0) return { lines: [], width: 0, height: 0 };\n // No caret reads this layout, so the transformed text simply replaces the source.\n const shown = transformRunTexts(runs.map((r) => r.text), runs.map((r) => r.textTransform ?? 'none'));\n // Small caps splits a run where its size changes, marking the small pieces.\n const segs: Segment[] = [];\n runs.forEach((r, i) => {\n const text = shown[i].text;\n if (r.fontVariantCaps !== 'small-caps') { segs.push(text === r.text ? r : { ...r, text }); return; }\n const caps = smallCapsText(text);\n if (!caps.small) { segs.push({ ...r, text: caps.text }); return; }\n let at = 0;\n for (const piece of caps.text) {\n const small = caps.small[at];\n at += piece.length;\n const prev = segs[segs.length - 1];\n if (prev?.source === r && (prev.smallCaps === true) === small) prev.text += piece;\n else segs.push({ ...r, text: piece, source: r, ...(small ? { smallCaps: true as const } : {}) });\n }\n });\n\n // One sequence across every run, so a break opportunity that depends on a\n // neighbor in the next run is found the way `layoutRuns` finds it.\n const cps: number[] = [];\n /** Per code point: its run, and its UTF-16 span in that run's text. */\n const runOf: number[] = [];\n const startOf: number[] = [];\n const endOf: number[] = [];\n segs.forEach((r, ri) => {\n let at = 0;\n for (const ch of r.text) {\n cps.push(ch.codePointAt(0)!);\n runOf.push(ri);\n startOf.push(at);\n at += ch.length;\n endOf.push(at);\n }\n });\n // Already a screen-pixel layout, so a run's `{ px }` size is its size.\n const placed = segs.map(({ smallCaps, source: _source, ...run }) => {\n const face = faceOf?.(run.bold ?? false, run.italic ?? false);\n const { size: runSize, y } = runMetrics(run, fontSize, face);\n // The run's size holds the line, as on the GL tier, however small its capitals.\n return { run, face, y, runSize, size: smallCaps ? runSize * smallCapsScale(face) : runSize };\n });\n const pieceWidth = (p: Piece): number => {\n const { run, size } = placed[p.run];\n return measure(run.text.slice(p.start, p.end), size, run.bold ?? false, run.italic ?? false);\n };\n\n /** A UTF-16 span of one run's text, set on the current line. */\n interface Piece { run: number; start: number; end: number }\n\n /** Code points `[from, to)` as spans of their runs' texts. */\n function piecesOf(from: number, to: number): Piece[] {\n const out: Piece[] = [];\n for (let k = from; k < to; k++) {\n const last = out[out.length - 1];\n if (last && last.run === runOf[k] && last.end === startOf[k]) {\n out[out.length - 1] = { ...last, end: endOf[k] };\n } else {\n out.push({ run: runOf[k], start: startOf[k], end: endOf[k] });\n }\n }\n return out;\n }\n\n const lines: LayoutLine[] = [];\n\n function commitLine(line: Piece[]) {\n let x = 0;\n let maxSize = 0;\n const positioned: PositionedRun[] = [];\n for (const p of line) {\n const { run, face, size, y, runSize } = placed[p.run];\n const width = pieceWidth(p);\n positioned.push({ ...run, text: run.text.slice(p.start, p.end), x, width, y, size, ...(face ? { face } : {}) });\n x += width;\n maxSize = Math.max(maxSize, runSize);\n }\n lines.push({ runs: positioned, width: x, height: (maxSize > 0 ? maxSize : fontSize) * lineHeightFactor });\n }\n\n const widthOf = (start: number, end: number): number =>\n piecesOf(start, end).reduce((w, p) => w + pieceWidth(p), 0);\n for (const line of wrapLines(cps, maxWidth, widthOf)) {\n let end = line.end;\n // A wrapped line's trailing spaces hang past the edge, as they do in `layoutRuns`.\n if (line.wrapped) while (end > line.start && hangs(cps[end - 1])) end--;\n commitLine(piecesOf(line.start, end));\n }\n\n if (lines.length === 0) return { lines: [], width: 0, height: 0 };\n const width = Math.max(...lines.map((l) => l.width));\n const height = lines.reduce((sum, l) => sum + l.height, 0);\n return { lines, width, height };\n}\n\n/** Pluggable text-painting strategy. The default fills white at `(x, y)`; markdown renderers replace this. */\nexport type TextRenderer = (\n ctx: CanvasRenderingContext2D,\n text: string,\n x: number,\n y: number,\n) => void;\n\n/** Font styling options threaded through `createMarkdownRenderer`. */\nexport interface MarkdownFontOptions {\n /** Font-family spec (e.g. `'\"Iowan Old Style\", Georgia, serif'`). Defaults to `sans-serif`. */\n family?: string;\n /** Numeric weight applied to non-bold runs. Bold runs always use `bold`. Default `normal`. */\n weight?: string | number;\n /** Override fill color. When set, used for all runs (italic and bold). */\n color?: string;\n /** Multiplier applied to font size for line height. Default 1.3. */\n lineHeight?: number;\n}\n\nfunction buildFont(\n fontSize: number,\n bold: boolean,\n italic: boolean,\n opts: MarkdownFontOptions = {},\n): string {\n const family = opts.family ?? 'sans-serif';\n const weight = bold ? 'bold' : (opts.weight !== undefined ? String(opts.weight) : 'normal');\n const parts: string[] = [];\n if (italic) parts.push('italic');\n parts.push(weight);\n parts.push(`${fontSize}px ${cssFamilyName(family)}`);\n return parts.join(' ');\n}\n\nfunction canvasMeasure(ctx: CanvasRenderingContext2D, opts: MarkdownFontOptions = {}): MeasureFn {\n return (text, fontSize, bold, italic) => {\n ctx.font = buildFont(fontSize, bold, italic, opts);\n return ctx.measureText(text).width;\n };\n}\n\n/** Distance from the context's current `textBaseline` down to the alphabetic\n * baseline, for the font already set on it; 0 where the metric is missing. */\nfunction alphabeticBaselineBelow(ctx: CanvasRenderingContext2D): number {\n const current = ctx.textBaseline;\n if (current === 'alphabetic') return 0;\n const here = ctx.measureText('').fontBoundingBoxAscent;\n ctx.textBaseline = 'alphabetic';\n const alphabetic = ctx.measureText('').fontBoundingBoxAscent;\n ctx.textBaseline = current;\n const d = alphabetic - here;\n return Number.isFinite(d) ? d : 0;\n}\n\n/** Where a block `width` wide starts, given the x the context aligns it to. */\nfunction blockLeft(ctx: CanvasRenderingContext2D, x: number, width: number): number {\n const rtl = ctx.direction === 'rtl';\n switch (ctx.textAlign) {\n case 'center': return x - width / 2;\n case 'right': return x - width;\n case 'end': return rtl ? x : x - width;\n case 'start': return rtl ? x - width : x;\n default: return x;\n }\n}\n\n/**\n * Build a fill+stroke `TextRenderer` pair, laying the text out once.\n *\n * `text` is markdown, read by `markdownToRuns`, or runs already styled. The\n * block is placed by the context's `textAlign` and each run by its\n * `textBaseline`. The fill pass also paints underline, strikethrough and\n * overline in their run's fill, placed by the same metrics as the GL tier;\n * the stroke pass paints no rules, as on the GL tier.\n */\nexport function createMarkdownRenderer(\n ctx: CanvasRenderingContext2D,\n text: string | StyledRun[],\n fontSize: number,\n maxWidth: number = Infinity,\n fontOpts: MarkdownFontOptions = {},\n): { renderer: TextRenderer; strokeRenderer: TextRenderer; width: number; height: number } {\n const measure = canvasMeasure(ctx, fontOpts);\n const parsed = typeof text === 'string' ? markdownToRuns(text) : text;\n const family = fontOpts.family ?? 'sans-serif';\n const weight = numericWeight(fontOpts.weight ?? 400);\n const faceOf: FaceMetricsFn = (bold, italic) =>\n faceMetricsFor(family, bold ? 700 : weight, italic ? 'italic' : 'normal');\n const layout = layoutMarkdown(parsed, maxWidth, fontSize, measure, fontOpts.lineHeight, faceOf);\n\n /** Walk the layout, setting each run's font and handing over its\n * left-aligned paint position and the index of its line. */\n function walk(\n c: CanvasRenderingContext2D,\n x: number,\n y: number,\n drawRun: (run: PositionedRun, rx: number, ry: number, lineIndex: number) => void,\n ): void {\n const align = c.textAlign;\n const left = blockLeft(c, x, layout.width);\n c.textAlign = 'left';\n let lineY = y;\n layout.lines.forEach((line, li) => {\n const lineLeft = left + (layout.width - line.width) / 2;\n for (const run of line.runs) {\n c.font = buildFont(run.size, run.bold ?? false, run.italic ?? false, fontOpts);\n drawRun(run, lineLeft + run.x, lineY + run.y, li);\n }\n lineY += line.height;\n });\n c.textAlign = align;\n }\n\n const renderer: TextRenderer = (_ctx, _text, x, y) => {\n interface Span {\n flags: Record<DecorationKind, boolean>;\n fill: string;\n size: number;\n face: FaceMetrics | undefined;\n baselineY: number;\n line: number;\n x0: number;\n x1: number;\n }\n let span: Span | null = null;\n const flush = (): void => {\n const s = span;\n span = null;\n if (!s || s.x1 <= s.x0) return;\n _ctx.fillStyle = s.fill;\n for (const kind of DECORATION_KINDS) {\n if (!s.flags[kind]) continue;\n const { y0, y1 } = decorationRule(kind, s.baselineY, s.size, s.face);\n _ctx.fillRect(s.x0, y0, s.x1 - s.x0, y1 - y0);\n }\n };\n\n walk(_ctx, x, y, (run, rx, ry, line) => {\n const fill = fontOpts.color\n ?? (run.italic && !run.bold ? 'rgba(255, 255, 255, 0.7)' : '#FFFFFF');\n _ctx.fillStyle = fill;\n _ctx.fillText(run.text, rx, ry);\n\n if (!(run.underline || run.strikethrough || run.overline)) {\n flush();\n return;\n }\n const flags: Record<DecorationKind, boolean> = {\n underline: run.underline ?? false,\n strikethrough: run.strikethrough ?? false,\n overline: run.overline ?? false,\n };\n const baselineY = ry + alphabeticBaselineBelow(_ctx);\n const open = span;\n if (\n open !== null\n && open.line === line\n && open.x1 === rx\n && open.fill === fill\n && open.size === run.size\n && open.face === run.face\n && open.baselineY === baselineY\n && DECORATION_KINDS.every((k) => open.flags[k] === flags[k])\n ) {\n open.x1 = rx + run.width;\n } else {\n flush();\n span = { flags, fill, size: run.size, face: run.face, baselineY, line, x0: rx, x1: rx + run.width };\n }\n });\n flush();\n };\n\n const strokeRenderer: TextRenderer = (_ctx, _text, x, y) => {\n walk(_ctx, x, y, (run, rx, ry) => _ctx.strokeText(run.text, rx, ry));\n };\n\n return { renderer, strokeRenderer, width: layout.width, height: layout.height };\n}\n"]}
1
+ {"version":3,"sources":["../src/runs.ts","../src/runs/textTransform.ts","../src/runs/smallCaps.ts","../src/runs/resolveRuns.ts","../src/layout/decorationMetrics.ts","../src/measure/verticalAlign.ts","../src/layout/textPoseLayout.ts","../src/layout/paintRuns.ts","../src/layout/paintCache.ts","../src/measure/measureText.ts","../src/measure/measureTextBounds.ts","../src/measure/lineBoxes.ts","../src/hitTest.ts","../src/fitTextPose.ts","../src/renderLabel.ts","../src/isTextData.ts","../src/markdownText.ts","../src/runs/rangeStyle.ts","../src/runs/flagRange.ts","../src/runs/effectiveRangeStyle.ts","../src/syntheticItalic.ts","../src/textToPath.ts"],"names":["faceMetricsOf","resolveFontVariant","paintKey","strokeKey","resolved","resolveScreenLength","width","own"],"mappings":";;;;;;;;;AAmFO,SAAS,OAAO,KAAA,EAA0C;AAC/D,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,OAAO,KAAA,CAAM,WAAW,CAAA,GAAI,KAAK,CAAC,EAAE,IAAA,EAAM,KAAA,EAAO,CAAA;AAAA,EACnD;AACA,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,KAAA,CAAM,QAAQ,CAAA,EAAA,EAAK;AACrC,IAAA,MAAM,CAAA,GAAI,MAAM,CAAC,CAAA;AACjB,IAAA,IAAI,OAAO,CAAA,EAAG,IAAA,KAAS,QAAA,EAAU;AAC/B,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,qBAAA,EAAwB,CAAC,CAAA,2BAAA,CAA6B,CAAA;AAAA,IACxE;AAAA,EACF;AACA,EAAA,OAAO,KAAA;AACT;AAGO,SAAS,gBAAgB,IAAA,EAAoC;AAClE,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,KAAA,MAAW,CAAA,IAAK,IAAA,EAAM,GAAA,IAAO,CAAA,CAAE,IAAA;AAC/B,EAAA,OAAO,GAAA;AACT;AAmCO,IAAM,oBAAA,GAAmC;AAAA,EAC9C,OAAA,EAAS;AAAA,IACP,EAAE,WAAW,GAAA,EAAK,MAAA,EAAQ,GAAG,KAAA,EAAO,CAAC,MAAA,EAAQ,QAAQ,CAAA,EAAE;AAAA,IACvD,EAAE,WAAW,GAAA,EAAK,M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EACA,IAAA,GAA0B,EAAC,EACZ;AACf,EAAA,MAAM,QAAA,GAAqB;AAAA,IACb,KAAA,EAAO,CAAA;AAAA,IACnB,MAAM,IAAA,CAAK,IAAA;AAAA,IACX,MAAM,IAAA,CAAK,IAAA;AAAA,IACX,OAAO,IAAA,CAAK;AAAA,GACd;AACA,EAAA,MAAM,EAAE,IAAA,EAAK,GAAI,oBAAoB,QAAA,EAAU,IAAA,CAAK,SAAS,CAAC,CAAA;AAC9D,EAAA,MAAM,OAAA,CAAQ,IAAI,OAAA,CAAQ,IAAI,EAAE,GAAA,CAAI,CAAC,MAAM,gBAAA,CAAiB,CAAA,CAAE,QAAQ,EAAE,MAAA,EAAQ,EAAE,MAAA,EAAQ,KAAA,EAAO,EAAE,KAAA,EAAO,CAAC,CAAC,CAAA;AAG5G,EAAA,MAAM,OAAA,CAAQ,IAAI,OAAA,CAAQ,IAAI,EAAE,GAAA,CAAI,CAAC,MAAM,gBAAA,CAAiB,CAAA,CAAE,QAAQ,EAAE,MAAA,EAAQ,EAAE,MAAA,EAAQ,KAAA,EAAO,EAAE,KAAA,EAAO,CAAC,CAAC,CAAA;AAC9G","file":"index.js","sourcesContent":["/**\n * Canonical inline-styling primitive for text nodes. A node's text is\n * either a plain `string` (treated as a single-run, default-styled fragment)\n * or `StyledRun[]` for rich content. `toRuns` is the funnel that normalizes\n * either form into the array shape used by the renderer.\n *\n * Every field except `text` is optional; missing fields fall back to the\n * node-level `TextStyle`. `bold`/`italic` are toggles; `fontWeight` is the\n * numeric weight `bold` is a preset over.\n */\n\nimport type { ScreenLength, Stroke, Fill } from '@weasel-js/paint';\nimport type { TextTransform } from './runs/textTransform';\nimport type { FontVariantCaps } from './runs/smallCaps';\n\n/** A span of text with its own styling, as authored. Fields left absent\n * inherit from the node's text style — this is the difference between a run\n * and a fully resolved one. */\nexport interface StyledRun {\n text: string;\n /** Draw at weight 700. A preset over `fontWeight`, which wins when both\n * are present. */\n bold?: boolean;\n /** Numeric weight, 100–900. Overrides the node's weight and `bold`. */\n fontWeight?: number;\n italic?: boolean;\n fontFamily?: string;\n /** World units, or `{ px }` for screen pixels — resolved against the view\n * scale `resolveRuns` is given, like `TextStyle.fontSize`. */\n fontSize?: ScreenLength;\n /** This run's ink. `null` is no fill at all, leaving the glyphs to `stroke`\n * alone; absent inherits the node's. */\n fill?: Fill | null;\n /** Outline over this run's glyphs. Overrides the node's own `data.stroke`;\n * absent inherits it. Only painted on the outline tier. */\n stroke?: Stroke;\n /** World units, or `{ px }` for screen pixels. */\n letterSpacing?: ScreenLength;\n underline?: boolean;\n strikethrough?: boolean;\n /** Draw a rule above this run's ascent. Additive over the node style. */\n overline?: boolean;\n /**\n * Set this run as a superscript or subscript — a raised or lowered baseline\n * and a smaller size together, which is the pair `<sup>` and `<sub>` imply.\n *\n * A preset over the two primitives below, not a third mechanism: it supplies\n * a `baselineShift` and a `fontScale`, and naming either of those directly\n * overrides that half while leaving the other alone. The numbers are the\n * face's own `OS/2` script metrics, or {@link SCRIPT_METRICS} for a face\n * that states none — `scriptMetricsFor` answers which.\n */\n script?: 'super' | 'sub';\n /**\n * Raise (positive) or lower (negative) this run off the line's shared\n * baseline, in ems of the *inherited* font size — so a run's rise does not\n * shrink along with the run when `fontScale` also applies.\n */\n baselineShift?: number;\n /**\n * Multiplier on the inherited font size. The relative counterpart to\n * `fontSize`, which pins an absolute size and wins over this when both are\n * present.\n */\n fontScale?: number;\n /**\n * CSS `text-transform` for this run's display. The run's `text` stays as\n * authored — carets, selections and edits address it — and only what is\n * drawn changes. Overrides the node's own; `'none'` turns an inherited one\n * off.\n */\n textTransform?: TextTransform;\n /**\n * `'small-caps'` draws this run's lowercase letters as capitals at a\n * smaller size — synthesized, at the face's x-height over its cap height.\n * Like `textTransform`, only what is drawn changes. Overrides the node's\n * own; `'normal'` turns an inherited one off.\n */\n fontVariantCaps?: FontVariantCaps;\n}\n\n/** Normalize the two accepted spellings of text content — a plain string or\n * an array of runs — to runs. Throws on a run with no string `text`. */\nexport function toRuns(input: string | StyledRun[]): StyledRun[] {\n if (typeof input === 'string') {\n return input.length === 0 ? [] : [{ text: input }];\n }\n for (let i = 0; i < input.length; i++) {\n const r = input[i];\n if (typeof r?.text !== 'string') {\n throw new Error(`toRuns: run at index ${i} is missing string \\`text\\``);\n }\n }\n return input;\n}\n\n/** Concatenate runs, dropping all styling. */\nexport function runsToPlainText(runs: readonly StyledRun[]): string {\n let out = '';\n for (const r of runs) out += r.text;\n return out;\n}\n\n/** A run flag an inline marker can toggle. The additive style toggles on\n * `StyledRun`; the valued fields (family, size, paint, `script`) have no\n * inline spelling and are not addressable this way. */\nexport type RunFlag = 'bold' | 'italic' | 'underline' | 'strikethrough' | 'overline';\n\n/** One inline marker: a delimiter repeated `repeat` times, and the flags it\n * turns on between its opening and closing occurrence. */\nexport interface RunMarker {\n delimiter: string;\n repeat: number;\n flags: readonly RunFlag[];\n}\n\n/**\n * The inline grammar `runsToMarkdown` writes and `markdownToRuns` reads.\n *\n * Markers sharing a delimiter are matched longest-first, which is what lets\n * `***` mean something other than `**` followed by `*`. A backslash escapes\n * any delimiter character and itself, in both directions.\n */\nexport interface RunGrammar {\n markers: readonly RunMarker[];\n}\n\n/**\n * The markdown subset the kit reads and writes: `**bold**`, `*italic*`,\n * `***both***`.\n *\n * Deliberately not the whole of markdown, and deliberately silent on\n * `underline` / `strikethrough` — the two run flags with no entry here are\n * dropped by `runsToMarkdown`, as they always have been. A grammar that wants\n * `~~struck~~` adds one marker; nothing else has to change.\n */\nexport const MARKDOWN_RUN_GRAMMAR: RunGrammar = {\n markers: [\n { delimiter: '*', repeat: 3, flags: ['bold', 'italic'] },\n { delimiter: '*', repeat: 2, flags: ['bold'] },\n { delimiter: '*', repeat: 1, flags: ['italic'] },\n ],\n};\n\n/** Delimiter characters of a grammar, plus the backslash that escapes them. */\nfunction escapees(grammar: RunGrammar): Set<string> {\n const out = new Set<string>(['\\\\']);\n for (const m of grammar.markers) out.add(m.delimiter);\n return out;\n}\n\nfunction escapeFor(text: string, chars: ReadonlySet<string>): string {\n let out = '';\n for (const ch of text) out += chars.has(ch) ? `\\\\${ch}` : ch;\n return out;\n}\n\n/** The flags a run turns on, in the grammar's own marker order so two runs\n * with the same flags always serialize identically. */\nfunction flagsOf(run: StyledRun, grammar: RunGrammar): Set<RunFlag> {\n const on = new Set<RunFlag>();\n for (const m of grammar.markers) {\n for (const f of m.flags) if (run[f]) on.add(f);\n }\n return on;\n}\n\nfunction sameFlags(a: ReadonlySet<RunFlag>, b: readonly RunFlag[]): boolean {\n return a.size === b.length && b.every((f) => a.has(f));\n}\n\n/**\n * Render runs in `grammar`, defaulting to the markdown subset. The flavor\n * written to the clipboard alongside the plain-text one.\n *\n * A run whose flags exactly match one marker takes it; otherwise the markers\n * that cover them nest. Flags no marker spells are dropped — the text still\n * round-trips, without that styling.\n */\nexport function runsToMarkdown(\n runs: readonly StyledRun[],\n grammar: RunGrammar = MARKDOWN_RUN_GRAMMAR,\n): string {\n const chars = escapees(grammar);\n let out = '';\n for (const r of runs) {\n // An empty run would write its markers back to back, which read as a toggle.\n if (r.text.length === 0) continue;\n const escaped = escapeFor(r.text, chars);\n const on = flagsOf(r, grammar);\n if (on.size === 0) { out += escaped; continue; }\n\n const exact = grammar.markers.find((m) => sameFlags(on, m.flags));\n if (exact) {\n const d = exact.delimiter.repeat(exact.repeat);\n out += `${d}${escaped}${d}`;\n continue;\n }\n // No single marker says all of it: nest the ones that each say part.\n const covering = grammar.markers.filter(\n (m) => m.flags.length === 1 && on.has(m.flags[0]),\n );\n const open = covering.map((m) => m.delimiter.repeat(m.repeat)).join('');\n const close = [...covering].reverse().map((m) => m.delimiter.repeat(m.repeat)).join('');\n out += `${open}${escaped}${close}`;\n }\n return out;\n}\n\n/**\n * Parse `input` in `grammar`, defaulting to the markdown subset, into styled\n * runs. Newlines are preserved as literal characters inside a run — they are\n * not run-boundary markers in this format.\n */\nexport function markdownToRuns(\n input: string,\n grammar: RunGrammar = MARKDOWN_RUN_GRAMMAR,\n): StyledRun[] {\n const chars = escapees(grammar);\n // Longest-first per delimiter, so `***` is tried before `**` before `*`.\n const byDelimiter = new Map<string, RunMarker[]>();\n for (const m of grammar.markers) {\n const list = byDelimiter.get(m.delimiter) ?? [];\n list.push(m);\n byDelimiter.set(m.delimiter, list);\n }\n for (const list of byDelimiter.values()) list.sort((a, b) => b.repeat - a.repeat);\n\n const runs: StyledRun[] = [];\n const active = new Set<RunFlag>();\n let buf = '';\n let i = 0;\n\n function flush(): void {\n if (buf.length === 0) return;\n const run: StyledRun = { text: buf };\n for (const f of active) run[f] = true;\n runs.push(run);\n buf = '';\n }\n\n while (i < input.length) {\n const ch = input[i];\n\n if (ch === '\\\\' && i + 1 < input.length && chars.has(input[i + 1])) {\n buf += input[i + 1];\n i += 2;\n continue;\n }\n\n const markers = byDelimiter.get(ch);\n if (markers) {\n let count = 0;\n while (i + count < input.length && input[i + count] === ch) count++;\n // The longest marker the delimiter run can pay for; a run shorter than\n // every marker is text.\n const marker = markers.find((m) => m.repeat <= count);\n if (!marker) {\n buf += ch.repeat(count);\n i += count;\n continue;\n }\n flush();\n for (const f of marker.flags) {\n if (active.has(f)) active.delete(f);\n else active.add(f);\n }\n i += marker.repeat;\n continue;\n }\n\n buf += ch;\n i++;\n }\n\n flush();\n return runs;\n}\n","/**\n * CSS `text-transform` over styled runs: `uppercase`, `lowercase` and\n * `capitalize`, with the source offsets each transformed character came from.\n *\n * Case mapping is not length-preserving — `'ß'.toUpperCase()` is `'SS'` — and\n * every caret, selection and hit-test in the kit addresses the *source* text.\n * So a transform that changes a code point's length reports a\n * {@link RunSourceMap} alongside the text, and layout reads each cell's source\n * span off it instead of counting the characters it drew.\n */\n\n/** The CSS `text-transform` keywords the run model carries. `none` is an\n * explicit override: a run can turn off a transform it would inherit. */\nexport type TextTransform = 'none' | 'uppercase' | 'lowercase' | 'capitalize';\n\n/**\n * Where each UTF-16 unit of a transformed run's text came from in its source,\n * as run-relative offsets. `starts[i]` / `ends[i]` bound the source code point\n * that produced output unit `i`, so the two units `ß` uppercases to share one\n * span. `length` is the source run's own length.\n */\nexport interface RunSourceMap {\n length: number;\n starts: readonly number[];\n ends: readonly number[];\n}\n\n/** A run's text after its transform. `srcMap` is present only when some code\n * point changed length — otherwise output offsets are source offsets. */\nexport interface TransformedRunText {\n text: string;\n srcMap?: RunSourceMap;\n}\n\n/** Title-case mappings that differ from the uppercase one (UnicodeData and\n * SpecialCasing). Everything absent titlecases as it uppercases. */\nconst TITLE: ReadonlyMap<number, string> = new Map<number, string>([\n [0x00df, 'Ss'],\n [0x01c4, 'Dž'], [0x01c5, 'Dž'], [0x01c6, 'Dž'],\n [0x01c7, 'Lj'], [0x01c8, 'Lj'], [0x01c9, 'Lj'],\n [0x01ca, 'Nj'], [0x01cb, 'Nj'], [0x01cc, 'Nj'],\n [0x01f1, 'Dz'], [0x01f2, 'Dz'], [0x01f3, 'Dz'],\n [0x0587, 'Եւ'],\n [0xfb00, 'Ff'], [0xfb01, 'Fi'], [0xfb02, 'Fl'], [0xfb03, 'Ffi'], [0xfb04, 'Ffl'],\n [0xfb05, 'St'], [0xfb06, 'St'],\n [0xfb13, 'Մն'], [0xfb14, 'Մե'], [0xfb15, 'Մի'],\n [0xfb16, 'Վն'], [0xfb17, 'Մխ'],\n [0x1fb3, 'ᾼ'], [0x1fbc, 'ᾼ'],\n [0x1fc3, 'ῌ'], [0x1fcc, 'ῌ'],\n [0x1ff3, 'ῼ'], [0x1ffc, 'ῼ'],\n [0x1fb2, 'Ὰͅ'], [0x1fb4, 'Άͅ'], [0x1fb7, 'ᾼ͂'],\n [0x1fc2, 'Ὴͅ'], [0x1fc4, 'Ήͅ'], [0x1fc7, 'ῌ͂'],\n [0x1ff2, 'Ὼͅ'], [0x1ff4, 'Ώͅ'], [0x1ff7, 'ῼ͂'],\n]);\n\nfunction titlecase(ch: string): string {\n const cp = ch.codePointAt(0)!;\n // Greek with ypogegrammeni: the titlecase form keeps the iota subscript,\n // where uppercase spells it out as a capital iota.\n if (cp >= 0x1f80 && cp <= 0x1faf) return String.fromCodePoint(cp | 0x8);\n return TITLE.get(cp) ?? ch.toUpperCase();\n}\n\nconst WORD_FALLBACK = /[\\p{L}\\p{N}][\\p{L}\\p{N}\\p{M}\\p{Pc}'’]*/gu;\n\n/** Source offsets at which a word begins, by the same UAX #29 word boundaries\n * browsers use for `capitalize`. */\nfunction wordStarts(text: string): Set<number> {\n const out = new Set<number>();\n if (typeof Intl !== 'undefined' && 'Segmenter' in Intl) {\n const seg = new Intl.Segmenter(undefined, { granularity: 'word' });\n for (const s of seg.segment(text)) if (s.isWordLike) out.add(s.index);\n return out;\n }\n for (const m of text.matchAll(WORD_FALLBACK)) out.add(m.index!);\n return out;\n}\n\n/** Whether mapping `full` per code point, run by run, produces exactly the\n * units `whole` does — true unless a mapping spans a run boundary. */\nfunction alignsPerCodePoint(\n texts: readonly string[], whole: string, map: (ch: string) => string,\n): boolean {\n let n = 0;\n for (const t of texts) for (const ch of t) n += map(ch).length;\n return n === whole.length;\n}\n\nconst upper = (ch: string): string => ch.toUpperCase();\nconst lower = (ch: string): string => ch.toLowerCase();\n\n/**\n * Apply each run's transform to its text. `texts[i]` is transformed by\n * `transforms[i]`; the runs are read as one paragraph, so final sigma and\n * `capitalize`'s word starts see across run boundaries — a word split by\n * styling still gets one capital.\n *\n * Mappings are the locale-independent ones JavaScript's `toUpperCase` /\n * `toLowerCase` implement, which include `ß` → `SS` and final sigma.\n * `capitalize` titlecases the first code point of each word when it has a\n * case to change, and leaves every other character as it was.\n */\nexport function transformRunTexts(\n texts: readonly string[],\n transforms: readonly TextTransform[],\n): TransformedRunText[] {\n if (transforms.every((t) => t === 'none')) return texts.map((text) => ({ text }));\n\n const full = texts.join('');\n // Lowercasing is contextual (final sigma), so the per-code-point pieces are\n // read out of the whole paragraph's mapping wherever the two align.\n const wholeUpper = transforms.includes('uppercase') ? full.toUpperCase() : '';\n const wholeLower = transforms.includes('lowercase') ? full.toLowerCase() : '';\n const upperAligned = wholeUpper !== '' && alignsPerCodePoint(texts, wholeUpper, upper);\n const lowerAligned = wholeLower !== '' && alignsPerCodePoint(texts, wholeLower, lower);\n const starts = transforms.includes('capitalize') ? wordStarts(full) : null;\n\n const out: TransformedRunText[] = [];\n let base = 0;\n let upOff = 0;\n let lowOff = 0;\n for (let i = 0; i < texts.length; i++) {\n const source = texts[i];\n const t = transforms[i] ?? 'none';\n let text = '';\n const srcStarts: number[] = [];\n const srcEnds: number[] = [];\n let resized = false;\n let local = 0;\n for (const ch of source) {\n const up = upper(ch);\n const lo = lower(ch);\n let piece = ch;\n if (t === 'uppercase') {\n piece = upperAligned ? wholeUpper.slice(upOff, upOff + up.length) : up;\n } else if (t === 'lowercase') {\n piece = lowerAligned ? wholeLower.slice(lowOff, lowOff + lo.length) : lo;\n } else if (t === 'capitalize' && starts!.has(base + local) && up !== ch) {\n piece = titlecase(ch);\n }\n upOff += up.length;\n lowOff += lo.length;\n if (piece.length !== ch.length) resized = true;\n text += piece;\n for (let k = 0; k < piece.length; k++) {\n srcStarts.push(local);\n srcEnds.push(local + ch.length);\n }\n local += ch.length;\n }\n out.push(resized\n ? { text, srcMap: { length: source.length, starts: srcStarts, ends: srcEnds } }\n : { text });\n base += source.length;\n }\n return out;\n}\n","/**\n * Synthetic small caps: lowercase drawn as capitals at a smaller size, the\n * way a browser synthesizes `font-variant: small-caps` for a face with no\n * `smcp` feature. It is the one run style that sizes characters within a run\n * differently, so it reports a per-unit size map beside the text.\n *\n * It reads the text *after* `textTransform`, as CSS does: `uppercase` leaves\n * nothing to shrink, and `lowercase` shrinks everything.\n */\n\nimport { faceMetricsOf, resolveFontVariant, type FaceMetrics, type FontStyle } from '@weasel-js/font';\nimport type { RunSourceMap } from './textTransform';\n\n/** The CSS `font-variant-caps` keywords the run model carries. `normal` is an\n * explicit override: a run can turn off small caps it would inherit. */\nexport type FontVariantCaps = 'normal' | 'small-caps';\n\n/**\n * The small-caps size, as a fraction of the run's, for a face that states no\n * x-height and cap height. 0.7 is the factor Chromium and WebKit synthesize\n * with.\n */\nexport const SMALL_CAPS_SCALE = 0.7;\n\n/** The small-caps size for a face: its x-height over its cap height, so a\n * small capital stands as tall as its lowercase letters do, or\n * {@link SMALL_CAPS_SCALE} where the face lacks either. */\nexport function smallCapsScale(face?: FaceMetrics): number {\n const x = face?.xHeight;\n const cap = face?.capHeight;\n if (x === undefined || cap === undefined || x >= cap) return SMALL_CAPS_SCALE;\n return x / cap;\n}\n\n/** The small-caps scale a run set in `(family, weight, style)` gets —\n * resolved through the font registry exactly as layout resolves the run. */\nexport function smallCapsScaleFor(family: string, weight: number, style: FontStyle): number {\n return smallCapsScale(faceMetricsOf(resolveFontVariant(family, weight, style)));\n}\n\n/** Whether small caps draws `ch` as a smaller capital: whether it has a\n * capital other than itself. */\nexport function isSmallCapsLetter(ch: string): boolean {\n return ch.toUpperCase() !== ch;\n}\n\n/** A run's drawn text under small caps. `small[i]` says whether UTF-16 unit\n * `i` of `text` draws at the small size; absent when none does. */\nexport interface SmallCapsText {\n text: string;\n srcMap?: RunSourceMap;\n small?: readonly boolean[];\n}\n\n/**\n * Apply small caps to a run's drawn text. `srcMap` is the map `textTransform`\n * already produced for it, if any; the result's map composes the two, so\n * each drawn unit still names the source character it came from.\n */\nexport function smallCapsText(text: string, srcMap?: RunSourceMap): SmallCapsText {\n let out = '';\n const small: boolean[] = [];\n const starts: number[] = [];\n const ends: number[] = [];\n let resized = false;\n let anySmall = false;\n let at = 0;\n for (const ch of text) {\n const shrink = isSmallCapsLetter(ch);\n const piece = shrink ? ch.toUpperCase() : ch;\n if (piece.length !== ch.length) resized = true;\n anySmall ||= shrink;\n const start = srcMap ? srcMap.starts[at] : at;\n const end = srcMap ? srcMap.ends[at] : at + ch.length;\n for (let k = 0; k < piece.length; k++) {\n small.push(shrink);\n starts.push(start);\n ends.push(end);\n }\n out += piece;\n at += ch.length;\n }\n if (!anySmall) return srcMap ? { text, srcMap } : { text };\n const map = resized\n ? { length: srcMap?.length ?? text.length, starts, ends }\n : srcMap;\n return { text: out, ...(map ? { srcMap: map } : {}), small };\n}\n","/**\n * Apply node-level `ResolvedTextStyle` defaults to each `StyledRun`,\n * producing a `ResolvedRun` with every styling field set.\n *\n * `bold`/`italic` on a run fold into `fontWeight`/`fontStyle`; a run's own\n * numeric `fontWeight` wins over both the flag and the node weight.\n * `letterSpacing: 0` on a run is an override, not an absence — it zeroes\n * inherited tracking. The decorations are *additive*: a run can turn one on\n * but never off, so they resolve as `run.x || style.x`.\n *\n * `script` folds into the two primitives it is a preset over, and comes out\n * as one world-unit `baselineShift` and a final `fontSize`. `textTransform`\n * is applied here, then small caps over the transformed text.\n */\n\nimport type { Stroke, Fill } from '@weasel-js/paint';\nimport { resolveScreenLength } from '@weasel-js/paint';\nimport { faceMetricsOf, resolveFontVariant, type FaceMetrics, type FontStyle } from '@weasel-js/font';\nimport type { StyledRun } from '../runs';\nimport type { ResolvedTextStyle } from '../textStyle';\nimport { transformRunTexts, type RunSourceMap } from './textTransform';\nimport { smallCapsScaleFor, smallCapsText } from './smallCaps';\n\n/** A run with every style resolved against the node's text style — no\n * optional inheritance left. This is what layout and painting consume. */\nexport interface ResolvedRun {\n /** The text as drawn — after `textTransform`, so not necessarily the\n * run's source text. */\n text: string;\n /** Present when `text` differs in length from the source it was\n * transformed from: where each of its UTF-16 units came from. Absent\n * means `text`'s offsets are the source's. */\n srcMap?: RunSourceMap;\n fontFamily: string;\n /** The run's size — what its line and its rules are set at, and what\n * every glyph is drawn at unless `sizeMap` says otherwise. */\n fontSize: number;\n /** Present when not every glyph is drawn at `fontSize`: the size each\n * UTF-16 unit of `text` is drawn at. Small caps is what produces one. */\n sizeMap?: readonly number[];\n fontWeight: number;\n fontStyle: 'normal' | 'italic';\n /** `null` is an explicit no-fill: the glyphs are painted by `stroke` alone,\n * which only the outline tier can do. Nothing is emitted for a run with\n * neither. */\n fill: Fill | null;\n /** Outline over this run's glyphs, or absent for none. Painted only on the\n * outline tier — a distance field has no geometry to stroke. */\n stroke?: Stroke;\n /** Extra advance added after each glyph of this run, in world units. */\n letterSpacing: number;\n /** Draw a rule below this run's baseline. Additive over the node style. */\n underline: boolean;\n /** Draw a rule through this run's x-height. Additive over the node style. */\n strikethrough: boolean;\n /** Draw a rule above this run's ascent. Additive over the node style. */\n overline: boolean;\n /**\n * How far this run sits off the line's shared baseline, in world units;\n * positive raises. 0 for ordinary text. Already carries whatever `script`\n * asked for.\n */\n baselineShift: number;\n /**\n * The size this run holds its line open at, when a relative size shrank it\n * below the size it inherited — so a superscript alone on its line keeps the\n * line's height and baseline instead of collapsing them. Absent means\n * `fontSize`.\n */\n strutSize?: number;\n}\n\n/** What one script preset expands to. */\nexport type ScriptPreset = Readonly<{ size: number; shift: number }>;\n\n/**\n * What `script: 'super'` and `script: 'sub'` expand to for a face that states\n * no script metrics of its own, as fractions of the inherited font size:\n * `size` scales it, `shift` raises (positive) or lowers (negative) the\n * baseline. These are Adobe's defaults. A face that carries `OS/2` script\n * metrics uses those instead; {@link scriptMetricsFor} is what a run gets.\n */\nexport const SCRIPT_METRICS: Readonly<Record<'super' | 'sub', ScriptPreset>> = Object.freeze({\n super: Object.freeze({ size: 0.583, shift: 0.333 }),\n sub: Object.freeze({ size: 0.583, shift: -0.333 }),\n});\n\nconst resolvedScripts = new WeakMap<FaceMetrics, Readonly<Record<'super' | 'sub', ScriptPreset>>>();\n\n/** The script presets for a face: its own `OS/2` values where it states\n * them, {@link SCRIPT_METRICS} per half where it does not. */\nexport function scriptMetrics(face?: FaceMetrics): Readonly<Record<'super' | 'sub', ScriptPreset>> {\n if (!face || (!face.superscript && !face.subscript)) return SCRIPT_METRICS;\n let out = resolvedScripts.get(face);\n if (!out) {\n out = Object.freeze({\n super: face.superscript ?? SCRIPT_METRICS.super,\n sub: face.subscript ?? SCRIPT_METRICS.sub,\n });\n resolvedScripts.set(face, out);\n }\n return out;\n}\n\n/**\n * The script presets a run set in `(family, weight, style)` gets — resolved\n * through the font registry exactly as layout resolves the run. Override\n * either half per run with `baselineShift` / `fontScale`.\n */\nexport function scriptMetricsFor(\n family: string,\n weight: number,\n style: FontStyle,\n): Readonly<Record<'super' | 'sub', ScriptPreset>> {\n return scriptMetrics(faceMetricsOf(resolveFontVariant(family, weight, style)));\n}\n\n/** A `TextStyle.fontWeight` as a number: the CSS keywords `bold` and\n * `normal` read as 700 and 400, anything unparseable as 400. */\nexport function numericWeight(w: number | string): number {\n if (typeof w === 'number') return w;\n if (w === 'bold' || w === 'bolder') return 700;\n if (w === 'normal') return 400;\n const parsed = Number(w);\n return Number.isFinite(parsed) ? parsed : 400;\n}\n\n/** Whether a weight reads as bold — 600 and up, the same line the font\n * registry draws between its regular and bold buckets. */\nexport function isBoldWeight(w: number | string): boolean {\n return numericWeight(w) >= 600;\n}\n\n/** The face a run is set in — its family, weight and style, each falling\n * back to the node's. Reads no font registry, so asking loads nothing. */\nexport function resolveRunFace(\n run: StyledRun,\n style: Pick<ResolvedTextStyle, 'fontFamily' | 'fontWeight' | 'fontStyle'>,\n): { fontFamily: string; fontWeight: number; fontStyle: FontStyle } {\n return {\n fontFamily: run.fontFamily ?? style.fontFamily,\n fontWeight: run.fontWeight ?? (run.bold ? 700 : numericWeight(style.fontWeight)),\n fontStyle: run.italic ? 'italic' : style.fontStyle,\n };\n}\n\n/** Resolve each run's styling against the node's text style, filling in\n * everything the run left inherited. `viewScale` resolves a run's own\n * `{ px }` size or spacing; the inherited ones arrived already resolved on\n * `style`. */\nexport function resolveRuns(\n runs: readonly StyledRun[],\n style: ResolvedTextStyle,\n viewScale = 1,\n): ResolvedRun[] {\n const out: ResolvedRun[] = [];\n const shown = transformRunTexts(\n runs.map((r) => r.text),\n runs.map((r) => r.textTransform ?? style.textTransform),\n );\n for (let i = 0; i < runs.length; i++) {\n const run = runs[i];\n let { text, srcMap } = shown[i];\n const scriptKey = run.script ?? style.script;\n const { fontFamily, fontWeight, fontStyle } = resolveRunFace(run, style);\n const script = scriptKey ? scriptMetricsFor(fontFamily, fontWeight, fontStyle)[scriptKey] : undefined;\n // Against the inherited size, not the run's own: a superscript that also\n // shrank its rise would climb less the smaller it got.\n const shiftEm = run.baselineShift ?? script?.shift ?? 0;\n const scale = run.fontScale ?? script?.size ?? 1;\n const relative = run.fontSize === undefined && scale !== 1;\n // An absolute size wins over a relative one.\n const fontSize = run.fontSize !== undefined\n ? resolveScreenLength(run.fontSize, viewScale)\n : style.fontSize * scale;\n let sizeMap: number[] | undefined;\n if ((run.fontVariantCaps ?? style.fontVariantCaps) === 'small-caps') {\n const caps = smallCapsText(text, srcMap);\n text = caps.text;\n srcMap = caps.srcMap;\n if (caps.small) {\n const small = fontSize * smallCapsScaleFor(fontFamily, fontWeight, fontStyle);\n sizeMap = caps.small.map((s) => (s ? small : fontSize));\n }\n }\n out.push({\n text,\n ...(srcMap ? { srcMap } : {}),\n fontFamily,\n fontSize,\n ...(sizeMap ? { sizeMap } : {}),\n fontWeight,\n fontStyle,\n fill: run.fill !== undefined ? run.fill : style.fill,\n // Unlike the decorations below, a run's stroke *replaces* the node's\n // rather than adding to it — there is only one outline to paint.\n ...((run.stroke ?? style.stroke) !== undefined\n ? { stroke: run.stroke ?? style.stroke }\n : {}),\n letterSpacing: run.letterSpacing !== undefined\n ? resolveScreenLength(run.letterSpacing, viewScale)\n : style.letterSpacing,\n // `||`, not `??`: run-level decorations are additive over the node style.\n underline: run.underline || style.underline,\n strikethrough: run.strikethrough || style.strikethrough,\n overline: run.overline || style.overline,\n baselineShift: shiftEm * style.fontSize,\n ...(relative ? { strutSize: style.fontSize } : {}),\n });\n }\n return out;\n}\n","import type { FaceMetrics, FaceRuleMetrics } from '@weasel-js/font';\nimport type { ResolvedRun } from '../runs/resolveRuns';\nimport type { PlacedGlyph } from './layoutRuns';\n\n/** The three text decoration rules, in the order every tier paints them. */\nexport type DecorationKind = 'underline' | 'strikethrough' | 'overline';\n\nexport const DECORATION_KINDS: readonly DecorationKind[] = ['underline', 'strikethrough', 'overline'];\n\n/**\n * Decoration placement and weight for a face that states none, as fractions\n * of the run's `fontSize`. Offsets are the *top* edge of the rule, measured\n * down from the baseline — so the two rules that sit above it are negative.\n *\n * Derived, not measured: they apply to an atlas baked before `gen-font`\n * recorded `faceMetrics`, a custom outline parser that reports none, and the\n * canvas tier, which has no font tables to read.\n */\nexport const DEFAULT_DECORATION_METRICS: Readonly<Record<DecorationKind, FaceRuleMetrics>> = Object.freeze({\n underline: Object.freeze({ offset: 0.10, thickness: 0.05 }),\n strikethrough: Object.freeze({ offset: -0.30, thickness: 0.05 }),\n overline: Object.freeze({ offset: -0.90, thickness: 0.05 }),\n});\n\nconst resolved = new WeakMap<FaceMetrics, Readonly<Record<DecorationKind, FaceRuleMetrics>>>();\n\n/**\n * Where each rule sits for a face, in ems: the face's own underline and\n * strikeout where it states them, the defaults where it does not. No font\n * table places an overline, so it keeps the default offset and takes the\n * underline's weight, as browsers draw it.\n *\n * Every text tier places its rules through this, so one face puts a rule in\n * the same place whichever tier paints it.\n */\nexport function decorationMetrics(face?: FaceMetrics): Readonly<Record<DecorationKind, FaceRuleMetrics>> {\n if (!face) return DEFAULT_DECORATION_METRICS;\n let out = resolved.get(face);\n if (!out) {\n const underline = face.underline ?? DEFAULT_DECORATION_METRICS.underline;\n out = Object.freeze({\n underline,\n strikethrough: face.strikethrough ?? DEFAULT_DECORATION_METRICS.strikethrough,\n overline: Object.freeze({ offset: DEFAULT_DECORATION_METRICS.overline.offset, thickness: underline.thickness }),\n });\n resolved.set(face, out);\n }\n return out;\n}\n\n/**\n * The vertical extent of one decoration rule for a run of `fontSize` whose\n * baseline sits at `baselineY` (y grows down), set in `face`.\n */\nexport function decorationRule(\n kind: DecorationKind,\n baselineY: number,\n fontSize: number,\n face?: FaceMetrics,\n): { y0: number; y1: number } {\n const m = decorationMetrics(face)[kind];\n const y0 = baselineY + fontSize * m.offset;\n return { y0, y1: y0 + fontSize * m.thickness };\n}\n\n/** One rule drawn across a stretch of a line. */\nexport interface DecorationRule {\n kind: DecorationKind;\n x0: number; y0: number; x1: number; y1: number;\n /** The run that opened the stretch. Every run in it paints its rules alike. */\n run: number;\n}\n\n/**\n * The decoration rules of one line, in visual order; within a stretch,\n * underline then strikethrough then overline.\n *\n * `glyphs` is the whole line in visual order. A rule runs across adjacent\n * glyphs whose runs agree on which rules to draw, on the size, face and\n * baseline that place them, and on `paintOf`: the identity of the paint a\n * run's rules wear, or null for a run that draws none. It is built from pen\n * positions rather than ink, so it covers the spaces, tracking and kerning\n * inside the stretch, and two alike runs join without a seam.\n */\nexport function lineDecorations(\n glyphs: readonly PlacedGlyph[],\n runs: readonly ResolvedRun[],\n faceOf: (run: number) => FaceMetrics | undefined,\n paintOf: (run: number) => string | null,\n): DecorationRule[] {\n interface Stretch {\n run: number;\n style: ResolvedRun;\n face: FaceMetrics | undefined;\n paint: string;\n baselineY: number;\n x0: number;\n x1: number;\n }\n const rules: DecorationRule[] = [];\n let open: Stretch | null = null;\n const close = (): void => {\n const s = open;\n open = null;\n if (!s || s.x1 <= s.x0) return;\n for (const kind of DECORATION_KINDS) {\n if (!s.style[kind]) continue;\n // The run's size, not the glyph's: a small-caps word is one rule.\n const { y0, y1 } = decorationRule(kind, s.baselineY, s.style.fontSize, s.face);\n rules.push({ kind, x0: s.x0, y0, x1: s.x1, y1, run: s.run });\n }\n };\n\n for (const g of glyphs) {\n const style = runs[g.run];\n const paint = paintOf(g.run);\n if (paint === null || !DECORATION_KINDS.some((kind) => style[kind])) {\n close();\n continue;\n }\n const face = faceOf(g.run);\n const joins = open !== null\n && DECORATION_KINDS.every((kind) => open!.style[kind] === style[kind])\n && open.style.fontSize === style.fontSize\n && open.face === face\n && open.baselineY === g.baselineY\n && open.paint === paint;\n if (joins) {\n open!.x1 = g.x + g.step;\n } else {\n close();\n open = { run: g.run, style, face, paint, baselineY: g.baselineY, x0: g.x, x1: g.x + g.step };\n }\n }\n close();\n return rules;\n}\n","/**\n * Box vertical alignment for text draw commands. Given the command's box\n * `height` and the laid-out text block's height, returns the Y offset to\n * apply to every quad. `'top'` (or an undefined `align`, or a missing box\n * `height`) is the legacy behavior: offset 0.\n */\nexport type TextVerticalAlign = 'top' | 'center' | 'bottom';\n\n/** How far to shift laid-out text down inside a box of `boxHeight` to satisfy\n * a vertical alignment. Zero when the box height is unknown or alignment is\n * top. */\nexport function verticalAlignOffset(\n align: TextVerticalAlign | undefined,\n boxHeight: number | undefined,\n textHeight: number,\n): number {\n if (align === undefined || align === 'top' || boxHeight === undefined) return 0;\n const slack = boxHeight - textHeight;\n return align === 'center' ? slack / 2 : slack;\n}\n","/**\n * How a text pose lays out — the one decision every consumer of a text node\n * reads: the painters (`kit:text`, `createTextLayer`), picking\n * (`textLineBoxes`), the caret (`caretIndexAt`), fitting (`fitTextPose`) and\n * the DOM edit overlay.\n *\n * The pose width is always the box `align` resolves within. It is the wrap\n * width only when the style declares `wrap`; otherwise a line runs as long as\n * its text, whichever of them is asking.\n */\nimport type { LayoutRunsOpts } from './layoutOpts';\nimport type { LaidOutRuns } from './layoutRuns';\nimport { cachedLayoutRuns } from './layoutCache';\nimport { resolveTextStyle, type ResolvedTextStyle } from '../textStyle';\nimport { resolveRuns, type ResolvedRun } from '../runs/resolveRuns';\nimport { toRuns } from '../runs';\nimport { verticalAlignOffset } from '../measure/verticalAlign';\nimport type { TextPose } from '../pose';\n\n/** What {@link layoutTextPose} hands `cachedLayoutRuns`. */\nexport interface TextPoseLayoutInput {\n style: ResolvedTextStyle;\n runs: ResolvedRun[];\n opts: LayoutRunsOpts & { justify: boolean };\n}\n\n/**\n * The resolved runs and layout options for `pose`. A text draw command built\n * from these lays out, in the renderer, into exactly the lines\n * {@link layoutTextPose} reports.\n *\n * `scale` is the view scale a `{ px }` `fontSize` or `letterSpacing` resolves\n * against. Everything past this point is world units, so a caller that\n * measures, hit-tests or paints one pose has to pass the same scale to each\n * or they disagree.\n */\nexport function textPoseLayoutInput(pose: TextPose, scale = 1): TextPoseLayoutInput {\n const style = resolveTextStyle(pose.style, { fill: pose.fill, stroke: pose.stroke }, scale);\n // Empty runs are not a styling, so they fall back to the plain string\n // rather than lay out nothing.\n const source = pose.runs && pose.runs.length > 0 ? pose.runs : pose.text;\n return {\n style,\n runs: resolveRuns(toRuns(source), style, scale),\n opts: {\n maxWidth: style.wrap ? pose.width : Infinity,\n alignWidth: pose.width,\n lineHeight: style.lineHeight,\n align: style.align,\n direction: style.direction,\n tabSize: style.tabSize,\n justify: style.align === 'justify',\n },\n };\n}\n\n/** A text pose laid out. */\nexport interface TextPoseLayout {\n /** Origin-relative, shared with the layout cache — treat as immutable. */\n laid: LaidOutRuns;\n /** World position of the layout's origin: `pose.x`, and `pose.y` shifted by\n * `verticalAlign` within the pose height. */\n x: number;\n y: number;\n}\n\n/** The lines `pose` lays out into, and where they sit in world space. */\nexport function layoutTextPose(pose: TextPose, scale = 1): TextPoseLayout {\n const { runs, opts } = textPoseLayoutInput(pose, scale);\n const laid = cachedLayoutRuns(runs, opts);\n return {\n laid,\n x: pose.x,\n y: pose.y + verticalAlignOffset(pose.verticalAlign, pose.height, laid.bounds.height),\n };\n}\n","/**\n * What to draw for laid-out text: which tier paints each glyph, which glyphs\n * can be staged together, and the decoration rules. Layout places the glyphs\n * and knows nothing of this; no decision here moves one.\n *\n * Underline, strikethrough and overline come out as solid rectangles built\n * from pen positions, not from quad extents: quads exist only for glyphs with\n * ink, so a decorated stretch's spaces would punch holes in a rule derived\n * from them.\n */\nimport {\n faceMetricsOf, glyphOutline, resolveFontVariant, type FaceMetrics, type FontStyle,\n} from '@weasel-js/font';\nimport {\n fillHasInk, paintKey, strokeHasInk, strokeKey, type Fill, type Stroke,\n} from '@weasel-js/paint';\nimport type { ResolvedRun } from '../runs/resolveRuns';\nimport { lineDecorations, type DecorationKind } from './decorationMetrics';\nimport type { LaidOutRuns, PlacedGlyph } from './layoutRuns';\n\n/** One textured glyph quad, relative to the text's own top-left. */\nexport interface LaidOutQuad {\n x0: number; y0: number; x1: number; y1: number;\n u0: number; v0: number; u1: number; v1: number;\n /** The glyph's baseline. The synthetic-italic skew leans vertices about it. */\n baselineY: number;\n}\n\n/**\n * One glyph the renderer should tessellate rather than sample.\n *\n * `d` is em-space SVG path data — 1 unit is 1 em, y grows down, origin on the\n * baseline at the pen. Placing it is therefore a uniform scale by `scale`\n * followed by a translate to `(x, baselineY)`. `key` identifies the cached\n * tessellation — face identity plus codepoint.\n */\nexport interface LaidOutOutlineGlyph {\n d: string;\n key: string;\n /** Pen position: where em-space x = 0 lands, in world units. */\n x: number;\n /** The glyph's baseline: where em-space y = 0 lands, in world units. */\n baselineY: number;\n /** World units per em — the glyph's `fontSize`, since em space is unit-scale. */\n scale: number;\n}\n\n/**\n * Glyphs that share a resolved face, glyph source and paint, so a renderer\n * can bind once for all of them. Groups come in the order their first glyph\n * appears, line by line in visual order, and paint in that order.\n */\nexport interface LaidOutGroup {\n /** Resolved atlas family — may differ from the requested family when the\n * cross-family fallback policy substituted a default. A renderer looks the\n * atlas up by this, exactly. */\n family: string;\n /** Resolved variant — matches the registered atlas and the texture-cache key. */\n weight: number;\n style: FontStyle;\n /** Gap between the request and the resolved match, for the renderer to fake. */\n synthetic: { bold: boolean; italic: boolean };\n /** Which glyph source this group binds: a baked MSDF atlas, the runtime\n * canvas-SDF dynamic atlas, tessellated font outlines, or the dynamic\n * atlas's color pages, whose quads are emoji painted in their own colors. */\n source: 'atlas' | 'canvas' | 'outline' | 'color';\n /** Dynamic-atlas page index for 'canvas' and 'color' groups, each in its\n * own set of pages; 0 for the others. */\n page: number;\n /** The run's fill. It holds no paint — `null`, or a fill without one — only\n * on an `'outline'` group carrying a stroke, since nothing else can put ink\n * down without a fill. A `'color'` group takes its opacity and nothing else\n * from it. */\n fill: Fill | null;\n /** Outline painted over the glyphs. Only ever set on an `'outline'` group —\n * the SDF tiers have no geometry to stroke, which is why a stroke pulls its\n * run onto the outline tier at any size. A run the tier cannot serve at all\n * (no registered outlines, synthetic bold) stays on the atlas, unstroked. */\n stroke?: Stroke;\n /** Textured glyph quads. Always empty for an `'outline'` group. */\n quads: LaidOutQuad[];\n /** Outline geometry. Always empty for an `'atlas'` / `'canvas'` group. */\n glyphs: LaidOutOutlineGlyph[];\n}\n\n/**\n * One decoration rule: an axis-aligned solid rectangle in the same space as\n * `LaidOutQuad`. Never spans a line break, and carries the fill of the run(s)\n * it decorates so the rule follows the text color.\n */\nexport interface LaidOutDecoration {\n kind: DecorationKind;\n x0: number; y0: number; x1: number; y1: number;\n fill: Fill;\n}\n\n/** Options for {@link paintRuns}. */\nexport interface PaintRunsOpts {\n /**\n * World-space `fontSize` at or above which glyphs are emitted as outline\n * geometry, when the resolved face has outlines registered. Omit (the\n * default) to keep every glyph on its SDF tier.\n *\n * Ignored for a family that resolved to the outline tier because it has no\n * atlas: there the geometry is the only rendering.\n */\n outlineMinSize?: number;\n}\n\n/** What {@link paintRuns} returns. Relative to the text's own top-left, as the layout is. */\nexport interface PaintedRuns {\n groups: LaidOutGroup[];\n /** Decoration rules, in line order; within a stretch, underline then\n * strikethrough then overline. Empty when nothing is decorated. */\n decorations: LaidOutDecoration[];\n}\n\n/**\n * Em-space outline for `g`, or `null` to leave it on its SDF tier. Decided per\n * glyph, so a face the resolver reports as atlas or canvas can still serve it.\n */\nexport function glyphOutlineD(g: PlacedGlyph, run: ResolvedRun, minSize: number | undefined): string | null {\n if (g.glyph?.color) return null;\n const { family, weight, style } = g.resolved.resolved;\n // An outline-only run has no atlas behind it. Every gate below trades one\n // rendering for another; here there is no other, so gating would paint\n // nothing at all.\n if (g.resolved.source === 'outline') return glyphOutline(family, weight, style, g.cp);\n // A slot the layout left empty has no width to draw in: an outline there\n // would land on top of its neighbor.\n if (g.glyph === null) return null;\n if (minSize === undefined) return null;\n // A stroked run ignores the size gate: the SDF tiers have no geometry to\n // stroke, so leaving it below the threshold drops the outline asked for.\n // Gated on the run's size, so a small-caps word is not split across tiers.\n if (run.fontSize < minSize && !strokeHasInk(run.stroke)) return null;\n // Synthetic bold is an SDF threshold shift, and a path has no threshold.\n // Painting the regular weight instead would make text get *lighter* as\n // you zoom past the threshold. Synthetic italic is a shear, exact on\n // geometry, and the renderer applies it.\n if (g.resolved.synthetic.bold) return null;\n return glyphOutline(family, weight, style, g.cp);\n}\n\n/**\n * The atlas quad for `g`, or null when it has nothing to sample: no atlas\n * record, a zero-area glyph, or a dynamic glyph not baked yet.\n */\nexport function glyphQuad(g: PlacedGlyph): LaidOutQuad | null {\n const { font, glyph } = g;\n if (font === null || glyph === null || glyph.width === 0 || glyph.page < 0) return null;\n const scale = g.fontSize / g.metrics.size;\n const x0 = g.x + glyph.xoffset * scale;\n // `yoffset` is measured from the line top in the atlas's own frame, so\n // subtracting that frame's baseline hangs the glyph off its own.\n const y0 = g.baselineY + (glyph.yoffset - g.metrics.base) * scale;\n return {\n x0, y0, x1: x0 + glyph.width * scale, y1: y0 + glyph.height * scale,\n u0: glyph.x / font.common.scaleW,\n v0: glyph.y / font.common.scaleH,\n u1: (glyph.x + glyph.width) / font.common.scaleW,\n v1: (glyph.y + glyph.height) / font.common.scaleH,\n baselineY: g.baselineY,\n };\n}\n\n/** Each run's own face, which places its rules: a glyph's `resolved` may be a\n * per-glyph fallback. */\nexport function runFaces(runs: readonly ResolvedRun[]): (run: number) => FaceMetrics | undefined {\n const faces = runs.map((r) => faceMetricsOf(resolveFontVariant(r.fontFamily, r.fontWeight, r.fontStyle)));\n return (run) => faces[run];\n}\n\nfunction groupFor(\n groups: Map<string, LaidOutGroup>,\n g: PlacedGlyph,\n run: ResolvedRun,\n source: LaidOutGroup['source'],\n): LaidOutGroup {\n const { family, weight, style } = g.resolved.resolved;\n const { synthetic } = g.resolved;\n const page = source === 'outline' ? 0 : g.glyph!.page;\n // Only the outline tier can paint a stroke; an SDF group carrying one would\n // be a promise the renderer cannot keep.\n const stroke = source === 'outline' && strokeHasInk(run.stroke) ? run.stroke : undefined;\n const key = `${family}|${weight}|${style}|${synthetic.bold ? 1 : 0}${synthetic.italic ? 1 : 0}`\n + `|${paintKey(run.fill?.paint)}|${strokeKey(stroke)}|${source}|${page}`;\n let group = groups.get(key);\n if (!group) {\n group = {\n family, weight, style, synthetic: { ...synthetic }, source, page,\n fill: run.fill,\n ...(stroke ? { stroke } : {}),\n quads: [], glyphs: [],\n };\n groups.set(key, group);\n }\n return group;\n}\n\n/**\n * Derive what to draw for `laid`, the layout of `runs` — or of runs that\n * differ from them only in paint and decoration, which a layout does not read.\n */\nexport function paintRuns(\n laid: LaidOutRuns,\n runs: readonly ResolvedRun[],\n opts: PaintRunsOpts = {},\n): PaintedRuns {\n const groups = new Map<string, LaidOutGroup>();\n const decorations: LaidOutDecoration[] = [];\n const faceOf = runFaces(runs);\n // A rule is a solid rect with only a fill to paint it.\n const rulePaint = (run: number): string | null =>\n (fillHasInk(runs[run].fill) ? paintKey(runs[run].fill!.paint) : null);\n\n for (const line of laid.lines) {\n for (const g of line.glyphs) {\n const run = runs[g.run];\n // Asked before the quad: a dynamic glyph still waiting for its bake has\n // no atlas rect, but its outline is available right now.\n const d = glyphOutlineD(g, run, opts.outlineMinSize);\n // An unfilled run paints through its stroke, and only tessellated\n // geometry can carry one. An atlas quad would paint the fill that was\n // refused, so it gets none.\n if (!fillHasInk(run.fill) && !(d !== null && strokeHasInk(run.stroke))) continue;\n if (d !== null) {\n const { family, weight, style } = g.resolved.resolved;\n groupFor(groups, g, run, 'outline').glyphs.push({\n d, key: `${family}|${weight}|${style}|${g.cp}`,\n x: g.x, baselineY: g.baselineY, scale: g.fontSize,\n });\n continue;\n }\n const quad = glyphQuad(g);\n if (quad) groupFor(groups, g, run, g.glyph?.color ? 'color' : g.resolved.source).quads.push(quad);\n }\n for (const rule of lineDecorations(line.glyphs, runs, faceOf, rulePaint)) {\n const { run, ...rect } = rule;\n decorations.push({ ...rect, fill: runs[run].fill! });\n }\n }\n return { groups: [...groups.values()], decorations };\n}\n","/**\n * `paintRuns`, memoized against the layout it was derived from.\n *\n * Kept apart from the layout cache because the two go stale for different\n * reasons: a recolor, a zoom across the outline threshold, or a dynamic bake\n * landing changes what is drawn and leaves every glyph where it was.\n */\nimport { glyphGeneration } from '@weasel-js/font';\nimport { paintKey, strokeKey } from '@weasel-js/paint';\nimport type { ResolvedRun } from '../runs/resolveRuns';\nimport type { LaidOutRuns } from './layoutRuns';\nimport { paintRuns, type PaintedRuns, type PaintRunsOpts } from './paintRuns';\n\n/** Paintings held for one layout on behalf of runs arrays that have since\n * gone, before the least recently used is dropped. Sized for a palette. */\nexport const PAINT_CACHE_VARIANT_LIMIT = 32;\n\ninterface Painting {\n /** `glyphGeneration()` when it was painted. */\n generation: number;\n key: string;\n painted: PaintedRuns;\n}\n\n/**\n * Two tiers, as the layout cache has and for the same reason. A runs array\n * that stays put, which is what the renderer is handed, keeps its own painting\n * for as long as it and its layout both live: any number of labels can share\n * one layout and none evicts another. Runs built fresh on every call can only\n * be found by what they paint, in a bounded map per layout.\n *\n * Both hang off the layout weakly and hold no reference back to it, so\n * neither keeps one the layout cache has let go.\n */\nconst own = new WeakMap<readonly ResolvedRun[], WeakMap<LaidOutRuns, Painting>>();\nconst shared = new WeakMap<LaidOutRuns, Map<string, Painting>>();\n\n/**\n * How many of the distinct font sizes present in `runs` reach `min`. The\n * threshold reaches `paintRuns` through one comparison against a run's size,\n * and the count is monotonic in `min` over fixed runs, so equal counts mean\n * the same runs cleared it. That keeps an entry across every zoom that crosses\n * no run size, where keying on `min` itself would miss on every frame.\n * Stroked runs need no term of their own: a stroke pulls its run onto the\n * outline tier at every `min`.\n *\n * `-1` is an absent threshold, which must stay distinct from one no run\n * reaches: an outline-only face aside, neither draws outlines, but only the\n * first leaves a stroked run on its atlas.\n */\nfunction outlineBucket(runs: readonly ResolvedRun[], min: number | undefined): number {\n if (min === undefined) return -1;\n const sizes = new Set<number>();\n for (const r of runs) sizes.add(r.fontSize);\n let n = 0;\n for (const size of sizes) if (size >= min) n++;\n return n;\n}\n\n/** Everything `paintRuns` reads from the runs that their layout does not. */\nfunction variantKey(runs: readonly ResolvedRun[], opts: PaintRunsOpts): string {\n let out = `${outlineBucket(runs, opts.outlineMinSize)}`;\n for (const r of runs) {\n out += `|${r.underline ? 1 : 0}${r.strikethrough ? 1 : 0}${r.overline ? 1 : 0}`\n + `${paintKey(r.fill?.paint)}|${strokeKey(r.stroke)}`;\n }\n return out;\n}\n\n/**\n * {@link paintRuns}, reusing the previous result while the paints, the outline\n * threshold's effect, and the glyphs available are what they were. `laid` must\n * be the layout of `runs`, as for `paintRuns`.\n *\n * **The result is shared and must be treated as immutable.**\n */\nexport function cachedPaintRuns(\n laid: LaidOutRuns,\n runs: readonly ResolvedRun[],\n opts: PaintRunsOpts = {},\n): PaintedRuns {\n const generation = glyphGeneration();\n const key = variantKey(runs, opts);\n const fresh = (p: Painting | undefined): p is Painting =>\n p !== undefined && p.generation === generation && p.key === key;\n\n let byLayout = own.get(runs);\n if (byLayout === undefined) {\n byLayout = new WeakMap();\n own.set(runs, byLayout);\n }\n const mine = byLayout.get(laid);\n if (fresh(mine)) return mine.painted;\n\n let byKey = shared.get(laid);\n if (byKey === undefined) {\n byKey = new Map();\n shared.set(laid, byKey);\n }\n let painting = byKey.get(key);\n // Deleted either way, so that setting it below makes it the youngest.\n byKey.delete(key);\n if (!fresh(painting)) painting = { generation, key, painted: paintRuns(laid, runs, opts) };\n if (byKey.size >= PAINT_CACHE_VARIANT_LIMIT) byKey.delete(byKey.keys().next().value!);\n byKey.set(key, painting);\n byLayout.set(laid, painting);\n return painting.painted;\n}\n","/**\n * Wrap-aware text measurement for a 2D context. Lines end where `layoutRuns`\n * ends them, with widths from `ctx.measureText` plus tracking. A word wider\n * than `maxWidth` is emitted on its own line unbroken.\n *\n * `lineStarts` is the UTF-16 offset of each line's first character in `text`.\n * Trailing spaces and tabs hang and are not included in `lines[i]`; neither is\n * the hard break that closed it.\n *\n * A tab runs to its next stop and `fillText` draws one as a single space, so\n * paint a line from `spans[i]` and not from `lines[i]`.\n *\n * The caller owns the `ctx.font` setup — pass a context whose `font`\n * already matches `style` (use `fontString(style)`).\n */\n\nimport type { ResolvedTextStyle } from '../textStyle';\nimport { graphemeCount } from './graphemes';\nimport { hangs, wrapLines } from '../layout/lineBreak/wrapLines';\nimport { widthWithTabs, type TabStop } from '../layout/tabStops';\n\n/**\n * Advance width of `text` in world units, tracking included.\n *\n * `letter-spacing` is not part of the CSS `font` shorthand, so `ctx` measures\n * glyphs only. `letterSpacing` is added after every grapheme cluster\n * including the last, as `layoutRuns` does — every 2D-side width has to go\n * through here or the two paths disagree about where a line breaks.\n */\nexport function measuredWidth(\n ctx: CanvasRenderingContext2D,\n text: string,\n style: ResolvedTextStyle,\n): number {\n return ctx.measureText(text).width\n + (style.letterSpacing === 0 ? 0 : graphemeCount(text) * style.letterSpacing);\n}\n\n/** A stretch of a line between tabs, and how far into the line it starts. */\nexport interface MeasuredSpan {\n text: string;\n x: number;\n}\n\n/** Result of `measureText`: wrapped lines, per-line source offsets, and total block height. */\nexport interface MeasuredText {\n lines: string[];\n /** Per line, what to paint and where: its text split at its tabs. */\n spans: MeasuredSpan[][];\n lineStarts: number[];\n height: number;\n}\n\n/** Wrap `text` against `maxWidth` at the break opportunities `layoutRuns` wraps at, measuring with `ctx`. */\nexport function measureText(\n ctx: CanvasRenderingContext2D,\n text: string,\n maxWidth: number,\n style: ResolvedTextStyle,\n): MeasuredText {\n const cps: number[] = [];\n /** UTF-16 offset of each code point, then `text.length`. */\n const at: number[] = [];\n let u = 0;\n for (const ch of text) {\n cps.push(ch.codePointAt(0)!);\n at.push(u);\n u += ch.length;\n }\n at.push(u);\n\n const flatWidth = (start: number, end: number): number =>\n measuredWidth(ctx, text.slice(at[start], at[end]), style);\n const tabs: number[] = [];\n cps.forEach((cp, k) => { if (cp === 9) tabs.push(k); });\n const space = tabs.length === 0 ? 0 : ctx.measureText(' ').width;\n const tab: TabStop = { stop: style.tabSize * (space + style.letterSpacing), min: space / 2 };\n const widthOf = (\n start: number, end: number, piece?: (start: number, end: number, x: number) => void,\n ): number => widthWithTabs(start, end, tabs, () => tab, flatWidth, piece);\n\n const wrapped = wrapLines(cps, maxWidth, (start, end) => widthOf(start, end));\n const lines: string[] = [];\n const spans: MeasuredSpan[][] = [];\n for (const l of wrapped) {\n let end = l.end;\n while (end > l.start && hangs(cps[end - 1])) end--;\n lines.push(text.slice(at[l.start], at[end]));\n const row: MeasuredSpan[] = [];\n widthOf(l.start, end, (from, to, x) => row.push({ text: text.slice(at[from], at[to]), x }));\n spans.push(row);\n }\n const lineStarts = wrapped.map((l) => at[l.start]);\n const height = lines.length * style.fontSize * style.lineHeight;\n return { lines, spans, lineStarts, height };\n}\n","import type { TextStyle } from '../textStyle';\nimport { resolveTextStyle } from '../textStyle';\nimport { resolveRuns } from '../runs/resolveRuns';\nimport { cachedLayoutRuns } from '../layout/layoutCache';\n\n/** Options for `measureTextBounds`. */\nexport interface MeasureTextBoundsOpts {\n /** Wrap width; words exceeding it start a new line. Default `Infinity` (no wrap). */\n maxWidth?: number;\n /** Overrides `style`'s `lineHeight` multiplier for this measurement. */\n lineHeight?: number;\n /** View scale any `{ px }` size in `style` resolves against. Default 1,\n * which measures a `{ px }` size as that many world units. */\n scale?: number;\n}\n\n/**\n * Measure how the GL/MSDF renderer will lay out a single plain-text string,\n * using the registered font atlas metrics. Mirrors `textCommand` exactly, so\n * the returned bounds match what actually gets drawn.\n *\n * Returns `{ width, height }` in the same units as `style.fontSize`. The font\n * must already be registered via `registerFont`; an unregistered family falls\n * back to the atlas fallback glyph (and warns).\n */\nexport function measureTextBounds(\n text: string,\n style?: TextStyle,\n opts?: MeasureTextBoundsOpts,\n): { width: number; height: number } {\n const resolved = resolveTextStyle(style, undefined, opts?.scale);\n const runs = resolveRuns([{ text }], resolved, opts?.scale);\n const { bounds } = cachedLayoutRuns(runs, {\n maxWidth: opts?.maxWidth ?? Infinity,\n lineHeight: opts?.lineHeight ?? resolved.lineHeight,\n align: resolved.align,\n direction: resolved.direction,\n tabSize: resolved.tabSize,\n });\n // Copied: the layout behind it is shared, and handing a caller a mutable\n // reference into a cache entry is how one measurement corrupts the next.\n return { width: bounds.width, height: bounds.height };\n}\n","/**\n * Where a text node's lines actually sit inside its pose box.\n *\n * A text pose is a layout box, not a bounding box, and anything that treats\n * the pose as the node's extent — picking, lasso, clipping, SVG export —\n * claims its empty space. The numbers come from `layoutTextPose`, the layout\n * every painter of a text pose draws, so the boxes cannot drift from what is\n * painted.\n *\n * These are line boxes, not ink boxes: each is `fontSize * lineHeight` tall\n * from the pen's line top. Ink can escape vertically at a `lineHeight` low\n * enough, which is the right trade for hit-testing, where a box that hugged\n * the ink would make an `x` harder to click than an `X`.\n */\n\nimport type { Rect } from '@weasel-js/geom';\nimport { layoutTextPose } from '../layout/textPoseLayout';\nimport type { TextPose } from '../pose';\n\n/** Options for {@link textLineBoxes}. */\nexport interface TextLineBoxesOpts {\n /** Grow every box by this much on all four sides (world units). Default 0.\n * Picking wants a little slack so a single hairline row of text is still\n * grabbable; clipping and export want none. */\n padding?: number;\n /** Keep boxes for blank lines (zero width). Default `false` — a blank line\n * covers no area, so for hit-testing and silhouettes it is noise. Pass\n * `true` when the indices have to line up with the laid-out lines. */\n includeEmpty?: boolean;\n}\n\n/** Per-line rectangles for a text pose, in world units, in layout order. */\nexport function textLineBoxes(pose: TextPose, opts: TextLineBoxesOpts = {}): Rect[] {\n const padding = opts.padding ?? 0;\n const { laid, x: dx, y: dy } = layoutTextPose(pose);\n\n const out: Rect[] = [];\n for (const line of laid.lines) {\n if (!opts.includeEmpty && line.x1 <= line.x0) continue;\n out.push({\n x: line.x0 + dx - padding,\n y: line.y0 + dy - padding,\n width: line.x1 - line.x0 + padding * 2,\n height: line.y1 - line.y0 + padding * 2,\n });\n }\n return out;\n}\n","/**\n * Hit-testing for text nodes. `caretIndexAt` reads the caret stops off\n * `layoutTextPose`, the layout the painters draw and `textLineBoxes` picks\n * against, so the caret cannot land on a different line — or between different\n * glyphs — than the one under the pointer.\n */\n\nimport type { LaidOutCell } from './layout/layoutRuns';\nimport { layoutTextPose } from './layout/textPoseLayout';\nimport type { TextPose } from './pose';\n\n/**\n * Merge neighboring cells a caret cannot stop between into one cell spanning\n * them: the cells of one grapheme cluster (a letter and its combining mark,\n * the parts of a joined emoji), and cells drawn from one source character\n * (the two `S`s an uppercased `ß` becomes).\n */\nfunction caretCells(cells: readonly LaidOutCell[]): LaidOutCell[] {\n const out: LaidOutCell[] = [];\n for (const c of cells) {\n const prev = out[out.length - 1];\n if (prev && (!prev.clusterEnd || (prev.srcIndex === c.srcIndex && prev.srcEnd === c.srcEnd))) {\n const x0 = Math.min(prev.x, c.x);\n const x1 = Math.max(prev.x + prev.advance, c.x + c.advance);\n out[out.length - 1] = {\n ...prev, x: x0, advance: x1 - x0,\n srcIndex: Math.min(prev.srcIndex, c.srcIndex), srcEnd: Math.max(prev.srcEnd, c.srcEnd),\n clusterEnd: c.clusterEnd,\n };\n } else {\n out.push(c);\n }\n }\n return out;\n}\n\n/** Options for `pointInTextPose`. */\nexport interface PointInTextPoseOpts {\n /** Extra padding (world units) added to the rect on all sides. Default 0. */\n padding?: number;\n}\n\n/** Coarse pose-rect hit-test for a text node — suitable for click-to-edit dispatch. */\nexport function pointInTextPose(\n x: number,\n y: number,\n pose: TextPose,\n opts: PointInTextPoseOpts = {},\n): boolean {\n const p = opts.padding ?? 0;\n return (\n x >= pose.x - p &&\n x <= pose.x + pose.width + p &&\n y >= pose.y - p &&\n y <= pose.y + pose.height + p\n );\n}\n\n/**\n * Map a world-space point inside `pose` to a character offset into the pose's\n * text (0..length). Clicks above the first line clamp to 0; clicks below the\n * last line clamp to the end. Within a line, the caret lands between two\n * glyphs at whichever side of the advance cell's midpoint `x` falls on.\n *\n * Honors `pose.runs` (a mixed-size line snaps on the cells each run actually\n * produced) and `pose.verticalAlign`. The offset is into the runs'\n * concatenated text, which `TextPose` requires to equal `pose.text`.\n */\nexport function caretIndexAt(x: number, y: number, pose: TextPose): number {\n const { laid, x: dx, y: dy } = layoutTextPose(pose);\n const lines = laid.lines;\n if (lines.length === 0) return 0;\n\n const last = lines[lines.length - 1];\n if (y < dy + lines[0].y0) return lines[0].cells[0]?.srcIndex ?? lines[0].srcEnd;\n if (y >= dy + last.y1) return last.srcEnd;\n\n let line = last;\n for (const candidate of lines) {\n if (y < dy + candidate.y1) { line = candidate; break; }\n }\n\n // Cells are in logical order and their x values need not ascend, so the\n // sweep has to be in visual order and each cell's own extent is what it is\n // tested against — the next cell along is not its right edge.\n if (line.cells.length === 0) return line.srcEnd;\n const cells = caretCells(line.cells);\n const visual = cells.map((_, i) => i).sort((a, b) => cells[a].x - cells[b].x);\n\n for (const i of visual) {\n const c = cells[i];\n if (x >= dx + c.x + c.advance / 2) continue;\n // A right-to-left cell reads the other way, so its visually-leading half\n // is the character's logical end.\n return c.level % 2 === 1 ? c.srcEnd : c.srcIndex;\n }\n const trailing = cells[visual[visual.length - 1]];\n return trailing.level % 2 === 1 ? trailing.srcIndex : trailing.srcEnd;\n}\n","/**\n * Resize a text node's pose to fit its content.\n *\n * - `axis: 'height'` (default): keep `pose.width`, recompute `height` as\n * the block height plus optional vertical padding — wrapped at the width\n * inside the horizontal padding when the style declares `wrap`.\n * - `axis: 'both'`: ignore wrapping; recompute both `width` (longest\n * `\\n`-split line) and `height` (line count × line height) plus padding.\n *\n * `pose.x` / `pose.y` are preserved; for a different growth direction, adjust\n * `x` / `y` after calling.\n */\n\nimport { layoutTextPose } from './layout/textPoseLayout';\nimport type { TextPose } from './pose';\n\n/** Options for `fitTextPose`. */\nexport interface FitTextPoseOptions {\n /** Which axis (or axes) to recompute. Default: `'height'`. */\n axis?: 'height' | 'both';\n /** Padding (world units) added to all four sides. Default 0. */\n padding?: number | { x?: number; y?: number };\n}\n\n/** Recompute a `TextPose`'s `width`/`height` to fit its content; pure helper, doesn't mutate scene state. */\nexport function fitTextPose(\n pose: TextPose,\n opts: FitTextPoseOptions = {},\n): TextPose {\n const axis = opts.axis ?? 'height';\n const { padX, padY } = resolvePadding(opts.padding);\n const { bounds } = layoutTextPose(axis === 'height'\n ? { ...pose, width: pose.width - padX * 2 }\n : { ...pose, style: { ...pose.style, wrap: false } }).laid;\n if (axis === 'height') return { ...pose, height: bounds.height + padY * 2 };\n return {\n ...pose,\n width: bounds.width + padX * 2,\n height: bounds.height + padY * 2,\n };\n}\n\nfunction resolvePadding(p: FitTextPoseOptions['padding']): { padX: number; padY: number } {\n if (p == null) return { padX: 0, padY: 0 };\n if (typeof p === 'number') return { padX: p, padY: p };\n return { padX: p.x ?? 0, padY: p.y ?? 0 };\n}\n","import type { TextRenderer } from './markdownText';\n\n\n/** Visual options for `renderLabel`. */\nexport interface LabelOptions {\n align?: 'center' | 'left';\n fontSize?: number;\n renderText?: TextRenderer;\n /** Override the pill width (content width, excluding padding). */\n width?: number;\n /** Override the pill height (content height, excluding padding). */\n height?: number;\n /** Horizontal padding inside the pill. Default 4 (screen-pixel default). */\n padX?: number;\n /** Vertical padding inside the pill. Default 1 (screen-pixel default). */\n padY?: number;\n /** Corner radius of the pill background. Default 3 (screen-pixel default). */\n cornerRadius?: number;\n}\n\n/** Render a text label with a 75%-opaque black pill background and white text. */\nexport function renderLabel(\n ctx: CanvasRenderingContext2D,\n text: string,\n x: number,\n y: number,\n options: LabelOptions = {},\n): void {\n const {\n align = 'center',\n fontSize = 13,\n renderText,\n width,\n height,\n padX = 4,\n padY = 1,\n cornerRadius = 3,\n } = options;\n\n ctx.save();\n ctx.font = `${fontSize}px sans-serif`;\n ctx.textBaseline = 'top';\n const contentW = width ?? ctx.measureText(text).width;\n const contentH = height ?? fontSize;\n const w = contentW + padX * 2;\n const h = contentH + padY * 2;\n const rx = align === 'center' ? x - w / 2 : x - padX;\n\n ctx.fillStyle = 'rgba(0, 0, 0, 0.75)';\n ctx.beginPath();\n ctx.roundRect(rx, y - padY, w, h, cornerRadius);\n ctx.fill();\n\n ctx.textAlign = align === 'center' ? 'center' : 'left';\n const tx = align === 'center' ? x : x;\n (renderText ?? defaultLabelTextRenderer)(ctx, text, tx, y);\n ctx.restore();\n}\n\n/** Default `TextRenderer` used by `renderLabel`: white fill, no styling. */\nexport const defaultLabelTextRenderer: TextRenderer = (ctx, text, x, y) => {\n ctx.fillStyle = '#FFFFFF';\n ctx.fillText(text, x, y);\n};\n","/**\n * The kit's one answer to \"is this node text?\": its data carries a string\n * `text`. Routing, the `textEdit` dep, and `useSceneTextEdit` all ask it.\n */\nexport function isTextData(data: unknown): data is { text: string } {\n return typeof data === 'object' && data !== null\n && typeof (data as { text?: unknown }).text === 'string';\n}\n","import { resolveScreenLength } from '@weasel-js/paint';\nimport { markdownToRuns, type StyledRun } from './runs';\nimport { cssFamilyName, faceMetricsFor, type FaceMetrics } from '@weasel-js/font';\nimport { numericWeight, scriptMetrics } from './runs/resolveRuns';\nimport { DECORATION_KINDS, decorationRule, type DecorationKind } from './layout/decorationMetrics';\nimport { transformRunTexts } from './runs/textTransform';\nimport { smallCapsScale, smallCapsText } from './runs/smallCaps';\nimport { hangs, wrapLines } from './layout/lineBreak/wrapLines';\nimport { DEFAULT_TAB_SIZE, tabAdvance, widthWithTabs, type TabStop } from './layout/tabStops';\n\nexport type { StyledRun };\n\n/** Width-measurement strategy for `layoutMarkdown`; canvas-backed default supplied by `createMarkdownRenderer`. */\nexport type MeasureFn = (text: string, fontSize: number, bold: boolean, italic: boolean) => number;\n\n/** The face a run's rules and script presets come from, for `layoutMarkdown`.\n * `createMarkdownRenderer` supplies one that looks the family up in the font\n * registry, so a registered face places them as it does on the GL tier. */\nexport type FaceMetricsFn = (bold: boolean, italic: boolean) => FaceMetrics | undefined;\n\n/** A `StyledRun` with its resolved size and its position relative to the\n * start of its line: `x` along the line, `y` off its baseline. */\nexport interface PositionedRun extends StyledRun {\n x: number;\n /** Advance width, as the layout's `MeasureFn` measured it. */\n width: number;\n /** Baseline offset, positive down — a superscript's is negative. Add it to\n * the line's baseline when painting. */\n y: number;\n /** The run's font size in px, with `fontScale` and `script` already folded\n * in. Resolved once here so layout and paint cannot disagree about it. */\n size: number;\n /** The face that placed the run's script and places its rules. */\n face?: FaceMetrics;\n}\n\n/**\n * A run's size and baseline offset, resolved the way `resolveRuns` resolves\n * them for the GL path: an absolute `fontSize` wins over a multiplier, and\n * the rise is measured against the *inherited* size so it does not shrink\n * along with the run.\n */\nfunction runMetrics(run: StyledRun, fontSize: number, face: FaceMetrics | undefined): { size: number; y: number } {\n const script = run.script ? scriptMetrics(face)[run.script] : undefined;\n const scale = run.fontScale ?? script?.size ?? 1;\n const shiftEm = run.baselineShift ?? script?.shift ?? 0;\n return {\n size: run.fontSize !== undefined\n ? resolveScreenLength(run.fontSize, 1)\n : fontSize * scale,\n // Canvas y grows downward; a positive shift is a rise. Guarded so an\n // unshifted run reports 0 rather than -0.\n y: shiftEm === 0 ? 0 : -shiftEm * fontSize,\n };\n}\n\n/** A run as `layoutMarkdown` walks it: small caps has split it where its\n * size changes, and marked the pieces drawn at the small size. */\ntype Segment = StyledRun & { smallCaps?: true; source?: StyledRun };\n\n/** A single laid-out line of text: its positioned runs, total width, and computed line height. */\nexport interface LayoutLine {\n runs: PositionedRun[];\n width: number;\n height: number;\n}\n\n/** Output of `layoutMarkdown`: per-line breakdown plus overall block dimensions. */\nexport interface LayoutResult {\n lines: LayoutLine[];\n width: number;\n height: number;\n}\n\n/**\n * Word-wrap parsed runs into lines bounded by `maxWidth`, breaking at the\n * UAX #14 opportunities `layoutRuns` breaks at; pass `Infinity` for\n * single-line layout. A tab is a run of its own, as wide as it takes to reach\n * its next stop, `tabSize` spaces apart.\n */\nexport function layoutMarkdown(\n runs: StyledRun[],\n maxWidth: number,\n fontSize: number,\n measure: MeasureFn,\n lineHeightFactor: number = 1.3,\n faceOf?: FaceMetricsFn,\n tabSize: number = DEFAULT_TAB_SIZE,\n): LayoutResult {\n if (runs.length === 0) return { lines: [], width: 0, height: 0 };\n // No caret reads this layout, so the transformed text simply replaces the source.\n const shown = transformRunTexts(runs.map((r) => r.text), runs.map((r) => r.textTransform ?? 'none'));\n // Small caps splits a run where its size changes, marking the small pieces.\n const segs: Segment[] = [];\n runs.forEach((r, i) => {\n const text = shown[i].text;\n if (r.fontVariantCaps !== 'small-caps') { segs.push(text === r.text ? r : { ...r, text }); return; }\n const caps = smallCapsText(text);\n if (!caps.small) { segs.push({ ...r, text: caps.text }); return; }\n let at = 0;\n for (const piece of caps.text) {\n const small = caps.small[at];\n at += piece.length;\n const prev = segs[segs.length - 1];\n if (prev?.source === r && (prev.smallCaps === true) === small) prev.text += piece;\n else segs.push({ ...r, text: piece, source: r, ...(small ? { smallCaps: true as const } : {}) });\n }\n });\n\n // One sequence across every run, so a break opportunity that depends on a\n // neighbor in the next run is found the way `layoutRuns` finds it.\n const cps: number[] = [];\n /** Per code point: its run, and its UTF-16 span in that run's text. */\n const runOf: number[] = [];\n const startOf: number[] = [];\n const endOf: number[] = [];\n segs.forEach((r, ri) => {\n let at = 0;\n for (const ch of r.text) {\n cps.push(ch.codePointAt(0)!);\n runOf.push(ri);\n startOf.push(at);\n at += ch.length;\n endOf.push(at);\n }\n });\n // Already a screen-pixel layout, so a run's `{ px }` size is its size.\n const placed = segs.map(({ smallCaps, source: _source, ...run }) => {\n const face = faceOf?.(run.bold ?? false, run.italic ?? false);\n const { size: runSize, y } = runMetrics(run, fontSize, face);\n // The run's size holds the line, as on the GL tier, however small its capitals.\n return { run, face, y, runSize, size: smallCaps ? runSize * smallCapsScale(face) : runSize };\n });\n const pieceWidth = (p: Piece): number => {\n const { run, size } = placed[p.run];\n return measure(run.text.slice(p.start, p.end), size, run.bold ?? false, run.italic ?? false);\n };\n\n /** A UTF-16 span of one run's text, set on the current line. */\n interface Piece { run: number; start: number; end: number }\n\n /** Code points `[from, to)` as spans of their runs' texts. */\n function piecesOf(from: number, to: number): Piece[] {\n const out: Piece[] = [];\n for (let k = from; k < to; k++) {\n const last = out[out.length - 1];\n if (last && last.run === runOf[k] && last.end === startOf[k] && cps[k] !== 9 && cps[k - 1] !== 9) {\n out[out.length - 1] = { ...last, end: endOf[k] };\n } else {\n out.push({ run: runOf[k], start: startOf[k], end: endOf[k] });\n }\n }\n return out;\n }\n\n const lines: LayoutLine[] = [];\n\n function commitLine(line: Piece[]) {\n let x = 0;\n let maxSize = 0;\n const positioned: PositionedRun[] = [];\n for (const p of line) {\n const { run, face, size, y, runSize } = placed[p.run];\n const tab = run.text[p.start] === '\\t' ? stopOf(p.run) : null;\n const width = tab ? tabAdvance(x, tab.stop, tab.min) : pieceWidth(p);\n positioned.push({ ...run, text: run.text.slice(p.start, p.end), x, width, y, size, ...(face ? { face } : {}) });\n x += width;\n maxSize = Math.max(maxSize, runSize);\n }\n lines.push({ runs: positioned, width: x, height: (maxSize > 0 ? maxSize : fontSize) * lineHeightFactor });\n }\n\n const stopOf = (run: number): TabStop => {\n const { run: r, size } = placed[run];\n const space = measure(' ', size, r.bold ?? false, r.italic ?? false);\n return { stop: tabSize * space, min: space / 2 };\n };\n const tabs: number[] = [];\n cps.forEach((cp, k) => { if (cp === 9) tabs.push(k); });\n const flatWidth = (start: number, end: number): number =>\n piecesOf(start, end).reduce((w, p) => w + pieceWidth(p), 0);\n const widthOf = (start: number, end: number): number =>\n widthWithTabs(start, end, tabs, (k) => stopOf(runOf[k]), flatWidth);\n for (const line of wrapLines(cps, maxWidth, widthOf)) {\n let end = line.end;\n // A wrapped line's trailing spaces hang past the edge, as they do in `layoutRuns`.\n if (line.wrapped) while (end > line.start && hangs(cps[end - 1])) end--;\n commitLine(piecesOf(line.start, end));\n }\n\n if (lines.length === 0) return { lines: [], width: 0, height: 0 };\n const width = Math.max(...lines.map((l) => l.width));\n const height = lines.reduce((sum, l) => sum + l.height, 0);\n return { lines, width, height };\n}\n\n/** Pluggable text-painting strategy. The default fills white at `(x, y)`; markdown renderers replace this. */\nexport type TextRenderer = (\n ctx: CanvasRenderingContext2D,\n text: string,\n x: number,\n y: number,\n) => void;\n\n/** Font styling options threaded through `createMarkdownRenderer`. */\nexport interface MarkdownFontOptions {\n /** Font-family spec (e.g. `'\"Iowan Old Style\", Georgia, serif'`). Defaults to `sans-serif`. */\n family?: string;\n /** Numeric weight applied to non-bold runs. Bold runs always use `bold`. Default `normal`. */\n weight?: string | number;\n /** Override fill color. When set, used for all runs (italic and bold). */\n color?: string;\n /** Multiplier applied to font size for line height. Default 1.3. */\n lineHeight?: number;\n /** Distance between tab stops, in spaces, as CSS `tab-size`. Default 8. */\n tabSize?: number;\n}\n\nfunction buildFont(\n fontSize: number,\n bold: boolean,\n italic: boolean,\n opts: MarkdownFontOptions = {},\n): string {\n const family = opts.family ?? 'sans-serif';\n const weight = bold ? 'bold' : (opts.weight !== undefined ? String(opts.weight) : 'normal');\n const parts: string[] = [];\n if (italic) parts.push('italic');\n parts.push(weight);\n parts.push(`${fontSize}px ${cssFamilyName(family)}`);\n return parts.join(' ');\n}\n\nfunction canvasMeasure(ctx: CanvasRenderingContext2D, opts: MarkdownFontOptions = {}): MeasureFn {\n return (text, fontSize, bold, italic) => {\n ctx.font = buildFont(fontSize, bold, italic, opts);\n return ctx.measureText(text).width;\n };\n}\n\n/** Distance from the context's current `textBaseline` down to the alphabetic\n * baseline, for the font already set on it; 0 where the metric is missing. */\nfunction alphabeticBaselineBelow(ctx: CanvasRenderingContext2D): number {\n const current = ctx.textBaseline;\n if (current === 'alphabetic') return 0;\n const here = ctx.measureText('').fontBoundingBoxAscent;\n ctx.textBaseline = 'alphabetic';\n const alphabetic = ctx.measureText('').fontBoundingBoxAscent;\n ctx.textBaseline = current;\n const d = alphabetic - here;\n return Number.isFinite(d) ? d : 0;\n}\n\n/** Where a block `width` wide starts, given the x the context aligns it to. */\nfunction blockLeft(ctx: CanvasRenderingContext2D, x: number, width: number): number {\n const rtl = ctx.direction === 'rtl';\n switch (ctx.textAlign) {\n case 'center': return x - width / 2;\n case 'right': return x - width;\n case 'end': return rtl ? x : x - width;\n case 'start': return rtl ? x - width : x;\n default: return x;\n }\n}\n\n/**\n * Build a fill+stroke `TextRenderer` pair, laying the text out once.\n *\n * `text` is markdown, read by `markdownToRuns`, or runs already styled. The\n * block is placed by the context's `textAlign` and each run by its\n * `textBaseline`. The fill pass also paints underline, strikethrough and\n * overline in their run's fill, placed by the same metrics as the GL tier;\n * the stroke pass paints no rules, as on the GL tier.\n */\nexport function createMarkdownRenderer(\n ctx: CanvasRenderingContext2D,\n text: string | StyledRun[],\n fontSize: number,\n maxWidth: number = Infinity,\n fontOpts: MarkdownFontOptions = {},\n): { renderer: TextRenderer; strokeRenderer: TextRenderer; width: number; height: number } {\n const measure = canvasMeasure(ctx, fontOpts);\n const parsed = typeof text === 'string' ? markdownToRuns(text) : text;\n const family = fontOpts.family ?? 'sans-serif';\n const weight = numericWeight(fontOpts.weight ?? 400);\n const faceOf: FaceMetricsFn = (bold, italic) =>\n faceMetricsFor(family, bold ? 700 : weight, italic ? 'italic' : 'normal');\n const layout = layoutMarkdown(parsed, maxWidth, fontSize, measure, fontOpts.lineHeight, faceOf, fontOpts.tabSize);\n\n /** Walk the layout, setting each run's font and handing over its\n * left-aligned paint position and the index of its line. */\n function walk(\n c: CanvasRenderingContext2D,\n x: number,\n y: number,\n drawRun: (run: PositionedRun, rx: number, ry: number, lineIndex: number) => void,\n ): void {\n const align = c.textAlign;\n const left = blockLeft(c, x, layout.width);\n c.textAlign = 'left';\n let lineY = y;\n layout.lines.forEach((line, li) => {\n const lineLeft = left + (layout.width - line.width) / 2;\n for (const run of line.runs) {\n c.font = buildFont(run.size, run.bold ?? false, run.italic ?? false, fontOpts);\n drawRun(run, lineLeft + run.x, lineY + run.y, li);\n }\n lineY += line.height;\n });\n c.textAlign = align;\n }\n\n const renderer: TextRenderer = (_ctx, _text, x, y) => {\n interface Span {\n flags: Record<DecorationKind, boolean>;\n fill: string;\n size: number;\n face: FaceMetrics | undefined;\n baselineY: number;\n line: number;\n x0: number;\n x1: number;\n }\n let span: Span | null = null;\n const flush = (): void => {\n const s = span;\n span = null;\n if (!s || s.x1 <= s.x0) return;\n _ctx.fillStyle = s.fill;\n for (const kind of DECORATION_KINDS) {\n if (!s.flags[kind]) continue;\n const { y0, y1 } = decorationRule(kind, s.baselineY, s.size, s.face);\n _ctx.fillRect(s.x0, y0, s.x1 - s.x0, y1 - y0);\n }\n };\n\n walk(_ctx, x, y, (run, rx, ry, line) => {\n const fill = fontOpts.color\n ?? (run.italic && !run.bold ? 'rgba(255, 255, 255, 0.7)' : '#FFFFFF');\n _ctx.fillStyle = fill;\n _ctx.fillText(run.text, rx, ry);\n\n if (!(run.underline || run.strikethrough || run.overline)) {\n flush();\n return;\n }\n const flags: Record<DecorationKind, boolean> = {\n underline: run.underline ?? false,\n strikethrough: run.strikethrough ?? false,\n overline: run.overline ?? false,\n };\n const baselineY = ry + alphabeticBaselineBelow(_ctx);\n const open = span;\n if (\n open !== null\n && open.line === line\n && open.x1 === rx\n && open.fill === fill\n && open.size === run.size\n && open.face === run.face\n && open.baselineY === baselineY\n && DECORATION_KINDS.every((k) => open.flags[k] === flags[k])\n ) {\n open.x1 = rx + run.width;\n } else {\n flush();\n span = { flags, fill, size: run.size, face: run.face, baselineY, line, x0: rx, x1: rx + run.width };\n }\n });\n flush();\n };\n\n const strokeRenderer: TextRenderer = (_ctx, _text, x, y) => {\n walk(_ctx, x, y, (run, rx, ry) => _ctx.strokeText(run.text, rx, ry));\n };\n\n return { renderer, strokeRenderer, width: layout.width, height: layout.height };\n}\n","/**\n * Range-addressed styling over `StyledRun[]`.\n *\n * Character offsets index the concatenated run text (`runsToPlainText`), and\n * a range is half-open: `[start, end)`. Ranges are clamped, never wrapped,\n * and a collapsed or inverted range (`start >= end`) is empty. Offsets are\n * UTF-16 code units, so a boundary can bisect a surrogate pair.\n *\n * **Run-level flags are additive over the node's `TextStyle`: a run can\n * turn `bold` / `italic` / `underline` / `strikethrough` on, never off.**\n * So a flag is stored only when true, and absent reads as `false`. A run\n * that must be lighter than a bold node says so with its own numeric\n * `fontWeight`, which `bold` is a preset over (see {@link supersededKey}).\n * The decorations have no such primitive, and the tri-state is collapsed by\n * choice, to keep one canonical form per styling. Resolution must therefore\n * read decorations as `run.underline || style.underline`, not `??`.\n *\n * Copies here are shallow: a `fill` object is shared by reference between\n * the input runs, the patch, every run the patch touched, and the value\n * `styleAtRange` reports. Treat `fill` values as immutable.\n */\n\nimport { MIXED, isPlainObject } from '@weasel-js/registry';\nimport type { Mixed } from '@weasel-js/registry';\nimport type { StyledRun } from '../runs';\n\nexport { MIXED };\nexport type { Mixed };\n\n/** Every styleable key of a run, each either a concrete value or MIXED (the\n * runs in the range disagree at that key). */\nexport type RangeStyle = {\n [K in Exclude<keyof StyledRun, 'text'>]?: StyledRun[K] | Mixed;\n};\n\n/** What `applyStyleToRange` writes. */\nexport type RunStylePatch = Partial<Omit<StyledRun, 'text'>>;\n\n/** Every key of a run that carries styling — i.e. everything but `text`. */\nexport type StyleKey = Exclude<keyof StyledRun, 'text'>;\n\nconst STYLE_KEYS = [\n 'bold',\n 'fontWeight',\n 'italic',\n 'underline',\n 'strikethrough',\n 'overline',\n 'fontFamily',\n 'fontSize',\n 'letterSpacing',\n 'fill',\n 'stroke',\n 'script',\n 'baselineShift',\n 'fontScale',\n 'textTransform',\n 'fontVariantCaps',\n] as const satisfies readonly StyleKey[];\n\n// A key missing from STYLE_KEYS is invisible to every function here.\n// `satisfies` only checks the entries that ARE listed, so this makes adding a\n// key to `StyledRun` without adding it here a compile error.\ntype MissingStyleKey = Exclude<StyleKey, (typeof STYLE_KEYS)[number]>;\ntype AssertNoMissingStyleKey = [MissingStyleKey] extends [never] ? true : never;\nconst STYLE_KEYS_ARE_EXHAUSTIVE: AssertNoMissingStyleKey = true;\nvoid STYLE_KEYS_ARE_EXHAUSTIVE;\n\n/** The additive flags: absent and `false` mean the same thing, so both read as `false`. */\nconst FLAG_KEYS: ReadonlySet<StyleKey> = new Set<StyleKey>([\n 'bold',\n 'italic',\n 'underline',\n 'strikethrough',\n 'overline',\n]);\n\n/**\n * Structural equality over the JSON-ish values a run can hold. Assumes\n * `Paint` stays acyclic and plain: a cyclic field would recurse forever.\n */\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((item, i) => deepEqual(item, b[i]));\n }\n if (isPlainObject(a) && isPlainObject(b)) {\n const keys = Object.keys(a);\n if (keys.length !== Object.keys(b).length) return false;\n return keys.every((k) => k in b && deepEqual(a[k], b[k]));\n }\n return false;\n}\n\n/** A run's value at `key`, with flags normalized so absent reads as `false`. */\nfunction valueAt(run: StyledRun, key: StyleKey): StyledRun[StyleKey] {\n const value = run[key];\n if (FLAG_KEYS.has(key)) return (value as boolean | undefined) ?? false;\n return value;\n}\n\n/** The structural values. Everything else is a primitive, and\n * `applyStyleToRange` spreads runs, so reference identity isn't reliable. */\nconst STRUCTURAL_KEYS: ReadonlySet<StyleKey> = new Set<StyleKey>(['fill', 'stroke']);\n\nfunction sameValue(key: StyleKey, a: unknown, b: unknown): boolean {\n return STRUCTURAL_KEYS.has(key) ? deepEqual(a, b) : Object.is(a, b);\n}\n\n/** Do two runs carry the same styling (their `text` aside)? */\nfunction sameStyle(a: StyledRun, b: StyledRun): boolean {\n return STYLE_KEYS.every((key) => sameValue(key, valueAt(a, key), valueAt(b, key)));\n}\n\n/** Total character length of a run array — the domain of its offsets. */\nfunction totalLength(runs: readonly StyledRun[]): number {\n let n = 0;\n for (const run of runs) n += run.text.length;\n return n;\n}\n\n/**\n * The styling shared by every run overlapping `[start, end)`: a concrete\n * value where the range agrees, `MIXED` where it doesn't. Keys no run\n * in range sets are absent (they inherit the node's `TextStyle`) — except\n * the additive flags, which read as `false`. An empty range reads as `{}`.\n * A reported `fill` is the run's own object, not a copy.\n */\nexport function styleAtRange(\n runs: readonly StyledRun[],\n start: number,\n end: number,\n): RangeStyle {\n const lo = Math.max(0, start);\n const hi = end;\n // Negated `<` rather than `>=` so a non-numeric offset reads as empty\n // instead of matching every run.\n if (!(lo < hi)) return {};\n\n const first = new Map<StyleKey, unknown>();\n const mixed = new Set<StyleKey>();\n let seen = false;\n let pos = 0;\n\n for (const run of runs) {\n const runEnd = pos + run.text.length;\n const a = Math.max(pos, lo);\n const b = Math.min(runEnd, hi);\n pos = runEnd;\n if (!(a < b)) continue;\n\n for (const key of STYLE_KEYS) {\n const value = valueAt(run, key);\n if (!seen) first.set(key, value);\n else if (!mixed.has(key) && !sameValue(key, first.get(key), value)) {\n mixed.add(key);\n }\n }\n seen = true;\n }\n\n if (!seen) return {};\n\n const style: Record<string, unknown> = {};\n for (const key of STYLE_KEYS) {\n if (mixed.has(key)) style[key] = MIXED;\n else {\n const value = first.get(key);\n if (value !== undefined) style[key] = value;\n }\n }\n return style as RangeStyle;\n}\n\n/**\n * Does any run carry styling of its own? A flag stored as `false` counts as\n * none, so runs whose styling was toggled back off read as `false`.\n */\nexport function runsCarryStyling(runs: readonly StyledRun[]): boolean {\n return runs.some((run) =>\n STYLE_KEYS.some((key) => {\n const value = run[key];\n return value !== undefined && value !== false;\n }),\n );\n}\n\n/**\n * The key a patch clears without naming it. `bold` is a preset over\n * `fontWeight`, and a run keeps at most one of the two: writing either drops\n * the other, so a Bold toggle is not hidden under a weight it cannot beat and\n * a picked weight is not shadowed by a stale flag. Naming both writes both.\n */\nexport function supersededKey(patch: RunStylePatch): 'bold' | 'fontWeight' | undefined {\n if ('bold' in patch && !('fontWeight' in patch)) return 'fontWeight';\n if (patch.fontWeight !== undefined && !('bold' in patch)) return 'bold';\n return undefined;\n}\n\n/**\n * `range` with `patch` laid over it, keyed as a write of `patch` would leave\n * the runs — for showing styling armed for the next keystroke over the\n * styling at the caret. A key the patch leaves `undefined` keeps the range's\n * value; the key it supersedes is dropped.\n */\nexport function patchRangeStyle(range: RangeStyle, patch: RunStylePatch): RangeStyle {\n const out: Record<string, unknown> = { ...range };\n const superseded = supersededKey(patch);\n if (superseded !== undefined) delete out[superseded];\n for (const [key, value] of Object.entries(patch)) {\n if (value !== undefined) out[key] = value;\n }\n return out as RangeStyle;\n}\n\n/** Apply `patch` to one run, deleting rather than storing \"no override\". */\nfunction patchRun(run: StyledRun, patch: RunStylePatch): StyledRun {\n const next: StyledRun = { ...run };\n const superseded = supersededKey(patch);\n if (superseded !== undefined) delete next[superseded];\n for (const key of STYLE_KEYS) {\n if (!(key in patch)) continue;\n const value = patch[key];\n // `false` is not a storable state — it means \"no run-level override\",\n // same as `undefined`. Deleting keeps one canonical form.\n if (value === undefined || value === false) delete next[key];\n else (next as unknown as Record<string, unknown>)[key] = value;\n }\n return next;\n}\n\n/** Merge neighbors that ended up styled identically; drop empty runs. */\nfunction coalesceRuns(runs: readonly StyledRun[]): StyledRun[] {\n const out: StyledRun[] = [];\n for (const run of runs) {\n if (run.text.length === 0) continue;\n const prev = out[out.length - 1];\n if (prev && sameStyle(prev, run)) prev.text += run.text;\n else out.push({ ...run });\n }\n return out;\n}\n\n/**\n * Write `patch` over `[start, end)`, splitting runs at the boundaries and\n * coalescing neighbors that end up identical. A patch value of `undefined`\n * or `false` deletes the key instead of storing it.\n *\n * Returns a new array of new runs (though a nested `fill` is shared by\n * reference). Normalization — merging identical neighbors, dropping empty\n * runs — applies to the whole array, not just the patched span, and to every\n * call, including one whose range is empty.\n */\nexport function applyStyleToRange(\n runs: readonly StyledRun[],\n start: number,\n end: number,\n patch: RunStylePatch,\n): StyledRun[] {\n const lo = Math.max(0, start);\n const hi = Math.min(totalLength(runs), end);\n if (!(lo < hi)) return coalesceRuns(runs);\n\n const out: StyledRun[] = [];\n let pos = 0;\n for (const run of runs) {\n const runEnd = pos + run.text.length;\n const a = Math.max(pos, lo);\n const b = Math.min(runEnd, hi);\n if (a < b) {\n if (pos < a) out.push({ ...run, text: run.text.slice(0, a - pos) });\n out.push(patchRun({ ...run, text: run.text.slice(a - pos, b - pos) }, patch));\n if (b < runEnd) out.push({ ...run, text: run.text.slice(b - pos) });\n } else {\n out.push({ ...run });\n }\n pos = runEnd;\n }\n\n return coalesceRuns(out);\n}\n","/**\n * Turning a run-level flag **off** inside a node that sets it.\n *\n * Run flags are additive over the node's `TextStyle` — a run turns `bold` /\n * `italic` / `underline` / `strikethrough` on, never off (see the contract at\n * the top of `rangeStyle.ts`). This resolves it by rewriting rather than by\n * widening the model: clear the flag on the node, and set it on every run\n * *outside* the range. The rendered result is identical, with `StyledRun`\n * unchanged.\n *\n * The alternative was a tri-state run flag (`true` / `false` / inherit). It\n * cannot cover `italic`: that is a boolean on a run but `fontStyle` on the\n * node, so a run's `false` has no node-level boolean to override.\n *\n * `bold` needs neither: a run carries a numeric `fontWeight`, which overrides\n * the node's outright, so lowering bold writes a regular weight over the\n * range and leaves the node and the rest of the text alone.\n */\n\nimport type { StyledRun } from '../runs';\nimport type { TextStyle } from '../textStyle';\nimport { isBoldWeight } from './resolveRuns';\nimport { applyStyleToRange } from './rangeStyle';\nimport type { RunStylePatch } from './rangeStyle';\n\n/** The additive run flags. */\nexport type FlagKey = 'bold' | 'italic' | 'underline' | 'strikethrough' | 'overline';\n\n/** The result of toggling a style flag over a text range: the rewritten runs\n * and node style. */\nexport interface SetFlagResult {\n runs: StyledRun[];\n style: TextStyle;\n}\n\n/** Does the node style carry this flag? */\nexport function nodeHasFlag(style: TextStyle, key: FlagKey): boolean {\n switch (key) {\n case 'bold': return style.fontWeight !== undefined && isBoldWeight(style.fontWeight);\n case 'italic': return style.fontStyle === 'italic';\n case 'underline': return style.underline === true;\n case 'strikethrough': return style.strikethrough === true;\n case 'overline': return style.overline === true;\n }\n}\n\n/** The patch that takes bold off a range: the flag, and — in a node that is\n * itself bold — a regular weight to override the node's. */\nexport function unboldPatch(style: TextStyle): RunStylePatch {\n return nodeHasFlag(style, 'bold') ? { bold: false, fontWeight: 400 } : { bold: false };\n}\n\n/** The node style with `key` cleared. */\nfunction clearNodeFlag(style: TextStyle, key: Exclude<FlagKey, 'bold'>): TextStyle {\n const next = { ...style };\n switch (key) {\n case 'italic': next.fontStyle = 'normal'; break;\n case 'underline': delete next.underline; break;\n case 'strikethrough': delete next.strikethrough; break;\n case 'overline': delete next.overline; break;\n }\n return next;\n}\n\n/**\n * Set `key` to `value` over `[start, end)`.\n *\n * Turning a flag **on**, or off in a node that doesn't set it, is the ordinary\n * additive write and leaves `style` alone. Turning it off in a node that *does*\n * set it takes the rewrite: the node flag is cleared and the flag is written\n * onto the complement of the range. Bold is the exception, written as a\n * weight over the range alone (see {@link unboldPatch}).\n *\n * `runs` is normalized on every path, so the complement collapses back to one\n * run when the range is empty and the whole array coalesces as usual.\n */\nexport function setFlagOverRange(\n runs: readonly StyledRun[],\n style: TextStyle,\n start: number,\n end: number,\n key: FlagKey,\n value: boolean,\n): SetFlagResult {\n if (value || !nodeHasFlag(style, key)) {\n return { runs: applyStyleToRange(runs, start, end, { [key]: value }), style };\n }\n\n if (key === 'bold') {\n return { runs: applyStyleToRange(runs, start, end, unboldPatch(style)), style };\n }\n\n const total = runs.reduce((n, r) => n + r.text.length, 0);\n const lo = Math.max(0, start);\n const hi = Math.min(total, end);\n\n // Raise the flag on everything, then lower it over the range. Doing it in\n // that order rather than patching the two complement spans keeps one code\n // path for a range at either edge, where one span is empty.\n let next = applyStyleToRange(runs, 0, total, { [key]: true });\n if (lo < hi) next = applyStyleToRange(next, lo, hi, { [key]: false });\n\n return { runs: next, style: clearNodeFlag(style, key) };\n}\n","import { resolveTextStyle } from '../textStyle';\nimport type { TextPaint, TextStyle } from '../textStyle';\nimport { isBoldWeight, numericWeight } from './resolveRuns';\nimport { nodeHasFlag } from './flagRange';\nimport { MIXED } from './rangeStyle';\nimport type { Mixed, RangeStyle } from './rangeStyle';\n\nconst FLAGS = ['italic', 'underline', 'strikethrough', 'overline'] as const;\n\n/**\n * The weight a range renders at, and whether that reads as bold, resolved as\n * `resolveRuns` resolves a run: its own `fontWeight`, else 700 for `bold`,\n * else the node's weight.\n */\nexport function rangeWeight(\n range: RangeStyle | null,\n style: TextStyle | undefined,\n): { fontWeight: number | Mixed; bold: boolean | Mixed } {\n const node = numericWeight(style?.fontWeight ?? 400);\n const own = range?.fontWeight;\n if (own === MIXED) return { fontWeight: MIXED, bold: MIXED };\n if (own !== undefined) return { fontWeight: own, bold: isBoldWeight(own) };\n const flag = range?.bold;\n if (flag === MIXED) {\n // Flagged runs draw at 700, the rest at the node's weight.\n if (node === 700) return { fontWeight: 700, bold: true };\n return { fontWeight: MIXED, bold: isBoldWeight(node) ? true : MIXED };\n }\n const weight = flag === true ? 700 : node;\n return { fontWeight: weight, bold: isBoldWeight(weight) };\n}\n\n/** Keys a run overrides outright. `script` and the two primitives it presets\n * have no node-level counterpart, so they only ever come from the range. */\nconst OVERRIDES = [\n 'fontFamily', 'fontSize', 'letterSpacing', 'fill', 'script', 'baselineShift', 'fontScale',\n 'textTransform', 'fontVariantCaps',\n] as const;\n\n/**\n * What is actually rendering across a range: `range` (from `styleAtRange`,\n * or `useTextEdit`'s `rangeStyle`) resolved against the node's own `style`\n * and `paint`, as the canvas resolves runs. `null` reads the node alone.\n *\n * Flags are additive — a run can turn one on, never off — so a node flag\n * makes the flag `true` across the range, `MIXED` runs included. Every other\n * key is the run's value where the range sets one, otherwise the node's.\n * The node level is resolved first, so the result has a value for every\n * key but the run-only ones, and for `fill` unless the node is unfilled.\n * Bold is read off the weight that renders (see {@link rangeWeight}), since\n * a run's own `fontWeight` can take a bold node's text back to regular.\n */\nexport function effectiveRangeStyle(\n range: RangeStyle | null,\n style: TextStyle | undefined,\n paint?: TextPaint,\n): RangeStyle {\n const resolved = resolveTextStyle(style, paint);\n const node = style ?? {};\n const out: RangeStyle = {\n fontFamily: resolved.fontFamily,\n fontSize: resolved.fontSize,\n letterSpacing: resolved.letterSpacing,\n textTransform: resolved.textTransform,\n fontVariantCaps: resolved.fontVariantCaps,\n };\n if (resolved.fill !== null) out.fill = resolved.fill;\n Object.assign(out, rangeWeight(range, style));\n for (const key of FLAGS) {\n const on = nodeHasFlag(node, key);\n const run = range?.[key];\n out[key] = on || run === undefined ? on : run;\n }\n if (range === null) return out;\n for (const key of OVERRIDES) {\n if (range[key] !== undefined) (out as Record<string, unknown>)[key] = range[key];\n }\n return out;\n}\n","/**\n * Synthetic-oblique angle, in radians — 12°, the conventional CSS\n * `font-style: oblique`. Shared by everything that fakes an italic: the SDF\n * tier skews quads by it, the outline tier shears glyph geometry by it, and\n * `textToPath` bakes the same shear into extracted outlines. One constant so a\n * face that falls back to the upright atlas leans the same amount however it\n * ends up being drawn.\n */\nexport const SYNTHETIC_ITALIC_RADIANS = 0.2094;\n","/**\n * Text as path geometry: the glyph outlines a text node draws, placed in\n * world space and composed into one `Path`. The glyphs are the ones\n * `layoutRuns` placed, so they land exactly where the renderer's outline tier\n * puts them, with the tier forced on for every glyph whatever its size.\n */\n\nimport { paintKey, strokeKey, type Stroke, type Fill } from '@weasel-js/paint';\n\nimport {\n loadFontOutlines, outlineStatus, resolveFontVariant, type FontStyle,\n} from '@weasel-js/font';\nimport {\n PATH_L, PATH_M, PATH_Z, pathFromD, pathSignedArea, poseFrameOf, reversePath,\n transformPath, type Mat3, type PathInWorldPose, type PolygonPath,\n} from '@weasel-js/geom';\nimport { lineDecorations } from './layout/decorationMetrics';\nimport { layoutRuns } from './layout/layoutRuns';\nimport { glyphOutlineD, glyphQuad, runFaces } from './layout/paintRuns';\nimport { textPoseLayoutInput } from './layout/textPoseLayout';\nimport { verticalAlignOffset, type TextVerticalAlign } from './measure/verticalAlign';\nimport type { TextPose } from './pose';\nimport type { StyledRun } from './runs';\nimport type { ResolvedRun } from './runs/resolveRuns';\nimport { SYNTHETIC_ITALIC_RADIANS } from './syntheticItalic';\nimport type { TextStyle } from './textStyle';\n\n/** The fields of a text node's data that decide its glyph geometry, and the\n * paint `textToPathsByPaint` splits it by. Paint never changes the geometry. */\nexport interface TextOutlineSource {\n text: string;\n runs?: readonly StyledRun[];\n style?: TextStyle;\n verticalAlign?: TextVerticalAlign;\n /** The node's `data.fill`: `null` is no fill, absent the default black. */\n fill?: Fill | null;\n /** The node's `data.stroke`: absent or `null` is no stroke. */\n stroke?: Stroke | null;\n}\n\n/** One paint's share of a text node's outlines — see {@link textToPathsByPaint}. */\nexport interface TextPaintPath {\n /** The resolved fill these glyphs wear: the run's own, else the node's.\n * `null` for unfilled text, painted by its stroke alone. */\n fill: Fill | null;\n /** The resolved stroke — the run's own, else the node's — or absent. */\n stroke?: Stroke;\n /** World-space outlines, as {@link textToPath} builds them. */\n path: PolygonPath;\n}\n\n/** A text node as {@link textToPath} reads it: its data and its pose. */\nexport interface TextNodeSource {\n data: TextOutlineSource;\n pose: PathInWorldPose;\n}\n\n/** Options for {@link textToPath}. */\nexport interface TextToPathOptions {\n /** The view scale a `{ px }` `fontSize` or `letterSpacing` resolves\n * against, as for `textCommandFromPose`. Default 1. */\n scale?: number;\n}\n\n/**\n * Why a text node has no outline geometry to give:\n *\n * - `'no-outlines'` — the face that serves it has no outlines registered\n * (`registerFontOutlines`), so there is no geometry to read.\n * - `'outlines-loading'` — registered but not parsed yet. `loadTextOutlines`\n * waits for it; the call has already started the load.\n * - `'outlines-failed'` — registered, and the bytes did not load or parse.\n * - `'synthetic-bold'` — the requested weight is faked from a lighter face.\n * The renderer thickens the distance field for that, and a path has no\n * field to thicken. Converting would silently lighten the text.\n */\nexport type TextOutlinesFailure =\n | 'no-outlines'\n | 'outlines-loading'\n | 'outlines-failed'\n | 'synthetic-bold';\n\n/** Thrown by {@link textToPath} when some run of the text has no outline\n * geometry. Names the run's requested face. */\nexport class TextOutlinesError extends Error {\n readonly reason: TextOutlinesFailure;\n readonly family: string;\n readonly weight: number;\n readonly style: FontStyle;\n\n constructor(reason: TextOutlinesFailure, family: string, weight: number, style: FontStyle, detail: string) {\n super(`textToPath: \"${family}\" ${weight}/${style} — ${detail}`);\n this.name = 'TextOutlinesError';\n this.reason = reason;\n this.family = family;\n this.weight = weight;\n this.style = style;\n }\n}\n\n/** The face every run is set in, before and after variant resolution. */\nfunction facesOf(runs: readonly ResolvedRun[]): { family: string; weight: number; style: FontStyle }[] {\n const out = new Map<string, { family: string; weight: number; style: FontStyle }>();\n const add = (family: string, weight: number, style: FontStyle) => {\n out.set(`${family}|${weight}|${style}`, { family, weight, style });\n };\n for (const r of runs) {\n add(r.fontFamily, r.fontWeight, r.fontStyle);\n const { family, weight, style } = resolveFontVariant(r.fontFamily, r.fontWeight, r.fontStyle).resolved;\n add(family, weight, style);\n }\n return [...out.values()];\n}\n\nfunction assertOutlinable(run: ResolvedRun): void {\n const { fontFamily, fontWeight, fontStyle } = run;\n const fail = (reason: TextOutlinesFailure, detail: string): never => {\n throw new TextOutlinesError(reason, fontFamily, fontWeight, fontStyle, detail);\n };\n const requested = outlineStatus(fontFamily, fontWeight, fontStyle);\n if (requested === 'idle' || requested === 'loading') {\n void loadFontOutlines(fontFamily, { weight: fontWeight, style: fontStyle });\n fail('outlines-loading', 'its outlines have not loaded yet; await loadTextOutlines first.');\n }\n const r = resolveFontVariant(fontFamily, fontWeight, fontStyle);\n const { family, weight, style } = r.resolved;\n if (r.synthetic.bold) {\n fail('synthetic-bold', `drawn as a faux bold of ${family} ${weight}/${style}, which has no ` +\n 'geometry to embolden. Register outlines for the real bold face.');\n }\n if (r.source === 'outline') return;\n const status = outlineStatus(family, weight, style);\n if (status === null) {\n fail('no-outlines', `served by ${family} ${weight}/${style}, which has no outlines ` +\n 'registered. Call registerFontOutlines for it.');\n }\n if (status === 'idle' || status === 'loading') {\n void loadFontOutlines(family, { weight, style });\n fail('outlines-loading', `the outlines of ${family} ${weight}/${style} have not loaded yet; ` +\n 'await loadTextOutlines first.');\n }\n if (status === 'failed') {\n fail('outlines-failed', `the outlines registered for ${family} ${weight}/${style} failed to load.`);\n }\n}\n\n// Em-space glyph geometry, wound one way, keyed by the outline data itself so a\n// re-registered face cannot serve stale geometry. The cap bounds a document\n// that cycles through many faces.\nconst EM_CACHE_LIMIT = 4096;\nconst emCache = new Map<string, PolygonPath>();\n\n/** A glyph's em-space path, wound positive so glyphs from faces that disagree\n * on winding — TrueType against CFF — still fill their overlaps under\n * `'nonzero'`, and so do the decoration rules drawn across them. */\nfunction emGlyph(d: string): PolygonPath {\n let p = emCache.get(d);\n if (p) return p;\n p = pathFromD(d);\n if (pathSignedArea(p) < 0) p = reversePath(p);\n if (emCache.size >= EM_CACHE_LIMIT) emCache.clear();\n emCache.set(d, p);\n return p;\n}\n\nfunction concat(parts: readonly PolygonPath[]): PolygonPath {\n let nc = 0, nk = 0;\n for (const p of parts) { nc += p.commands.length; nk += p.coords.length; }\n const commands = new Uint8Array(nc);\n const coords = new Float32Array(nk);\n let ci = 0, ki = 0;\n for (const p of parts) {\n commands.set(p.commands, ci); ci += p.commands.length;\n coords.set(p.coords, ki); ki += p.coords.length;\n }\n return { kind: 'polygon', commands, coords, fillRule: 'nonzero' };\n}\n\nfunction ruleContour(x0: number, y0: number, x1: number, y1: number): PolygonPath {\n return {\n kind: 'polygon',\n commands: new Uint8Array([PATH_M, PATH_L, PATH_L, PATH_L, PATH_Z]),\n coords: new Float32Array([x0, y0, x1, y0, x1, y1, x0, y1]),\n fillRule: 'nonzero',\n };\n}\n\n/**\n * The one glyph walk behind both entry points: every placed glyph's outline\n * and every decoration rule, gathered by the paint its run wears. Paint\n * decides only which path a contour lands in, so an unfilled run's glyphs and\n * rules are geometry like any other.\n */\nfunction walkOutlines(\n data: TextOutlineSource,\n pose: PathInWorldPose,\n opts: TextToPathOptions,\n): { paints: { fill: Fill | null; stroke?: Stroke }[]; paths: PolygonPath[] } {\n const textPose: TextPose = {\n x: pose.x, y: pose.y, width: pose.width, height: pose.height,\n text: data.text,\n runs: data.runs as StyledRun[] | undefined,\n style: data.style,\n verticalAlign: data.verticalAlign,\n fill: data.fill,\n stroke: data.stroke,\n };\n const { runs, opts: layoutOpts } = textPoseLayoutInput(textPose, opts.scale ?? 1);\n for (const run of runs) assertOutlinable(run);\n\n const paints: { fill: Fill | null; stroke?: Stroke }[] = [];\n const indexOf = new Map<string, number>();\n const paintOf = runs.map((run): number => {\n const key = `${paintKey(run.fill?.paint)}|${strokeKey(run.stroke)}`;\n let i = indexOf.get(key);\n if (i === undefined) {\n i = paints.length;\n indexOf.set(key, i);\n paints.push(run.stroke !== undefined ? { fill: run.fill, stroke: run.stroke } : { fill: run.fill });\n }\n return i;\n });\n\n const laid = layoutRuns(runs, layoutOpts);\n const dx = pose.x;\n const dy = pose.y + verticalAlignOffset(data.verticalAlign, pose.height, laid.bounds.height);\n const parts: PolygonPath[][] = paints.map(() => []);\n const rules: PolygonPath[][] = paints.map(() => []);\n const faceOf = runFaces(runs);\n for (const line of laid.lines) {\n for (const g of line.glyphs) {\n const d = glyphOutlineD(g, runs[g.run], 0);\n if (d === null) {\n // A code point the run's own face lacks escalates to a fallback face,\n // which the per-run check above never saw.\n if (glyphQuad(g) !== null) {\n const { family, weight, style } = g.resolved.resolved;\n throw new TextOutlinesError('no-outlines', family, weight, style,\n 'a fallback face serving some of the text\\'s characters has no outlines registered.');\n }\n continue;\n }\n const s = g.fontSize;\n const shear = g.resolved.synthetic.italic ? Math.tan(SYNTHETIC_ITALIC_RADIANS) : 0;\n // The renderer's placement (`mergeGlyphMeshes`): x = pen + (ex - ey·shear)·s.\n const m: Mat3 = [s, 0, -shear * s, s, g.x + dx, g.baselineY + dy];\n parts[paintOf[g.run]]!.push(transformPath(emGlyph(d), m) as PolygonPath);\n }\n for (const r of lineDecorations(line.glyphs, runs, faceOf, (run) => String(paintOf[run]))) {\n rules[paintOf[r.run]]!.push(ruleContour(r.x0 + dx, r.y0 + dy, r.x1 + dx, r.y1 + dy));\n }\n }\n\n const frame = poseFrameOf(pose);\n const paths = parts.map((glyphs, i) => {\n const path = concat([...glyphs, ...rules[i]!]);\n if (!frame || path.commands.length === 0) return path;\n return transformPath(path, frame) as PolygonPath;\n });\n return { paints, paths };\n}\n\n/**\n * The outline geometry of a text node, in world space: every glyph and every\n * underline, strikethrough and overline rule it draws, as one `'nonzero'`\n * compound path whose filled region is their union. Glyphs keep the font's\n * curves; overlapping contours are not merged — run the result through\n * `pathUnion` for that, at the cost of flattening the curves.\n *\n * `pose` is the node's box, rotation, and `transform`. Throws\n * {@link TextOutlinesError} when any run's face cannot supply outlines — never\n * returns a partial or empty path for that. Text with no ink (empty, or only\n * spaces) returns an empty path.\n */\nexport function textToPath(\n data: TextOutlineSource,\n pose: PathInWorldPose,\n opts: TextToPathOptions = {},\n): PolygonPath {\n return concat(walkOutlines(data, pose, opts).paths);\n}\n\n/**\n * {@link textToPath}, split by paint: one path per distinct resolved fill and\n * stroke, each gathering the glyphs and decoration rules that wear it — a\n * rule takes the fill of the run it underlines. Groups come in the order\n * their paint first appears in the text; a paint whose runs put down no ink\n * has none. Paint resolves as the renderer resolves it. Throws as\n * `textToPath` does.\n */\nexport function textToPathsByPaint(\n data: TextOutlineSource,\n pose: PathInWorldPose,\n opts: TextToPathOptions = {},\n): TextPaintPath[] {\n const { paints, paths } = walkOutlines(data, pose, opts);\n const out: TextPaintPath[] = [];\n paints.forEach((paint, i) => {\n if (paths[i]!.commands.length > 0) out.push({ ...paint, path: paths[i]! });\n });\n return out;\n}\n\n/**\n * Load the outlines of every face `data` is set in — the requested faces and\n * the ones they resolve to — so a following {@link textToPath} does not fail\n * with `'outlines-loading'`. Resolves once each has loaded or failed.\n */\nexport async function loadTextOutlines(\n data: TextOutlineSource,\n opts: TextToPathOptions = {},\n): Promise<void> {\n const textPose: TextPose = {\n x: 0, y: 0, width: 0, height: 0,\n text: data.text,\n runs: data.runs as StyledRun[] | undefined,\n style: data.style,\n };\n const { runs } = textPoseLayoutInput(textPose, opts.scale ?? 1);\n await Promise.all(facesOf(runs).map((f) => loadFontOutlines(f.family, { weight: f.weight, style: f.style })));\n // An outline-only family resolves to its own face only once that face has\n // parsed; before, it resolved to whatever stood in. Ask again.\n await Promise.all(facesOf(runs).map((f) => loadFontOutlines(f.family, { weight: f.weight, style: f.style })));\n}\n\n"]}