AI-native design editor. Open-source Figma alternative.
fix(core): confirm the font of saved glyphs by shaping its run (#1626)
Danila Poyarkove9aa2b0b569e
diff --git a/changes/1626/fixed.md b/changes/1626/fixed.mdnew file mode 100644index 000000000..0a479f438--- /dev/null+++ b/changes/1626/fixed.md@@ -0,0 +1 @@+- Text saved to `.fig` files keeps its letters when its glyphs were drawn from another file of the same family, such as a static face beside the variable font, instead of reopening with other letters.diff --git a/packages/core/src/canvas/text/placed.ts b/packages/core/src/canvas/text/placed.tsindex d8842ae41..581c6d08f 100644--- a/packages/core/src/canvas/text/placed.ts+++ b/packages/core/src/canvas/text/placed.ts@@ -1,7 +1,10 @@import type { Paragraph } from 'canvaskit-wasm'import { uniq } from 'es-toolkit/array'+import { isEqual } from 'es-toolkit/predicate'import type { SceneNode } from '@open-pencil/scene-graph'+import { textLengthPixels } from '@open-pencil/scene-graph/text'+import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text/direction'import {drawnFontVariations,@@ -12,12 +15,17 @@ import { laidOutText } from '#core/canvas/text/keycap'import type { TextLayout, TextLayoutMarker } from '#core/canvas/text/layout'import { utf16IndicesByUtf8 } from '#core/canvas/text/utf8'import { DEFAULT_FONT_FAMILY } from '#core/constants'+import { shownCharacters } from '#core/text/case'import { ELLIPSIS } from '#core/text/ellipsis'import {glyphOutlineSourceSync,shardCovers,- type GlyphOutlineSource+ shardOutlineSources,+ type GlyphOutlineSource,+ type RunShaping,+ type ShapedGlyph} from '#core/text/font/glyphs'+import type { ShapingFeature } from '#core/text/font/harfbuzz'import { fontManager } from '#core/text/font/manager'import { textFontFace } from '#core/text/requirements/collect'@@ -56,7 +64,7 @@ function loadedStyle(* `drawnFontStyle` asks CanvasKit.*/function fontAt(node: SceneNode, index: number) {- const run = node.styleRuns.find((item) => index >= item.start && index < item.start + item.length)+ const run = styleRunAt(node, index)const family = run?.style.fontFamily ?? (node.fontFamily || DEFAULT_FONT_FAMILY)const weight = run?.style.fontWeight ?? node.fontWeightconst italic = run?.style.italic ?? node.italic@@ -74,6 +82,49 @@ function fontAt(node: SceneNode, index: number) {return { family, weight, italic, style, variations, drawn }}+type StyleRun = SceneNode['styleRuns'][number]++function styleRunAt(node: SceneNode, index: number): StyleRun | undefined {+ return node.styleRuns.find((item) => index >= item.start && index < item.start + item.length)+}++/**+ * The style run of each code unit of the shown text from `start` to `end`, scanning the node's+ * style runs only where one ends.+ */+function styleRunsOver(+ node: SceneNode,+ start: number,+ end: number,+ sourceAt: (index: number) => number+): Array<StyleRun | undefined> {+ const runs: Array<StyleRun | undefined> = []+ let current: StyleRun | undefined+ for (let index = start; index < end; index++) {+ const source = sourceAt(index)+ if (!current || source < current.start || source >= current.start + current.length)+ current = styleRunAt(node, source)+ runs.push(current)+ }+ return runs+}++/** The letter spacing a style run sets after each of its characters, in pixels. */+function letterSpacingOf(node: SceneNode, run: StyleRun | undefined): number {+ return textLengthPixels(+ run?.style.letterSpacing ?? node.letterSpacing,+ run?.style.fontSize ?? node.fontSize+ )+}++/** The features a style run shapes its characters with, as CanvasKit is given them. */+function featuresOf(node: SceneNode, run: StyleRun | undefined): ShapingFeature[] {+ return (run?.style.fontFeatures ?? node.fontFeatures).map((feature) => ({+ tag: feature.tag.toLowerCase(),+ value: feature.enabled ? 1 : 0+ }))+}+/*** The style a family of the paragraph is drawn in: the face its own family draws the asked style* in, and Regular for the Arabic and CJK fallbacks, as the paragraph asks CanvasKit for them.@@ -87,12 +138,17 @@ function sourceStyle(family: string, font: ReturnType<typeof fontAt>): string |return loadedStyle(family, font.drawn.weight, font.drawn.italic, font.drawn.style)}-/** The outline source of each font the paragraph may have drawn a character in, in its order. */+/**+ * The outline source of each file the paragraph may have drawn a character in, in its order:+ * each family's own file, then its shards.+ */function* candidateSources(font: ReturnType<typeof fontAt>) {for (const family of paragraphSourceFamilies(font.family)) {const style = sourceStyle(family, font)- const source = style ? glyphOutlineSourceSync(family, style, font.variations) : null+ if (!style) continue+ const source = glyphOutlineSourceSync(family, style, font.variations)if (source) yield source+ yield* shardOutlineSources(family, style, font.variations)}}@@ -135,21 +191,42 @@ export function characterFamily(node: SceneNode, text: string, index: number): sreturn characterFace(node, text, index)?.family ?? null}-/** Whether a glyph the shaper chose is the one the font maps its character to. */-function drawsOwnGlyph(- source: GlyphOutlineSource,- run: GlyphRun,- text: string,- characterAt: (offset: number) => number-): boolean {- for (let index = 0; index < run.glyphs.length; index++) {- const start = characterAt(run.offsets[index])- const end = characterAt(run.offsets[index + 1])- // A glyph for one character, not a ligature or a cluster, maps straight from it.- if (end - start !== 1 || /\s/.test(text[start])) continue- if (source.glyphOf(text[start]) === run.glyphs[index]) return true- }- return false+/** The characters of a run as the paragraph laid them out, and the features it shaped them with. */+interface RunShape {+ text: string+ runText: string+ /** The character each glyph starts at. */+ offsets: number[]+ /** Where the characters a glyph starts at end. */+ nextBoundary: Map<number, number>+ start: number+ end: number+ /** How the paragraph shaped the run, worked out when HarfBuzz shapes it. */+ shaping: () => RunShaping+}++/**+ * Whether the font drew the run. Every glyph of one character being the one the font maps it to+ * says so. A run whose features or ligatures changed glyphs ("12:30", "->", Arabic forms) is the+ * font's when HarfBuzz shapes its characters to the same glyphs in it, as CanvasKit, which+ * shapes with HarfBuzz, shaped them. One matching glyph says nothing: two files of a family, such+ * as a static instance and the variable font, number most glyphs alike.+ */+function drewRun(source: GlyphOutlineSource, run: GlyphRun, shape: RunShape): boolean {+ const mapped = Array.from(run.glyphs).every((glyph, index) => {+ const from = shape.offsets[index]+ const character = shape.text.slice(from, shape.nextBoundary.get(from))+ // A glyph for a ligature or a cluster does not map from one character.+ const codePoint = character.codePointAt(0)+ if (codePoint === undefined || String.fromCodePoint(codePoint) !== character) return false+ // The missing glyph, like whitespace, says nothing about which font drew it.+ return glyph === 0 || /\s/.test(character) || source.glyphOf(character) === glyph+ })+ if (mapped) return true+ const glyphs = source.shape(shape.runText, shape.shaping())+ return (+ glyphs.length === run.glyphs.length && glyphs.every(({ id }, index) => id === run.glyphs[index])+ )}/** Characters a shaper draws as nothing, such as variation selectors and joiners, whatever the font. */@@ -161,19 +238,8 @@ const DRAWN_AS_NOTHING = /[\s\p{Default_Ignorable_Code_Point}]/u* (ID 0), which says nothing about which font that is, so it does not count against the font* the run's other characters confirm.*/-function drawnCharacters(- text: string,- run: GlyphRun,- offsets: number[],- start: number,- end: number-): string {- // A glyph covers the characters up to the next greater offset in the run, whatever its- // direction; the sorted offsets give that once for every glyph.- const boundaries = uniq([...offsets, end]).sort((a, b) => a - b)- const nextBoundary = new Map(- boundaries.map((offset, index) => [offset, boundaries[index + 1] ?? end])- )+function drawnCharacters(run: GlyphRun, shape: RunShape): string {+ const { text, offsets, nextBoundary, start, end } = shapeconst missing = new Set<number>()for (const [index, glyph] of run.glyphs.entries()) {if (glyph !== 0) continue@@ -191,29 +257,104 @@ function drawnCharacters(return characters}+/**+ * The font a run's outlines come from, and the glyphs to save when it shaped them itself:+ * HarfBuzz's, from the run's first character, with the letter spacing of each code unit's style.+ */+type RunOutline =+ | { source: GlyphOutlineSource; glyphs?: undefined }+ | { source: GlyphOutlineSource; glyphs: ShapedGlyph[]; start: number; letterSpacing: number[] }+/*** The font a run was shaped with. CanvasKit leaves `GlyphRun.typeface` null, so the run's font* is found as the paragraph falls back: the first of the fonts it lists, the style's own then- * its fallbacks, that has every character of the run, confirmed by the glyph IDs it chose.+ * its fallbacks, that has every character of the run, confirmed by the glyphs it chose. When no+ * font confirms them their IDs name no outline, so the text keeps its characters in the first+ * font that has them all, shaped by HarfBuzz as the paragraph would shape them in it.* The paragraph asks each family for a face it has loaded, so CanvasKit never fakes one.*/-function runOutlineSource(+function runOutline(node: SceneNode,- text: string,shaped: string,run: GlyphRun,- characterAt: (offset: number) => number-): GlyphOutlineSource | null {+ characterAt: (offset: number) => number,+ sourceAt: (index: number) => number+): RunOutline | null {if (run.glyphs.length === 0) return nullconst offsets = Array.from(run.offsets, characterAt)const start = Math.min(...offsets)const end = Math.max(...offsets)- const characters = drawnCharacters(shaped, run, offsets, start, end)- for (const source of candidateSources(fontAt(node, start))) {+ // A glyph covers the characters up to the next greater offset in the run, whatever its+ // direction; the sorted offsets give that once for every glyph.+ const boundaries = uniq([...offsets, end]).sort((a, b) => a - b)+ const nextBoundary = new Map(+ boundaries.map((offset, index) => [offset, boundaries[index + 1] ?? end])+ )+ const font = fontAt(node, sourceAt(start))+ let styles: Array<StyleRun | undefined> | undefined+ const stylesOver = () => (styles ??= styleRunsOver(node, start, end, sourceAt))+ let shaping: RunShaping | undefined+ const shape: RunShape = {+ text: shaped,+ runText: shaped.slice(start, end),+ offsets,+ nextBoundary,+ start,+ end,+ shaping: () => (shaping ??= runShaping(node, run, offsets, stylesOver()))+ }+ const characters = drawnCharacters(run, shape)+ let primary: GlyphOutlineSource | null = null+ for (const source of candidateSources(font)) {if (!source.covers(characters)) continue- if (characters === '' || drawsOwnGlyph(source, run, text, characterAt)) return source+ if (characters === '' || drewRun(source, run, shape)) return { source }+ primary ??= source+ }+ if (!primary) return null+ return {+ source: primary,+ glyphs: primary.shape(shape.runText, shape.shaping()),+ start,+ letterSpacing: stylesOver().map((style) => letterSpacingOf(node, style))}- return null+}++/**+ * How the paragraph shaped a run: with the features of each style run in it, as CanvasKit gives+ * them for blocks it shapes as one run; in the direction its glyphs, in visual order, show by+ * their characters, the paragraph's for one glyph; and in its style's language.+ */+function runShaping(+ node: SceneNode,+ run: GlyphRun,+ offsets: readonly number[],+ styles: ReadonlyArray<StyleRun | undefined>+): RunShaping {+ const glyphCount = run.glyphs.length+ const ranges: Array<{ start: number; features: ShapingFeature[] }> = []+ for (const [index, style] of styles.entries()) {+ if (index > 0 && style === styles[index - 1]) continue+ const features = featuresOf(node, style)+ if (!isEqual(ranges.at(-1)?.features, features)) ranges.push({ start: index, features })+ }+ const features =+ ranges.length === 1+ ? ranges[0].features+ : ranges.flatMap((range, index) =>+ range.features.map((feature) => ({+ ...feature,+ start: range.start,+ end: ranges.at(index + 1)?.start ?? styles.length+ }))+ )+ const rtl =+ glyphCount > 1 && offsets[0] !== offsets[glyphCount - 1]+ ? offsets[0] > offsets[glyphCount - 1]+ : resolveNodeTextDirection(node) === 'RTL'+ const style = styles.at(0)?.style+ const language =+ (style?.textLanguage !== undefined ? style.textLanguage : node.textLanguage) ?? undefined+ return { features, rtl, language }}/**@@ -223,15 +364,94 @@ function runOutlineSource(function ellipsisSource(node: SceneNode,run: GlyphRun,- characterAt: (offset: number) => number+ characterAt: (offset: number) => number,+ sourceAt: (index: number) => number): GlyphOutlineSource | null {if (run.glyphs.length !== 1) return null- for (const source of candidateSources(fontAt(node, characterAt(run.offsets[0])))) {+ for (const source of candidateSources(fontAt(node, sourceAt(characterAt(run.offsets[0]))))) {if (source.glyphOf(ELLIPSIS) === run.glyphs[0]) return source}return null}+/**+ * The outline of a run of a line, and whether the run is the ellipsis that ends truncated text.+ * The last run of truncated text that no font confirms may be an ellipsis, which keeps its glyph+ * unoutlined: shaping it again would save the characters its offsets point at instead.+ */+function lineRunOutline(+ node: SceneNode,+ shaped: string,+ run: GlyphRun,+ endsTruncated: boolean,+ indices: { characterAt: (offset: number) => number; sourceAt: (index: number) => number }+): { outline: RunOutline | null; ellipsis: boolean } {+ const { characterAt, sourceAt } = indices+ const ellipsis = endsTruncated ? ellipsisSource(node, run, characterAt, sourceAt) : null+ if (ellipsis) return { outline: { source: ellipsis }, ellipsis: true }+ const outline = runOutline(node, shaped, run, characterAt, sourceAt)+ return { outline: endsTruncated && outline?.glyphs ? null : outline, ellipsis: false }+}++/**+ * The character of the node's own text each character of the shown `text` comes from, which+ * its style run is found by: a case can show one character as several, as `ß` upper-cases to+ * `SS`.+ */+function sourceIndices(node: SceneNode, text: string): (index: number) => number {+ if (text === node.text) return (index) => index+ const indices: number[] = []+ for (const { character, sourceIndex } of shownCharacters(node)) {+ indices.push(...Array.from({ length: character.length }, () => sourceIndex))+ }+ return (index) => indices.at(index) ?? index+}++/** Whether HarfBuzz shaped the run to glyphs of the same characters as CanvasKit's. */+function sameClusters(+ run: GlyphRun,+ outline: Extract<RunOutline, { glyphs: ShapedGlyph[] }>,+ characterAt: (offset: number) => number+): boolean {+ return (+ outline.glyphs.length === run.glyphs.length &&+ outline.glyphs.every(+ (glyph, index) => outline.start + glyph.cluster === characterAt(run.offsets[index])+ )+ )+}++/**+ * The glyphs HarfBuzz shaped for a run, when they are not as many as CanvasKit's or stand for+ * other characters: placed one after another from where the run starts.+ */+function reshapedGlyphs(+ run: GlyphRun,+ outline: Extract<RunOutline, { glyphs: ShapedGlyph[] }>,+ lineLeft: number,+ y: number+): LaidOutGlyph[] {+ let x = run.positions[0]+ return outline.glyphs.map((glyph, index) => {+ // Spacing follows a character once, after its last glyph, so marks stay on their base.+ const endsCharacter = outline.glyphs.at(index + 1)?.cluster !== glyph.cluster+ const spacing = endsCharacter ? (outline.letterSpacing.at(glyph.cluster) ?? 0) : 0+ const advance = glyph.advance * run.size + spacing+ const placed: LaidOutGlyph = {+ id: glyph.id,+ x: x + glyph.xOffset * run.size,+ y: y - glyph.yOffset * run.size,+ fontSize: run.size,+ firstCharacter: outline.start + glyph.cluster,+ advance,+ lineLeft,+ source: outline.source+ }+ x += advance+ return placed+ })+}+/*** A list marker's glyphs as Figma saves them: placed beside their item and drawing no* character of the text.@@ -276,6 +496,7 @@ export function laidOutGlyphs(const characterAt = utf16IndicesByUtf8(text)// The runs drew the text as laid out, a keycap mark as a zero-width space.const shaped = laidOutText(text)+ const sourceAt = sourceIndices(node, text)const markers = new Map(layout.getMarkers().map((marker) => [marker.lineNumber, marker]))const glyphs: LaidOutGlyph[] = []for (const [lineIndex, line] of lines.entries()) {@@ -284,24 +505,30 @@ export function laidOutGlyphs(const { left, baseline } = metrics[lineIndex]const lastLine = lineIndex === lines.length - 1for (const [runIndex, run] of line.runs.entries()) {- const ellipsis =+ const endsTruncated =lastLine && runIndex === line.runs.length - 1 && layout.didExceedMaxLines()- ? ellipsisSource(node, run, characterAt)- : null- const source = ellipsis ?? runOutlineSource(node, text, shaped, run, characterAt)+ const { outline, ellipsis } = lineRunOutline(node, shaped, run, endsTruncated, {+ characterAt,+ sourceAt+ })+ // Run positions round the baseline to whole pixels; line metrics keep it exact.+ const y = baseline + offsetY+ if (outline?.glyphs && !sameClusters(run, outline, characterAt)) {+ glyphs.push(...reshapedGlyphs(run, outline, left, y))+ continue+ }for (let index = 0; index < run.glyphs.length; index++) {const x = run.positions[index * 2]glyphs.push({- id: run.glyphs[index],+ id: outline?.glyphs?.[index].id ?? run.glyphs[index],x,- // Run positions round the baseline to whole pixels; line metrics keep it exact.- y: baseline + offsetY,+ y,fontSize: run.size,// The ellipsis truncation adds draws no character, as Figma saves it.firstCharacter: ellipsis ? undefined : characterAt(run.offsets[index]),advance: run.positions[(index + 1) * 2] - x,lineLeft: left,- source+ source: outline?.source ?? null})}}diff --git a/packages/core/src/text/font/glyphs.ts b/packages/core/src/text/font/glyphs.tsindex 9e7e8d827..52e97422d 100644--- a/packages/core/src/text/font/glyphs.ts+++ b/packages/core/src/text/font/glyphs.ts@@ -10,7 +10,8 @@ import {loadHarfBuzz,shapeText,type HarfBuzzFont,- type OutlineCommand+ type OutlineCommand,+ type ShapingOptions} from './harfbuzz'import { fontTableView } from './variation'@@ -37,12 +38,17 @@ const shardFontCache = new WeakMap<ArrayBuffer, HarfBuzzFont | null>()/** Whether a shard of a style, one of `FontManager.shardData`'s files, maps `character`. */export function shardCovers(data: ArrayBuffer, character: string): boolean {if (!isHarfBuzzLoaded()) return false+ const parsed = shardFont(data)+ return parsed !== null && glyphIndex(parsed, character) !== 0+}++function shardFont(data: ArrayBuffer): HarfBuzzFont | null {let parsed = shardFontCache.get(data)if (parsed === undefined) {parsed = harfBuzzFont(data)shardFontCache.set(data, parsed)}- return parsed !== null && glyphIndex(parsed, character) !== 0+ return parsed}function getParsedFont(family: string, style: string): HarfBuzzFont | null {@@ -248,11 +254,26 @@ export function getGlyphOutlineMetricsSync(}/** Outlines of one loaded font, addressed by the glyph IDs a shaper produced. */+/** A glyph HarfBuzz shaped text into: its ID, the UTF-16 index it starts at, and its advance in em. */+export interface ShapedGlyph {+ id: number+ cluster: number+ advance: number+ /** How far HarfBuzz moved it from the pen, in em, such as a mark onto its base; y runs up. */+ xOffset: number+ yOffset: number+}++/** How a run is shaped, apart from the font and its axes. */+export type RunShaping = Omit<ShapingOptions, 'instance'>+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+ /** The glyphs HarfBuzz shapes `text` into in this font, at its axes and as `shaping` asks. */+ shape(text: string, shaping: RunShaping): ShapedGlyph[]outline(glyphId: number, fontSize: number): OutlineCommand[] | null}@@ -266,11 +287,41 @@ export function glyphOutlineSourceSync(variations: readonly FontVariation[] = []): GlyphOutlineSource | null {const parsed = getParsedFont(family, style)- if (!parsed) return null+ return parsed ? outlineSource(parsed, variations) : null+}++/**+ * Glyph outlines of each shard of a loaded style, the files `FontManager.shardData` lists for+ * the characters its own file lacks, at `variations`.+ */+export function shardOutlineSources(+ family: string,+ style: string,+ variations: readonly FontVariation[] = []+): GlyphOutlineSource[] {+ if (!isHarfBuzzLoaded()) return []+ return fontManager.shardData(family, style).flatMap((data) => {+ const parsed = shardFont(data)+ return parsed ? [outlineSource(parsed, variations)] : []+ })+}++function outlineSource(+ parsed: HarfBuzzFont,+ variations: readonly FontVariation[]+): GlyphOutlineSource {const instance = fontInstance(parsed, variations)return {covers: (text) => Array.from(text).every((char) => glyphIndex(parsed, char) !== 0),glyphOf: (character) => glyphIndex(parsed, character),+ shape: (text, shaping) =>+ shapeText(parsed, text, { ...shaping, instance }).map((glyph) => ({+ id: glyph.codepoint,+ cluster: glyph.cluster,+ advance: (glyph.xAdvance ?? 0) / parsed.face.upem,+ xOffset: (glyph.xOffset ?? 0) / parsed.face.upem,+ yOffset: (glyph.yOffset ?? 0) / parsed.face.upem+ })),outline: (glyphId, fontSize) =>glyphId < parsed.glyphCount ? glyphCommands(parsed, instance, glyphId, fontSize) : null}diff --git a/packages/core/src/text/font/harfbuzz.ts b/packages/core/src/text/font/harfbuzz.tsindex a8e304b41..9d792c4a6 100644--- a/packages/core/src/text/font/harfbuzz.ts+++ b/packages/core/src/text/font/harfbuzz.ts@@ -270,15 +270,48 @@ export function glyphCommands(let shapingBuffer: HarfBuzzModule.Buffer | null = null-/** The glyphs HarfBuzz shapes `text` into with the font's default instance, and their positions. */+/** An OpenType feature set on or off for shaping, by its lowercase tag ("liga", "tnum"). */+export interface ShapingFeature {+ tag: string+ value: number+ /** The code units of the text it applies to, from `start` up to `end`; all when left out. */+ start?: number+ end?: number+}++/**+ * How text is shaped: at a variable font's instance, with features over the defaults, and in a+ * direction and language, which HarfBuzz guesses from the text when they are left out.+ */+export interface ShapingOptions {+ instance?: HarfBuzzInstance+ features?: readonly ShapingFeature[]+ rtl?: boolean+ language?: string+}++/**+ * The glyphs HarfBuzz shapes `text` into, and their positions: at the font's default instance+ * and HarfBuzz's default features unless `options` sets others, as CanvasKit shapes a run.+ */export function shapeText(parsed: HarfBuzzFont,- text: string+ text: string,+ options: ShapingOptions = {}): ReturnType<HarfBuzzModule.Buffer['getGlyphInfosAndPositions']> {shapingBuffer ??= new parsed.hb.Buffer()shapingBuffer.reset()shapingBuffer.addText(text)+ const { Direction, Feature } = parsed.hb+ if (options.rtl !== undefined) {+ shapingBuffer.setDirection(options.rtl ? Direction.RTL : Direction.LTR)+ }+ if (options.language) shapingBuffer.setLanguage(options.language)shapingBuffer.guessSegmentProperties()- parsed.hb.shape(parsed.font, shapingBuffer)+ const features = options.features?.map(+ ({ tag, value, start, end }) =>+ new Feature(tag, value, start ?? Feature.GLOBAL_START, end ?? Feature.GLOBAL_END)+ )+ parsed.hb.shape(options.instance?.font ?? parsed.font, shapingBuffer, features)return shapingBuffer.getGlyphInfosAndPositions()}diff --git a/packages/core/tests/canvas/text/placed.test.ts b/packages/core/tests/canvas/text/placed.test.tsnew file mode 100644index 000000000..4e7bce13f--- /dev/null+++ b/packages/core/tests/canvas/text/placed.test.ts@@ -0,0 +1,180 @@+import { afterAll, beforeAll, describe, expect, test } from 'bun:test'++import { expectDefined } from '#core-tests/helpers/assert'+import type { CanvasKit, TypefaceFontProvider } from 'canvaskit-wasm'++import { SceneGraph } from '@open-pencil/scene-graph'+import type { SceneNode } from '@open-pencil/scene-graph'+import { pixelLength } from '@open-pencil/scene-graph/text'++import { TextLayout } from '#core/canvas/text/layout'+import { laidOutGlyphs } from '#core/canvas/text/placed'+import { getCanvasKit } from '#core/canvaskit'+import { glyphOutlineSourceSync } from '#core/text/font/glyphs'+import { fontManager } from '#core/text/font/manager'++const FAMILY = 'Placed Test Inter'+const FONT_SIZE = 20++/**+ * The family is outlined from InterVariable, as the font manager has it, and drawn by providers+ * holding that file or the static Inter SemiBold file, which numbers most glyphs alike.+ */+let ck: CanvasKit+let staticProvider: TypefaceFontProvider+let variableProvider: TypefaceFontProvider++beforeAll(async () => {+ ck = await getCanvasKit()+ const variable = expectDefined(await fontManager.fetchBundledFont('/InterVariable.ttf'))+ const semibold = expectDefined(await fontManager.fetchBundledFont('/Inter-SemiBold.ttf'))+ await fontManager.markLoaded(FAMILY, 'Regular', variable)+ staticProvider = ck.TypefaceFontProvider.Make()+ staticProvider.registerFont(semibold, FAMILY)+ variableProvider = ck.TypefaceFontProvider.Make()+ variableProvider.registerFont(variable, FAMILY)+})++afterAll(() => {+ staticProvider.delete()+ variableProvider.delete()+})++type PaintFeatures = { name: string; value: number }[]++/**+ * Text in the family, its glyphs drawn from `provider` with `features`, and with `restyled`'s+ * from its index on, as they are saved.+ */+function placed(+ text: string,+ provider: TypefaceFontProvider,+ features: PaintFeatures = [],+ props: Partial<SceneNode> = {},+ restyled?: { from: number; features: PaintFeatures }+) {+ const graph = new SceneGraph()+ const node = graph.createNode('TEXT', graph.getPages()[0].id, {+ text,+ fontFamily: FAMILY,+ fontSize: FONT_SIZE,+ ...props+ })+ const textStyle = { fontFamilies: [FAMILY], fontSize: FONT_SIZE, fontFeatures: features }+ const builder = ck.ParagraphBuilder.MakeFromFontProvider(+ new ck.ParagraphStyle({ textStyle }),+ provider+ )+ builder.addText(text.slice(0, restyled?.from))+ if (restyled) {+ builder.pushStyle(new ck.TextStyle({ ...textStyle, fontFeatures: restyled.features }))+ builder.addText(text.slice(restyled.from))+ builder.pop()+ }+ const paragraph = builder.build()+ builder.delete()+ try {+ const layout = TextLayout.ofParagraph(ck, paragraph, text.length)+ layout.layout(1000)+ return expectDefined(laidOutGlyphs(node, layout, text, 0), 'laid-out glyphs')+ } finally {+ paragraph.delete()+ }+}++const variableSource = () => expectDefined(glyphOutlineSourceSync(FAMILY, 'Regular'))++describe('the font saved glyphs are outlined from', () => {+ /**+ * The files number `B` and `a` alike but not `t` (#1619): one matching glyph must not let the+ * variable file outline the static file's glyphs, which would save another letter for `t`.+ */+ test('saves the characters in the font it outlines when another file drew them', () => {+ const source = variableSource()+ const glyphs = placed('Bat', staticProvider)++ expect(glyphs.map((glyph) => glyph.id)).toEqual(+ Array.from('Bat', (character) => source.glyphOf(character))+ )+ expect(glyphs.map((glyph) => glyph.firstCharacter)).toEqual([0, 1, 2])+ })++ test('keeps glyphs the font drew for its features and ligatures', () => {+ const source = variableSource()+ // Inter draws the colon between figures and the arrow from glyphs no character maps to.+ for (const text of ['12:30', 'a->b']) {+ const glyphs = placed(text, variableProvider)+ expect(glyphs.map((glyph) => glyph.id)).toEqual(+ source.shape(text, {}).map((glyph) => glyph.id)+ )+ expect(glyphs.some((glyph, index) => glyph.id !== source.glyphOf(text[index]))).toBe(true)+ expect(glyphs.every((glyph) => glyph.source !== null)).toBe(true)+ expect(glyphs.every((glyph) => glyph.source === glyphs[0].source)).toBe(true)+ }+ })++ test('shapes the run itself, placed from its start, when the drawn glyphs are more', () => {+ const source = variableSource()+ // The static file draws `t`, `-` and `>` apart; the font the text asks for joins the arrow.+ const glyphs = placed('t->b', staticProvider, [{ name: 'calt', value: 0 }])++ expect(glyphs.map((glyph) => glyph.id)).toEqual(+ source.shape('t->b', {}).map((glyph) => glyph.id)+ )+ expect(glyphs.map((glyph) => glyph.firstCharacter)).toEqual([0, 1, 3])+ expect(glyphs[0].x).toBe(0)+ for (const [index, glyph] of glyphs.slice(1).entries()) {+ expect(glyph.x).toBeCloseTo(glyphs[index].x + glyphs[index].advance, 3)+ }+ })++ test('confirms a run whose style runs set features of their own', () => {+ const source = variableSource()+ const text = 'a->b a->b'+ // The second arrow keeps its characters: the run drawn from one font has both arrows.+ const glyphs = placed(text, variableProvider, [], {+ styleRuns: [{ start: 5, length: 4, style: { fontFeatures: [{ tag: 'CALT', enabled: false }] } }]+ }, { from: 5, features: [{ name: 'calt', value: 0 }] })++ expect(glyphs.map((glyph) => glyph.firstCharacter)).toEqual([0, 1, 3, 4, 5, 6, 7, 8])+ expect(glyphs.slice(4).map((glyph) => glyph.id)).toEqual(+ Array.from('a->b', (character) => source.glyphOf(character))+ )+ expect(glyphs.every((glyph) => glyph.source !== null)).toBe(true)+ })++ test('spaces reshaped glyphs once per character, by the style of each', () => {+ // The text draws Inter at the optical size of its font size.+ const source = expectDefined(+ glyphOutlineSourceSync(FAMILY, 'Regular', [{ axis: 'opsz', value: FONT_SIZE }])+ )+ // `q` has no precomposed acute, so the mark is a glyph of its own on the same character.+ const text = 't->q\u0301'+ const glyphs = placed(text, staticProvider, [{ name: 'calt', value: 0 }], {+ letterSpacing: pixelLength(10),+ styleRuns: [{ start: 3, length: 2, style: { letterSpacing: pixelLength(4) } }]+ })+ const advances = source.shape(text, {}).map((glyph) => glyph.advance * FONT_SIZE)++ expect(glyphs.map((glyph) => glyph.firstCharacter)).toEqual([0, 1, 3, 3])+ expect(glyphs.map((glyph) => glyph.advance)).toEqual([+ advances[0] + 10,+ advances[1] + 10,+ advances[2],+ advances[3] + 4+ ])+ })++ test('shapes the run itself with the features the text sets', () => {+ const source = variableSource()+ // With contextual alternates off in the text too, the arrow stays its three characters.+ const glyphs = placed('t->b', staticProvider, [{ name: 'calt', value: 0 }], {+ fontFeatures: [{ tag: 'CALT', enabled: false }]+ })++ expect(glyphs.map((glyph) => glyph.id)).toEqual(+ Array.from('t->b', (character) => source.glyphOf(character))+ )+ expect(glyphs.map((glyph) => glyph.firstCharacter)).toEqual([0, 1, 2, 3])+ })+})