Skip to content

AI-native design editor. Open-source Figma alternative.

fix: draw a missing font face as the face the font has instead of faking it (#1305)

Danila Poyarkov58b0bbde381e
diff --git a/changes/1305/fixed.md b/changes/1305/fixed.md
new file mode 100644
index 000000000..6d61a24c9
--- /dev/null
+++ b/changes/1305/fixed.md
@@ -0,0 +1 @@
+- Text set in a style its font lacks, such as italic in a font without an italic face, draws in the face the font has, as Figma draws it, instead of a slanted or emboldened imitation that copies, saved files, and exported code did not keep; the font status lists the style as missing.
diff --git a/packages/core/src/canvas/text/font-families.ts b/packages/core/src/canvas/text/font-families.ts
index f0e5632f7..a48b644f4 100644
--- a/packages/core/src/canvas/text/font-families.ts
+++ b/packages/core/src/canvas/text/font-families.ts
@@ -3,10 +3,26 @@ import { uniq } from 'es-toolkit/array'
import { ResourceCache } from '#core/cache/resource'
import { DEFAULT_FONT_FAMILY } from '#core/constants'
import { EMOJI_METRICS_FAMILY } from '#core/text/emoji'
-import { fontManager } from '#core/text/fonts'
+import type { FamilyFace } from '#core/text/font/faces'
+import { fontManager, fontWeightMatchOrder, weightToStyle } from '#core/text/fonts'
const familiesCache = new ResourceCache<string, string[]>({ maxEntries: 256 })
+/**
+ * The loaded face of a family that text asking for a style is drawn in: that style, or the
+ * nearest loaded weight in the same slant, then the other, as font matching picks it; `null`
+ * when the family has none loaded.
+ */
+export function loadedFace(family: string, weight: number, italic: boolean): FamilyFace | null {
+ for (const slant of [italic, !italic]) {
+ for (const candidate of fontWeightMatchOrder(weight)) {
+ if (fontManager.isStyleLoaded(family, weightToStyle(candidate, slant)))
+ return { weight: candidate, italic: slant }
+ }
+ }
+ return null
+}
+
export function resolveParagraphFontFamilies(
primary: string,
style: string,
diff --git a/packages/core/src/canvas/text/index.ts b/packages/core/src/canvas/text/index.ts
index 175abd5ff..a46d77d5f 100644
--- a/packages/core/src/canvas/text/index.ts
+++ b/packages/core/src/canvas/text/index.ts
@@ -73,8 +73,8 @@ function requiredFacesReadiness(r: FontReadinessRenderer, node: SceneNode): Node
const state = fontResolver.state(demand).state
demandFace(r, node, family, style)
if (state === 'failed' || state === 'exhausted') {
- // CanvasKit can synthesize a missing slant or weight from another loaded face in the same
- // family. Keep the text visible when an exact face (for example, Italic) is unavailable.
+ // A missing face is drawn in another loaded face of the family, as Figma draws it, and
+ // reported missing; the text stays visible when an exact face (Italic) is unavailable.
if (fontManager.isLoaded(family)) continue
exhausted = true
} else {
diff --git a/packages/core/src/canvas/text/paragraph/index.ts b/packages/core/src/canvas/text/paragraph/index.ts
index 90ca1cc1a..99a0bd49f 100644
--- a/packages/core/src/canvas/text/paragraph/index.ts
+++ b/packages/core/src/canvas/text/paragraph/index.ts
@@ -1,5 +1,6 @@
import type {
CanvasKit,
+ FontStyle,
FontWeight,
Paint,
Paragraph,
@@ -13,7 +14,7 @@ import type { SceneNode } from '@open-pencil/scene-graph'
import { resolveRGBAForPreview } from '@open-pencil/scene-graph/color'
import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text-direction'
-import { resolveParagraphFontFamilies } from '#core/canvas/text/font-families'
+import { loadedFace, resolveParagraphFontFamilies } from '#core/canvas/text/font-families'
import { laidOutText } from '#core/canvas/text/keycap'
import {
pushParagraphStyle,
@@ -117,6 +118,20 @@ function blockHeightBehavior(
return ck.TextHeightBehavior.All
}
+/**
+ * The style a paragraph asks CanvasKit for: the face of the family that is loaded. Asked for a
+ * face it lacks, CanvasKit slants and emboldens another, which neither Figma, a browser, nor a
+ * native text stack draws the same, so a missing face is drawn as the face that exists and
+ * reported missing, as Figma does. A family with no face loaded asks for the style as given.
+ */
+function drawnFontStyle(ck: CanvasKit, family: string, weight: number, italic: boolean): FontStyle {
+ const face = loadedFace(family, weight, italic) ?? { weight, italic }
+ return {
+ weight: { value: face.weight } as FontWeight,
+ slant: face.italic ? ck.FontSlant.Italic : ck.FontSlant.Upright
+ }
+}
+
/** The colour a style run's text is drawn in: its first visible solid fill, or `baseColor`. */
export function styleRunColor(
ck: CanvasKit,
@@ -160,10 +175,7 @@ function pushStyleRun(
fontFamilies: fontFamilies(runFamily, runWeight, runItalic),
fontSize: runFontSize,
locale: styleRunLanguage(style, node),
- fontStyle: {
- weight: { value: runWeight } as FontWeight,
- slant: runItalic ? ck.FontSlant.Italic : ck.FontSlant.Upright
- },
+ fontStyle: drawnFontStyle(ck, runFamily, runWeight, runItalic),
fontVariations: textFontVariations(
style.fontVariations ?? node.fontVariations,
fontManager.namedInstanceVariations(runFamily, weightToStyle(runWeight, runItalic))
@@ -271,10 +283,12 @@ export function buildSkParagraph(
),
fontSize: baseFontSize,
locale: node.textLanguage ?? undefined,
- fontStyle: {
- weight: { value: node.fontWeight } as FontWeight,
- slant: node.italic ? ck.FontSlant.Italic : ck.FontSlant.Upright
- },
+ fontStyle: drawnFontStyle(
+ ck,
+ node.fontFamily || DEFAULT_FONT_FAMILY,
+ node.fontWeight,
+ node.italic
+ ),
fontVariations: textFontVariations(
node.fontVariations,
fontManager.namedInstanceVariations(
diff --git a/packages/core/src/canvas/text/placed.ts b/packages/core/src/canvas/text/placed.ts
index ac8721bb6..9190ffaf1 100644
--- a/packages/core/src/canvas/text/placed.ts
+++ b/packages/core/src/canvas/text/placed.ts
@@ -3,12 +3,13 @@ import { uniq } from 'es-toolkit/array'
import type { SceneNode } from '@open-pencil/scene-graph'
-import { resolveParagraphFontFamilies } from '#core/canvas/text/font-families'
+import { loadedFace, resolveParagraphFontFamilies } from '#core/canvas/text/font-families'
import { laidOutText } from '#core/canvas/text/keycap'
import type { TextLayout, TextLayoutMarker } from '#core/canvas/text/layout'
import { textFontVariations } from '#core/canvas/text/paragraph'
import { utf16IndicesByUtf8 } from '#core/canvas/text/utf8'
-import { fontManager, fontWeightMatchOrder, weightToStyle } from '#core/text/fonts'
+import { DEFAULT_FONT_FAMILY } from '#core/constants'
+import { fontManager, weightToStyle } from '#core/text/fonts'
import { glyphOutlineSourceSync, type GlyphOutlineSource } from '#core/text/opentype'
type GlyphRun = ReturnType<Paragraph['getShapedLines']>[number]['runs'][number]
@@ -30,24 +31,20 @@ export interface LaidOutGlyph {
source: GlyphOutlineSource | null
}
-/**
- * The loaded face of a family the paragraph draws a style in: the style itself, or the nearest
- * loaded weight in the same slant, then the other, as font matching picks it.
- */
+/** The loaded face of a family the paragraph draws a style in, as its style name. */
function loadedStyle(family: string, weight: number, italic: boolean): string | null {
- for (const slant of [italic, !italic]) {
- for (const candidate of fontWeightMatchOrder(weight)) {
- const style = weightToStyle(candidate, slant)
- if (fontManager.isStyleLoaded(family, style)) return style
- }
- }
- return null
+ const face = loadedFace(family, weight, italic)
+ return face ? weightToStyle(face.weight, face.italic) : null
}
-/** The font a character asks for: its family, weight, and slant, and the variable axes it sets. */
+/**
+ * The font a character asks for: its family, weight, and slant, and the variable axes it sets;
+ * and the face the paragraph asks every family for, the one its own family has loaded, as
+ * `drawnFontStyle` asks CanvasKit.
+ */
function fontAt(node: SceneNode, index: number) {
const run = node.styleRuns.find((item) => index >= item.start && index < item.start + item.length)
- const family = run?.style.fontFamily ?? node.fontFamily
+ const family = run?.style.fontFamily ?? (node.fontFamily || DEFAULT_FONT_FAMILY)
const weight = run?.style.fontWeight ?? node.fontWeight
const italic = run?.style.italic ?? node.italic
const style = weightToStyle(weight, italic)
@@ -56,13 +53,14 @@ function fontAt(node: SceneNode, index: number) {
run?.style.fontVariations ?? node.fontVariations,
fontManager.namedInstanceVariations(family, style)
) ?? []
- return { family, weight, italic, style, variations }
+ const drawn = loadedFace(family, weight, italic) ?? { weight, italic }
+ return { family, weight, italic, style, variations, drawn }
}
/** The outline source of each font the paragraph may have drawn a character in, in its order. */
function* candidateSources(font: ReturnType<typeof fontAt>) {
for (const family of resolveParagraphFontFamilies(font.family, font.style)) {
- const style = loadedStyle(family, font.weight, font.italic)
+ const style = loadedStyle(family, font.drawn.weight, font.drawn.italic)
const source = style ? glyphOutlineSourceSync(family, style, font.variations) : null
if (source) yield source
}
@@ -78,7 +76,7 @@ export function characterFamily(node: SceneNode, text: string, index: number): s
const character = String.fromCodePoint(codePoint)
const font = fontAt(node, index)
for (const family of resolveParagraphFontFamilies(font.family, font.style)) {
- const style = loadedStyle(family, font.weight, font.italic)
+ const style = loadedStyle(family, font.drawn.weight, font.drawn.italic)
if (style && glyphOutlineSourceSync(family, style, font.variations)?.covers(character))
return family
}
@@ -145,7 +143,7 @@ function drawnCharacters(
* 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.
- * Glyphs CanvasKit emboldened or slanted itself match no font's outlines.
+ * The paragraph asks each family for a face it has loaded, so CanvasKit never fakes one.
*/
function runOutlineSource(
node: SceneNode,
@@ -154,7 +152,7 @@ function runOutlineSource(
run: GlyphRun,
characterAt: (offset: number) => number
): GlyphOutlineSource | null {
- if (run.fakeBold || run.fakeItalic || run.glyphs.length === 0) return null
+ if (run.glyphs.length === 0) return null
const offsets = Array.from(run.offsets, characterAt)
const start = Math.min(...offsets)
const end = Math.max(...offsets)
@@ -178,7 +176,7 @@ function ellipsisSource(
run: GlyphRun,
characterAt: (offset: number) => number
): GlyphOutlineSource | null {
- if (run.glyphs.length !== 1 || run.fakeBold || run.fakeItalic) return null
+ if (run.glyphs.length !== 1) return null
for (const source of candidateSources(fontAt(node, characterAt(run.offsets[0])))) {
if (source.glyphOf(ELLIPSIS) === run.glyphs[0]) return source
}
@@ -195,7 +193,6 @@ function markerGlyphs(marker: TextLayoutMarker, offsetY: number): LaidOutGlyph[]
const glyphs: LaidOutGlyph[] = []
for (const line of marker.paragraph.getShapedLines()) {
for (const run of line.runs) {
- const trusted = !run.fakeBold && !run.fakeItalic
for (let index = 0; index < run.glyphs.length; index++) {
const x = run.positions[index * 2]
glyphs.push({
@@ -205,7 +202,7 @@ function markerGlyphs(marker: TextLayoutMarker, offsetY: number): LaidOutGlyph[]
fontSize: run.size,
advance: run.positions[(index + 1) * 2] - x,
lineLeft: marker.x,
- source: trusted ? source : null
+ source
})
}
}
diff --git a/packages/core/tests/canvas/text/faces.test.ts b/packages/core/tests/canvas/text/faces.test.ts
new file mode 100644
index 000000000..10cc2eebc
--- /dev/null
+++ b/packages/core/tests/canvas/text/faces.test.ts
@@ -0,0 +1,109 @@
+import { describe, expect, test } from 'bun:test'
+
+import type { CanvasKit, TypefaceFontProvider } from 'canvaskit-wasm'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { createDefaultNode } from '@open-pencil/scene-graph/node-defaults'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+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'
+
+/** A family only these tests load, so faces other tests load cannot answer for it. */
+const FAMILY = 'Faces Test Sans'
+
+async function bundled(file: string): Promise<ArrayBuffer> {
+ return expectDefined(await new FontManager().fetchBundledFont(file), file)
+}
+
+/** The pixels of text in a style, drawn by the paragraph the canvas draws. */
+function drawn(
+ ck: CanvasKit,
+ fontProvider: TypefaceFontProvider,
+ style: { fontWeight: number; italic: boolean }
+): Uint8Array {
+ const node = createDefaultNode(() => 'face-text', 'TEXT', {
+ text: 'Faces',
+ fontFamily: FAMILY,
+ fontSize: 40,
+ width: 300,
+ height: 60,
+ ...style
+ })
+ const paragraph = buildParagraph({ ck, fontProvider, fontsLoaded: true }, node, ck.BLACK, {
+ halfLeading: true
+ })
+ const surface = expectDefined(ck.MakeSurface(300, 60), 'surface')
+ try {
+ surface.getCanvas().clear(ck.WHITE)
+ paragraph.layout(300)
+ paragraph.draw(surface.getCanvas(), 0, 0)
+ return expectDefined(
+ surface.getCanvas().readPixels(0, 0, { width: 300, height: 60, colorType: ck.ColorType.RGBA_8888, alphaType: ck.AlphaType.Unpremul, colorSpace: ck.ColorSpace.SRGB }),
+ 'pixels'
+ ) as Uint8Array
+ } finally {
+ surface.delete()
+ }
+}
+
+/**
+ * Asked for a face a family has not loaded, CanvasKit would slant or embolden another, which
+ * neither Figma, a browser, nor a native text stack draws the same. Figma draws a missing face as
+ * the face that exists and reports it missing; so does the canvas.
+ */
+describe('text faces', () => {
+ test('draws a missing face as the loaded one rather than faking it', async () => {
+ const ck = await getCanvasKit()
+ const fontProvider = ck.TypefaceFontProvider.Make()
+ fontManager.attachProvider(ck, fontProvider)
+ fontManager.markLoaded(FAMILY, 'Regular', await bundled('/Inter-Regular.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)
+ })
+
+ test('draws a face the family has loaded', async () => {
+ const ck = await getCanvasKit()
+ const fontProvider = ck.TypefaceFontProvider.Make()
+ fontManager.attachProvider(ck, fontProvider)
+ fontManager.markLoaded(FAMILY, 'Regular', await bundled('/Inter-Regular.ttf'))
+ fontManager.markLoaded(FAMILY, 'Bold', await bundled('/Inter-Bold.ttf'))
+ const regular = drawn(ck, fontProvider, { fontWeight: 400, italic: false })
+ expect(drawn(ck, fontProvider, { fontWeight: 700, italic: false })).not.toEqual(regular)
+ })
+
+ /**
+ * One face for the whole text: a family without the requested face draws its own, and the
+ * characters it lacks fall back in that same face, which is the outline saved for them.
+ */
+ 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('/Inter-Regular.ttf'))
+ fontManager.markLoaded('Inter', 'Bold', await bundled('/Inter-Bold.ttf'))
+ const graph = new SceneGraph()
+ const node = graph.createNode('TEXT', graph.getPages()[0].id, {
+ text: 'F',
+ fontFamily: primary,
+ fontWeight: 700,
+ fontSize: 40,
+ width: 200,
+ height: 60,
+ textAutoResize: 'NONE'
+ })
+ const shaped = expectDefined(
+ await withFigExportRuntime(graph, await getCanvasKit(), async (runtime) =>
+ runtime.shapeText(node)
+ ),
+ 'shaped text'
+ )
+ const regular = expectDefined(glyphOutlineSourceSync('Inter', 'Regular'), 'Inter Regular')
+ expect(shaped.glyphs[0]?.commands).toEqual(regular.outline(regular.glyphOf('F'), 40))
+ })
+})