Skip to content

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

Fix .fig import/export round-trip

Danila Poyarkovdc3c5a47b186
diff --git a/public/figma-schema.bin b/public/figma-schema.bin
deleted file mode 100644
index 6f2fb3d4f..000000000
Binary files a/public/figma-schema.bin and /dev/null differ
diff --git a/src/constants.ts b/src/constants.ts
index 6020650e1..154280051 100644
--- a/src/constants.ts
+++ b/src/constants.ts
@@ -1,7 +1,7 @@
import type { Color } from './types'
import type { Fill, Stroke } from './engine/scene-graph'
-export const IS_TAURI = '__TAURI_INTERNALS__' in window
+export const IS_TAURI = typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window
export const SELECTION_COLOR = { r: 0.23, g: 0.51, b: 0.96, a: 1 } satisfies Color
export const SNAP_COLOR = { r: 1.0, g: 0.0, b: 0.56, a: 1 } satisfies Color
diff --git a/src/engine/clipboard.ts b/src/engine/clipboard.ts
index 2b743c486..4227cb54b 100644
--- a/src/engine/clipboard.ts
+++ b/src/engine/clipboard.ts
@@ -1,5 +1,6 @@
-import { decodeBinarySchema, compileSchema, ByteBuffer } from '../kiwi/kiwi-schema'
import { inflateSync, deflateSync } from 'fflate'
+import { decodeBinarySchema, compileSchema, ByteBuffer } from '../kiwi/kiwi-schema'
+import { initCodec, getCompiledSchema, getSchemaBytes } from '../kiwi/codec'
import type { SceneGraph, SceneNode, Fill, Stroke, Color, LayoutMode, LayoutSizing, LayoutAlign, LayoutCounterAlign, VectorNetwork } from './scene-graph'
import { decodeVectorNetworkBlob, encodeVectorNetworkBlob } from './vector'
@@ -50,36 +51,8 @@ interface KiwiNodeChange {
[key: string]: unknown
}
-type CompiledSchema = ReturnType<typeof compileSchema>
-
-let cachedSchema: CompiledSchema | null = null
-let cachedSchemaDeflated: Uint8Array | null = null
-
-export function prefetchFigmaSchema(): void {
- getFigmaSchemaAsync()
-}
-
-function getFigmaSchemaSync(): { compiled: CompiledSchema; deflated: Uint8Array } | null {
- if (cachedSchema && cachedSchemaDeflated) {
- return { compiled: cachedSchema, deflated: cachedSchemaDeflated }
- }
- return null
-}
-
-async function getFigmaSchemaAsync(): Promise<{ compiled: CompiledSchema; deflated: Uint8Array }> {
- if (cachedSchema && cachedSchemaDeflated) {
- return { compiled: cachedSchema, deflated: cachedSchemaDeflated }
- }
-
- const resp = await fetch('/figma-schema.bin')
- const deflated = new Uint8Array(await resp.arrayBuffer())
- const schemaBytes = inflateSync(deflated)
- const schema = decodeBinarySchema(new ByteBuffer(schemaBytes))
- const compiled = compileSchema(schema)
-
- cachedSchema = compiled
- cachedSchemaDeflated = deflated
- return { compiled, deflated }
+export async function prefetchFigmaSchema(): Promise<void> {
+ await initCodec()
}
function parseFigKiwi(binary: Uint8Array): { schemaDeflated: Uint8Array; dataRaw: Uint8Array } | null {
@@ -585,9 +558,8 @@ export function buildFigmaClipboardHTML(
nodes: SceneNode[],
graph: SceneGraph
): string | null {
- const schema = getFigmaSchemaSync()
- if (!schema) return null
- const { compiled, deflated: schemaDeflated } = schema
+ const compiled = getCompiledSchema()
+ const schemaDeflated = deflateSync(getSchemaBytes())
const docGuid = { sessionID: 0, localID: 0 }
const canvasGuid = { sessionID: 0, localID: 1 }
diff --git a/src/engine/fig-export.ts b/src/engine/fig-export.ts
index 4cc4fac29..80cab6355 100644
--- a/src/engine/fig-export.ts
+++ b/src/engine/fig-export.ts
@@ -1,8 +1,7 @@
import { zipSync, deflateSync } from 'fflate'
-import { decodeBinarySchema, compileSchema, ByteBuffer } from '../kiwi/kiwi-schema'
-import { inflateSync } from 'fflate'
import { encodeVectorNetworkBlob } from './vector'
import { IS_TAURI } from '../constants'
+import { initCodec, getCompiledSchema, getSchemaBytes } from '../kiwi/codec'
import type { SceneGraph, SceneNode, Color } from './scene-graph'
@@ -46,23 +45,7 @@ interface KiwiNodeChange {
[key: string]: unknown
}
-type CompiledSchema = ReturnType<typeof compileSchema>
-let cachedSchema: CompiledSchema | null = null
-let cachedSchemaDeflated: Uint8Array | null = null
-
-async function getSchema(): Promise<{ compiled: CompiledSchema; deflated: Uint8Array }> {
- if (cachedSchema && cachedSchemaDeflated) {
- return { compiled: cachedSchema, deflated: cachedSchemaDeflated }
- }
- const resp = await fetch('/figma-schema.bin')
- const deflated = new Uint8Array(await resp.arrayBuffer())
- const schemaBytes = inflateSync(deflated)
- const schema = decodeBinarySchema(new ByteBuffer(schemaBytes))
- cachedSchema = compileSchema(schema)
- cachedSchemaDeflated = deflated
- return { compiled: cachedSchema, deflated }
-}
function mapToFigmaType(type: SceneNode['type']): string {
switch (type) {
@@ -243,7 +226,9 @@ async function buildFigKiwi(schemaDeflated: Uint8Array, dataRaw: Uint8Array): Pr
}
export async function exportFigFile(graph: SceneGraph): Promise<Uint8Array> {
- const { compiled, deflated: schemaDeflated } = await getSchema()
+ await initCodec()
+ const compiled = getCompiledSchema()
+ const schemaDeflated = deflateSync(getSchemaBytes())
const docGuid = { sessionID: 0, localID: 0 }
const localIdCounter = { value: 2 }
diff --git a/src/kiwi/codec.ts b/src/kiwi/codec.ts
index b71dc6440..dceb9bd0a 100644
--- a/src/kiwi/codec.ts
+++ b/src/kiwi/codec.ts
@@ -7,7 +7,7 @@
*/
import { decompress as zstdDecompress } from 'fzstd'
-import { compileSchema } from './kiwi-schema'
+import { compileSchema, encodeBinarySchema } from './kiwi-schema'
import type { Schema } from './kiwi-schema'
@@ -30,6 +30,15 @@ export async function initCodec(): Promise<void> {
compiledSchema = compileSchema(figmaSchema as Schema) as CompiledSchema
}
+export function getCompiledSchema() {
+ if (!compiledSchema) throw new Error('Codec not initialized')
+ return compiledSchema
+}
+
+export function getSchemaBytes(): Uint8Array {
+ return encodeBinarySchema(figmaSchema as Schema)
+}
+
/**
* Check if codec is initialized
*/
diff --git a/src/kiwi/fig-file.ts b/src/kiwi/fig-file.ts
index e9c434e7a..3f9a16d9f 100644
--- a/src/kiwi/fig-file.ts
+++ b/src/kiwi/fig-file.ts
@@ -1,39 +1,56 @@
-import { unzipSync } from 'fflate'
+import { unzipSync, inflateSync } from 'fflate'
+import { decompress as zstdDecompress } from 'fzstd'
-import { initCodec, decodeMessage } from './codec'
+import { decodeBinarySchema, compileSchema, ByteBuffer } from './kiwi-schema'
import { importNodeChanges } from './fig-import'
+import { isZstdCompressed } from './protocol'
import type { SceneGraph } from '../engine/scene-graph'
+import type { FigmaMessage } from './codec'
-/**
- * Parse a .fig file into a SceneGraph.
- *
- * A .fig file is a ZIP archive containing:
- * - `canvas.fig` or similar blob: Kiwi-encoded document state
- * - `thumbnail.png`: preview image
- * - `meta.json`: file metadata
- *
- * The Kiwi payload is a serialized Message with nodeChanges.
- */
-export async function parseFigFile(buffer: ArrayBuffer): Promise<SceneGraph> {
- await initCodec()
+interface FigKiwiPayload {
+ schemaDeflated: Uint8Array
+ dataRaw: Uint8Array
+}
+
+function parseFigKiwiContainer(data: Uint8Array): FigKiwiPayload | null {
+ const header = new TextDecoder().decode(data.slice(0, 8))
+ if (header !== 'fig-kiwi') return null
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength)
+ let offset = 12
+
+ const chunks: Uint8Array[] = []
+ while (offset < data.length) {
+ const len = view.getUint32(offset, true)
+ offset += 4
+ chunks.push(data.slice(offset, offset + len))
+ offset += len
+ }
+ if (chunks.length < 2) return null
+
+ const compressed = chunks[1]
+ let dataRaw: Uint8Array
+ if (isZstdCompressed(compressed)) {
+ dataRaw = zstdDecompress(compressed)
+ } else {
+ try { dataRaw = inflateSync(compressed) } catch { dataRaw = compressed }
+ }
+
+ return { schemaDeflated: chunks[0], dataRaw }
+}
+
+export async function parseFigFile(buffer: ArrayBuffer): Promise<SceneGraph> {
const zip = unzipSync(new Uint8Array(buffer))
const entries = Object.keys(zip)
- // Find the Kiwi-encoded canvas data
- // .fig files may have various structures; the binary blob is typically the largest non-image file
let canvasData: Uint8Array | null = null
-
- // Try known names first
for (const name of entries) {
if (name === 'canvas.fig' || name === 'canvas') {
canvasData = zip[name]
break
}
}
-
- // Fallback: find the largest binary file that's not an image/json
if (!canvasData) {
let maxSize = 0
for (const name of entries) {
@@ -50,8 +67,14 @@ export async function parseFigFile(buffer: ArrayBuffer): Promise<SceneGraph> {
throw new Error(`No canvas data found in .fig file. Entries: ${entries.join(', ')}`)
}
- // Decode the Kiwi message
- const message = decodeMessage(canvasData)
+ const payload = parseFigKiwiContainer(canvasData)
+ if (!payload) throw new Error('Invalid fig-kiwi container')
+
+ const schemaBytes = inflateSync(payload.schemaDeflated)
+ const schema = decodeBinarySchema(new ByteBuffer(schemaBytes))
+ const compiled = compileSchema(schema) as { decodeMessage(data: Uint8Array): unknown }
+ const message = compiled.decodeMessage(payload.dataRaw) as FigmaMessage
+
const nodeChanges = message.nodeChanges
if (!nodeChanges || nodeChanges.length === 0) {
throw new Error('No nodes found in .fig file')