AI-native design editor. Open-source Figma alternative.
feat(fonts): draw Figma Hand with Caveat sized to its widths and line box (#1645)
Danila Poyarkov8686a56ca502
diff --git a/changes/1645/fixed.md b/changes/1645/fixed.mdnew file mode 100644index 000000000..fefe68363--- /dev/null+++ b/changes/1645/fixed.md@@ -0,0 +1 @@+- Text in FigJam's Cute typeface, Figma Hand, which is licensed for Figma only, draws in the open Caveat font sized to Figma Hand's widths and line height instead of falling back to Inter; files keep Figma Hand, and the font notice names the substitution.diff --git a/packages/core/assets/Caveat-OFL.txt b/packages/core/assets/Caveat-OFL.txtnew file mode 100644index 000000000..6e5220c95--- /dev/null+++ b/packages/core/assets/Caveat-OFL.txt@@ -0,0 +1,93 @@+Copyright 2014 The Caveat Project Authors (https://github.com/googlefonts/caveat)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/packages/core/assets/CaveatVariable.woff2 b/packages/core/assets/CaveatVariable.woff2new file mode 100644index 000000000..230a433b5Binary files /dev/null and b/packages/core/assets/CaveatVariable.woff2 differdiff --git a/packages/core/src/text/font/manager.ts b/packages/core/src/text/font/manager.tsindex 9cdaa70f9..ad8e024a2 100644--- a/packages/core/src/text/font/manager.ts+++ b/packages/core/src/text/font/manager.ts@@ -29,6 +29,7 @@ import {type HostFontLoader,type LocalFontAccessState} from '#core/text/font/sources'+import { fontStandIn, standInFont } from '#core/text/font/stand-in'import {fontAxes,hasNamedInstance,@@ -37,6 +38,7 @@ import {type FontAxis,type NamedInstance} from '#core/text/font/variation'+import { sfntFont } from '#core/text/font/woff2'import { collectGraphFontKeys } from '#core/text/requirements/collect'import { normalizedCoverageText, WebFontResolver } from '#core/text/web-font/resolver'import type { WebFontFetch, WebFontProviderId } from '#core/text/web-font/resolver'@@ -381,6 +383,13 @@ export class FontManager {): Promise<ArrayBuffer | null> {signal?.throwIfAborted()const loaded = this.loadedData(family, style)+ // A stand-in gives way to the family's own face once it is installed or local access is granted.+ if (loaded && this.loadedFontSource(family, style) === 'stand-in') {+ const installed = await this.loadInstalledFont(family, style)+ if (installed) return installed+ this.registerFontInCanvasKit(family, loaded)+ return loaded+ }if (loaded) {this.registerFontInCanvasKit(family, loaded)return this.withRemoteCoverage(family, style, loaded, characters, signal)@@ -395,10 +404,29 @@ export class FontManager {return ((await this.loadBundledFont(family, style)) ??(await this.loadCachedFont(family, style, characters)) ??- (await this.loadRemoteFont(family, style, characters, signal))+ (await this.loadRemoteFont(family, style, characters, signal)) ??+ (await this.loadStandIn(family, style)))}+ /**+ * The open font that draws a family nobody may ship, made to the family's widths and line box,+ * under the family's own name, so text is laid out and drawn alike wherever it is read from.+ */+ private async loadStandIn(family: string, style: string): Promise<ArrayBuffer | null> {+ const standIn = fontStandIn(family)+ if (!standIn) return null+ try {+ const file = await this.fetchBundledFont(standIn.file)+ if (!file) return null+ const font = standInFont(await sfntFont(file), standIn)+ return font ? this.registerAndCache(family, style, font, 'stand-in') : null+ } catch (e) {+ console.warn(`Stand-in font load failed for "${family}" ${style}:`, e)+ return null+ }+ }+/*** `data`, or a web font fetched again with `characters` when it came from the web without them,* as a provider cuts a font down to the text it is asked for.diff --git a/packages/core/src/text/font/sources.ts b/packages/core/src/text/font/sources.tsindex e4269e35c..e845d5b71 100644--- a/packages/core/src/text/font/sources.ts+++ b/packages/core/src/text/font/sources.ts@@ -9,7 +9,8 @@ export interface FontInfo {export type LocalFontAccessState = 'unsupported' | 'prompt' | 'granted' | 'denied'export type FontFamilySource = 'local' | 'bundled' | 'fallback' | WebFontProviderId-export type FontLoadedSource = FontFamilySource | 'cache' | 'registered'+/** Where a loaded face came from; `stand-in` is an open font drawn in a missing family's place. */+export type FontLoadedSource = FontFamilySource | 'cache' | 'registered' | 'stand-in'export interface FontFamilyOption {family: stringdiff --git a/packages/core/src/text/font/stand-in.ts b/packages/core/src/text/font/stand-in.tsnew file mode 100644index 000000000..020e00f36--- /dev/null+++ b/packages/core/src/text/font/stand-in.ts@@ -0,0 +1,69 @@+import { fontTableView } from '#core/text/font/variation'++/**+ * An open font drawn in place of a family nobody may ship, sized and set in that family's line+ * box so text wraps and stacks as it does in it. The document keeps the family's own name, so the+ * real font draws it wherever it is installed.+ */+export interface FontStandIn {+ /** The open family drawn in its place, as the font status names it. */+ family: string+ /** The bundled file that draws it. */+ file: string+ /** How much larger it is drawn, so its letters take the widths the family's do. */+ scale: number+ /** The family's line box above and below the baseline, in ems. */+ ascent: number+ descent: number+}++/**+ * Families drawn by a stand-in when they are not installed. FigJam's "Cute" typeface is Figma+ * Hand, which OH no Type licensed for Figma's own products only. Measured in Figma on 2026-11-01+ * against 25 open handwriting fonts, Caveat is the nearest: drawn 1.69 times larger its lines+ * take Figma Hand's widths, and Figma Hand's line box is 1.38 em, 1.02 of it above the baseline.+ */+export const FONT_STAND_INS: Readonly<Record<string, FontStandIn>> = {+ 'Figma Hand': {+ family: 'Caveat',+ file: '/CaveatVariable.woff2',+ scale: 1.69,+ ascent: 1.02,+ descent: 0.36+ }+}++/** The stand-in that draws `family` when it is missing, if it has one. */+export function fontStandIn(family: string): FontStandIn | null {+ return Object.hasOwn(FONT_STAND_INS, family) ? FONT_STAND_INS[family] : null+}++/**+ * `font` (an sfnt file) made to draw as `standIn` asks: a smaller em, so every glyph, advance and+ * kerning value is `scale` times larger at the same font size, and the family's ascent and descent+ * in all three places fonts give them, with no line gap. The outlines stay as they are. `null` when+ * `font` is not a font, as a host that answers a missing file with a page would give.+ */+export function standInFont(font: ArrayBuffer, standIn: FontStandIn): ArrayBuffer | null {+ const data = font.slice(0)+ const head = fontTableView(data, 'head')+ const hhea = fontTableView(data, 'hhea')+ // The fields read and written: the em in `head`, the line metrics in `hhea`.+ if (!head || !hhea || head.byteLength < 20 || hhea.byteLength < 10) return null+ const unitsPerEm = Math.round(head.getUint16(18) / standIn.scale)+ const ascent = Math.round(standIn.ascent * unitsPerEm)+ const descent = Math.round(standIn.descent * unitsPerEm)+ head.setUint16(18, unitsPerEm)+ hhea.setInt16(4, ascent)+ hhea.setInt16(6, -descent)+ hhea.setInt16(8, 0)+ const os2 = fontTableView(data, 'OS/2')+ if (os2 && os2.byteLength >= 78) {+ os2.setInt16(68, ascent)+ os2.setInt16(70, -descent)+ os2.setInt16(72, 0)+ os2.setUint16(74, ascent)+ os2.setUint16(76, descent)+ }+ return data+}diff --git a/packages/core/src/text/font/status.ts b/packages/core/src/text/font/status.tsindex 5ae786501..6e907e057 100644--- a/packages/core/src/text/font/status.ts+++ b/packages/core/src/text/font/status.ts@@ -4,6 +4,7 @@ import { DEFAULT_FONT_FAMILY } from '#core/constants'import { fontManager, type FontManager } from '#core/text/font/manager'import { collectNamedNodeFontFaces } from '#core/text/font/names'import type { FontLoadedSource, FontUnavailableReason } from '#core/text/font/sources'+import { fontStandIn } from '#core/text/font/stand-in'export type FontFaceStatus = 'available' | 'substituted' | 'unresolved'@@ -140,6 +141,21 @@ export class DocumentFontUses {function faceStatus(use: MutableFontFaceUse, manager: FontManager): DocumentFontFaceStatus {const exactSource = manager.loadedFontSource(use.family, use.style)+ // A family nobody may ship is drawn by an open font in its place, which still substitutes it.+ const standIn = exactSource === 'stand-in' ? fontStandIn(use.family) : null+ if (standIn) {+ return {+ family: use.family,+ style: use.style,+ name: use.name,+ status: 'substituted',+ source: exactSource,+ substituteFamily: standIn.family,+ reason: manager.unavailableReason(use.family, use.style),+ nodeIds: [...use.nodeIds],+ nodeNames: [...use.nodeNames]+ }+ }if (exactSource) {return {family: use.family,diff --git a/packages/core/tests/text/font/stand-in.test.ts b/packages/core/tests/text/font/stand-in.test.tsnew file mode 100644index 000000000..88a1dee43--- /dev/null+++ b/packages/core/tests/text/font/stand-in.test.ts@@ -0,0 +1,85 @@+import { describe, expect, test } from 'bun:test'++import { SceneGraph } from '@open-pencil/scene-graph'++import {+ documentFontStatus,+ FontManager,+ fontTableView,+ sfntFont+} from '@open-pencil/core/text'+import { FONT_STAND_INS, standInFont } from '#core/text/font/stand-in'++const FIGMA_HAND = FONT_STAND_INS['Figma Hand']++/** A font manager that asks no web provider, so a missing family can only fall to its stand-in. */+function offlineManager() {+ const manager = new FontManager()+ manager.setOnlineFontProviders({})+ return manager+}++async function bundledCaveat() {+ const manager = offlineManager()+ const file = await manager.fetchBundledFont(FIGMA_HAND.file)+ if (!file) throw new Error('Caveat is not bundled')+ return sfntFont(file)+}++describe('stand-in fonts', () => {+ test("Caveat stands in for Figma Hand at its widths, in Figma Hand's line box", async () => {+ const caveat = await bundledCaveat()+ const font = standInFont(caveat, FIGMA_HAND)+ if (!font) throw new Error('No stand-in font')+ const unitsPerEm = fontTableView(font, 'head')?.getUint16(18) ?? 0+ // Caveat's 1000-unit em, made 1.69 times smaller, so its letters are 1.69 times wider.+ expect(unitsPerEm).toBe(592)+ const hhea = fontTableView(font, 'hhea')+ expect([hhea?.getInt16(4), hhea?.getInt16(6), hhea?.getInt16(8)]).toEqual([604, -213, 0])+ // The file it was made from is left as it was.+ expect(fontTableView(caveat, 'head')?.getUint16(18)).toBe(1000)+ })++ test('a page served in place of the file is not taken for a font', () => {+ const page = new TextEncoder().encode('<!doctype html><title>Not found</title>').buffer+ expect(standInFont(page, FIGMA_HAND)).toBeNull()+ })++ test('a missing Figma Hand loads the stand-in under its own name, reported as Caveat', async () => {+ const manager = offlineManager()+ const font = await manager.loadFont('Figma Hand', 'Regular')+ expect(font).not.toBeNull()+ expect(manager.loadedFontSource('Figma Hand', 'Regular')).toBe('stand-in')++ const graph = new SceneGraph()+ const pageId = graph.getPages()[0]?.id ?? graph.rootId+ graph.createNode('TEXT', pageId, { fontFamily: 'Figma Hand', fontWeight: 400, text: 'Hi' })+ const [face] = documentFontStatus(graph, pageId, manager).issues+ expect(face).toMatchObject({ family: 'Figma Hand', status: 'substituted', substituteFamily: 'Caveat' })+ })++ test('other missing families have no stand-in', async () => {+ expect(await offlineManager().loadFont('No Such Family', 'Regular')).toBeNull()+ })++ test('a font whose head table is cut short is not taken for one', async () => {+ const caveat = await bundledCaveat()+ const view = new DataView(caveat)+ // Shorten the head table's directory record to 4 bytes, too short for the em it holds.+ for (let i = 0; i < view.getUint16(4); i++) {+ const record = 12 + i * 16+ const tag = String.fromCharCode(...new Uint8Array(caveat, record, 4))+ if (tag === 'head') view.setUint32(record + 12, 4)+ }+ expect(standInFont(caveat, FIGMA_HAND)).toBeNull()+ })++ test('an installed Figma Hand replaces the stand-in once it can be read', async () => {+ const manager = offlineManager()+ await manager.loadFont('Figma Hand', 'Regular')+ const installed = await bundledCaveat()+ manager.setHostFontLoader((family) => Promise.resolve(family === 'Figma Hand' ? installed : null))+ await manager.loadFont('Figma Hand', 'Regular')+ expect(manager.loadedFontSource('Figma Hand', 'Regular')).toBe('local')+ })+})diff --git a/src/app/editor/fonts/bundled.ts b/src/app/editor/fonts/bundled.tsindex 590d67053..125983318 100644--- a/src/app/editor/fonts/bundled.ts+++ b/src/app/editor/fonts/bundled.ts@@ -1,5 +1,6 @@import harfBuzzSubset from 'harfbuzzjs/dist/harfbuzz-subset.wasm?url'+import caveatVariable from '@open-pencil/core/assets/CaveatVariable.woff2?url'import interSemiBold from '@open-pencil/core/assets/Inter-SemiBold.ttf?url'import interVariableItalic from '@open-pencil/core/assets/InterVariable-Italic.ttf?url'import interVariable from '@open-pencil/core/assets/InterVariable.ttf?url'@@ -18,7 +19,8 @@ const BUNDLED_FONT_URLS: Record<string, string> = {'InterVariable-Italic.ttf': interVariableItalic,'Inter-SemiBold.ttf': interSemiBold,'NotoNaskhArabic-Regular.ttf': notoNaskhArabic,- 'OpenPencilEmojiMetrics-Regular.ttf': emojiMetrics+ 'OpenPencilEmojiMetrics-Regular.ttf': emojiMetrics,+ 'CaveatVariable.woff2': caveatVariable}/**