Skip to content

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

feat(core): decode WOFF2 fonts when they load (#1452)

Danila Poyarkovcdc9933c197b
diff --git a/bun.lock b/bun.lock
index 0112e86fa..b8e8b6599 100644
--- a/bun.lock
+++ b/bun.lock
@@ -295,6 +295,7 @@
"twirlwind": "^0.4.1",
"unifont": "0.7.4",
"valibot": "^1.5.0",
+ "woff2-encoder": "2.0.0",
"yoga-layout": "npm:@open-pencil/[email protected]",
},
"devDependencies": {
@@ -4964,6 +4965,8 @@
"with": ["[email protected]", "", { "dependencies": { "@babel/parser": "^7.9.6", "@babel/types": "^7.9.6", "assert-never": "^1.2.1", "babel-walk": "3.0.0-canary-5" } }, "sha512-RNGKj82nUPg3g5ygxkQl0R937xLyho1J24ItRCBTr/m1YnZkzJy1hUiHUJrc/VlsDQzsCnInEGSg3bci0Lmd4w=="],
+ "woff2-encoder": ["[email protected]", "", {}, "sha512-wH1rcskczCP5+BJABM88aM3hoEX1VUW6U+Ksx/7bmXvctWGqF+O/YQdC6vWQ7lJS7ny21a0MkAqcZyOP2O8CAg=="],
+
"word-wrap": ["[email protected]", "", {}, "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA=="],
"workbox-background-sync": ["[email protected]", "", { "dependencies": { "idb": "^7.0.1", "workbox-core": "7.4.1" } }, "sha512-HhT7KE8tOWDm02wRNshXUnUPofMlhenF2DBdUnDPOubhizzPeItkYTmAB6td1Z2cjYPa98vzEiPLEuzn5hN66g=="],
diff --git a/packages/core/package.json b/packages/core/package.json
index 15a993843..bd64311a5 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -213,6 +213,7 @@
"twirlwind": "^0.4.1",
"unifont": "0.7.4",
"valibot": "^1.5.0",
+ "woff2-encoder": "2.0.0",
"yoga-layout": "npm:@open-pencil/[email protected]"
},
"devDependencies": {
diff --git a/packages/core/src/text/font/woff2.ts b/packages/core/src/text/font/woff2.ts
new file mode 100644
index 000000000..43868c87f
--- /dev/null
+++ b/packages/core/src/text/font/woff2.ts
@@ -0,0 +1,17 @@
+/** `wOF2`, the signature a WOFF2 file starts with. */
+const WOFF2_SIGNATURE = 0x774f4632
+
+export function isWOFF2(data: ArrayBuffer): boolean {
+ return data.byteLength >= 4 && new DataView(data).getUint32(0) === WOFF2_SIGNATURE
+}
+
+/**
+ * The font as an sfnt (TrueType or OpenType) file. CanvasKit draws WOFF2, but opentype.js, 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.
+ */
+export async function sfntFont(data: ArrayBuffer): Promise<ArrayBuffer> {
+ if (!isWOFF2(data)) return data
+ const { default: decompress } = await import('woff2-encoder/decompress')
+ return new Uint8Array(await decompress(data)).buffer
+}
diff --git a/packages/core/src/text/fonts.ts b/packages/core/src/text/fonts.ts
index 99e58f47c..b23da4549 100644
--- a/packages/core/src/text/fonts.ts
+++ b/packages/core/src/text/fonts.ts
@@ -12,6 +12,7 @@ import { isVariableFont, namedInstanceVariations } from '#core/text/font/variati
export * from '#core/text/font/sources'
export * from '#core/text/font/style'
export * from '#core/text/font/variation'
+export * from '#core/text/font/woff2'
import {
normalizeFontFamily,
styleToWeight,
diff --git a/packages/core/src/text/web-fonts.ts b/packages/core/src/text/web-fonts.ts
index 52cb704d7..7956af713 100644
--- a/packages/core/src/text/web-fonts.ts
+++ b/packages/core/src/text/web-fonts.ts
@@ -5,6 +5,7 @@ import { parseFontStyle } from '@open-pencil/scene-graph/font-style'
import { IS_BROWSER } from '#core/constants'
import type { FamilyFace } from '#core/text/font/faces'
+import { sfntFont } from '#core/text/font/woff2'
import {
createProviderUnifont,
isRemoteFontSource,
@@ -410,7 +411,7 @@ export class WebFontResolver {
const buffers = await Promise.all(
faces.map(async ({ source, init }) => {
const response = await this.fetchRemote(source.url, { ...init, signal })
- return response.ok ? response.arrayBuffer() : null
+ return response.ok ? sfntFont(await response.arrayBuffer()) : null
})
)
return buffers.filter(isArrayBuffer)
diff --git a/packages/core/tests/text/font/woff2.test.ts b/packages/core/tests/text/font/woff2.test.ts
new file mode 100644
index 000000000..3ce12a2a2
--- /dev/null
+++ b/packages/core/tests/text/font/woff2.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, test } from 'bun:test'
+import { join } from 'node:path'
+
+import { FIXTURES } from '#core-tests/helpers/paths'
+
+import { isVariableFont, isWOFF2, sfntFont } from '@open-pencil/core/text'
+
+const font = (name: string) => Bun.file(join(FIXTURES, 'fonts', name)).arrayBuffer()
+
+describe('sfntFont', () => {
+ test('decompresses a WOFF2 font into the TrueType font it holds, axes included', async () => {
+ const woff2 = await font('InterVariable-Faces.woff2')
+ expect(isWOFF2(woff2)).toBe(true)
+ const sfnt = await sfntFont(woff2)
+ expect(isWOFF2(sfnt)).toBe(false)
+ expect(new DataView(sfnt).getUint32(0)).toBe(0x00010000)
+ expect(isVariableFont(sfnt)).toBe(true)
+ })
+
+ test('keeps an sfnt font as it is', async () => {
+ const ttf = await font('InterVariable-Latin.ttf')
+ expect(await sfntFont(ttf)).toBe(ttf)
+ })
+})
diff --git a/packages/core/tests/text/web-fonts.test.ts b/packages/core/tests/text/web-fonts.test.ts
new file mode 100644
index 000000000..0e27fae07
--- /dev/null
+++ b/packages/core/tests/text/web-fonts.test.ts
@@ -0,0 +1,32 @@
+import { expect, test } from 'bun:test'
+import { join } from 'node:path'
+
+import { FIXTURES } from '#core-tests/helpers/paths'
+
+import { isVariableFont, isWOFF2, WebFontResolver } from '@open-pencil/core/text'
+
+test('loads a web font served as WOFF2 as the TrueType font it holds', async () => {
+ const woff2 = await Bun.file(join(FIXTURES, 'fonts', 'InterVariable-Faces.woff2')).arrayBuffer()
+ const family = 'Web Font Test WOFF2'
+ const fontURL = 'https://fonts.gstatic.com/s/test/faces.woff2'
+ const resolver = new WebFontResolver()
+ resolver.setEnabled({ google: true })
+ resolver.setRemoteFetch(async (input) => {
+ const url = String(input)
+ if (url.startsWith('https://fonts.google.com/metadata/fonts'))
+ return Response.json({ familyMetadataList: [{ family, fonts: { '400': {} }, axes: [] }] })
+ if (url.startsWith('https://fonts.googleapis.com/css2'))
+ return new Response(
+ `@font-face { font-family: '${family}'; font-style: normal; font-weight: 400; src: url(${fontURL}) format('woff2'); }`
+ )
+ if (url === fontURL) return new Response(woff2)
+ return new Response(null, { status: 404 })
+ })
+
+ const resolved = await resolver.fetchFont([family], 'Regular', '')
+ const font = resolved?.buffers[0]
+ expect(font).toBeDefined()
+ if (!font) return
+ expect(isWOFF2(font)).toBe(false)
+ expect(isVariableFont(font)).toBe(true)
+})
diff --git a/tests/fixtures/fonts/InterVariable-Faces.woff2 b/tests/fixtures/fonts/InterVariable-Faces.woff2
new file mode 100644
index 000000000..7dfc05288
Binary files /dev/null and b/tests/fixtures/fonts/InterVariable-Faces.woff2 differ