AI-native design editor. Open-source Figma alternative.
refactor(core): read glyphs with HarfBuzz instead of opentype.js (#1517)
Danila Poyarkovf21ff090406f
diff --git a/bun.lock b/bun.lockindex af52b166a..1dde482bb 100644--- a/bun.lock+++ b/bun.lock@@ -78,7 +78,6 @@"lib0": "^0.2.117","motion-v": "^2.5.2","nanostores": "^1.5.4",- "opentype.js": "^2.0.0","partial-json": "^0.1.7","pathe": "^2.0.3","qrcode": "1.5.4",@@ -128,7 +127,6 @@"@types/bun": "^1.3.14","@types/culori": "^4.0.1","@types/node": "^25.9.9",- "@types/opentype.js": "^1.3.10","@types/qrcode": "1.5.5","@types/ws": "^8.18.1","@typescript-eslint/utils": "^8.71.0",@@ -279,13 +277,13 @@"es-toolkit": "^1.52.0","fflate": "^0.8.3","fontoxpath": "^3.34.0",+ "harfbuzzjs": "1.6.4","js-base64": "^3.9.3","jsep": "^1.4.0","jsondiffpatch": "^0.7.6","jspdf": "^4.2.1","nanoevents": "^9.1.0","ofetch": "^1.5.1",- "opentype.js": "^2.0.0","parse5": "^8.0.1","pathe": "^2.0.3","pixelmatch": "^7.2.0",@@ -304,7 +302,6 @@"@types/bun": "^1.3.14","@types/culori": "^4.0.1","@types/diff": "^8.0.0",- "@types/opentype.js": "^1.3.10","@types/rbush": "^4.0.0","typescript": "~5.8.3","unplugin-raw": "^0.7.0",@@ -764,7 +761,7 @@"tools/generate/emoji-metrics": {"name": "@open-pencil/emoji-metrics-tools","dependencies": {- "opentype.js": "^2.0.0",+ "harfbuzzjs": "1.6.4",},"devDependencies": {"@open-pencil/core": "workspace:*",@@ -837,9 +834,6 @@},},},- "patchedDependencies": {- "[email protected]": "patches/[email protected]",- },"overrides": {"@codemirror/view": "6.43.9","protobufjs": "7.5.5",@@ -2406,8 +2400,6 @@"@types/normalize-package-data": ["@types/[email protected]", "", {}, "sha512-37i+OaWTh9qeK4LSHPsyRC7NahnGotNuZvjLSgcPzblpHB3rrCJxAOgI5gCdKm7coonsaX1Of0ILiTcnZjbfxA=="],- "@types/opentype.js": ["@types/[email protected]", "", {}, "sha512-F67EFyk6j02okHz5JCgata3ZRAcZi9GLnzmkHw/rzJq3OCc8/ZVdoKrxMTYjcQP6IYHGBz2cav1cpzkOkPiPCQ=="],-"@types/pako": ["@types/[email protected]", "", {}, "sha512-VWDCbrLeVXJM9fihYodcLiIv0ku+AlOa/TQ1SvYOaBuyrSKgEcro95LJyIsJ4vSo6BXIxOKxiJAat04CmST9Fw=="],"@types/pg": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*", "pg-protocol": "*", "pg-types": "^2.2.0" } }, "sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A=="],@@ -3456,6 +3448,8 @@"grok-mermaid": ["[email protected]", "", {}, "sha512-XcJEP5dDC8liHBh52mlLjU18fNvu1ckFsu0QpIG3+APZ270fsj9wxpiA6cOURmbUEuoMVgjbC2+UYgTdCqqgzA=="],+ "harfbuzzjs": ["[email protected]", "", {}, "sha512-T/PyfhVt1gGR2Tkf5KJUj1DQFkVBXHw552lS1iLEEDhV1Lukb3eq1pk2ov85kgbT2YUiZtJBTak9w+M7YgzUEQ=="],+"has-bigints": ["[email protected]", "", {}, "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg=="],"has-flag": ["[email protected]", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],@@ -4064,8 +4058,6 @@"openai": ["[email protected]", "", { "peerDependencies": { "ws": "^8.18.0", "zod": "^3.25 || ^4.0" }, "optionalPeers": ["ws", "zod"], "bin": { "openai": "bin/cli" } }, "sha512-zd23dbWTjiJ6sSAX6s0HrCZi41JwTA1bQVs0wLQPZ2/5o2gxOJA5wh7yOAUgwYybfhDXyhwlpeQf7Mlgx8EOCA=="],- "opentype.js": ["[email protected]", "", { "bin": { "ot": "bin/ot" } }, "sha512-kCyjv6xdDY1W/jLWZ/L3QhhTlKUqDZMQ5+Jdlw12b3dXkKNpYBqqlMMj0YDQPShWFTMwgZI1hG14kN3XUDSg/A=="],-"optionator": ["[email protected]", "", { "dependencies": { "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", "levn": "^0.4.1", "prelude-ls": "^1.2.1", "type-check": "^0.4.0", "word-wrap": "^1.2.5" } }, "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g=="],"own-keys": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.4", "get-intrinsic": "^1.3.0", "object-keys": "^1.1.1", "safe-push-apply": "^1.0.0" } }, "sha512-19YVAg7T+WTrxggPukVq7DjTv6+PJ867TmhCvBsYwmbFCsZd344rq2Ld1p0wo8f8Qrrhgp82c6FJRqdXWtSEhg=="],diff --git a/changes/1517/changed.md b/changes/1517/changed.mdnew file mode 100644index 000000000..cb64ad827--- /dev/null+++ b/changes/1517/changed.md@@ -0,0 +1,2 @@+- Text on a path is shaped with HarfBuzz, so it keeps every kerning, ligature, and contextual form its font defines, where it used to fall back to plain advances for fonts with OpenType lookups the old parser could not apply.+- `fontManager.markLoaded` returns a promise that resolves once the font's glyph outlines can be read; Core's glyph readers answer as for an unloaded font until then.diff --git a/package.json b/package.jsonindex 16f943d8e..9c2ac2cb1 100644--- a/package.json+++ b/package.json@@ -193,7 +193,6 @@"lib0": "^0.2.117","motion-v": "^2.5.2","nanostores": "^1.5.4",- "opentype.js": "^2.0.0","partial-json": "^0.1.7","pathe": "^2.0.3","qrcode": "1.5.4",@@ -243,7 +242,6 @@"@types/bun": "^1.3.14","@types/culori": "^4.0.1","@types/node": "^25.9.9",- "@types/opentype.js": "^1.3.10","@types/qrcode": "1.5.5","@types/ws": "^8.18.1","@typescript-eslint/utils": "^8.71.0",@@ -301,8 +299,5 @@"protobufjs": "7.5.5","websocket-driver": "0.7.5"},- "packageManager": "[email protected]",- "patchedDependencies": {- "[email protected]": "patches/[email protected]"- }+ "packageManager": "[email protected]"}diff --git a/packages/core/package.json b/packages/core/package.jsonindex 44261f781..65556193c 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -196,13 +196,13 @@"es-toolkit": "^1.52.0","fflate": "^0.8.3","fontoxpath": "^3.34.0",+ "harfbuzzjs": "1.6.4","js-base64": "^3.9.3","jsep": "^1.4.0","jsondiffpatch": "^0.7.6","jspdf": "^4.2.1","nanoevents": "^9.1.0","ofetch": "^1.5.1",- "opentype.js": "^2.0.0","parse5": "^8.0.1","pathe": "^2.0.3","pixelmatch": "^7.2.0",@@ -221,7 +221,6 @@"@types/bun": "^1.3.14","@types/culori": "^4.0.1","@types/diff": "^8.0.0",- "@types/opentype.js": "^1.3.10","@types/rbush": "^4.0.0","typescript": "~5.8.3","unplugin-raw": "^0.7.0"diff --git a/packages/core/src/canvas/text/decorations.ts b/packages/core/src/canvas/text/decorations.tsindex 54471584e..99f1b583a 100644--- a/packages/core/src/canvas/text/decorations.ts+++ b/packages/core/src/canvas/text/decorations.ts@@ -18,7 +18,7 @@ import { laidOutGlyphs, type LaidOutGlyph } from '#core/canvas/text/placed'import type { PreparedText } from '#core/canvas/text/preparation/cache'import { shownCharacters, shownText } from '#core/text/case'import { characterStyles, TEXT_STYLE_KEYS, type CharacterStyle } from '#core/text/character-style'-import { fontDecorationMetricsSync, type FontDecorationMetrics } from '#core/text/opentype'+import { fontDecorationMetricsSync, type FontDecorationMetrics } from '#core/text/font/glyphs'/*** Figma's Inter, measured from the decorations it saves, for text drawn without its font: itsdiff --git a/packages/core/src/canvas/text/ink.ts b/packages/core/src/canvas/text/ink.tsindex 254075488..d5f2197e0 100644--- a/packages/core/src/canvas/text/ink.ts+++ b/packages/core/src/canvas/text/ink.ts@@ -1,6 +1,6 @@import { geometryCommandCoordCount } from '@open-pencil/scene-graph/geometry'-import type { OutlineCommand } from '#core/text/opentype'+import type { OutlineCommand } from '#core/text/font/glyphs'/** Straight pieces a curve is followed in: a fraction of a pixel off at display sizes. */const CURVE_STEPS = 24@@ -69,7 +69,7 @@ class BandInk {}/**- * The ink of a font outline in the band, given in pixels below the baseline as opentype.js+ * The ink of a font outline in the band, given in pixels below the baseline as HarfBuzz* draws it, for a glyph at `x`, `y`.*/export function outlineInk(diff --git a/packages/core/src/canvas/text/keycap.ts b/packages/core/src/canvas/text/keycap.tsindex 6d4560d2a..dea5eb14e 100644--- a/packages/core/src/canvas/text/keycap.ts+++ b/packages/core/src/canvas/text/keycap.ts@@ -1,7 +1,7 @@import type { Canvas, CanvasKit, Paint } from 'canvaskit-wasm'+import type { OutlineCommand } from '#core/text/font/glyphs'import { KEYCAP_FRAME } from '#core/text/keycap'-import type { OutlineCommand } from '#core/text/opentype'import { appendOutlineCommand } from './outline-path'diff --git a/packages/core/src/canvas/text/layout/build.ts b/packages/core/src/canvas/text/layout/build.tsindex ce3576685..23dc547ab 100644--- a/packages/core/src/canvas/text/layout/build.ts+++ b/packages/core/src/canvas/text/layout/build.ts@@ -30,7 +30,7 @@ import type { TextRenderer } from '#core/canvas/text/renderer'import { utf8Length } from '#core/canvas/text/utf8'import { DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE } from '#core/constants'import { shownText } from '#core/text/case'-import { glyphAdvanceSync } from '#core/text/opentype'+import { glyphAdvanceSync } from '#core/text/font/glyphs'/** A list item's indent per level, in ems of the list's first character. */const LIST_INDENT_EMS = 1.5diff --git a/packages/core/src/canvas/text/outline-path.ts b/packages/core/src/canvas/text/outline-path.tsindex 788f0fec7..a568b3f4a 100644--- a/packages/core/src/canvas/text/outline-path.ts+++ b/packages/core/src/canvas/text/outline-path.ts@@ -1,6 +1,6 @@import type { PathBuilder } from 'canvaskit-wasm'-import type { OutlineCommand } from '#core/text/opentype'+import type { OutlineCommand } from '#core/text/font/glyphs'/** Appends an outline command, offset by `xOffset` and `yOffset`, to a path being built. */export function appendOutlineCommand(diff --git a/packages/core/src/canvas/text/placed.ts b/packages/core/src/canvas/text/placed.tsindex 1b4f85232..02443b4ae 100644--- a/packages/core/src/canvas/text/placed.ts+++ b/packages/core/src/canvas/text/placed.ts@@ -14,7 +14,7 @@ import type { TextLayout, TextLayoutMarker } from '#core/canvas/text/layout'import { utf16IndicesByUtf8 } from '#core/canvas/text/utf8'import { DEFAULT_FONT_FAMILY } from '#core/constants'import { ELLIPSIS } from '#core/text/ellipsis'-import { glyphOutlineSourceSync, type GlyphOutlineSource } from '#core/text/opentype'+import { glyphOutlineSourceSync, type GlyphOutlineSource } from '#core/text/font/glyphs'type GlyphRun = ReturnType<Paragraph['getShapedLines']>[number]['runs'][number]diff --git a/packages/core/src/canvas/text/shape.ts b/packages/core/src/canvas/text/shape.tsindex e2048ecd8..a7f2a9635 100644--- a/packages/core/src/canvas/text/shape.ts+++ b/packages/core/src/canvas/text/shape.ts@@ -18,9 +18,9 @@ import { characterFamily, laidOutGlyphs, type LaidOutGlyph } from '#core/canvas/import { getCanvasKit } from '#core/canvaskit'import { shownText } from '#core/text/case'import { EMOJI_METRICS_FAMILY } from '#core/text/emoji'+import type { OutlineCommand } from '#core/text/font/glyphs'import { fontManager } from '#core/text/fonts'import { nextGraphemeBoundary } from '#core/text/graphemes'-import type { OutlineCommand } from '#core/text/opentype'/*** Whether saved glyphs could stand for this text: case changes that alter its length movediff --git a/packages/core/src/editor/text.ts b/packages/core/src/editor/text.tsindex 1debbbe9b..11c51cec1 100644--- a/packages/core/src/editor/text.ts+++ b/packages/core/src/editor/text.ts@@ -9,7 +9,7 @@ import {import { textAutoResizeChanges } from '#core/layout/text-auto-resize'import type { TextEditorState } from '#core/text/editor'-import { hasGlyphOutlines } from '#core/text/opentype'+import { hasGlyphOutlines } from '#core/text/font/glyphs'import { applyBoundTextEdit } from './components/authoring/text-edit'import { fitEmptyLabelToPlaceholder } from './connectors/label-edit'diff --git a/packages/core/src/editor/text/path-edit.ts b/packages/core/src/editor/text/path-edit.tsindex 0da3d1469..9a4b3b66a 100644--- a/packages/core/src/editor/text/path-edit.ts+++ b/packages/core/src/editor/text/path-edit.ts@@ -6,7 +6,7 @@ import { weightToStyle } from '@open-pencil/scene-graph/font-style'import type { Rect } from '@open-pencil/scene-graph/primitives'import { textLengthPixels } from '@open-pencil/scene-graph/text'-import { getGlyphOutlineMetricsSync } from '#core/text/opentype'+import { getGlyphOutlineMetricsSync } from '#core/text/font/glyphs'import {calibratePathTextLayout,getTextPathData,diff --git a/packages/core/src/icons/material-symbols/font.ts b/packages/core/src/icons/material-symbols/font.tsindex c3b2af54b..0a8bee7ae 100644--- a/packages/core/src/icons/material-symbols/font.ts+++ b/packages/core/src/icons/material-symbols/font.ts@@ -1,11 +1,17 @@-import * as OpenType from 'opentype.js'-import type { IconOptions } from '@open-pencil/scene-graph/icons'import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'import type { IconOption, IconPath } from '#core/icons/types'+import {+ fontInstance,+ glyphCommands,+ harfBuzzFont,+ loadHarfBuzz,+ shapeText,+ type HarfBuzzFont,+ type OutlineCommand+} from '#core/text/font/harfbuzz'import { sfntFont } from '#core/text/font/woff2'-import type { OutlineCommand } from '#core/text/opentype'/** Material Symbols' sets, each one of Google's three fonts. */export const MATERIAL_SYMBOLS_PREFIXES = [@@ -35,32 +41,8 @@ export const MATERIAL_SYMBOLS_OPTIONS = [{ key: 'GRAD', name: 'Grade', min: -50, max: 200, default: 0, step: 1 }] as const satisfies readonly IconOption[]-interface LigatureSubtable {- coverage?: { glyphs?: number[]; ranges?: { start: number; end: number; index: number }[] }- ligatureSets?: { ligGlyph: number; components: number[] }[][]- extension?: LigatureSubtable-}--/** What drawing Material Symbols reads of a font parsed by opentype.js, which ships no types. */-export interface MaterialSymbolsFont {- charToGlyphIndex(character: string): number- glyphs: {- get(index: number): {- getPath(- x: number,- y: number,- fontSize: number,- options: { variation: Record<string, number> },- font: MaterialSymbolsFont- ): { commands: OutlineCommand[] }- }- }- tables: { gsub?: { lookups: { subtables: LigatureSubtable[] }[] } }-}--interface OpenTypeModule {- parse(buffer: ArrayBuffer): MaterialSymbolsFont-}+/** A Material Symbols font, as HarfBuzz reads it. */+export type MaterialSymbolsFont = HarfBuzzFontconst CSS_API = 'https://fonts.googleapis.com/css2'/** Google serves variable fonts as WOFF2, and only to clients that say they read it. */@@ -96,38 +78,16 @@ export async function fetchMaterialSymbolsFont(if (!url) throw new Error(`Google Fonts served no font for ${prefix}`)const file = await fetcher(url)if (!file.ok) throw new Error(`Google Fonts answered ${file.status} for ${url}`)- return (OpenType as OpenTypeModule).parse(await sfntFont(await file.arrayBuffer()))-}--/** Where `glyph` stands in a coverage table, or -1 when the table does not cover it. */-function coverageIndex(coverage: LigatureSubtable['coverage'], glyph: number): number {- const listed = coverage?.glyphs?.indexOf(glyph) ?? -1- if (listed !== -1) return listed- const range = coverage?.ranges?.find((item) => glyph >= item.start && glyph <= item.end)- return range ? range.index + glyph - range.start : -1+ const [bytes] = await Promise.all([sfntFont(await file.arrayBuffer()), loadHarfBuzz()])+ const font = harfBuzzFont(bytes)+ if (!font) throw new Error(`Google Fonts served a font for ${prefix} that cannot be read`)+ return font}-/**- * The glyph a Material Symbols name draws: the ligature its letters form. The fonts keep their- * ligatures in an extension lookup, which opentype.js parses but does not apply, so the lookup is- * read here.- */+/** The glyph a Material Symbols name draws: the ligature its letters form. */export function materialSymbolsGlyph(font: MaterialSymbolsFont, name: string): number | null {- const letters = Array.from(name, (character) => font.charToGlyphIndex(character))- const [first, ...rest] = letters- for (const lookup of font.tables.gsub?.lookups ?? []) {- for (const table of lookup.subtables) {- const subtable = table.extension ?? table- const set = subtable.ligatureSets?.[coverageIndex(subtable.coverage, first)]- const ligature = set?.find(- (item) =>- item.components.length === rest.length &&- item.components.every((component, index) => component === rest[index])- )- if (ligature) return ligature.ligGlyph- }- }- return null+ const glyphs = shapeText(font, name)+ return glyphs.length === 1 && Array.from(name).length > 1 ? glyphs[0].codepoint : null}/**@@ -140,31 +100,23 @@ export function materialSymbolsPathData(size: number,axes: Record<string, number>): string {- const path = font.glyphs.get(glyph).getPath(0, size, size, { variation: axes }, font)- return closedPathData(path.commands)+ const variations = Object.entries(axes).map(([axis, value]) => ({ axis, value }))+ return pathData(glyphCommands(font, fontInstance(font, variations), glyph, size, size))}const coordinate = (value: number | undefined) => Number((value ?? 0).toFixed(3))-/**- * Commands as SVG path data with every contour closed. TrueType contours always are, but- * opentype.js leaves the close out of a glyph it draws at variation axes, and an open contour- * fills on its own rather than cutting the holes its direction cuts.- */-function closedPathData(commands: readonly OutlineCommand[]): string {- const parts: string[] = []- let open = false- for (const command of commands) {- if (command.type === 'Z') continue- if (command.type === 'M' && open) parts.push('Z')- const points = [command.x1, command.y1, command.x2, command.y2].filter(- (value) => value !== undefined- )- parts.push(`${command.type}${[...points, command.x, command.y].map(coordinate).join(' ')}`)- open = true- }- if (open) parts.push('Z')- return parts.join('')+/** Commands as SVG path data. */+function pathData(commands: readonly OutlineCommand[]): string {+ return commands+ .map((command) => {+ const points = [command.x1, command.y1, command.x2, command.y2, command.x, command.y]+ return `${command.type}${points+ .filter((value) => value !== undefined)+ .map(coordinate)+ .join(' ')}`+ })+ .join('')}/** A glyph as an icon path filling a `size` square, painted in the icon's color. */diff --git a/packages/core/src/layout/text-measurement.ts b/packages/core/src/layout/text-measurement.tsindex 146e4bc84..88d23a3ef 100644--- a/packages/core/src/layout/text-measurement.ts+++ b/packages/core/src/layout/text-measurement.ts@@ -2,7 +2,7 @@ import type { SceneNode } from '@open-pencil/scene-graph'import { weightToStyle } from '@open-pencil/scene-graph/font-style'import { lineHeightPixels } from '@open-pencil/scene-graph/text'-import { measureTextWithOpenType } from '#core/text/opentype'+import { measureTextWithFont } from '#core/text/font/glyphs'export type TextMeasurer = (node: SceneNode,@@ -24,7 +24,7 @@ export function estimateTextSize(const ownLineH = lineHeightPixels(node.lineHeight, fontSize) ?? 0const explicitLineH = ownLineH > 0 ? ownLineH : undefined- const measured = measureTextWithOpenType(text, fontSize, family, style, maxWidth, explicitLineH)+ const measured = measureTextWithFont(text, fontSize, family, style, maxWidth, explicitLineH)if (measured) return measuredconst charWidth = fontSize * GLYPH_WIDTH_FACTORdiff --git a/packages/core/src/text/coverage.ts b/packages/core/src/text/coverage.tsindex dfb20b7e2..3e6e9f91a 100644--- a/packages/core/src/text/coverage.ts+++ b/packages/core/src/text/coverage.ts@@ -3,7 +3,7 @@ import { weightToStyle } from '@open-pencil/scene-graph/font-style'import { DEFAULT_FONT_FAMILY } from '#core/constants'import { cjkFallbackScriptForLanguage, type FontFallbackScript } from '#core/text/fallbacks'-import { fontGlyphCoverageSync } from '#core/text/opentype'+import { fontGlyphCoverageSync } from '#core/text/font/glyphs'const CJK_IDEOGRAPH_CHAR_RE = /\p{Script=Han}/uconst CJK_HIRAGANA_KATAKANA_RE = /[\u3040-\u30ff]/udiff --git a/packages/core/src/text/editor.ts b/packages/core/src/text/editor.tsindex c783e9525..aa8a439e8 100644--- a/packages/core/src/text/editor.ts+++ b/packages/core/src/text/editor.ts@@ -7,8 +7,8 @@ import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text/directioimport type { SkiaRenderer } from '#core/canvas'import type { TextLayout } from '#core/canvas/text/layout'+import { fontVerticalMetricsSync } from '#core/text/font/glyphs'import { nextGraphemeBoundary, previousGraphemeBoundary } from '#core/text/graphemes'-import { fontVerticalMetricsSync } from '#core/text/opentype'import {pathTextCaret,pathTextIndexAt,diff --git a/packages/core/src/text/font/glyphs.ts b/packages/core/src/text/font/glyphs.tsnew file mode 100644index 000000000..a5837869b--- /dev/null+++ b/packages/core/src/text/font/glyphs.ts@@ -0,0 +1,300 @@+import type { FontVariation } from '@open-pencil/scene-graph'++import { fontManager } from '#core/text/fonts'++import {+ fontInstance,+ glyphCommands,+ harfBuzzFont,+ isHarfBuzzLoaded,+ loadHarfBuzz,+ shapeText,+ type HarfBuzzFont,+ type OutlineCommand+} from './harfbuzz'+import { fontTableView } from './variation'++export type { OutlineCommand } from './harfbuzz'++export interface GlyphOutlineProbe {+ family: string+ style: string+ unitsPerEm: number+ commandCount: number+ firstGlyphCommandSample: OutlineCommand[]+}++interface ParsedFontCacheEntry {+ bytes: ArrayBuffer+ font: HarfBuzzFont | null+}++const parsedFontCache = new Map<string, ParsedFontCacheEntry>()++function getParsedFont(family: string, style: string): HarfBuzzFont | null {+ if (!isHarfBuzzLoaded()) return null+ const key = `${family}|${style}`+ const bytes = fontManager.loadedData(family, style)+ if (!bytes) return null+ const cached = parsedFontCache.get(key)+ if (cached?.bytes === bytes) return cached.font+ const font = harfBuzzFont(bytes)+ parsedFontCache.set(key, { bytes, font })+ return font+}++/** The glyph the font maps a character to, 0 (`.notdef`) when it has none. */+export function glyphIndex(parsed: HarfBuzzFont, character: string): number {+ const codePoint = character.codePointAt(0)+ if (codePoint === undefined) return 0+ let glyph = parsed.glyphIds.get(codePoint)+ if (glyph === undefined) {+ glyph = parsed.font.glyph(codePoint) ?? 0+ parsed.glyphIds.set(codePoint, glyph)+ }+ return glyph+}++/** A glyph's advance in the font's default instance, in font units. */+function glyphAdvanceUnits(parsed: HarfBuzzFont, glyphId: number): number {+ let advance = parsed.advances.get(glyphId)+ if (advance === undefined) {+ advance = parsed.font.glyphHAdvance(glyphId)+ parsed.advances.set(glyphId, advance)+ }+ return advance+}++/** A glyph's advance in the font's default instance, at `fontSize`. */+function glyphAdvanceWidth(parsed: HarfBuzzFont, glyphId: number, fontSize: number): number {+ return (glyphAdvanceUnits(parsed, glyphId) * fontSize) / parsed.face.upem+}++/**+ * True when the font is available AND parseable for glyph-outline extraction —+ * i.e. getGlyphOutlineMetricsSync can produce outlines for it. Availability is+ * currently local (fontManager), but the contract is provider-agnostic so a+ * future remote source can satisfy it. Path-text editing needs this to reflow;+ * without it the text is a baked graphic.+ */+export function hasGlyphOutlines(family: string, style: string): boolean {+ return getParsedFont(family, style) !== null+}++interface LineMetrics {+ ascender: number+ descender: number+ lineGap: number+}++const lineMetricsCache = new WeakMap<HarfBuzzFont, LineMetrics>()++/** The line metrics the font's `hhea` and `OS/2` tables declare, in font units, read once. */+function lineMetrics(parsed: HarfBuzzFont): LineMetrics {+ const cached = lineMetricsCache.get(parsed)+ if (cached) return cached+ const hhea = fontTableView(parsed.bytes, 'hhea')+ const os2 = fontTableView(parsed.bytes, 'OS/2')+ const hasHhea = hhea !== null && hhea.byteLength >= 8+ const metrics = {+ ascender: hasHhea ? hhea.getInt16(4) : 0,+ descender: hasHhea ? hhea.getInt16(6) : 0,+ lineGap: os2 && os2.byteLength >= 74 ? os2.getInt16(72) : 0+ }+ lineMetricsCache.set(parsed, metrics)+ return metrics+}++export function measureTextWithFont(+ text: string,+ fontSize: number,+ family: string,+ style: string,+ maxWidth?: number,+ lineHeight?: number+): { width: number; height: number } | null {+ const parsed = getParsedFont(family, style)+ if (!parsed) return null++ const scale = fontSize / parsed.face.upem+ const { ascender, descender, lineGap } = lineMetrics(parsed)+ const lineH = lineHeight ?? Math.ceil((ascender - descender + lineGap) * scale)++ let units = 0+ for (const character of text) units += glyphAdvanceUnits(parsed, glyphIndex(parsed, character))+ const singleLineWidth = units * scale++ if (maxWidth && maxWidth > 0 && singleLineWidth > maxWidth) {+ const lines = Math.ceil(singleLineWidth / maxWidth)+ return { width: maxWidth, height: Math.ceil(lines * lineH) }+ }+ return { width: Math.ceil(singleLineWidth), height: lineH }+}++/**+ * Where a font draws its underline and strikethrough, in ems: each line's top edge below the+ * baseline (negative above it) and its thickness. Figma places an underline's top half its+ * thickness below the font's underline position, and a strikethrough's top at its strikeout+ * position.+ */+export interface FontDecorationMetrics {+ underlineTop: number+ underlineThickness: number+ strikethroughTop: number+ strikethroughThickness: number+}++/** The decoration metrics of a loaded font, or `null` when it is not loaded or lacks them. */+export function fontDecorationMetricsSync(+ family: string,+ style: string+): FontDecorationMetrics | null {+ const parsed = getParsedFont(family, style)+ if (!parsed) return null+ const { MetricsTag } = parsed.hb+ const underlinePosition = parsed.font.getMetricPosition(MetricsTag.UNDERLINE_OFFSET)+ const underlineThickness = parsed.font.getMetricPosition(MetricsTag.UNDERLINE_SIZE)+ const strikeoutPosition = parsed.font.getMetricPosition(MetricsTag.STRIKEOUT_OFFSET)+ const strikeoutSize = parsed.font.getMetricPosition(MetricsTag.STRIKEOUT_SIZE)+ if (+ underlinePosition === undefined ||+ !underlineThickness ||+ strikeoutPosition === undefined ||+ !strikeoutSize+ )+ return null+ const em = parsed.face.upem+ return {+ underlineTop: (underlineThickness / 2 - underlinePosition) / em,+ underlineThickness: underlineThickness / em,+ strikethroughTop: -strikeoutPosition / em,+ strikethroughThickness: strikeoutSize / em+ }+}++/** How far a loaded font reaches above and below the baseline, in ems; null when not loaded. */+export function fontVerticalMetricsSync(+ family: string,+ style: string+): { ascent: number; descent: number } | null {+ const parsed = getParsedFont(family, style)+ if (!parsed) return null+ const { ascender, descender } = lineMetrics(parsed)+ return { ascent: ascender / parsed.face.upem, descent: -descender / parsed.face.upem }+}++/** A shaped glyph: its outline relative to the pen at `x`, where shaping placed it, and its advance. */+export interface GlyphOutlineMetrics {+ commands: OutlineCommand[]+ x: number+ advance: number+}++export type FontGlyphCoverage = 'has' | 'missing' | 'unknown'++export function fontGlyphCoverageSync(+ family: string,+ style: string,+ char: string+): FontGlyphCoverage {+ const parsed = getParsedFont(family, style)+ if (!parsed) return 'unknown'+ return glyphIndex(parsed, char) !== 0 ? 'has' : 'missing'+}++export function fontHasGlyphSync(family: string, style: string, char: string): boolean {+ return fontGlyphCoverageSync(family, style, char) === 'has'+}++/** Each glyph HarfBuzz shapes `text` into, with its outline, pen position, and advance. */+export function getGlyphOutlineMetricsSync(+ family: string,+ style: string,+ text: string,+ fontSize: number+): GlyphOutlineMetrics[] | null {+ const parsed = getParsedFont(family, style)+ if (!parsed) return null+ const scale = fontSize / parsed.face.upem+ const instance = fontInstance(parsed, [])+ let pen = 0+ return shapeText(parsed, text).map((glyph) => {+ // Shaping moves some glyphs off the pen, such as marks onto their base letter.+ const offsetX = (glyph.xOffset ?? 0) * scale+ // y runs down; subtracting keeps an unmoved glyph's baseline 0 rather than -0.+ const baseline = 0 - (glyph.yOffset ?? 0) * scale+ const metrics = {+ commands: glyphCommands(parsed, instance, glyph.codepoint, fontSize, baseline, offsetX),+ x: pen,+ advance: (glyph.xAdvance ?? 0) * scale+ }+ pen += metrics.advance+ return metrics+ })+}++/** Outlines of one loaded font, addressed by the glyph IDs a shaper produced. */+export interface GlyphOutlineSource {+ /** Whether the font has a glyph for every code point, so a shaper used it rather than a fallback. */+ covers(text: string): boolean+ /** The glyph the font maps `character` to, to check a shaper's glyph IDs are this font's. */+ glyphOf(character: string): number+ outline(glyphId: number, fontSize: number): OutlineCommand[] | null+}++/**+ * Glyph outlines by glyph ID for a loaded font, or `null` when it is not loaded or cannot be+ * parsed. A variable font draws the instance at `variations`, the axis values the shaper used.+ */+export function glyphOutlineSourceSync(+ family: string,+ style: string,+ variations: readonly FontVariation[] = []+): GlyphOutlineSource | null {+ const parsed = getParsedFont(family, style)+ if (!parsed) return null+ const instance = fontInstance(parsed, variations)+ return {+ covers: (text) => Array.from(text).every((char) => glyphIndex(parsed, char) !== 0),+ glyphOf: (character) => glyphIndex(parsed, character),+ outline: (glyphId, fontSize) =>+ glyphId < parsed.glyphCount ? glyphCommands(parsed, instance, glyphId, fontSize) : null+ }+}++/** The advance of glyph `glyphId` of a loaded font at `fontSize`, or `null` when it has none. */+export function glyphAdvanceSync(+ family: string,+ style: string,+ glyphId: number,+ fontSize: number+): number | null {+ const parsed = getParsedFont(family, style)+ if (!parsed || glyphId >= parsed.glyphCount) return null+ return glyphAdvanceWidth(parsed, glyphId, fontSize)+}++export async function probeGlyphOutlineCommands(+ family: string,+ style: string,+ text: string,+ fontSize: number+): Promise<GlyphOutlineProbe | null> {+ const bytes = fontManager.loadedData(family, style)+ if (!bytes) return null+ await loadHarfBuzz()+ const parsed = harfBuzzFont(bytes)+ if (!parsed) return null+ const outlines = Array.from(text, (character) =>+ glyphCommands(parsed, fontInstance(parsed, []), glyphIndex(parsed, character), fontSize)+ )+ const first = outlines.find((commands) => commands.length > 0) ?? []++ return {+ family,+ style,+ unitsPerEm: parsed.face.upem,+ commandCount: first.length,+ firstGlyphCommandSample: first.slice(0, 12)+ }+}diff --git a/packages/core/src/text/font/harfbuzz.ts b/packages/core/src/text/font/harfbuzz.tsnew file mode 100644index 000000000..599e358b9--- /dev/null+++ b/packages/core/src/text/font/harfbuzz.ts@@ -0,0 +1,201 @@+import type * as HarfBuzzModule from 'harfbuzzjs'++import type { FontVariation } from '@open-pencil/scene-graph'++import { ResourceCache } from '#core/cache/resource'++import { fontTableView } from './variation'++export interface OutlineCommand {+ type: string+ x?: number+ y?: number+ x1?: number+ y1?: number+ x2?: number+ y2?: number+}++type HarfBuzz = typeof HarfBuzzModule++let harfBuzz: HarfBuzz | null = null+let harfBuzzLoading: Promise<HarfBuzz | null> | null = null++/** Whether HarfBuzz has loaded, so fonts can be read synchronously. */+export function isHarfBuzzLoaded(): boolean {+ return harfBuzz !== null+}++/**+ * Loads HarfBuzz, which reads glyph outlines, advances, and shaping for Core's synchronous font+ * readers. Fonts only arrive asynchronously, so the font manager waits for it as it loads one;+ * until then, or if it fails to load, the readers answer as for a font that is not loaded.+ */+export function loadHarfBuzz(): Promise<HarfBuzz | null> {+ harfBuzzLoading ??= import('harfbuzzjs').then(+ (module) => (harfBuzz = module),+ (error: unknown) => {+ console.warn('HarfBuzz failed to load; glyph outlines are unavailable:', error)+ return null+ }+ )+ return harfBuzzLoading+}++/** A font drawing one instance of a font file, and the number its outlines are cached under. */+export interface HarfBuzzInstance {+ font: HarfBuzzModule.Font+ id: number+}++/** A font file as HarfBuzz reads it: its face, and the font drawing its default instance. */+export interface HarfBuzzFont {+ hb: HarfBuzz+ face: HarfBuzzModule.Face+ font: HarfBuzzModule.Font+ bytes: ArrayBuffer+ glyphCount: number+ /** Glyph IDs by code point and default advances by glyph ID, read once each. */+ glyphIds: Map<number, number>+ advances: Map<number, number>+ /** The instances text has been drawn at, by their axis values; '' is the default. */+ instances: ResourceCache<string, HarfBuzzInstance>+}++/** How many instances of one file keep their font and outlines, such as each optical size. */+const INSTANCES_PER_FONT = 16+/**+ * Outlines drawn by any instance, in font units with y running up, so a glyph is drawn once+ * whatever size it is asked for. Weighed by commands: 100,000 are about 7.5 MB of CJK outlines.+ */+const outlineCache = new ResourceCache<number, readonly OutlineCommand[]>({+ maxWeight: 100_000,+ weight: (commands) => commands.length + 1+})+let nextInstanceId = 0++/** A font file read by HarfBuzz, or `null` when HarfBuzz is not loaded or the file has no glyphs. */+export function harfBuzzFont(bytes: ArrayBuffer): HarfBuzzFont | null {+ const hb = harfBuzz+ const maxp = fontTableView(bytes, 'maxp')+ const glyphCount = maxp && maxp.byteLength >= 6 ? maxp.getUint16(4) : 0+ if (!hb || glyphCount === 0) return null+ const face = new hb.Face(new hb.Blob(bytes))+ return {+ hb,+ face,+ font: new hb.Font(face),+ bytes,+ glyphCount,+ glyphIds: new Map(),+ advances: new Map(),+ instances: new ResourceCache({ maxEntries: INSTANCES_PER_FONT })+ }+}++/** The instance of the file at `variations`, drawn by the default font when none are set. */+export function fontInstance(+ parsed: HarfBuzzFont,+ variations: readonly FontVariation[]+): HarfBuzzInstance {+ const key = variations.map(({ axis, value }) => `${axis}=${value}`).join(',')+ const cached = parsed.instances.get(key)+ if (cached) return cached+ let font = parsed.font+ if (variations.length > 0) {+ font = new parsed.hb.Font(parsed.face)+ font.setVariations(variations.map(({ axis, value }) => new parsed.hb.Variation(axis, value)))+ }+ // Glyph IDs are 16-bit, so an instance's outlines take the keys from its id times 65536.+ const instance = { font, id: nextInstanceId++ * 65536 }+ parsed.instances.set(key, instance)+ return instance+}++let outlineDrawing: HarfBuzzModule.DrawFuncs | null = null++/**+ * The draw callbacks that collect an outline, in font units, into the array passed as draw data.+ * HarfBuzz registers each callback in the WebAssembly function table, so one set serves every+ * glyph.+ */+function outlineDrawFuncs(hb: HarfBuzz): HarfBuzzModule.DrawFuncs {+ if (outlineDrawing) return outlineDrawing+ const commands = (data: unknown) => data as OutlineCommand[]+ const draw = new hb.DrawFuncs()+ draw.setMoveToFunc((x, y, data) => commands(data).push({ type: 'M', x, y }))+ draw.setLineToFunc((x, y, data) => commands(data).push({ type: 'L', x, y }))+ draw.setQuadraticToFunc((x1, y1, x, y, data) => commands(data).push({ type: 'Q', x1, y1, x, y }))+ draw.setCubicToFunc((x1, y1, x2, y2, x, y, data) =>+ commands(data).push({ type: 'C', x1, y1, x2, y2, x, y })+ )+ draw.setClosePathFunc((data) => commands(data).push({ type: 'Z' }))+ outlineDrawing = draw+ return draw+}++/**+ * The outline of `glyphId` in `instance`, scaled from font units to `fontSize` with y running down+ * from the baseline at `baseline`, and its origin at `originX`.+ */+export function glyphCommands(+ parsed: HarfBuzzFont,+ instance: HarfBuzzInstance,+ glyphId: number,+ fontSize: number,+ baseline = 0,+ originX = 0+): OutlineCommand[] {+ let outline = outlineCache.get(instance.id + glyphId)+ if (!outline) {+ const drawn: OutlineCommand[] = []+ instance.font.drawGlyph(glyphId, outlineDrawFuncs(parsed.hb), drawn)+ outlineCache.set(instance.id + glyphId, drawn)+ outline = drawn+ }+ const scale = fontSize / parsed.face.upem+ const x = (value: number) => originX + value * scale+ const y = (value: number) => baseline - value * scale+ return outline.map((command) => {+ switch (command.type) {+ case 'M':+ case 'L':+ return { type: command.type, x: x(command.x ?? 0), y: y(command.y ?? 0) }+ case 'Q':+ return {+ type: 'Q',+ x1: x(command.x1 ?? 0),+ y1: y(command.y1 ?? 0),+ x: x(command.x ?? 0),+ y: y(command.y ?? 0)+ }+ case 'C':+ return {+ type: 'C',+ x1: x(command.x1 ?? 0),+ y1: y(command.y1 ?? 0),+ x2: x(command.x2 ?? 0),+ y2: y(command.y2 ?? 0),+ x: x(command.x ?? 0),+ y: y(command.y ?? 0)+ }+ default:+ return { type: command.type }+ }+ })+}++let shapingBuffer: HarfBuzzModule.Buffer | null = null++/** The glyphs HarfBuzz shapes `text` into with the font's default instance, and their positions. */+export function shapeText(+ parsed: HarfBuzzFont,+ text: string+): ReturnType<HarfBuzzModule.Buffer['getGlyphInfosAndPositions']> {+ shapingBuffer ??= new parsed.hb.Buffer()+ shapingBuffer.reset()+ shapingBuffer.addText(text)+ shapingBuffer.guessSegmentProperties()+ parsed.hb.shape(parsed.font, shapingBuffer)+ return shapingBuffer.getGlyphInfosAndPositions()+}diff --git a/packages/core/src/text/font/variation.ts b/packages/core/src/text/font/variation.tsindex 19187fdd0..4576a50e7 100644--- a/packages/core/src/text/font/variation.ts+++ b/packages/core/src/text/font/variation.ts@@ -30,6 +30,12 @@ function sfntTable(view: DataView, tag: string): TableRange | null {return null}+/** One of the font's tables, or `null` when it has none. */+export function fontTableView(data: ArrayBuffer, tag: string): DataView | null {+ const table = sfntTable(new DataView(data), tag)+ return table ? new DataView(data, table.offset, table.length) : null+}+export function isVariableFont(data: ArrayBuffer): boolean {return sfntTable(new DataView(data), 'fvar') !== null}diff --git a/packages/core/src/text/font/woff2.ts b/packages/core/src/text/font/woff2.tsindex 43868c87f..0367d3206 100644--- a/packages/core/src/text/font/woff2.ts+++ b/packages/core/src/text/font/woff2.ts@@ -6,7 +6,7 @@ export function isWOFF2(data: ArrayBuffer): boolean {}/**- * The font as an sfnt (TrueType or OpenType) file. CanvasKit draws WOFF2, but opentype.js, the PDF+ * The font as an sfnt (TrueType or OpenType) file. CanvasKit draws WOFF2, but HarfBuzz, the PDF* exporter, and the font table readers need the tables themselves, so a WOFF2 font is decompressed* with Google's reference decoder, loaded only when one arrives. Other files stay as they are.*/diff --git a/packages/core/src/text/fonts.ts b/packages/core/src/text/fonts.tsindex 921b5138b..3a2724bc3 100644--- a/packages/core/src/text/fonts.ts+++ b/packages/core/src/text/fonts.ts@@ -29,6 +29,7 @@ import {import { fontFallbackEntry } from '#core/text/fallbacks'import type { FontFallbackScript } from '#core/text/fallbacks'+import { loadHarfBuzz } from '#core/text/font/harfbuzz'import { UnsupportedFontFormatError } from '#core/text/font/sources'import type {DownloadedFontCache,@@ -74,6 +75,12 @@ export type BundledFontLocator = (file: string) => stringconst defaultBundledFontLocator: BundledFontLocator = (file) => `/${file}`+/** `load`'s answer once HarfBuzz has loaded too, the two loading side by side. */+async function withHarfBuzz<T>(load: Promise<T>): Promise<T> {+ const [answer] = await Promise.all([load, loadHarfBuzz()])+ return answer+}+export class FontManager {private loadedFamilies = new Map<string, ArrayBuffer>()private loadedFamilySources = new Map<string, FontLoadedSource>()@@ -271,7 +278,11 @@ export class FontManager {return this.webFonts.enabledProviders()}- async loadCachedFont(+ loadCachedFont(family: string, style = 'Regular', characters = ''): Promise<ArrayBuffer | null> {+ return withHarfBuzz(this.restoreCachedFont(family, style, characters))+ }++ private async restoreCachedFont(family: string,style = 'Regular',characters = ''@@ -369,7 +380,14 @@ export class FontManager {return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)}- async loadLocalFont(family: string, style = 'Regular'): Promise<ArrayBuffer | null> {+ loadLocalFont(family: string, style = 'Regular'): Promise<ArrayBuffer | null> {+ return withHarfBuzz(this.findLocalOrBundledFont(family, style))+ }++ private async findLocalOrBundledFont(+ family: string,+ style = 'Regular'+ ): Promise<ArrayBuffer | null> {const loaded = this.loadedFamilies.get(`${family}|${style}`)if (loaded) {this.registerFontInCanvasKit(family, loaded)@@ -400,7 +418,16 @@ export class FontManager {}}- async loadRemoteFont(+ loadRemoteFont(+ family: string,+ style = 'Regular',+ characters = '',+ signal?: AbortSignal+ ): Promise<ArrayBuffer | null> {+ return withHarfBuzz(this.downloadFont(family, style, characters, signal))+ }++ private async downloadFont(family: string,style = 'Regular',characters = '',@@ -441,7 +468,16 @@ export class FontManager {}}- async loadFont(+ loadFont(+ family: string,+ style = 'Regular',+ characters = '',+ signal?: AbortSignal+ ): Promise<ArrayBuffer | null> {+ return withHarfBuzz(this.findFont(family, style, characters, signal))+ }++ private async findFont(family: string,style = 'Regular',characters = '',@@ -511,13 +547,15 @@ export class FontManager {await this.loadFont(family, weightToStyle(weight))}- markLoaded(+ /** Registers a font the caller already has, resolving once its outlines can be read. */+ async markLoaded(family: string,style: string,data: ArrayBuffer,source: FontLoadedSource = 'registered'- ): void {+ ): Promise<void> {this.registerAndCache(family, style, data, source)+ await loadHarfBuzz()}loadedFontSource(family: string, style: string): FontLoadedSource | null {@@ -646,7 +684,15 @@ export class FontManager {return this.arabicFallbackPromise}- async ensureFallbackPack(+ ensureFallbackPack(+ scripts: FontFallbackScript[] = ['cjk', 'arabic'],+ characters = '',+ signal?: AbortSignal+ ): Promise<Partial<Record<FontFallbackScript, string[]>>> {+ return withHarfBuzz(this.loadFallbackPack(scripts, characters, signal))+ }++ private async loadFallbackPack(scripts: FontFallbackScript[] = ['cjk', 'arabic'],characters = '',signal?: AbortSignaldiff --git a/packages/core/src/text/index.ts b/packages/core/src/text/index.tsindex 2b75b47f2..37aa85235 100644--- a/packages/core/src/text/index.ts+++ b/packages/core/src/text/index.ts@@ -13,4 +13,8 @@ export * from './path'export * from './prepare'export * from './font/faces'export { fontFaceFromFigmaFontName, fontFaceRenderFamily, type FontFaceRef } from './face'-export { probeGlyphOutlineCommands, type GlyphOutlineProbe, type OutlineCommand } from './opentype'+export {+ probeGlyphOutlineCommands,+ type GlyphOutlineProbe,+ type OutlineCommand+} from './font/glyphs'diff --git a/packages/core/src/text/keycap.ts b/packages/core/src/text/keycap.tsindex 574ceccd0..2d23383ee 100644--- a/packages/core/src/text/keycap.ts+++ b/packages/core/src/text/keycap.ts@@ -2,7 +2,7 @@// Copyright 2022 The Noto Project Authors (https://github.com/notofonts/symbols)// Licensed under the SIL Open Font License, Version 1.1 (packages/core/assets/NotoSansSymbols-OFL.txt).-import type { OutlineCommand } from './opentype'+import type { OutlineCommand } from './font/glyphs'/*** The frame Figma draws a keycap with: Noto Sans Symbols' combining enclosing keycap (U+20E3),@@ -12,30 +12,20 @@ import type { OutlineCommand } from './opentype'export const KEYCAP_FRAME: readonly OutlineCommand[] = [{type: 'M',- x: 0.336,- y: 0.01- },- {- type: 'L',x: -0.335,y: 0.01},{type: 'Q',- x: -0.398,- y: -0.0135,x1: -0.374,- y1: 0.01+ y1: 0.01,+ x: -0.398,+ y: -0.0135},{type: 'Q',- x: -0.422,- y: -0.076,x1: -0.422,- y1: -0.037- },- {- type: 'L',+ y1: -0.037,x: -0.422,y: -0.076},@@ -46,20 +36,15 @@ export const KEYCAP_FRAME: readonly OutlineCommand[] = [},{type: 'Q',- x: -0.398,- y: -0.8085,x1: -0.422,- y1: -0.785+ y1: -0.785,+ x: -0.398,+ y: -0.8085},{type: 'Q',- x: -0.335,- y: -0.832,x1: -0.374,- y1: -0.832- },- {- type: 'L',+ y1: -0.832,x: -0.335,y: -0.832},@@ -70,20 +55,15 @@ export const KEYCAP_FRAME: readonly OutlineCommand[] = [},{type: 'Q',- x: 0.3985,- y: -0.8085,x1: 0.375,- y1: -0.832+ y1: -0.832,+ x: 0.3985,+ y: -0.8085},{type: 'Q',- x: 0.422,- y: -0.746,x1: 0.422,- y1: -0.785- },- {- type: 'L',+ y1: -0.785,x: 0.422,y: -0.746},@@ -94,21 +74,21 @@ export const KEYCAP_FRAME: readonly OutlineCommand[] = [},{type: 'Q',- x: 0.3985,- y: -0.0135,x1: 0.422,- y1: -0.037+ y1: -0.037,+ x: 0.3985,+ y: -0.0135},{type: 'Q',- x: 0.336,- y: 0.01,x1: 0.375,- y1: 0.01+ y1: 0.01,+ x: 0.336,+ y: 0.01},{type: 'L',- x: 0.336,+ x: -0.335,y: 0.01},{@@ -119,11 +99,6 @@ export const KEYCAP_FRAME: readonly OutlineCommand[] = [x: -0.197,y: -0.122},- {- type: 'L',- x: -0.197,- y: -0.122- },{type: 'L',x: 0.198,@@ -131,20 +106,15 @@ export const KEYCAP_FRAME: readonly OutlineCommand[] = [},{type: 'Q',- x: 0.251,- y: -0.137,x1: 0.236,- y1: -0.122+ y1: -0.122,+ x: 0.251,+ y: -0.137},{type: 'Q',- x: 0.266,- y: -0.19,x1: 0.266,- y1: -0.152- },- {- type: 'L',+ y1: -0.152,x: 0.266,y: -0.19},@@ -155,20 +125,15 @@ export const KEYCAP_FRAME: readonly OutlineCommand[] = [},{type: 'Q',- x: 0.251,- y: -0.6845,x1: 0.266,- y1: -0.669+ y1: -0.669,+ x: 0.251,+ y: -0.6845},{type: 'Q',- x: 0.198,- y: -0.7,x1: 0.236,- y1: -0.7- },- {- type: 'L',+ y1: -0.7,x: 0.198,y: -0.7},@@ -179,20 +144,15 @@ export const KEYCAP_FRAME: readonly OutlineCommand[] = [},{type: 'Q',- x: -0.2495,- y: -0.684,x1: -0.234,- y1: -0.7+ y1: -0.7,+ x: -0.2495,+ y: -0.684},{type: 'Q',- x: -0.265,- y: -0.631,x1: -0.265,- y1: -0.668- },- {- type: 'L',+ y1: -0.668,x: -0.265,y: -0.631},@@ -203,28 +163,23 @@ export const KEYCAP_FRAME: readonly OutlineCommand[] = [},{type: 'Q',- x: -0.2495,- y: -0.1375,x1: -0.265,- y1: -0.153+ y1: -0.153,+ x: -0.2495,+ y: -0.1375},{type: 'Q',- x: -0.197,- y: -0.122,x1: -0.234,- y1: -0.122+ y1: -0.122,+ x: -0.197,+ y: -0.122},{type: 'Z'},{type: 'M',- x: 0.314,- y: -0.093- },- {- type: 'L',x: 0.398,y: -0.052},@@ -235,20 +190,15 @@ export const KEYCAP_FRAME: readonly OutlineCommand[] = [},{type: 'Q',- x: 0.3785,- y: -0.7865,x1: 0.398,- y1: -0.765+ y1: -0.765,+ x: 0.3785,+ y: -0.7865},{type: 'Q',- x: 0.327,- y: -0.808,x1: 0.359,- y1: -0.808- },- {- type: 'L',+ y1: -0.808,x: 0.327,y: -0.808},@@ -269,27 +219,22 @@ export const KEYCAP_FRAME: readonly OutlineCommand[] = [},{type: 'Q',- x: 0.2845,- y: -0.7405,x1: 0.27,- y1: -0.748+ y1: -0.748,+ x: 0.2845,+ y: -0.7405},{type: 'Q',- x: 0.3065,- y: -0.7175,x1: 0.299,- y1: -0.733+ y1: -0.733,+ x: 0.3065,+ y: -0.7175},{type: 'Q',- x: 0.314,- y: -0.678,x1: 0.314,- y1: -0.702- },- {- type: 'L',+ y1: -0.702,x: 0.314,y: -0.678},@@ -298,6 +243,11 @@ export const KEYCAP_FRAME: readonly OutlineCommand[] = [x: 0.314,y: -0.093},+ {+ type: 'L',+ x: 0.398,+ y: -0.052+ },{type: 'Z'}diff --git a/packages/core/src/text/opentype.ts b/packages/core/src/text/opentype.tsdeleted file mode 100644index 230d60a90..000000000--- a/packages/core/src/text/opentype.ts+++ /dev/null@@ -1,315 +0,0 @@-import * as OpenTypeSync from 'opentype.js'--import type { FontVariation } from '@open-pencil/scene-graph'--import { fontManager } from './fonts'--export interface OutlineCommand {- type: string- x?: number- y?: number- x1?: number- y1?: number- x2?: number- y2?: number-}--interface OutlinePath {- commands: OutlineCommand[]-}--interface OutlineGlyph {- path: OutlinePath- advanceWidth?: number- /**- * The default instance's advance, which opentype.js sets aside when it draws a variable font's- * instance and overwrites `advanceWidth` with that instance's.- */- _advanceWidth?: number- getPath(- x: number,- y: number,- fontSize: number,- options?: { variation?: Record<string, number> },- font?: OutlineFont- ): OutlinePath-}--interface OutlineFont {- unitsPerEm: number- ascender: number- descender: number- tables: {- os2?: { sTypoLineGap?: number; yStrikeoutPosition?: number; yStrikeoutSize?: number }- post?: { underlinePosition?: number; underlineThickness?: number }- fvar?: unknown- }- glyphs: { get(index: number): OutlineGlyph | undefined }- charToGlyphIndex(char: string): number- charToGlyph(char: string): OutlineGlyph- forEachGlyph(- text: string,- x: number,- y: number,- fontSize: number,- options: undefined,- callback: (glyph: OutlineGlyph, x: number) => void- ): number-}--export interface GlyphOutlineProbe {- family: string- style: string- unitsPerEm: number- commandCount: number- firstGlyphCommandSample: OutlineCommand[]-}--interface OpenTypeModule {- parse(buffer: ArrayBuffer): OutlineFont-}--interface ParsedFontCacheEntry {- bytes: ArrayBuffer- font: OutlineFont | null-}--const parsedFontCache = new Map<string, ParsedFontCacheEntry>()--function getParsedFont(family: string, style: string): OutlineFont | null {- const key = `${family}|${style}`- const bytes = fontManager.loadedData(family, style)- if (!bytes) return null- const cached = parsedFontCache.get(key)- if (cached?.bytes === bytes) return cached.font- try {- const font = (OpenTypeSync as OpenTypeModule).parse(bytes.slice(0))- parsedFontCache.set(key, { bytes, font })- return font- } catch {- parsedFontCache.set(key, { bytes, font: null })- return null- }-}--/**- * True when the font is available AND parseable for glyph-outline extraction —- * i.e. getGlyphOutlineMetricsSync can produce outlines for it. Availability is- * currently local (fontManager), but the contract is provider-agnostic so a- * future remote source can satisfy it. Path-text editing needs this to reflow;- * without it the text is a baked graphic.- */-export function hasGlyphOutlines(family: string, style: string): boolean {- return getParsedFont(family, style) !== null-}--function glyphsForCodePoints(font: OutlineFont, text: string): OutlineGlyph[] {- return Array.from(text, (character) => font.charToGlyph(character))-}--/** A glyph's advance in the font's default instance, whatever instance was last drawn. */-function glyphAdvanceWidth(font: OutlineFont, glyph: OutlineGlyph, fontSize: number): number {- return ((glyph._advanceWidth ?? glyph.advanceWidth ?? 0) * fontSize) / font.unitsPerEm-}--export function measureTextWithOpenType(- text: string,- fontSize: number,- family: string,- style: string,- maxWidth?: number,- lineHeight?: number-): { width: number; height: number } | null {- const font = getParsedFont(family, style)- if (!font) return null-- const scale = fontSize / font.unitsPerEm- const lineGap = font.tables.os2?.sTypoLineGap ?? 0- const lineH = lineHeight ?? Math.ceil((font.ascender - font.descender + lineGap) * scale)-- const singleLineWidth = glyphsForCodePoints(font, text).reduce(- (width, glyph) => width + glyphAdvanceWidth(font, glyph, fontSize),- 0- )-- if (maxWidth && maxWidth > 0 && singleLineWidth > maxWidth) {- const lines = Math.ceil(singleLineWidth / maxWidth)- return { width: maxWidth, height: Math.ceil(lines * lineH) }- }- return { width: Math.ceil(singleLineWidth), height: lineH }-}--/**- * Where a font draws its underline and strikethrough, in ems: each line's top edge below the- * baseline (negative above it) and its thickness. Figma places an underline's top half its- * thickness below the font's underline position, and a strikethrough's top at its strikeout- * position.- */-export interface FontDecorationMetrics {- underlineTop: number- underlineThickness: number- strikethroughTop: number- strikethroughThickness: number-}--/** The decoration metrics of a loaded font, or `null` when it is not loaded or lacks them. */-export function fontDecorationMetricsSync(- family: string,- style: string-): FontDecorationMetrics | null {- const font = getParsedFont(family, style)- const post = font?.tables.post- const os2 = font?.tables.os2- if (- !font ||- post?.underlinePosition === undefined ||- !post.underlineThickness ||- os2?.yStrikeoutPosition === undefined ||- !os2.yStrikeoutSize- )- return null- const em = font.unitsPerEm- return {- underlineTop: (post.underlineThickness / 2 - post.underlinePosition) / em,- underlineThickness: post.underlineThickness / em,- strikethroughTop: -os2.yStrikeoutPosition / em,- strikethroughThickness: os2.yStrikeoutSize / em- }-}--/** How far a loaded font reaches above and below the baseline, in ems; null when not loaded. */-export function fontVerticalMetricsSync(- family: string,- style: string-): { ascent: number; descent: number } | null {- const font = getParsedFont(family, style)- if (!font || !(font.unitsPerEm > 0)) return null- return { ascent: font.ascender / font.unitsPerEm, descent: -font.descender / font.unitsPerEm }-}--export interface GlyphOutlineMetrics {- commands: OutlineCommand[]- x: number- advance: number-}--export type FontGlyphCoverage = 'has' | 'missing' | 'unknown'--export function fontGlyphCoverageSync(- family: string,- style: string,- char: string-): FontGlyphCoverage {- const bytes = fontManager.loadedData(family, style)- if (!bytes) return 'unknown'- const font = getParsedFont(family, style)- if (!font) return 'unknown'- return font.charToGlyphIndex(char) !== 0 ? 'has' : 'missing'-}--export function fontHasGlyphSync(family: string, style: string, char: string): boolean {- return fontGlyphCoverageSync(family, style, char) === 'has'-}--export function getGlyphOutlineMetricsSync(- family: string,- style: string,- text: string,- fontSize: number-): GlyphOutlineMetrics[] | null {- const font = getParsedFont(family, style)- if (!font) return null-- try {- const positioned: Array<{ glyph: OutlineGlyph; x: number }> = []- const endX = font.forEachGlyph(text, 0, 0, fontSize, undefined, (glyph, x) => {- positioned.push({ glyph, x })- })- return positioned.map(({ glyph, x }, index) => ({- commands: glyph.getPath(0, 0, fontSize).commands,- x,- // opentype.js applies substitutions, ligatures, GPOS kerning, and default- // render features in forEachGlyph. Derive each shaped advance from those- // positions rather than reconstructing it from raw code points.- advance: (positioned[index + 1]?.x ?? endX) - x- }))- } catch {- // Some fonts use OpenType lookup formats that opentype.js cannot shape yet.- // Preserve outline editing with the dependency's basic glyph/advance APIs.- const glyphs = glyphsForCodePoints(font, text)- let x = 0- return glyphs.map((glyph) => {- const commands = glyph.getPath(0, 0, fontSize).commands- const advance = glyphAdvanceWidth(font, glyph, fontSize)- const metrics = { commands, x, advance }- x += advance- return metrics- })- }-}--/** Outlines of one loaded font, addressed by the glyph IDs a shaper produced. */-export interface GlyphOutlineSource {- /** Whether the font has a glyph for every code point, so a shaper used it rather than a fallback. */- covers(text: string): boolean- /** The glyph the font maps `character` to, to check a shaper's glyph IDs are this font's. */- glyphOf(character: string): number- outline(glyphId: number, fontSize: number): OutlineCommand[] | null-}--/**- * Glyph outlines by glyph ID for a loaded font, or `null` when it is not loaded or cannot be- * parsed. A variable font draws the instance at `variations`, the axis values the shaper used.- */-export function glyphOutlineSourceSync(- family: string,- style: string,- variations: readonly FontVariation[] = []-): GlyphOutlineSource | null {- const font = getParsedFont(family, style)- if (!font) return null- const variation = font.tables.fvar- ? { variation: Object.fromEntries(variations.map(({ axis, value }) => [axis, value])) }- : undefined- return {- covers: (text) => Array.from(text).every((char) => font.charToGlyphIndex(char) !== 0),- glyphOf: (character) => font.charToGlyphIndex(character),- outline: (glyphId, fontSize) =>- font.glyphs.get(glyphId)?.getPath(0, 0, fontSize, variation, font).commands ?? null- }-}--/** The advance of glyph `glyphId` of a loaded font at `fontSize`, or `null` when it has none. */-export function glyphAdvanceSync(- family: string,- style: string,- glyphId: number,- fontSize: number-): number | null {- const font = getParsedFont(family, style)- const glyph = font?.glyphs.get(glyphId)- return font && glyph ? glyphAdvanceWidth(font, glyph, fontSize) : null-}--export async function probeGlyphOutlineCommands(- family: string,- style: string,- text: string,- fontSize: number-): Promise<GlyphOutlineProbe | null> {- const bytes = fontManager.loadedData(family, style)- if (!bytes) return null-- const font = (OpenTypeSync as OpenTypeModule).parse(bytes.slice(0))- const glyphs = glyphsForCodePoints(font, text)- const firstGlyph = glyphs.find((glyph: OutlineGlyph) => glyph.path.commands.length > 0)- const firstGlyphCommandSample = (firstGlyph?.getPath(0, 0, fontSize).commands ?? []).slice(0, 12)-- return {- family,- style,- unitsPerEm: font.unitsPerEm,- commandCount: firstGlyph?.path.commands.length ?? 0,- firstGlyphCommandSample- }-}diff --git a/packages/core/src/text/outlines.ts b/packages/core/src/text/outlines.tsindex c2cd4f88d..422e8c8a8 100644--- a/packages/core/src/text/outlines.ts+++ b/packages/core/src/text/outlines.ts@@ -4,12 +4,12 @@ import type { CharacterStyleOverride, SceneNode } from '@open-pencil/scene-graphimport { weightToStyle } from '@open-pencil/scene-graph/font-style'import { lineHeightPixels, textLengthPixels } from '@open-pencil/scene-graph/text'-import { fontManager } from '#core/text/fonts'import {fontHasGlyphSync,getGlyphOutlineMetricsSync,type OutlineCommand-} from '#core/text/opentype'+} from '#core/text/font/glyphs'+import { fontManager } from '#core/text/fonts'export type TextOutlineUnsupportedReason =| 'not-text'diff --git a/packages/core/src/text/prepare.ts b/packages/core/src/text/prepare.tsindex d0e23d1a8..31341df32 100644--- a/packages/core/src/text/prepare.ts+++ b/packages/core/src/text/prepare.ts@@ -7,8 +7,8 @@ import {NOTO_COLOR_EMOJI_FAMILY,savedEmojiCharacters} from '#core/text/emoji'+import { fontGlyphCoverageSync } from '#core/text/font/glyphs'import { fontManager } from '#core/text/fonts'-import { fontGlyphCoverageSync } from '#core/text/opentype'import { collectGraphFontRequirements, collectNodeFontFaces } from '#core/text/requirements'import { missingGraphFontScripts } from '#core/text/resolved-requirements'diff --git a/packages/core/tests/canvas/text/faces.test.ts b/packages/core/tests/canvas/text/faces.test.tsindex a802cb1f9..ad2d682ee 100644--- a/packages/core/tests/canvas/text/faces.test.ts+++ b/packages/core/tests/canvas/text/faces.test.ts@@ -12,7 +12,7 @@ import { buildParagraph } from '#core/canvas/text'import { withFigExportRuntime } from '#core/canvas/text/shape'import { getCanvasKit } from '#core/canvaskit'import { FontManager, fontManager } from '#core/text/fonts'-import { glyphOutlineSourceSync } from '#core/text/opentype'+import { glyphOutlineSourceSync } from '#core/text/font/glyphs'/** A family only these tests load, so faces other tests load cannot answer for it. */const FAMILY = 'Faces Test Sans'@@ -68,7 +68,7 @@ describe('text faces', () => {const ck = await getCanvasKit()const fontProvider = ck.TypefaceFontProvider.Make()fontManager.attachProvider(ck, fontProvider)- fontManager.markLoaded(FAMILY, 'Regular', await bundled('/InterVariable.ttf'))+ await fontManager.markLoaded(FAMILY, 'Regular', await bundled('/InterVariable.ttf'))const regular = drawn(ck, fontProvider, { fontWeight: 400, italic: false })expect(drawn(ck, fontProvider, { fontWeight: 400, italic: true })).toEqual(regular)expect(drawn(ck, fontProvider, { fontWeight: 700, italic: false })).toEqual(regular)@@ -78,8 +78,8 @@ describe('text faces', () => {const ck = await getCanvasKit()const fontProvider = ck.TypefaceFontProvider.Make()fontManager.attachProvider(ck, fontProvider)- fontManager.markLoaded(FAMILY, 'Regular', await bundled('/InterVariable.ttf'))- fontManager.markLoaded(FAMILY, 'Bold', await bundled('/InterVariable.ttf'))+ await fontManager.markLoaded(FAMILY, 'Regular', await bundled('/InterVariable.ttf'))+ await fontManager.markLoaded(FAMILY, 'Bold', await bundled('/InterVariable.ttf'))const regular = drawn(ck, fontProvider, { fontWeight: 400, italic: false })expect(drawn(ck, fontProvider, { fontWeight: 700, italic: false })).not.toEqual(regular)})@@ -93,7 +93,7 @@ describe('text faces', () => {join(FIXTURES, 'fonts', 'InterVariable-Latin.ttf')).arrayBuffer()const fontFamily = 'Faces Test Optical'- fontManager.markLoaded(fontFamily, 'Regular', variable)+ await fontManager.markLoaded(fontFamily, 'Regular', variable)const face = (fields: Partial<SceneNode>) =>drawn(ck, fontProvider, { fontFamily, fontWeight: 400, italic: false, ...fields })const automatic = face({})@@ -116,9 +116,9 @@ describe('text faces', () => {const variable = await Bun.file(join(FIXTURES, 'fonts', 'InterVariable-Latin.ttf')).arrayBuffer()- fontManager.markLoaded('Faces Test Mixed', 'Regular', regular)- fontManager.markLoaded('Faces Test Mixed', 'Light', variable)- fontManager.markLoaded('Faces Test Variable Only', 'Light', variable)+ await fontManager.markLoaded('Faces Test Mixed', 'Regular', regular)+ await fontManager.markLoaded('Faces Test Mixed', 'Light', variable)+ await fontManager.markLoaded('Faces Test Variable Only', 'Light', variable)const light = (fontFamily: string) =>drawn(ck, fontProvider, { fontFamily, fontWeight: 300, italic: false })expect(light('Faces Test Mixed')).toEqual(light('Faces Test Variable Only'))@@ -130,9 +130,9 @@ describe('text faces', () => {*/test('saves fallback characters in the face the text is drawn in', async () => {const primary = 'Faces Test Naskh'- fontManager.markLoaded(primary, 'Regular', await bundled('/NotoNaskhArabic-Regular.ttf'))- fontManager.markLoaded('Inter', 'Regular', await bundled('/InterVariable.ttf'))- fontManager.markLoaded('Inter', 'Bold', await bundled('/InterVariable.ttf'))+ await fontManager.markLoaded(primary, 'Regular', await bundled('/NotoNaskhArabic-Regular.ttf'))+ await fontManager.markLoaded('Inter', 'Regular', await bundled('/InterVariable.ttf'))+ await fontManager.markLoaded('Inter', 'Bold', await bundled('/InterVariable.ttf'))const graph = new SceneGraph()const node = graph.createNode('TEXT', graph.getPages()[0].id, {text: 'F',@@ -149,7 +149,11 @@ describe('text faces', () => {),'shaped text')- const regular = expectDefined(glyphOutlineSourceSync('Inter', 'Regular'), 'Inter Regular')+ // At the optical size the font size sets, as the paragraph draws every family it falls back to.+ const regular = expectDefined(+ glyphOutlineSourceSync('Inter', 'Regular', [{ axis: 'opsz', value: 40 }]),+ 'Inter Regular'+ )expect(shaped.glyphs[0]?.commands).toEqual(regular.outline(regular.glyphOf('F'), 40))})})diff --git a/packages/core/tests/canvas/text/lines.test.ts b/packages/core/tests/canvas/text/lines.test.tsindex f2e5dd8b2..0364736c2 100644--- a/packages/core/tests/canvas/text/lines.test.ts+++ b/packages/core/tests/canvas/text/lines.test.ts@@ -97,7 +97,7 @@ describe('lines of mixed sizes', () => {'bundled Inter font')provider.registerFont(inter, 'Inter')- fontManager.markLoaded('Inter', 'Regular', inter)+ await fontManager.markLoaded('Inter', 'Regular', inter)})afterAll(() => {diff --git a/packages/core/tests/canvas/text/lists.test.ts b/packages/core/tests/canvas/text/lists.test.tsindex 80bf35c36..850ff805e 100644--- a/packages/core/tests/canvas/text/lists.test.ts+++ b/packages/core/tests/canvas/text/lists.test.ts@@ -9,7 +9,7 @@ import { buildParagraph } from '#core/canvas/text/layout/build'import { withFigExportRuntime } from '#core/canvas/text/shape'import { getCanvasKit } from '#core/canvaskit'import { fontManager } from '#core/text/fonts'-import { glyphAdvanceSync } from '#core/text/opentype'+import { glyphAdvanceSync } from '#core/text/font/glyphs'const ul = (indentation = 1): TextParagraphStyle => ({ listType: 'UNORDERED', indentation })const ol = (indentation = 1): TextParagraphStyle => ({ listType: 'ORDERED', indentation })@@ -48,7 +48,7 @@ describe('text lists', () => {await fontManager.fetchBundledFont('/InterVariable.ttf'),'bundled Inter font')- fontManager.markLoaded('Inter', 'Regular', inter)+ await fontManager.markLoaded('Inter', 'Regular', inter)})test('indents items one and a half ems per level and centres bullets in the indent', async () => {diff --git a/packages/core/tests/canvas/text/readiness.test.ts b/packages/core/tests/canvas/text/readiness.test.tsindex c4760f9fe..752157fef 100644--- a/packages/core/tests/canvas/text/readiness.test.ts+++ b/packages/core/tests/canvas/text/readiness.test.ts@@ -18,7 +18,7 @@ describe('text readiness with characters no font has', () => {await fontManager.fetchBundledFont('/InterVariable.ttf'),'bundled Inter font')- fontManager.markLoaded('Inter', 'Regular', inter)+ await fontManager.markLoaded('Inter', 'Regular', inter)})test('draws the text with the fonts it has', async () => {diff --git a/packages/core/tests/canvas/text/shape.test.ts b/packages/core/tests/canvas/text/shape.test.tsindex 3d65ac822..c03c8946d 100644--- a/packages/core/tests/canvas/text/shape.test.ts+++ b/packages/core/tests/canvas/text/shape.test.ts@@ -14,7 +14,7 @@ import { withFigExportRuntime, withTextShaper } from '#core/canvas/text/shape'import { getCanvasKit } from '#core/canvaskit'import { EMOJI_METRICS_FAMILY } from '#core/text/emoji'import { fontManager } from '#core/text/fonts'-import { getGlyphOutlineMetricsSync } from '#core/text/opentype'+import { getGlyphOutlineMetricsSync } from '#core/text/font/glyphs'const testFont = (name: string) => join(FIXTURES, 'fonts', name)@@ -42,7 +42,7 @@ describe('text shaping for saved glyphs', () => {await fontManager.fetchBundledFont('/InterVariable.ttf'),'bundled Inter font')- fontManager.markLoaded('Inter', 'Regular', inter)+ await fontManager.markLoaded('Inter', 'Regular', inter)})/**@@ -54,7 +54,7 @@ describe('text shaping for saved glyphs', () => {await fontManager.fetchBundledFont('/OpenPencilEmojiMetrics-Regular.ttf'),'bundled emoji metrics font')- fontManager.markLoaded(EMOJI_METRICS_FAMILY, 'Regular', metrics)+ await fontManager.markLoaded(EMOJI_METRICS_FAMILY, 'Regular', metrics)const family = '👨👩👧👦'const shaped = expectDefined(await shape({ text: `a😀${family}🇺🇸b`, fontSize: 40, width: 400, textAutoResize: 'NONE' }),@@ -75,7 +75,7 @@ describe('text shaping for saved glyphs', () => {await fontManager.fetchBundledFont('/OpenPencilEmojiMetrics-Regular.ttf'),'bundled emoji metrics font')- fontManager.markLoaded(EMOJI_METRICS_FAMILY, 'Regular', metrics)+ await fontManager.markLoaded(EMOJI_METRICS_FAMILY, 'Regular', metrics)const shaped = expectDefined(await shape({ text: 'a😀☺©', fontSize: 40, width: 400, textAutoResize: 'NONE' }),'shaped text'@@ -152,7 +152,7 @@ describe('text shaping for saved glyphs', () => {await fontManager.fetchBundledFont('/OpenPencilEmojiMetrics-Regular.ttf'),'bundled emoji metrics font')- fontManager.markLoaded(EMOJI_METRICS_FAMILY, 'Regular', metrics)+ await fontManager.markLoaded(EMOJI_METRICS_FAMILY, 'Regular', metrics)const sequence = '\u{1f469}\u200d\u{1f9af}\u200d\u{1f4bb}'const shaped = expectDefined(await shape({ text: `x${sequence}x`, fontSize: 40, width: 400, textAutoResize: 'NONE' }),@@ -174,7 +174,7 @@ describe('text shaping for saved glyphs', () => {await fontManager.fetchBundledFont('/OpenPencilEmojiMetrics-Regular.ttf'),'bundled emoji metrics font')- fontManager.markLoaded(EMOJI_METRICS_FAMILY, 'Regular', metrics)+ await fontManager.markLoaded(EMOJI_METRICS_FAMILY, 'Regular', metrics)const shaped = expectDefined(await shape({text: '\u05d0\u{1f600}\u05d1',@@ -201,7 +201,7 @@ describe('text shaping for saved glyphs', () => {await fontManager.fetchBundledFont('/OpenPencilEmojiMetrics-Regular.ttf'),'bundled emoji metrics font')- fontManager.markLoaded(EMOJI_METRICS_FAMILY, 'Regular', metrics)+ await fontManager.markLoaded(EMOJI_METRICS_FAMILY, 'Regular', metrics)const scotland = '\u{1f3f4}\u{e0067}\u{e0062}\u{e0073}\u{e0063}\u{e0074}\u{e007f}'const shaped = expectDefined(await shape({@@ -334,7 +334,7 @@ describe('text shaping for saved glyphs', () => {fallbackFamilies.length = 0try {const cjk = await Bun.file(testFont('NotoSansCJK-Test.otf')).arrayBuffer()- fontManager.markLoaded('Shape Test CJK', 'Regular', cjk)+ await fontManager.markLoaded('Shape Test CJK', 'Regular', cjk)fontManager.setCJKFallbackFamily('Shape Test CJK')const shaped = expectDefined(await shape({ text: 'Hi 你好' }), 'shaped text')const ni = expectDefined(@@ -354,7 +354,7 @@ describe('text shaping for saved glyphs', () => {test('outlines a variable font at the instance the text is set in', async () => {const variable = await Bun.file(testFont('InterVariable-Latin.ttf')).arrayBuffer()- fontManager.markLoaded('Shape Test Variable', 'Bold', variable)+ await fontManager.markLoaded('Shape Test Variable', 'Bold', variable)const shaped = expectDefined(await shape({ text: 'l', fontFamily: 'Shape Test Variable', fontWeight: 700 }),'shaped text'diff --git a/packages/core/tests/editor/structure/flatten.test.ts b/packages/core/tests/editor/structure/flatten.test.tsindex 4d3d91456..c6e02a8f0 100644--- a/packages/core/tests/editor/structure/flatten.test.ts+++ b/packages/core/tests/editor/structure/flatten.test.ts@@ -32,12 +32,12 @@ async function createEditorWithRenderer() {async function loadInterRegular() {const data = await Bun.file('packages/core/assets/InterVariable.ttf').arrayBuffer()- fontManager.markLoaded('Inter', 'Regular', data)+ await fontManager.markLoaded('Inter', 'Regular', data)}async function loadInterBold() {const data = await Bun.file('packages/core/assets/InterVariable.ttf').arrayBuffer()- fontManager.markLoaded('Inter', 'Bold', data)+ await fontManager.markLoaded('Inter', 'Bold', data)}async function loadNotoSansSC() {@@ -45,7 +45,7 @@ async function loadNotoSansSC() {const text = await file.slice(0, 32).text()if (text.startsWith('version ')) return falseconst data = await file.arrayBuffer()- fontManager.markLoaded('Noto Sans SC', 'Regular', data)+ await fontManager.markLoaded('Noto Sans SC', 'Regular', data)fontManager.setCJKFallbackFamily('Noto Sans SC')return true}diff --git a/packages/core/tests/figma-api/text/autosize.test.ts b/packages/core/tests/figma-api/text/autosize.test.tsindex c8ffebe8a..893371a1e 100644--- a/packages/core/tests/figma-api/text/autosize.test.ts+++ b/packages/core/tests/figma-api/text/autosize.test.ts@@ -11,7 +11,7 @@ import { fontManager } from '#core/text/fonts'// differently by up to a pixel.beforeAll(async () => {- fontManager.markLoaded(+ await fontManager.markLoaded('Inter','Regular',expectDefined(await fontManager.fetchBundledFont('/InterVariable.ttf'), 'bundled Inter font')diff --git a/packages/core/tests/figma-api/text/styles.test.ts b/packages/core/tests/figma-api/text/styles.test.tsindex de92aef54..4bc573b51 100644--- a/packages/core/tests/figma-api/text/styles.test.ts+++ b/packages/core/tests/figma-api/text/styles.test.ts@@ -28,7 +28,7 @@ beforeAll(async () => {await fontManager.fetchBundledFont('/InterVariable.ttf'),'bundled Inter font')- fontManager.markLoaded('Inter', 'Regular', inter)+ await fontManager.markLoaded('Inter', 'Regular', inter)})describe('styled text segments', () => {diff --git a/packages/core/tests/figma-api/text/variations.test.ts b/packages/core/tests/figma-api/text/variations.test.tsindex 81509a558..b5ac7fdde 100644--- a/packages/core/tests/figma-api/text/variations.test.ts+++ b/packages/core/tests/figma-api/text/variations.test.ts@@ -16,8 +16,8 @@ const STATIC = 'Variations Static'beforeAll(async () => {const variable = await Bun.file(join(FIXTURES, 'fonts', 'InterVariable-Latin.ttf')).arrayBuffer()const static_ = await Bun.file(join(FIXTURES, 'fonts', 'InterRegular-Faces.ttf')).arrayBuffer()- fontManager.markLoaded(VARIABLE, 'Regular', variable)- fontManager.markLoaded(STATIC, 'Regular', static_)+ await fontManager.markLoaded(VARIABLE, 'Regular', variable)+ await fontManager.markLoaded(STATIC, 'Regular', static_)})function text(family = VARIABLE) {@@ -97,8 +97,8 @@ describe('variable fonts in the plugin API', () => {const data = await Bun.file(join(FIXTURES, 'fonts', 'InterVariable-Latin.ttf')).arrayBuffer()const upright = data.slice(0)const italic = data.slice(0)- fontManager.markLoaded('Variations Slant', 'Regular', upright)- fontManager.markLoaded('Variations Slant', 'Italic', italic)+ await fontManager.markLoaded('Variations Slant', 'Regular', upright)+ await fontManager.markLoaded('Variations Slant', 'Italic', italic)expect(fontManager.familyVariation('Variations Slant', true)?.data).toBe(italic)expect(fontManager.familyVariation('Variations Slant', false)?.data).toBe(upright)})diff --git a/packages/core/tests/io/formats/fig/export/live-document.test.ts b/packages/core/tests/io/formats/fig/export/live-document.test.tsindex 181726d4a..b5839d116 100644--- a/packages/core/tests/io/formats/fig/export/live-document.test.ts+++ b/packages/core/tests/io/formats/fig/export/live-document.test.ts@@ -18,8 +18,8 @@ test('font digests cover a font added while they load', async () => {await fontManager.fetchBundledFont('/InterVariable.ttf'),'bundled Inter font')- fontManager.markLoaded('Inter', 'Regular', inter)- fontManager.markLoaded('Inter', 'Bold', inter)+ await fontManager.markLoaded('Inter', 'Regular', inter)+ await fontManager.markLoaded('Inter', 'Bold', inter)const graph = new SceneGraph()const pageId = graph.getPages()[0].idgraph.createNode('TEXT', pageId, { text: 'Body', fontFamily: 'Inter', fontWeight: 400 })diff --git a/packages/core/tests/io/formats/fig/roundtrip/glyph-blob.test.ts b/packages/core/tests/io/formats/fig/roundtrip/glyph-blob.test.tsindex c05d64168..b2f33ea09 100644--- a/packages/core/tests/io/formats/fig/roundtrip/glyph-blob.test.ts+++ b/packages/core/tests/io/formats/fig/roundtrip/glyph-blob.test.ts@@ -36,10 +36,10 @@ function countGlyphBlobs(bytes: Uint8Array) {return { glyphs, glyphsWithBlob, uniqueGlyphBlobs: uniqueGlyphBlobs.size }}-function loadInterFonts() {+async function loadInterFonts() {for (const style of ['Regular', 'Medium', 'SemiBold', 'Bold', 'ExtraBold']) {const bytes = readFileSync(resolve(INTER_ASSETS, `Inter-${style}.ttf`))- fontManager.markLoaded(+ await fontManager.markLoaded('Inter',style,bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)@@ -78,7 +78,7 @@ heavy('roundtrip: text glyph blobs', () => {)test('deduplicates generated glyph blobs across repeated text', async () => {- loadInterFonts()+ await loadInterFonts()const graph = new SceneGraph()const page = graph.getPages()[0]@@ -104,7 +104,7 @@ heavy('roundtrip: text glyph blobs', () => {})test('reopens wrapped text on the lines it was drawn on (#914)', async () => {- loadInterFonts()+ await loadInterFonts()const graph = new SceneGraph()const page = graph.getPages()[0]diff --git a/packages/core/tests/io/formats/fig/roundtrip/text/lists.test.ts b/packages/core/tests/io/formats/fig/roundtrip/text/lists.test.tsindex 82d244efd..61f75be46 100644--- a/packages/core/tests/io/formats/fig/roundtrip/text/lists.test.ts+++ b/packages/core/tests/io/formats/fig/roundtrip/text/lists.test.ts@@ -21,7 +21,7 @@ beforeAll(async () => {await fontManager.fetchBundledFont('/InterVariable.ttf'),'bundled Inter font')- fontManager.markLoaded('Inter', 'Regular', inter)+ await fontManager.markLoaded('Inter', 'Regular', inter)})test('writes lists as Figma does and reads them back', async () => {diff --git a/packages/core/tests/io/formats/fig/roundtrip/text/styles.test.ts b/packages/core/tests/io/formats/fig/roundtrip/text/styles.test.tsindex bc62a723c..603fbdf4e 100644--- a/packages/core/tests/io/formats/fig/roundtrip/text/styles.test.ts+++ b/packages/core/tests/io/formats/fig/roundtrip/text/styles.test.ts@@ -13,7 +13,7 @@ beforeAll(async () => {await fontManager.fetchBundledFont('/InterVariable.ttf'),'bundled Inter font')- fontManager.markLoaded('Inter', 'Regular', inter)+ await fontManager.markLoaded('Inter', 'Regular', inter)})test('keeps auto line height on text that mixes font sizes', async () => {diff --git a/packages/core/tests/io/formats/pdf/text-layout.test.ts b/packages/core/tests/io/formats/pdf/text-layout.test.tsindex f2bff85c4..7b19982e4 100644--- a/packages/core/tests/io/formats/pdf/text-layout.test.ts+++ b/packages/core/tests/io/formats/pdf/text-layout.test.ts@@ -13,7 +13,7 @@ const SENTENCE = 'A sentence long enough that it has to wrap onto a second line.beforeAll(async () => {const inter = expectDefined(await fontManager.fetchBundledFont('/InterVariable.ttf'), 'Inter')- fontManager.markLoaded('Inter', 'Regular', inter)+ await fontManager.markLoaded('Inter', 'Regular', inter)})test('a paragraph wrapped on the canvas keeps its lines in the SVG drawn into a PDF', async () => {diff --git a/packages/core/tests/text/font/glyphs.test.ts b/packages/core/tests/text/font/glyphs.test.tsnew file mode 100644index 000000000..c24355000--- /dev/null+++ b/packages/core/tests/text/font/glyphs.test.ts@@ -0,0 +1,42 @@+import { expect, test } from 'bun:test'+import { join } from 'node:path'++import { corePackagePath, FIXTURES } from '#core-tests/helpers/paths'++import { fontManager } from '@open-pencil/core/text'++import {+ getGlyphOutlineMetricsSync,+ glyphAdvanceSync,+ glyphOutlineSourceSync+} from '#core/text/font/glyphs'++test('measures default advances whatever instance of a variable font was last outlined', async () => {+ const family = 'OpenType Test Variable'+ await fontManager.markLoaded(+ family,+ 'Regular',+ await Bun.file(join(FIXTURES, 'fonts', 'InterVariable-Latin.ttf')).arrayBuffer()+ )+ const source = glyphOutlineSourceSync(family, 'Regular', [{ axis: 'wght', value: 900 }])+ const glyph = source?.glyphOf('H') ?? 0+ const before = glyphAdvanceSync(family, 'Regular', glyph, 100)+ // Outlining an instance must not change the default instance's advances.+ source?.outline(glyph, 100)+ expect(glyphAdvanceSync(family, 'Regular', glyph, 100)).toBe(before)+})++test('outlines a shaped mark where shaping places it on its base letter', async () => {+ const family = 'HarfBuzz Test Marks'+ await fontManager.markLoaded(+ family,+ 'Regular',+ await Bun.file(corePackagePath('assets', 'InterVariable.ttf')).arrayBuffer()+ )+ const [base, mark] = getGlyphOutlineMetricsSync(family, 'Regular', 'q́', 100) ?? []+ const xs = (mark?.commands ?? []).flatMap((command) => (command.x === undefined ? [] : [command.x]))+ expect(xs.length).toBeGreaterThan(0)+ // The acute's pen is past the q; its outline reaches back over the q.+ expect(mark?.x).toBe(base?.advance)+ expect(Math.max(...xs)).toBeLessThan(0)+})diff --git a/packages/core/tests/text/fonts.test.ts b/packages/core/tests/text/fonts.test.tsindex e230bf971..045b8876c 100644--- a/packages/core/tests/text/fonts.test.ts+++ b/packages/core/tests/text/fonts.test.ts@@ -37,7 +37,7 @@ test('a new catalog tells listeners to ask for their families again', () => {test('draws every weight its variable font covers from the one file, in the same slant', async () => {const manager = offlineManager()const variable = await Bun.file(join(FIXTURES, 'fonts', 'InterVariable-Latin.ttf')).arrayBuffer()- manager.markLoaded('Fonts Test Variable', 'Regular', variable)+ await manager.markLoaded('Fonts Test Variable', 'Regular', variable)expect(await manager.loadFont('Fonts Test Variable', 'Bold')).toBe(variable)expect(manager.isStyleLoaded('Fonts Test Variable', 'Bold')).toBe(true)// The file is upright, so it does not stand in for an italic.@@ -52,7 +52,7 @@ test('an installed face of the style comes before a variable file loaded for anomanager.setHostFontLoader(async (name, style) =>name === family && style === 'Regular' ? installed : null)- manager.markLoaded(family, 'Light', variable)+ await manager.markLoaded(family, 'Light', variable)expect(await manager.loadFont(family, 'Regular')).toBe(installed)// A weight nothing installs draws from the variable file.expect(await manager.loadFont(family, 'Bold')).toBe(variable)diff --git a/packages/core/tests/text/opentype.test.ts b/packages/core/tests/text/opentype.test.tsdeleted file mode 100644index 36860dab6..000000000--- a/packages/core/tests/text/opentype.test.ts+++ /dev/null@@ -1,23 +0,0 @@-import { expect, test } from 'bun:test'-import { join } from 'node:path'--import { FIXTURES } from '#core-tests/helpers/paths'--import { fontManager } from '@open-pencil/core/text'--import { glyphAdvanceSync, glyphOutlineSourceSync } from '#core/text/opentype'--test('measures default advances whatever instance of a variable font was last outlined', async () => {- const family = 'OpenType Test Variable'- fontManager.markLoaded(- family,- 'Regular',- await Bun.file(join(FIXTURES, 'fonts', 'InterVariable-Latin.ttf')).arrayBuffer()- )- const source = glyphOutlineSourceSync(family, 'Regular', [{ axis: 'wght', value: 900 }])- const glyph = source?.glyphOf('H') ?? 0- const before = glyphAdvanceSync(family, 'Regular', glyph, 100)- // opentype.js writes the instance's advance onto the glyph it outlines.- source?.outline(glyph, 100)- expect(glyphAdvanceSync(family, 'Regular', glyph, 100)).toBe(before)-})diff --git a/packages/core/tests/text/prepare.test.ts b/packages/core/tests/text/prepare.test.tsindex ebcbfc431..ee360b345 100644--- a/packages/core/tests/text/prepare.test.ts+++ b/packages/core/tests/text/prepare.test.ts@@ -28,7 +28,7 @@ describe('emoji font preparation', () => {await fontManager.fetchBundledFont('/InterVariable.ttf'),'bundled Inter font')- fontManager.markLoaded('Inter', 'Regular', inter)+ await fontManager.markLoaded('Inter', 'Regular', inter)})afterEach(() => {diff --git a/patches/[email protected] b/patches/[email protected]deleted file mode 100644index 8c58bf35a..000000000--- a/patches/[email protected]+++ /dev/null@@ -1,88 +0,0 @@-diff --git a/dist/opentype.js b/dist/opentype.js-index 4dc6dea3bc470c5932364e0162bca66d614c8045..2568c3fc2c5a1a5cd5a556a08dd73ccf17b412f3 100644---- a/dist/opentype.js-+++ b/dist/opentype.js-@@ -2322,7 +2322,6 @@ var opentype = (() => {- let serializedDataOffset = this.relativeOffset;- for (let h = 0; h < count; h++) {- const header = headers[h];-- header.privatePoints = [];- this.relativeOffset = serializedDataOffset;- if (flavor === "cvar" && !header.peakTuple) {- console.warn("An embedded peak tuple is required in TupleVariationHeaders for the cvar table.");-@@ -2339,11 +2338,11 @@ var opentype = (() => {- const parseDeltas = () => {- let pointsCount = 0;- if (flavor === "gvar") {-- pointsCount = header.privatePoints.length || sharedPoints.length;-+ pointsCount = header.privatePoints ? header.privatePoints.length : sharedPoints.length;- if (!pointsCount) {- const glyph = glyphs.get(glyphIndex);- glyph.path;-- pointsCount = glyph.points.length;-+ pointsCount = glyph.isComposite ? glyph.components.length : glyph.points.length;- pointsCount += 4;- }- } else if (flavor === "cvar") {-@@ -11303,7 +11302,7 @@ var opentype = (() => {- const component = glyph.components[c];- const componentGlyph = this.font.glyphs.get(component.glyphIndex);- const componentTransform = copyComponent(component);-- const deltaIndex = tuplePoints.indexOf(c);-+ const deltaIndex = tuplePoints.length ? tuplePoints.indexOf(c) : c;- if (deltaIndex > -1) {- componentTransform.dx += Math.round(header.deltas[deltaIndex] * factor);- componentTransform.dy += Math.round(header.deltasY[deltaIndex] * factor);-@@ -11366,7 +11365,7 @@ var opentype = (() => {- if (factor === 0) {- continue;- }-- const tuplePoints = header.privatePoints.length ? header.privatePoints : sharedPoints;-+ const tuplePoints = header.privatePoints ? header.privatePoints : sharedPoints;- if (flavor === "gvar" && args.glyph && args.glyph.isComposite) {- this.transformComponents(args.glyph, transformedPoints, coords, tuplePoints, header, factor);- } else if (tuplePoints.length === 0) {-diff --git a/dist/opentype.mjs b/dist/opentype.mjs-index 53ed20eccb08a16519bbd40a866e0bdc3fa9f2d6..30542d96f3bca0bf559fb099fa382808a78b01dd 100644---- a/dist/opentype.mjs-+++ b/dist/opentype.mjs-@@ -2290,7 +2290,6 @@ Parser.prototype.parseTupleVariationStore = function(tableOffset, axisCount, fla- let serializedDataOffset = this.relativeOffset;- for (let h = 0; h < count; h++) {- const header = headers[h];-- header.privatePoints = [];- this.relativeOffset = serializedDataOffset;- if (flavor === "cvar" && !header.peakTuple) {- console.warn("An embedded peak tuple is required in TupleVariationHeaders for the cvar table.");-@@ -2307,11 +2306,11 @@ Parser.prototype.parseTupleVariationStore = function(tableOffset, axisCount, fla- const parseDeltas = () => {- let pointsCount = 0;- if (flavor === "gvar") {-- pointsCount = header.privatePoints.length || sharedPoints.length;-+ pointsCount = header.privatePoints ? header.privatePoints.length : sharedPoints.length;- if (!pointsCount) {- const glyph = glyphs.get(glyphIndex);- glyph.path;-- pointsCount = glyph.points.length;-+ pointsCount = glyph.isComposite ? glyph.components.length : glyph.points.length;- pointsCount += 4;- }- } else if (flavor === "cvar") {-@@ -11271,7 +11270,7 @@ var VariationProcessor = class {- const component = glyph.components[c];- const componentGlyph = this.font.glyphs.get(component.glyphIndex);- const componentTransform = copyComponent(component);-- const deltaIndex = tuplePoints.indexOf(c);-+ const deltaIndex = tuplePoints.length ? tuplePoints.indexOf(c) : c;- if (deltaIndex > -1) {- componentTransform.dx += Math.round(header.deltas[deltaIndex] * factor);- componentTransform.dy += Math.round(header.deltasY[deltaIndex] * factor);-@@ -11334,7 +11333,7 @@ var VariationProcessor = class {- if (factor === 0) {- continue;- }-- const tuplePoints = header.privatePoints.length ? header.privatePoints : sharedPoints;-+ const tuplePoints = header.privatePoints ? header.privatePoints : sharedPoints;- if (flavor === "gvar" && args.glyph && args.glyph.isComposite) {- this.transformComponents(args.glyph, transformedPoints, coords, tuplePoints, header, factor);- } else if (tuplePoints.length === 0) {diff --git a/tests/e2e/canvas/text/path-shaping-visual.spec.ts b/tests/e2e/canvas/text/path-shaping-visual.spec.tsnew file mode 100644index 000000000..d9bbcf7d9--- /dev/null+++ b/tests/e2e/canvas/text/path-shaping-visual.spec.ts@@ -0,0 +1,55 @@+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'++const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')++/**+ * Path text is laid out from the shaped glyphs of its font when its text changes: kerned pairs,+ * ligatures, and marks placed on their base letters.+ */+test('reflows text on a path with its kerning, ligatures, and marks', async () => {+ const reflowed = await editor.page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('Missing editor')+ const box = { x: 40, y: 40, width: 400, height: 100 }+ const node = store.graph.createNode('TEXT', store.state.currentPageId, {+ ...box,+ text: 'AB',+ fontFamily: 'Inter',+ fontWeight: 400,+ italic: false,+ fontSize: 40,+ textAutoResize: 'NONE',+ textPathBox: { ...box },+ // Where the old text sat on the path, which the new text is laid out from.+ derivedTextGlyphs: [+ { commandsBlob: new Uint8Array(4), x: 50, y: 50, fontSize: 40, rotation: 0 },+ { commandsBlob: new Uint8Array(4), x: 90, y: 50, fontSize: 40, rotation: 0 }+ ]+ })+ node.textPathData = {+ network: {+ vertices: [+ { x: 0, y: 50 },+ { x: 400, y: 50 }+ ],+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],+ regions: []+ },+ normalizedSize: { x: 400, y: 100 },+ tValue: 0,+ forward: true+ }+ store.updateNode(node.id, { text: 'AVATAR office q́ x̣' })+ store.requestRender()+ return store.graph.getNode(node.id)?.derivedTextGlyphs?.length ?? 0+ })+ expect(reflowed).toBeGreaterThan(0)+ await editor.canvas.waitForRender()+ editor.canvas.assertNoErrors()++ // A misplaced mark moves a few hundred pixels, which the default 1% of the region would allow.+ expect(await editor.canvas.screenshotCanvasRegion(480, 180)).toMatchSnapshot(+ 'text-path-reflowed-shaping.png',+ { maxDiffPixels: 50 }+ )+})diff --git a/tests/e2e/canvas/text/path-shaping-visual.spec.ts-snapshots/text-path-reflowed-shaping-openpencil-darwin.png b/tests/e2e/canvas/text/path-shaping-visual.spec.ts-snapshots/text-path-reflowed-shaping-openpencil-darwin.pngnew file mode 100644index 000000000..45b5912dcBinary files /dev/null and b/tests/e2e/canvas/text/path-shaping-visual.spec.ts-snapshots/text-path-reflowed-shaping-openpencil-darwin.png differdiff --git a/tests/e2e/fonts/cjk-fallback.spec.ts b/tests/e2e/fonts/cjk-fallback.spec.tsindex c2e20829c..2af1135bf 100644--- a/tests/e2e/fonts/cjk-fallback.spec.ts+++ b/tests/e2e/fonts/cjk-fallback.spec.ts@@ -108,7 +108,7 @@ test('CJK text waits for fallback fonts and repaints after they load', async ({const originalRender = renderer.renderFromEditorState.bind(renderer)fontManager.ensureFallbackPack = async (scripts = ['cjk', 'arabic']) => {await fallbackGate- fontManager.markLoaded('Noto Sans CJK SC', 'Regular', fallbackData)+ await fontManager.markLoaded('Noto Sans CJK SC', 'Regular', fallbackData)fontManager.setCJKFallbackFamily('Noto Sans CJK SC')return Object.fromEntries(scripts.map((script) => [script, ['Noto Sans CJK SC']]))}diff --git a/tests/e2e/fonts/cjk-rendering-visual.spec.ts b/tests/e2e/fonts/cjk-rendering-visual.spec.tsindex 7b028d594..fe3e17210 100644--- a/tests/e2e/fonts/cjk-rendering-visual.spec.ts+++ b/tests/e2e/fonts/cjk-rendering-visual.spec.ts@@ -142,8 +142,8 @@ test('international text is correct on its first visible paint', async ({ page }response.arrayBuffer())])- fontManager.markLoaded('Noto Sans CJK SC', 'Regular', cjk)- fontManager.markLoaded('Noto Naskh Arabic', 'Regular', arabic)+ await fontManager.markLoaded('Noto Sans CJK SC', 'Regular', cjk)+ await fontManager.markLoaded('Noto Naskh Arabic', 'Regular', arabic)fontManager.setCJKFallbackFamily('Noto Sans CJK SC')fontManager.setArabicFallbackFamily('Noto Naskh Arabic')@@ -319,8 +319,8 @@ test('typed and tool-created text repaint with the same resolved fallbacks', asyresponse.arrayBuffer())])- fontManager.markLoaded('Noto Sans CJK SC', 'Regular', cjk)- fontManager.markLoaded('Noto Naskh Arabic', 'Regular', arabic)+ await fontManager.markLoaded('Noto Sans CJK SC', 'Regular', cjk)+ await fontManager.markLoaded('Noto Naskh Arabic', 'Regular', arabic)fontManager.setCJKFallbackFamily('Noto Sans CJK SC')fontManager.setArabicFallbackFamily('Noto Naskh Arabic')store.commitTextEdit()@@ -383,7 +383,7 @@ test('substituted fonts still request fallbacks for CJK text', async ({ page })const requestedScripts: string[] = []fontManager.ensureFallbackPack = async (scripts = ['cjk', 'arabic']) => {requestedScripts.push(...scripts)- fontManager.markLoaded('Noto Sans CJK SC', 'Regular', cjk, 'fallback')+ await fontManager.markLoaded('Noto Sans CJK SC', 'Regular', cjk, 'fallback')fontManager.setCJKFallbackFamily('Noto Sans CJK SC')return { cjk: ['Noto Sans CJK SC'] }}diff --git a/tests/e2e/fonts/variable-weights-visual.spec.ts b/tests/e2e/fonts/variable-weights-visual.spec.tsindex 19dc081a9..03a7f4b0d 100644--- a/tests/e2e/fonts/variable-weights-visual.spec.ts+++ b/tests/e2e/fonts/variable-weights-visual.spec.ts@@ -41,7 +41,7 @@ test('variable fonts render each style at its named instance', async ({ page })response.arrayBuffer())for (const style of ['Regular', 'Medium', 'SemiBold', 'Bold']) {- fontManager.markLoaded('Inter Variable', style, data)+ await fontManager.markLoaded('Inter Variable', style, data)}const samples = [diff --git a/tests/engine/app/font-loading.test.ts b/tests/engine/app/font-loading.test.tsindex 2a11beb91..351dc332b 100644--- a/tests/engine/app/font-loading.test.ts+++ b/tests/engine/app/font-loading.test.ts@@ -33,7 +33,7 @@ describe('app font loading', () => {const interData = await Bun.file(repoPath('packages/core/assets/InterVariable.ttf')).arrayBuffer()- fontManager.markLoaded('Inter', 'Regular', interData)+ await fontManager.markLoaded('Inter', 'Regular', interData)const graph = new SceneGraph()const page = graph.getPages()[0]diff --git a/tests/engine/clipboard/figma/html.test.ts b/tests/engine/clipboard/figma/html.test.tsindex 7ecc5c951..14ccfbfb3 100644--- a/tests/engine/clipboard/figma/html.test.ts+++ b/tests/engine/clipboard/figma/html.test.ts@@ -32,7 +32,7 @@ describe('buildFigmaClipboardHTML', () => {await fontManager.fetchBundledFont('/InterVariable.ttf'),'bundled Inter font')- fontManager.markLoaded('Inter', 'Regular', inter)+ await fontManager.markLoaded('Inter', 'Regular', inter)})it('encodes a simple frame without throwing', async () => {diff --git a/tests/engine/core/editor/text/path-edit.test.ts b/tests/engine/core/editor/text/path-edit.test.tsindex 91b045f72..c06fb607e 100644--- a/tests/engine/core/editor/text/path-edit.test.ts+++ b/tests/engine/core/editor/text/path-edit.test.ts@@ -4,8 +4,8 @@ import { SceneGraph } from '@open-pencil/scene-graph'import { pixelLength } from '@open-pencil/scene-graph/text'import { pathTextEditChanges, resizedPathTextGlyphs } from '#core/editor/text/path-edit'+import { getGlyphOutlineMetricsSync } from '#core/text/font/glyphs'import { fontManager } from '#core/text/fonts'-import { getGlyphOutlineMetricsSync } from '#core/text/opentype'import { nearestArcPoint, pointAtArc, sampleTextPath, textPathStartArc } from '#core/text/path'import { expectDefined } from '#tests/helpers/assert'@@ -27,7 +27,7 @@ describe('pathTextEditChanges — reflow on character edit', () => {const font = await fontManager.fetchBundledFont('/InterVariable.ttf')expect(font).toBeTruthy()if (!font) return- fontManager.markLoaded('Inter', 'Regular', font)+ await fontManager.markLoaded('Inter', 'Regular', font)const graph = new SceneGraph()const page = expectDefined(graph.getPages()[0])@@ -69,11 +69,11 @@ describe('pathTextEditChanges — reflow on character edit', () => {}})- test('uses opentype.js glyph positioning when the font supports its shaping pipeline', async () => {+ test('positions glyphs as HarfBuzz shapes them', async () => {const font = await fontManager.fetchBundledFont('/InterVariable.ttf')expect(font).toBeTruthy()if (!font) return- fontManager.markLoaded('Inter', 'Regular', font)+ await fontManager.markLoaded('Inter', 'Regular', font)const metrics = getGlyphOutlineMetricsSync('Inter', 'Regular', 'AV ffi', 40)expect(metrics).toBeTruthy()@@ -87,7 +87,7 @@ describe('pathTextEditChanges — reflow on character edit', () => {const font = await fontManager.fetchBundledFont('/InterVariable.ttf')expect(font).toBeTruthy()if (!font) return- fontManager.markLoaded('Inter', 'Regular', font)+ await fontManager.markLoaded('Inter', 'Regular', font)function lastGlyphX(letterSpacing: number): number {const graph = new SceneGraph()@@ -160,7 +160,7 @@ describe('pathTextEditChanges — reflow on character edit', () => {const font = await fontManager.fetchBundledFont('/InterVariable.ttf')expect(font).toBeTruthy()if (!font) return- fontManager.markLoaded('Inter', 'Regular', font)+ await fontManager.markLoaded('Inter', 'Regular', font)const graph = new SceneGraph()const page = expectDefined(graph.getPages()[0])@@ -202,7 +202,7 @@ describe('pathTextEditChanges — alignment', () => {async function alignedText(align: 'LEFT' | 'CENTER' | 'RIGHT', forward = true) {const font = await fontManager.fetchBundledFont('/InterVariable.ttf')if (!font) throw new Error('missing bundled font')- fontManager.markLoaded('Inter', 'Regular', font)+ await fontManager.markLoaded('Inter', 'Regular', font)const graph = new SceneGraph()const page = expectDefined(graph.getPages()[0])const node = graph.createNode('TEXT', page.id, {@@ -323,7 +323,7 @@ describe('aligned path text is laid out from the text path start, as in Figma',async function edited(align: 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED', forward = true) {const font = await fontManager.fetchBundledFont('/InterVariable.ttf')if (!font) throw new Error('bundled font missing')- fontManager.markLoaded('Inter', 'Regular', font)+ await fontManager.markLoaded('Inter', 'Regular', font)const text = 'Hello'const width = expectDefined(getGlyphOutlineMetricsSync('Inter', 'Regular', text, 40)).reduce((sum, glyph) => sum + glyph.advance,@@ -386,7 +386,7 @@ describe('path text that overflows its alignment’s part of the path, as in Figasync function overflowing(align: 'LEFT' | 'CENTER' | 'RIGHT', tValue = 0.5) {const font = await fontManager.fetchBundledFont('/InterVariable.ttf')if (!font) throw new Error('bundled font missing')- fontManager.markLoaded('Inter', 'Regular', font)+ await fontManager.markLoaded('Inter', 'Regular', font)const graph = new SceneGraph()const page = expectDefined(graph.getPages()[0])const node = graph.createNode('TEXT', page.id, {@@ -467,7 +467,7 @@ describe('path text that overflows its alignment’s part of the path, as in Figtest('overflowing text on a closed path keeps what fits one loop', async () => {const font = await fontManager.fetchBundledFont('/InterVariable.ttf')if (!font) throw new Error('bundled font missing')- fontManager.markLoaded('Inter', 'Regular', font)+ await fontManager.markLoaded('Inter', 'Regular', font)const graph = new SceneGraph()const page = expectDefined(graph.getPages()[0])const node = graph.createNode('TEXT', page.id, {@@ -530,7 +530,7 @@ describe('resizedPathTextGlyphs — resize lays the text out again', () => {test('a squashed or stretched square keeps every letter on the path, in order', async () => {const font = await fontManager.fetchBundledFont('/InterVariable.ttf')if (!font) throw new Error('expected the bundled Inter font')- fontManager.markLoaded('Inter', 'Regular', font)+ await fontManager.markLoaded('Inter', 'Regular', font)const corner = (x: number, y: number) => ({ x, y })const side = (start: number, end: number) => ({diff --git a/tests/engine/core/editor/text/start-editing-gate.test.ts b/tests/engine/core/editor/text/start-editing-gate.test.tsindex de3dab1bb..7377c03a4 100644--- a/tests/engine/core/editor/text/start-editing-gate.test.ts+++ b/tests/engine/core/editor/text/start-editing-gate.test.ts@@ -15,7 +15,7 @@ describe('startTextEditing — path-text font gate', () => {const font = await fontManager.fetchBundledFont('/InterVariable.ttf')expect(font).toBeTruthy()if (!font) return- fontManager.markLoaded('Inter', 'Regular', font)+ await fontManager.markLoaded('Inter', 'Regular', font)const editor = createEditor()const page = editor.state.currentPageIddiff --git a/tests/engine/render/canvas/font-readiness.test.ts b/tests/engine/render/canvas/font-readiness.test.tsindex 7ddcae0eb..e54f57d24 100644--- a/tests/engine/render/canvas/font-readiness.test.ts+++ b/tests/engine/render/canvas/font-readiness.test.ts@@ -6,7 +6,7 @@ import { isNodeFontLoaded } from '#core/canvas/text'import { fontManager } from '#core/text/fonts'describe('canvas text font readiness', () => {- test('requires the exact requested font weight before rendering text', () => {+ test('requires the exact requested font weight before rendering text', async () => {const family = `ExactWeight_${Date.now()}`const node = createDefaultNode(() => 'text', 'TEXT', {text: 'Bold title',@@ -16,10 +16,10 @@ describe('canvas text font readiness', () => {styleRuns: []})- fontManager.markLoaded(family, 'Regular', new ArrayBuffer(8))+ await fontManager.markLoaded(family, 'Regular', new ArrayBuffer(8))expect(isNodeFontLoaded({} as Parameters<typeof isNodeFontLoaded>[0], node)).toBe(false)- fontManager.markLoaded(family, 'Bold', new ArrayBuffer(8))+ await fontManager.markLoaded(family, 'Bold', new ArrayBuffer(8))expect(isNodeFontLoaded({} as Parameters<typeof isNodeFontLoaded>[0], node)).toBe(true)})})diff --git a/tests/engine/render/canvas/painted-text.test.ts b/tests/engine/render/canvas/painted-text.test.tsindex 2c7737d86..2342f4ef0 100644--- a/tests/engine/render/canvas/painted-text.test.ts+++ b/tests/engine/render/canvas/painted-text.test.ts@@ -15,7 +15,8 @@ const FONT_FAMILY = 'Painted text fixture'beforeAll(async () => {// Inter's variable file draws both styles, as the bundled Inter does.const data = await Bun.file(repoPath('packages/core/assets/InterVariable.ttf')).arrayBuffer()- for (const style of ['Regular', 'SemiBold']) fontManager.markLoaded(FONT_FAMILY, style, data)+ for (const style of ['Regular', 'SemiBold'])+ await fontManager.markLoaded(FONT_FAMILY, style, data)})const solid: Fill = { type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }diff --git a/tests/engine/render/canvas/text/preparation-cache.test.ts b/tests/engine/render/canvas/text/preparation-cache.test.tsindex f4fa321d3..bc3828126 100644--- a/tests/engine/render/canvas/text/preparation-cache.test.ts+++ b/tests/engine/render/canvas/text/preparation-cache.test.ts@@ -63,7 +63,7 @@ describe('text preparation cache', () => {const f = await fixture(8)const data = await Bun.file('packages/core/assets/InterVariable.ttf').arrayBuffer()f.provider.registerFont(data, 'Inter')- fontManager.markLoaded('Inter', 'Regular', data)+ await fontManager.markLoaded('Inter', 'Regular', data)let builds = 0const ck: CanvasKit = {...f.ck,diff --git a/tests/engine/render/canvas/text/render.test.ts b/tests/engine/render/canvas/text/render.test.tsindex c3aff3726..4351312cc 100644--- a/tests/engine/render/canvas/text/render.test.ts+++ b/tests/engine/render/canvas/text/render.test.ts@@ -198,7 +198,7 @@ describe('renderText', () => {const interData = await Bun.file(repoPath('packages/core/assets/InterVariable.ttf')).arrayBuffer()- fontManager.markLoaded('Inter', 'Regular', interData)+ await fontManager.markLoaded('Inter', 'Regular', interData)const r = createMockRenderer()const canvas = createMockCanvas()@@ -320,8 +320,8 @@ describe('paragraph font weights', () => {await renderer.loadFonts()const regular = await Bun.file(repoPath('packages/core/assets/InterVariable.ttf')).arrayBuffer()const bold = await Bun.file(repoPath('packages/core/assets/InterVariable.ttf')).arrayBuffer()- fontManager.markLoaded('Inter', 'Regular', regular)- fontManager.markLoaded('Inter', 'Bold', bold)+ await fontManager.markLoaded('Inter', 'Regular', regular)+ await fontManager.markLoaded('Inter', 'Bold', bold)const base = textNode({text: 'World largest design',@@ -345,7 +345,7 @@ describe('paragraph font weights', () => {const { renderer, surface } = await createTextRenderer()await renderer.loadFonts()const regular = await Bun.file(repoPath('packages/core/assets/InterVariable.ttf')).arrayBuffer()- fontManager.markLoaded('Inter', 'Regular', regular)+ await fontManager.markLoaded('Inter', 'Regular', regular)const demand = fontFaceDemand('Inter', 'Regular Italic', 'Synthetic italic')fontResolver.reset(demand)fontResolver.exhaust(demand)@@ -382,7 +382,7 @@ describe('renderText headless visual', () => {fontManager.attachProvider(ck, fontProvider)const interData = await Bun.file('packages/core/assets/InterVariable.ttf').arrayBuffer()fontProvider.registerFont(interData, 'Inter')- fontManager.markLoaded('Inter', 'Regular', interData)+ await fontManager.markLoaded('Inter', 'Regular', interData)const fallbackFamilies = fontManager.getCJKFallbackFamilies()const originalFallbacks = [...fallbackFamilies]fallbackFamilies.length = 0@@ -411,7 +411,7 @@ describe('renderText headless visual', () => {const fontProvider = ck.TypefaceFontProvider.Make()fontManager.attachProvider(ck, fontProvider)const interData = await Bun.file('packages/core/assets/InterVariable.ttf').arrayBuffer()- fontManager.markLoaded('Inter', 'Regular', interData)+ await fontManager.markLoaded('Inter', 'Regular', interData)const fallbackFamilies = fontManager.getCJKFallbackFamilies()const originalFallbacks = [...fallbackFamilies]fallbackFamilies.length = 0@@ -441,7 +441,7 @@ describe('renderText headless visual', () => {test('does not require fallback families when the primary font covers CJK glyphs', async () => {const notoPath = repoPath('tests/fixtures/fonts/NotoSansSC-Regular.ttf')const notoData = await Bun.file(notoPath).arrayBuffer()- fontManager.markLoaded('Noto Sans SC', 'Regular', notoData)+ await fontManager.markLoaded('Noto Sans SC', 'Regular', notoData)const fallbackFamilies = fontManager.getCJKFallbackFamilies()const originalFallbacks = [...fallbackFamilies]fallbackFamilies.length = 0@@ -464,14 +464,14 @@ describe('renderText headless visual', () => {fontManager.attachProvider(ck, fontProvider)const interData = await Bun.file('packages/core/assets/InterVariable.ttf').arrayBuffer()- fontManager.markLoaded('Inter', 'Regular', interData)+ await fontManager.markLoaded('Inter', 'Regular', interData)const notoPath = repoPath('tests/fixtures/fonts/NotoSansSC-Regular.ttf')const notoData = await Bun.file(notoPath).arrayBuffer()- fontManager.markLoaded('Noto Sans SC', 'Regular', notoData)+ await fontManager.markLoaded('Noto Sans SC', 'Regular', notoData)fontManager.setCJKFallbackFamily('Noto Sans SC')for (let attempt = 0; attempt < 5; attempt++) {- fontManager.markLoaded('Noto Sans SC', 'Regular', notoData)+ await fontManager.markLoaded('Noto Sans SC', 'Regular', notoData)}const graph = new SceneGraph()@@ -537,7 +537,7 @@ describe('renderText headless visual', () => {const interData = await Bun.file('packages/core/assets/InterVariable.ttf').arrayBuffer()fontProvider.registerFont(interData, 'Inter')- fontManager.markLoaded('Inter', 'Regular', interData)+ await fontManager.markLoaded('Inter', 'Regular', interData)const graph = new SceneGraph()const page = graph.getPages()[0]@@ -616,7 +616,7 @@ describe('renderText headless visual', () => {const interData = await Bun.file('packages/core/assets/InterVariable.ttf').arrayBuffer()fontProvider.registerFont(interData, 'Inter')- fontManager.markLoaded('Inter', 'Regular', interData)+ await fontManager.markLoaded('Inter', 'Regular', interData)const arabicPath = repoPath('tests/fixtures/fonts/NotoNaskhArabic-Regular.ttf')const arabicData = await Bun.file(arabicPath).arrayBuffer()diff --git a/tests/engine/render/canvas/visual/inner-shadow-counter.ts b/tests/engine/render/canvas/visual/inner-shadow-counter.tsindex 893c4f482..fda525ceb 100644--- a/tests/engine/render/canvas/visual/inner-shadow-counter.ts+++ b/tests/engine/render/canvas/visual/inner-shadow-counter.ts@@ -19,7 +19,7 @@ async function main() {const fontPath = join(process.cwd(), 'packages/core/assets/Inter-SemiBold.ttf')const fontData = await readFile(fontPath)- fontManager.markLoaded(+ await fontManager.markLoaded('Inter','SemiBold',fontData.buffer.slice(fontData.byteOffset, fontData.byteOffset + fontData.byteLength)diff --git a/tests/engine/render/canvas/visual/sdf-test-matrix.ts b/tests/engine/render/canvas/visual/sdf-test-matrix.tsindex 6200479a2..ee99a0319 100644--- a/tests/engine/render/canvas/visual/sdf-test-matrix.ts+++ b/tests/engine/render/canvas/visual/sdf-test-matrix.ts@@ -151,7 +151,7 @@ async function main() {const fontPath = join(process.cwd(), 'packages/core/assets/Inter-SemiBold.ttf')const fontData = await readFile(fontPath)- fontManager.markLoaded(+ await fontManager.markLoaded('Inter','SemiBold',fontData.buffer.slice(fontData.byteOffset, fontData.byteOffset + fontData.byteLength)diff --git a/tests/engine/render/canvas/visual/verify-text-inner-shadow.ts b/tests/engine/render/canvas/visual/verify-text-inner-shadow.tsindex 5ec629357..6ae7ad73b 100644--- a/tests/engine/render/canvas/visual/verify-text-inner-shadow.ts+++ b/tests/engine/render/canvas/visual/verify-text-inner-shadow.ts@@ -22,7 +22,7 @@ async function main() {const fontPath = join(process.cwd(), 'packages/core/assets/Inter-SemiBold.ttf')console.warn('Loading font from:', fontPath)const fontData = await readFile(fontPath)- fontManager.markLoaded(+ await fontManager.markLoaded('Inter','SemiBold',fontData.buffer.slice(fontData.byteOffset, fontData.byteOffset + fontData.byteLength)diff --git a/tests/engine/text/coverage.test.ts b/tests/engine/text/coverage.test.tsindex 5af52fc7e..990cafdcd 100644--- a/tests/engine/text/coverage.test.ts+++ b/tests/engine/text/coverage.test.ts@@ -21,7 +21,7 @@ describe('font fallback coverage indexing', () => {test('detects supplementary-plane Han code points', async () => {const family = `SupplementaryHan_${Date.now()}`const data = await Bun.file('packages/core/assets/InterVariable.ttf').arrayBuffer()- fontManager.markLoaded(family, 'Regular', data)+ await fontManager.markLoaded(family, 'Regular', data)const graph = new SceneGraph()const node = graph.createNode('TEXT', pageId(graph), {text: 'A𠀀B',@@ -35,7 +35,7 @@ describe('font fallback coverage indexing', () => {test('uses BCP-47 language hints for Han fallback selection', async () => {const family = `LanguageHint_${Date.now()}`const data = await Bun.file('packages/core/assets/InterVariable.ttf').arrayBuffer()- fontManager.markLoaded(family, 'Regular', data)+ await fontManager.markLoaded(family, 'Regular', data)const graph = new SceneGraph()const node = graph.createNode('TEXT', pageId(graph), {text: '骨骨',@@ -59,8 +59,8 @@ describe('font fallback coverage indexing', () => {const latinData = await Bun.file('packages/core/assets/InterVariable.ttf').arrayBuffer()const cjkFamily = `CJKRunBase_${Date.now()}`const latinFamily = `CJKRunOverride_${Date.now()}`- fontManager.markLoaded(cjkFamily, 'Regular', cjkData)- fontManager.markLoaded(latinFamily, 'Regular', latinData)+ await fontManager.markLoaded(cjkFamily, 'Regular', cjkData)+ await fontManager.markLoaded(latinFamily, 'Regular', latinData)const graph = new SceneGraph()const node = graph.createNode('TEXT', pageId(graph), {text: '😀你',diff --git a/tests/engine/text/edit-undo.test.ts b/tests/engine/text/edit-undo.test.tsindex c51010835..9e31be74c 100644--- a/tests/engine/text/edit-undo.test.ts+++ b/tests/engine/text/edit-undo.test.ts@@ -88,7 +88,7 @@ async function setupPathText() {const font = await fontManager.fetchBundledFont('/InterVariable.ttf')expect(font).toBeTruthy()if (!font) return null- fontManager.markLoaded('Inter', 'Regular', font)+ await fontManager.markLoaded('Inter', 'Regular', font)const setupResult = setup()const glyphs: DerivedTextGlyph[] = [diff --git a/tests/engine/text/fonts/coverage.test.ts b/tests/engine/text/fonts/coverage.test.tsindex 121302380..7ac6fd3eb 100644--- a/tests/engine/text/fonts/coverage.test.ts+++ b/tests/engine/text/fonts/coverage.test.ts@@ -7,7 +7,7 @@ import { repoPath } from '#tests/helpers/paths'async function loadInter() {const interData = await Bun.file(repoPath('packages/core/assets/InterVariable.ttf')).arrayBuffer()- fontManager.markLoaded('Inter', 'Regular', interData)+ await fontManager.markLoaded('Inter', 'Regular', interData)}function textNode(text: string) {diff --git a/tests/engine/text/fonts/lifecycle.test.ts b/tests/engine/text/fonts/lifecycle.test.tsindex 9bf8c97c4..620f1c9cc 100644--- a/tests/engine/text/fonts/lifecycle.test.ts+++ b/tests/engine/text/fonts/lifecycle.test.ts@@ -14,7 +14,7 @@ function pageId(graph: SceneGraph): string {}describe('font lifecycle', () => {- test('advances generation only for provider epochs and unique registrations', () => {+ test('advances generation only for provider epochs and unique registrations', async () => {const manager = new FontManager()const registrations: string[] = []const provider = {@@ -27,9 +27,9 @@ describe('font lifecycle', () => {expect(manager.generation()).toBe(0)manager.attachProvider({} as CanvasKit, provider)const providerGeneration = manager.generation()- manager.markLoaded('Generation Test', 'Regular', data)+ await manager.markLoaded('Generation Test', 'Regular', data)const registrationGeneration = manager.generation()- manager.markLoaded('Generation Test', 'Regular', data)+ await manager.markLoaded('Generation Test', 'Regular', data)expect(providerGeneration).toBeGreaterThan(0)expect(registrationGeneration).toBeGreaterThan(providerGeneration)@@ -37,7 +37,7 @@ describe('font lifecycle', () => {expect(registrations).toEqual(['Generation Test'])})- test('keeps cumulative subset registrations under the source family', () => {+ test('keeps cumulative subset registrations under the source family', async () => {const manager = new FontManager()const registrations: string[] = []const provider = {@@ -47,9 +47,9 @@ describe('font lifecycle', () => {} as TypefaceFontProvidermanager.attachProvider({} as CanvasKit, provider)- manager.markLoaded('Subset Font', 'Regular', new ArrayBuffer(8))+ await manager.markLoaded('Subset Font', 'Regular', new ArrayBuffer(8))const firstGeneration = manager.generation()- manager.markLoaded('Subset Font', 'Regular', new ArrayBuffer(12))+ await manager.markLoaded('Subset Font', 'Regular', new ArrayBuffer(12))expect(manager.renderFamily('Subset Font', 'Regular')).toBe('Subset Font')expect(manager.generation()).toBeGreaterThan(firstGeneration)@@ -87,12 +87,12 @@ describe('font lifecycle', () => {expect(isTextPictureCurrent(renderer, node)).toBe(false)})- test('keeps text visible when an unavailable italic face can use a loaded family face', () => {+ test('keeps text visible when an unavailable italic face can use a loaded family face', async () => {const family = 'Missing Italic Regression'const demand = fontFaceDemand(family, 'Regular Italic', 'Hello')fontResolver.reset(demand)fontResolver.exhaust(demand)- fontManager.markLoaded(family, 'Regular', new ArrayBuffer(12))+ await fontManager.markLoaded(family, 'Regular', new ArrayBuffer(12))const graph = new SceneGraph()const node = graph.createNode('TEXT', pageId(graph), {diff --git a/tests/engine/text/fonts/loading.test.ts b/tests/engine/text/fonts/loading.test.tsindex 49c5ebc43..a1a137f56 100644--- a/tests/engine/text/fonts/loading.test.ts+++ b/tests/engine/text/fonts/loading.test.ts@@ -134,36 +134,36 @@ describe('fontWeightMatchOrder', () => {})describe('FontManager loaded font cache', () => {- test('marks and checks font', () => {+ test('marks and checks font', async () => {const family = `TestFont_${Date.now()}`expect(fontManager.isLoaded(family)).toBe(false)- fontManager.markLoaded(family, 'Regular', new ArrayBuffer(8))+ await fontManager.markLoaded(family, 'Regular', new ArrayBuffer(8))expect(fontManager.isLoaded(family)).toBe(true)})- test('different styles for same family', () => {+ test('different styles for same family', async () => {const family = `MultiStyle_${Date.now()}`expect(fontManager.isLoaded(family)).toBe(false)- fontManager.markLoaded(family, 'Bold', new ArrayBuffer(8))+ await fontManager.markLoaded(family, 'Bold', new ArrayBuffer(8))expect(fontManager.isLoaded(family)).toBe(true)expect(fontManager.isStyleLoaded(family, 'Bold')).toBe(true)expect(fontManager.isStyleLoaded(family, 'Regular')).toBe(false)})- test('re-registers cached fonts when provider changes', () => {+ test('re-registers cached fonts when provider changes', async () => {const manager = new FontManager()const canvasKit = {} as CanvasKitconst first = createRecordingProvider()const second = createRecordingProvider()manager.attachProvider(canvasKit, first.provider)- manager.markLoaded('ProviderLifecycle', 'Regular', new ArrayBuffer(12))+ await manager.markLoaded('ProviderLifecycle', 'Regular', new ArrayBuffer(12))expect(first.registrations).toEqual([{ family: 'ProviderLifecycle', byteLength: 12 }])manager.attachProvider(canvasKit, second.provider)expect(second.registrations).toEqual([{ family: 'ProviderLifecycle', byteLength: 12 }])- manager.markLoaded('SharedProviderLifecycle', 'Regular', new ArrayBuffer(16))+ await manager.markLoaded('SharedProviderLifecycle', 'Regular', new ArrayBuffer(16))expect(first.registrations.at(-1)).toEqual({family: 'SharedProviderLifecycle',byteLength: 16@@ -180,12 +180,12 @@ describe('FontManager loaded font cache', () => {expect(manager.provider()).toBeNull()})- test('renders loaded faces under their source families', () => {+ test('renders loaded faces under their source families', async () => {const manager = new FontManager()const recording = createRecordingProvider()manager.attachProvider({} as CanvasKit, recording.provider)- manager.markLoaded('Inter', 'SemiBold', new ArrayBuffer(12))+ await manager.markLoaded('Inter', 'SemiBold', new ArrayBuffer(12))const renderFamily = manager.renderFamily('Inter', 'SemiBold')diff --git a/tests/engine/text/fonts/status.test.ts b/tests/engine/text/fonts/status.test.tsindex e5c03d17c..7ed63c046 100644--- a/tests/engine/text/fonts/status.test.ts+++ b/tests/engine/text/fonts/status.test.ts@@ -8,10 +8,10 @@ function pageId(graph: SceneGraph): string {}describe('documentFontStatus', () => {- test('reports loaded faces and their source without false warnings', () => {+ test('reports loaded faces and their source without false warnings', async () => {const graph = new SceneGraph()const manager = new FontManager()- manager.markLoaded('Inter', 'Regular', new ArrayBuffer(8), 'bundled')+ await manager.markLoaded('Inter', 'Regular', new ArrayBuffer(8), 'bundled')graph.createNode('TEXT', pageId(graph), {name: 'Title',text: 'Hello',@@ -37,10 +37,10 @@ describe('documentFontStatus', () => {})})- test('counts a root that is itself a text node', () => {+ test('counts a root that is itself a text node', async () => {const graph = new SceneGraph()const manager = new FontManager()- manager.markLoaded('Inter', 'Regular', new ArrayBuffer(8), 'bundled')+ await manager.markLoaded('Inter', 'Regular', new ArrayBuffer(8), 'bundled')const node = graph.createNode('TEXT', pageId(graph), {text: 'Hello',fontFamily: 'Inter',@@ -53,10 +53,10 @@ describe('documentFontStatus', () => {])})- test('reports the active default-family substitution for missing faces', () => {+ test('reports the active default-family substitution for missing faces', async () => {const graph = new SceneGraph()const manager = new FontManager()- manager.markLoaded('Inter', 'Regular', new ArrayBuffer(8), 'bundled')+ await manager.markLoaded('Inter', 'Regular', new ArrayBuffer(8), 'bundled')const node = graph.createNode('TEXT', pageId(graph), {name: 'Unavailable label',text: 'Hello',@@ -81,10 +81,10 @@ describe('documentFontStatus', () => {])})- test('reports synthesized styles and style-run faces separately', () => {+ test('reports synthesized styles and style-run faces separately', async () => {const graph = new SceneGraph()const manager = new FontManager()- manager.markLoaded('Example Sans', 'Regular', new ArrayBuffer(8), 'local')+ await manager.markLoaded('Example Sans', 'Regular', new ArrayBuffer(8), 'local')const node = graph.createNode('TEXT', pageId(graph), {name: 'Mixed text',text: 'Bold and serif',@@ -128,7 +128,7 @@ describe('documentFontStatus', () => {test('reports why the host could not load an installed face until it loads', async () => {const graph = new SceneGraph()const manager = new FontManager()- manager.markLoaded('Inter', 'Regular', new ArrayBuffer(8), 'bundled')+ await manager.markLoaded('Inter', 'Regular', new ArrayBuffer(8), 'bundled')let host: 'unsupported' | 'failed' | 'drawable' = 'unsupported'manager.setHostFontLoader(async (family, style) => {if (host === 'unsupported') throw new UnsupportedFontFormatError(family, style)diff --git a/tests/engine/text/fonts/variations.test.ts b/tests/engine/text/fonts/variations.test.tsindex 0e80f9ba3..84844b0f3 100644--- a/tests/engine/text/fonts/variations.test.ts+++ b/tests/engine/text/fonts/variations.test.ts@@ -186,9 +186,9 @@ describe('namedInstanceVariations with malformed fonts', () => {})describe('FontManager.namedInstanceVariations', () => {- test('resolves variations from the face loaded for a style', () => {+ test('resolves variations from the face loaded for a style', async () => {const manager = new FontManager()- manager.markLoaded('SF Pro', 'Medium', SF_PRO_LIKE)+ await manager.markLoaded('SF Pro', 'Medium', SF_PRO_LIKE)expect(manager.namedInstanceVariations('SF Pro', 'Medium')).toEqual([{ axis: 'wdth', value: 100 },{ axis: 'wght', value: 510 }diff --git a/tests/engine/text/opentype/outlines.test.ts b/tests/engine/text/harfbuzz/outlines.test.tssimilarity index 82%rename from tests/engine/text/opentype/outlines.test.tsrename to tests/engine/text/harfbuzz/outlines.test.tsindex 983db1d21..3797a53dc 100644--- a/tests/engine/text/opentype/outlines.test.ts+++ b/tests/engine/text/harfbuzz/outlines.test.ts@@ -3,12 +3,12 @@ import { describe, expect, test } from 'bun:test'import { fontManager, probeGlyphOutlineCommands } from '@open-pencil/core/text'describe('clipboard text outline probe', () => {- test('lazy-loads opentype.js and extracts glyph commands from a loaded font', async () => {+ test('loads HarfBuzz and extracts glyph commands from a loaded font', async () => {const font = await fontManager.fetchBundledFont('/InterVariable.ttf')expect(font).toBeTruthy()if (!font) return- fontManager.markLoaded('Inter', 'Regular', font)+ await fontManager.markLoaded('Inter', 'Regular', font)const probe = await probeGlyphOutlineCommands('Inter', 'Regular', 'Hello', 16)expect(probe).toBeTruthy()diff --git a/tests/engine/tools/modify.test.ts b/tests/engine/tools/modify.test.tsindex f3a2adc86..c7c0559c9 100644--- a/tests/engine/tools/modify.test.ts+++ b/tests/engine/tools/modify.test.ts@@ -309,7 +309,7 @@ describe('set_font_range', () => {describe('set_font', () => {test('sets variable font axes, picking the nearest named style when none is given', async () => {const family = 'Tool Variations'- fontManager.markLoaded(+ await fontManager.markLoaded(family,'Regular',await Bun.file(repoPath('tests/fixtures/fonts/InterVariable-Latin.ttf')).arrayBuffer()diff --git a/tools/checks/test-homes/engine-baseline.txt b/tools/checks/test-homes/engine-baseline.txtindex 8770f8fe7..e2aa4fd94 100644--- a/tools/checks/test-homes/engine-baseline.txt+++ b/tools/checks/test-homes/engine-baseline.txt@@ -388,7 +388,7 @@ tests/engine/text/fonts/normalize-export.test.tstests/engine/text/fonts/status.test.tstests/engine/text/fonts/variations.test.tstests/engine/text/fonts/web-fonts.test.ts-tests/engine/text/opentype/outlines.test.ts+tests/engine/text/harfbuzz/outlines.test.tstests/engine/text/resolver.test.tstests/engine/text/rtl-auto-layout-input.test.tstests/engine/text/style-runs.test.tsdiff --git a/tools/generate/emoji-metrics/package.json b/tools/generate/emoji-metrics/package.jsonindex 9325a3d3a..519654b78 100644--- a/tools/generate/emoji-metrics/package.json+++ b/tools/generate/emoji-metrics/package.json@@ -9,7 +9,7 @@"test": "bun test tests"},"dependencies": {- "opentype.js": "^2.0.0"+ "harfbuzzjs": "1.6.4"},"devDependencies": {"@open-pencil/core": "workspace:*",diff --git a/tools/generate/emoji-metrics/src/keycap.ts b/tools/generate/emoji-metrics/src/keycap.tsindex d93735394..e918b073d 100644--- a/tools/generate/emoji-metrics/src/keycap.ts+++ b/tools/generate/emoji-metrics/src/keycap.ts@@ -1,12 +1,11 @@-import * as opentype from 'opentype.js'+import * as hb from 'harfbuzzjs'import type { OutlineCommand } from '@open-pencil/core/text'/** The combining enclosing keycap, which draws a keycap's frame around the character before it. */export const COMBINING_KEYCAP = 0x20e3-const round = (value: number | undefined) =>- value === undefined ? undefined : Math.round(value * 10000) / 10000+const round = (value: number) => Math.round(value * 10000) / 10000/*** The keycap frame of a font, in em with y down from the baseline as Core's outline commands@@ -14,20 +13,35 @@ const round = (value: number | undefined) =>* ends.*/export function keycapOutline(font: Uint8Array): OutlineCommand[] {- const parsed = opentype.parse(- font.buffer.slice(font.byteOffset, font.byteOffset + font.byteLength)- )- const glyph = parsed.charToGlyph(String.fromCodePoint(COMBINING_KEYCAP))- if (!glyph.index) throw new Error('The source font has no keycap')- const em = parsed.unitsPerEm- return glyph.path.commands.map((command) => {- const scaled: OutlineCommand = { type: command.type }- for (const key of ['x', 'y', 'x1', 'y1', 'x2', 'y2'] as const) {- const value = (command as Record<string, number | undefined>)[key]- if (value !== undefined) scaled[key] = round(key.startsWith('y') ? -value / em : value / em)- }- return scaled+ const face = new hb.Face(new hb.Blob(font))+ const parsed = new hb.Font(face)+ const glyph = parsed.glyph(COMBINING_KEYCAP)+ if (!glyph) throw new Error('The source font has no keycap')+ const em = face.upem+ const point = (x: number, y: number) => ({ x: round(x / em), y: round(-y / em) })+ const commands: OutlineCommand[] = []+ const draw = new hb.DrawFuncs()+ draw.setMoveToFunc((x, y) => commands.push({ type: 'M', ...point(x, y) }))+ draw.setLineToFunc((x, y) => commands.push({ type: 'L', ...point(x, y) }))+ draw.setQuadraticToFunc((cx, cy, x, y) => {+ const control = point(cx, cy)+ commands.push({ type: 'Q', x1: control.x, y1: control.y, ...point(x, y) })})+ draw.setCubicToFunc((c1x, c1y, c2x, c2y, x, y) => {+ const first = point(c1x, c1y)+ const second = point(c2x, c2y)+ commands.push({+ type: 'C',+ x1: first.x,+ y1: first.y,+ x2: second.x,+ y2: second.y,+ ...point(x, y)+ })+ })+ draw.setClosePathFunc(() => commands.push({ type: 'Z' }))+ parsed.drawGlyph(glyph, draw)+ return commands}/** Core's source holding the frame, with where it came from and its licence. */@@ -36,7 +50,7 @@ export function keycapModule(commands: OutlineCommand[], copyright: string): str// ${copyright}// Licensed under the SIL Open Font License, Version 1.1 (packages/core/assets/NotoSansSymbols-OFL.txt).-import type { OutlineCommand } from './opentype'+import type { OutlineCommand } from './font/glyphs'/*** The frame Figma draws a keycap with: Noto Sans Symbols' combining enclosing keycap (U+20E3),diff --git a/vite/aliases.ts b/vite/aliases.tsindex dc9317fdb..ee936e054 100644--- a/vite/aliases.ts+++ b/vite/aliases.ts@@ -100,10 +100,6 @@ export function createOpenPencilAliases(rootDir: string, options: { cloud?: boolreplacement: `${resolve(rootDir, 'packages/core/assets')}/`},{ find: /^@open-pencil\/core$/, replacement: resolve(rootDir, 'packages/core/src/index.ts') },- { find: '@open-pencil/core', replacement: resolve(rootDir, 'packages/core/src') },- {- find: 'opentype.js',- replacement: resolve(rootDir, 'node_modules/opentype.js/dist/opentype.mjs')- }+ { find: '@open-pencil/core', replacement: resolve(rootDir, 'packages/core/src') }]}