Skip to content

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

fix(fig): deduplicate exported text glyph blobs

Danila Poyarkovc1ddbf7039bb
diff --git a/packages/core/src/io/formats/fig/export.ts b/packages/core/src/io/formats/fig/export.ts
index a3259a9e8..71a23f617 100644
--- a/packages/core/src/io/formats/fig/export.ts
+++ b/packages/core/src/io/formats/fig/export.ts
@@ -192,6 +192,7 @@ export async function exportFigFile(
const varIdToGuid = new Map<string, GUID>()
const modeIdToGuid = new Map<string, GUID>()
const fontDigestMap = await buildFontDigestMap(graph)
+ const glyphBlobMap = new Map<string, number>()
let internalCanvasGuid: GUID | null = null
assignVariableGuids(graph, localIdCounter, varIdToGuid, modeIdToGuid)
@@ -223,7 +224,8 @@ export async function exportFigFile(
blobs,
nodeIdToGuid,
fontDigestMap,
- varIdToGuid
+ varIdToGuid,
+ glyphBlobMap
)
)
}
diff --git a/packages/core/src/kiwi/node-change/export-node.ts b/packages/core/src/kiwi/node-change/export-node.ts
index 1e617484e..26d2dfce5 100644
--- a/packages/core/src/kiwi/node-change/export-node.ts
+++ b/packages/core/src/kiwi/node-change/export-node.ts
@@ -17,6 +17,7 @@ interface SceneNodeToKiwiContext {
blobs: Uint8Array[]
nodeIdToGuid?: Map<string, GUID>
fontDigestMap?: Map<string, Uint8Array>
+ glyphBlobMap?: Map<string, number>
varIdToGuid?: Map<string, GUID>
fractionalPosition: (index: number) => string
mapToFigmaType: (type: SceneNode['type']) => string
@@ -29,7 +30,8 @@ interface SceneNodeToKiwiContext {
nc: KiwiNodeChange,
graph: SceneGraph,
fontDigestMap: Map<string, Uint8Array> | undefined,
- blobs: Uint8Array[]
+ blobs: Uint8Array[],
+ glyphBlobMap: Map<string, number> | undefined
) => void
serializeLayoutProps: (node: SceneNode, nc: KiwiNodeChange) => void
serializeGeometry: (node: SceneNode, nc: KiwiNodeChange, blobs: Uint8Array[]) => void
@@ -173,7 +175,14 @@ function applyNodeVisualProps(
}
if (node.type === 'TEXT') {
- context.serializeTextProps(node, nc, context.graph, context.fontDigestMap, context.blobs)
+ context.serializeTextProps(
+ node,
+ nc,
+ context.graph,
+ context.fontDigestMap,
+ context.blobs,
+ context.glyphBlobMap
+ )
}
nc.frameMaskDisabled = !node.clipsContent
diff --git a/packages/core/src/kiwi/node-change/serialize.ts b/packages/core/src/kiwi/node-change/serialize.ts
index 867dd58a2..9d130593b 100644
--- a/packages/core/src/kiwi/node-change/serialize.ts
+++ b/packages/core/src/kiwi/node-change/serialize.ts
@@ -1,4 +1,4 @@
-import { hexToBytes } from '#core/bytes/hex'
+import { bytesToHex, hexToBytes } from '#core/bytes/hex'
import { encodePathCommandsBlob } from '#core/kiwi/node-change/path-commands'
import { buildDerivedTextData as buildSharedDerivedTextData } from '#core/text/derived-text/data'
import { normalizeFontFamily, weightToFigmaStyle, weightToStyle } from '#core/text/fonts'
@@ -74,10 +74,24 @@ function textLines(text: string): NonNullable<NodeChange['textData']>['lines'] {
return Array.from({ length: lineCount }, () => ({ lineType: 'PLAIN' }))
}
+function appendGlyphBlob(
+ blobs: Uint8Array[],
+ glyphBlobMap: Map<string, number>,
+ blob: Uint8Array
+): number {
+ const key = bytesToHex(blob)
+ const existing = glyphBlobMap.get(key)
+ if (existing !== undefined) return existing
+ const index = blobs.push(blob) - 1
+ glyphBlobMap.set(key, index)
+ return index
+}
+
function buildDerivedTextData(
node: SceneNode,
digestMap: Map<string, Uint8Array>,
- blobs: Uint8Array[]
+ blobs: Uint8Array[],
+ glyphBlobMap: Map<string, number>
): NodeChange['derivedTextData'] {
const fontMeta: NonNullable<NodeChange['derivedTextData']>['fontMetaData'] = []
const seen = new Set<string>()
@@ -106,20 +120,41 @@ function buildDerivedTextData(
)
}
- const style = weightToStyle(node.fontWeight, node.italic)
- const glyphMetrics =
- getGlyphOutlineMetricsSync(node.fontFamily, style, node.text, node.fontSize) ?? []
const lineHeight = node.lineHeight ?? Math.ceil(node.fontSize * 1.2)
const glyphAdvance = node.text.length > 0 ? node.width / Math.max(node.text.length, 1) : 0
- const glyphs = glyphMetrics.map((glyph, index) => ({
- commandsBlob: blobs.push(encodePathCommandsBlob(glyph.commands, node.fontSize)) - 1,
- position: { x: glyph.x || index * glyphAdvance, y: lineHeight },
- fontSize: node.fontSize,
- firstCharacter: index,
- advance: glyph.advance || glyphAdvance,
- rotation: 0
- }))
+ const derivedGlyphs = node.figmaDerivedTextGlyphs ?? []
+ const glyphs =
+ derivedGlyphs.length > 0
+ ? derivedGlyphs.map((glyph, index) => ({
+ commandsBlob: appendGlyphBlob(blobs, glyphBlobMap, glyph.commandsBlob),
+ position: { x: glyph.x, y: glyph.y },
+ fontSize: glyph.fontSize,
+ firstCharacter: index,
+ advance:
+ index + 1 < derivedGlyphs.length
+ ? Math.max(derivedGlyphs[index + 1].x - glyph.x, 0)
+ : glyphAdvance,
+ rotation: 0
+ }))
+ : (getGlyphOutlineMetricsSync(
+ node.fontFamily,
+ weightToStyle(node.fontWeight, node.italic),
+ node.text,
+ node.fontSize
+ ) ?? []
+ ).map((glyph, index) => ({
+ commandsBlob: appendGlyphBlob(
+ blobs,
+ glyphBlobMap,
+ encodePathCommandsBlob(glyph.commands, node.fontSize)
+ ),
+ position: { x: glyph.x || index * glyphAdvance, y: lineHeight },
+ fontSize: node.fontSize,
+ firstCharacter: index,
+ advance: glyph.advance || glyphAdvance,
+ rotation: 0
+ }))
const logicalIndexToCharacterOffsetMap = Array.from(
{ length: node.text.length + 1 },
@@ -254,7 +289,8 @@ function serializeTextProps(
nc: KiwiNodeChange,
graph: SceneGraph,
fontDigestMap: Map<string, Uint8Array> | undefined,
- blobs: Uint8Array[]
+ blobs: Uint8Array[],
+ glyphBlobMap: Map<string, number> | undefined
): void {
upsertPluginData(node, TEXT_DIRECTION_PLUGIN_KEY, node.textDirection)
nc.fontSize = node.fontSize
@@ -276,7 +312,9 @@ function serializeTextProps(
nc.fontVariantContextualLigatures = true
nc.fontVersion = ''
nc.emojiImageSet = 'APPLE'
- if (fontDigestMap) nc.derivedTextData = buildDerivedTextData(node, fontDigestMap, blobs)
+ if (fontDigestMap) {
+ nc.derivedTextData = buildDerivedTextData(node, fontDigestMap, blobs, glyphBlobMap ?? new Map())
+ }
if (node.lineHeight != null) nc.lineHeight = { value: node.lineHeight, units: 'PIXELS' }
nc.letterSpacing = { value: node.letterSpacing, units: 'PIXELS' }
if (node.textDecoration !== 'NONE') {
@@ -421,13 +459,15 @@ export function sceneNodeToKiwi(
blobs: Uint8Array[],
nodeIdToGuid?: Map<string, GUID>,
fontDigestMap?: Map<string, Uint8Array>,
- varIdToGuid?: Map<string, GUID>
+ varIdToGuid?: Map<string, GUID>,
+ glyphBlobMap = new Map<string, number>()
): KiwiNodeChange[] {
return sceneNodeToKiwiWithContext(node, parentGuid, childIndex, localIdCounter, {
graph,
blobs,
nodeIdToGuid,
fontDigestMap,
+ glyphBlobMap,
varIdToGuid,
fractionalPosition,
mapToFigmaType,
diff --git a/tests/engine/io/fig/roundtrip/glyph-blob.test.ts b/tests/engine/io/fig/roundtrip/glyph-blob.test.ts
new file mode 100644
index 000000000..0bd61573c
--- /dev/null
+++ b/tests/engine/io/fig/roundtrip/glyph-blob.test.ts
@@ -0,0 +1,89 @@
+import { beforeAll, describe, expect, test } from 'bun:test'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+
+import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'
+import { parseFigBuffer } from '#core/kiwi/fig/parse/core'
+import { fontManager } from '@open-pencil/core/text'
+
+const FIXTURES = resolve(import.meta.dir, '../../../../fixtures')
+const INTER_ASSETS = resolve(import.meta.dir, '../../../../../packages/core/assets')
+
+function countGlyphBlobs(bytes: Uint8Array) {
+ const parsed = parseFigBuffer(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength))
+ let glyphs = 0
+ let glyphsWithBlob = 0
+ const uniqueGlyphBlobs = new Set<number>()
+
+ for (const nc of parsed.nodeChanges) {
+ if (nc.type !== 'TEXT') continue
+ for (const glyph of nc.derivedTextData?.glyphs ?? []) {
+ glyphs++
+ if (glyph.commandsBlob !== undefined) {
+ glyphsWithBlob++
+ uniqueGlyphBlobs.add(glyph.commandsBlob)
+ }
+ }
+ }
+
+ return { glyphs, glyphsWithBlob, uniqueGlyphBlobs: uniqueGlyphBlobs.size }
+}
+
+function loadInterFonts() {
+ for (const style of ['Regular', 'Medium', 'SemiBold', 'Bold', 'ExtraBold']) {
+ const bytes = readFileSync(resolve(INTER_ASSETS, `Inter-${style}.ttf`))
+ fontManager.markLoaded(
+ 'Inter',
+ style,
+ bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)
+ )
+ }
+}
+
+describe('roundtrip: text glyph blobs', () => {
+ beforeAll(async () => {
+ await initCodec()
+ })
+
+ test('preserves imported Figma glyph blobs for fallback rendering', async () => {
+ const fixtureBytes = new Uint8Array(readFileSync(resolve(FIXTURES, 'gold-preview.fig')))
+ const input = countGlyphBlobs(fixtureBytes)
+
+ const graph = await parseFigFile(
+ fixtureBytes.buffer.slice(fixtureBytes.byteOffset, fixtureBytes.byteOffset + fixtureBytes.byteLength)
+ )
+ const exported = await exportFigFile(graph)
+ const output = countGlyphBlobs(exported)
+
+ expect(input.glyphsWithBlob).toBeGreaterThan(0)
+ expect(output.glyphsWithBlob).toBeGreaterThan(0)
+ expect(output.uniqueGlyphBlobs).toBeLessThan(output.glyphsWithBlob / 100)
+ expect(output.uniqueGlyphBlobs).toBeLessThanOrEqual(input.uniqueGlyphBlobs + 20)
+ })
+
+ test('deduplicates generated glyph blobs across repeated text', async () => {
+ loadInterFonts()
+
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ for (let i = 0; i < 100; i++) {
+ graph.createNode('TEXT', page.id, {
+ name: `Label ${i}`,
+ text: 'Hello',
+ x: 0,
+ y: i * 20,
+ width: 80,
+ height: 20,
+ fontFamily: 'Inter',
+ fontWeight: 400,
+ fontSize: 14
+ })
+ }
+
+ const exported = await exportFigFile(graph)
+ const output = countGlyphBlobs(exported)
+
+ expect(output.glyphsWithBlob).toBe(500)
+ expect(output.uniqueGlyphBlobs).toBeLessThanOrEqual(4)
+ })
+})