Skip to content

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

Decode/encode Figma vectorNetworkBlob binary format

Danila Poyarkovb4c7700f05a0
diff --git a/src/engine/clipboard.ts b/src/engine/clipboard.ts
index d97db569c..a0e1bdc09 100644
--- a/src/engine/clipboard.ts
+++ b/src/engine/clipboard.ts
@@ -1,7 +1,8 @@
import { decodeBinarySchema, compileSchema, ByteBuffer } from 'kiwi-schema'
import { inflateSync, deflateSync } from 'fflate'
-import type { SceneGraph, SceneNode, Fill, Stroke, Color, LayoutMode, LayoutSizing, LayoutAlign, LayoutCounterAlign } from './scene-graph'
+import type { SceneGraph, SceneNode, Fill, Stroke, Color, LayoutMode, LayoutSizing, LayoutAlign, LayoutCounterAlign, VectorNetwork } from './scene-graph'
+import { decodeVectorNetworkBlob, encodeVectorNetworkBlob } from './vector'
interface FigmaClipboardMeta {
fileKey: string
@@ -184,7 +185,7 @@ function base64ToBinary(b64: string): Uint8Array {
export async function parseFigmaClipboard(
html: string
-): Promise<{ nodes: KiwiNodeChange[]; meta: FigmaClipboardMeta } | null> {
+): Promise<{ nodes: KiwiNodeChange[]; meta: FigmaClipboardMeta; blobs: Uint8Array[] } | null> {
const metaMatch = html.match(/\(figmeta\)(.*?)\(\/figmeta\)/)
const bufMatch = html.match(/\(figma\)(.*?)\(\/figma\)/s)
if (!metaMatch || !bufMatch) return null
@@ -198,9 +199,37 @@ export async function parseFigmaClipboard(
const schemaBytes = inflateSync(parsed.schemaDeflated)
const schema = decodeBinarySchema(new ByteBuffer(schemaBytes))
const compiled = compileSchema(schema)
- const msg = compiled.decodeMessage(parsed.dataRaw) as { nodeChanges?: KiwiNodeChange[] }
+ const msg = compiled.decodeMessage(parsed.dataRaw) as {
+ nodeChanges?: KiwiNodeChange[]
+ blobs?: Array<{ bytes: Uint8Array | Record<string, number> }>
+ }
+
+ const blobs: Uint8Array[] = (msg.blobs ?? []).map((b) =>
+ b.bytes instanceof Uint8Array
+ ? b.bytes
+ : new Uint8Array(Object.values(b.bytes) as number[])
+ )
- return { nodes: msg.nodeChanges ?? [], meta }
+ return { nodes: msg.nodeChanges ?? [], meta, blobs }
+}
+
+function decodeVectorData(nc: KiwiNodeChange, blobs: Uint8Array[]): VectorNetwork | null {
+ const vectorData = nc.vectorData as {
+ vectorNetworkBlob?: number
+ normalizedSize?: { x: number; y: number }
+ styleOverrideTable?: Array<{ styleID: number; handleMirroring?: string }>
+ } | undefined
+
+ if (!vectorData || vectorData.vectorNetworkBlob === undefined) return null
+
+ const blobIdx = vectorData.vectorNetworkBlob
+ if (blobIdx < 0 || blobIdx >= blobs.length) return null
+
+ try {
+ return decodeVectorNetworkBlob(blobs[blobIdx], vectorData.styleOverrideTable)
+ } catch {
+ return null
+ }
}
export function importClipboardNodes(
@@ -208,7 +237,8 @@ export function importClipboardNodes(
graph: SceneGraph,
targetParentId: string,
offsetX = 0,
- offsetY = 0
+ offsetY = 0,
+ blobs: Uint8Array[] = []
): string[] {
const guidMap = new Map<string, KiwiNodeChange>()
const parentMap = new Map<string, string>()
@@ -302,7 +332,8 @@ export function importClipboardNodes(
layoutWrap: (nc.stackWrap as string) === 'WRAP' ? 'WRAP' as const : 'NO_WRAP' as const,
counterAxisSpacing: (nc.stackCounterSpacing as number) ?? 0,
layoutPositioning: (nc.stackPositioning as string) === 'ABSOLUTE' ? 'ABSOLUTE' as const : 'AUTO' as const,
- layoutGrow: (nc.stackChildPrimaryGrow as number) ?? 0
+ layoutGrow: (nc.stackChildPrimaryGrow as number) ?? 0,
+ vectorNetwork: decodeVectorData(nc, blobs)
})
created.set(figmaId, node.id)
@@ -429,7 +460,8 @@ function sceneNodeToKiwi(
parentGuid: { sessionID: number; localID: number },
childIndex: number,
localIdCounter: { value: number },
- graph: SceneGraph
+ graph: SceneGraph,
+ blobs: Uint8Array[]
): KiwiNodeChange[] {
const localID = localIdCounter.value++
const guid = { sessionID: 1, localID }
@@ -531,10 +563,19 @@ function sceneNodeToKiwi(
nc.stackChildPrimaryGrow = node.layoutGrow
}
+ if (node.vectorNetwork && node.type === 'VECTOR') {
+ const blobIdx = blobs.length
+ blobs.push(encodeVectorNetworkBlob(node.vectorNetwork))
+ nc.vectorData = {
+ vectorNetworkBlob: blobIdx,
+ normalizedSize: { x: node.width, y: node.height }
+ }
+ }
+
const result: KiwiNodeChange[] = [nc]
const children = graph.getChildren(node.id)
for (let i = 0; i < children.length; i++) {
- result.push(...sceneNodeToKiwi(children[i], guid, i, localIdCounter, graph))
+ result.push(...sceneNodeToKiwi(children[i], guid, i, localIdCounter, graph, blobs))
}
return result
@@ -574,11 +615,12 @@ export function buildFigmaClipboardHTML(
}
]
+ const blobs: Uint8Array[] = []
for (let i = 0; i < nodes.length; i++) {
- nodeChanges.push(...sceneNodeToKiwi(nodes[i], canvasGuid, i, localIdCounter, graph))
+ nodeChanges.push(...sceneNodeToKiwi(nodes[i], canvasGuid, i, localIdCounter, graph, blobs))
}
- const msg = {
+ const msg: Record<string, unknown> = {
type: 'NODE_CHANGES',
sessionID: 0,
ackID: 0,
@@ -587,13 +629,17 @@ export function buildFigmaClipboardHTML(
nodeChanges
}
+ if (blobs.length > 0) {
+ msg.blobs = blobs.map((bytes) => ({ bytes }))
+ }
+
const dataRaw = compiled.encodeMessage(msg)
const figKiwiBinary = buildFigKiwi(schemaDeflated, dataRaw)
const bufferB64 = binaryToBase64(figKiwiBinary)
const meta: FigmaClipboardMeta = {
fileKey: 'openpencil',
- pasteID: msg.pasteID,
+ pasteID: msg.pasteID as number,
dataType: 'scene'
}
const metaB64 = btoa(JSON.stringify(meta))
diff --git a/src/engine/fig-file.ts b/src/engine/fig-file.ts
index 7b94f2c8a..c2d4f7a94 100644
--- a/src/engine/fig-file.ts
+++ b/src/engine/fig-file.ts
@@ -57,7 +57,10 @@ export async function parseFigFile(buffer: ArrayBuffer): Promise<SceneGraph> {
throw new Error('No nodes found in .fig file')
}
- return importNodeChanges(nodeChanges)
+ const blobs: Uint8Array[] = ((message as unknown as Record<string, unknown>).blobs as Array<{ bytes: Uint8Array }> ?? [])
+ .map((b) => b.bytes instanceof Uint8Array ? b.bytes : new Uint8Array(Object.values(b.bytes) as number[]))
+
+ return importNodeChanges(nodeChanges, blobs)
}
/**
diff --git a/src/engine/fig-import.ts b/src/engine/fig-import.ts
index 9ef0800a2..77016e738 100644
--- a/src/engine/fig-import.ts
+++ b/src/engine/fig-import.ts
@@ -1,7 +1,8 @@
import { SceneGraph } from './scene-graph'
+import { decodeVectorNetworkBlob } from './vector'
import type { NodeChange, Paint, Effect as KiwiEffect, GUID } from '../kiwi/codec'
-import type { NodeType, Fill, Stroke, Effect, Color, LayoutMode, LayoutSizing, LayoutAlign, LayoutCounterAlign } from './scene-graph'
+import type { NodeType, Fill, Stroke, Effect, Color, LayoutMode, LayoutSizing, LayoutAlign, LayoutCounterAlign, VectorNetwork } from './scene-graph'
function ext(nc: NodeChange): Record<string, unknown> {
return nc as unknown as Record<string, unknown>
@@ -127,7 +128,24 @@ function mapStackCounterAlign(align?: string): LayoutCounterAlign {
}
}
-export function importNodeChanges(nodeChanges: NodeChange[]): SceneGraph {
+function resolveVectorNetwork(nc: NodeChange, blobs: Uint8Array[]): VectorNetwork | null {
+ const vectorData = (nc as unknown as Record<string, unknown>).vectorData as {
+ vectorNetworkBlob?: number
+ styleOverrideTable?: Array<{ styleID: number; handleMirroring?: string }>
+ } | undefined
+
+ if (!vectorData || vectorData.vectorNetworkBlob === undefined) return null
+ const idx = vectorData.vectorNetworkBlob
+ if (idx < 0 || idx >= blobs.length) return null
+
+ try {
+ return decodeVectorNetworkBlob(blobs[idx], vectorData.styleOverrideTable)
+ } catch {
+ return null
+ }
+}
+
+export function importNodeChanges(nodeChanges: NodeChange[], blobs: Uint8Array[] = []): SceneGraph {
const graph = new SceneGraph()
// Build guid→nodeChange map and parent relationships
@@ -217,7 +235,8 @@ export function importNodeChanges(nodeChanges: NodeChange[]): SceneGraph {
layoutWrap: ext(nc).stackWrap === 'WRAP' ? 'WRAP' : 'NO_WRAP',
counterAxisSpacing: (ext(nc).stackCounterSpacing as number) ?? 0,
layoutPositioning: ext(nc).stackPositioning === 'ABSOLUTE' ? 'ABSOLUTE' : 'AUTO',
- layoutGrow: (ext(nc).stackChildPrimaryGrow as number) ?? 0
+ layoutGrow: (ext(nc).stackChildPrimaryGrow as number) ?? 0,
+ vectorNetwork: resolveVectorNetwork(nc, blobs)
})
// Create children (find all nodes whose parent is this node)
diff --git a/src/engine/vector.ts b/src/engine/vector.ts
index f3ee1d20d..f2c146e41 100644
--- a/src/engine/vector.ts
+++ b/src/engine/vector.ts
@@ -1,6 +1,137 @@
import type { CanvasKit, Path } from 'canvaskit-wasm'
-import type { VectorNetwork, VectorSegment, VectorVertex } from './scene-graph'
+import type { HandleMirroring, VectorNetwork, VectorRegion, VectorSegment, VectorVertex, WindingRule } from './scene-graph'
+
+// --- vectorNetworkBlob binary format ---
+// Header: [numVertices:u32, numSegments:u32, numRegions:u32] (12 bytes)
+// Vertex: [styleOverrideIdx:u32, x:f32, y:f32] (12 bytes)
+// Segment: [styleOverrideIdx:u32, start:u32, tsX:f32, tsY:f32, end:u32, teX:f32, teY:f32] (28 bytes)
+// Region: [windingRule:u32, numLoops:u32, {numSegs:u32, segIdx...}... ] (variable)
+
+interface StyleOverride {
+ styleID: number
+ handleMirroring?: string
+}
+
+export function decodeVectorNetworkBlob(
+ data: Uint8Array,
+ styleOverrideTable?: StyleOverride[]
+): VectorNetwork {
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength)
+ let o = 0
+
+ const nV = view.getUint32(o, true); o += 4
+ const nS = view.getUint32(o, true); o += 4
+ const nR = view.getUint32(o, true); o += 4
+
+ const styleMap = new Map<number, StyleOverride>()
+ if (styleOverrideTable) {
+ for (const entry of styleOverrideTable) {
+ styleMap.set(entry.styleID, entry)
+ }
+ }
+
+ const vertices: VectorVertex[] = []
+ for (let i = 0; i < nV; i++) {
+ const styleIdx = view.getUint32(o, true); o += 4
+ const x = view.getFloat32(o, true); o += 4
+ const y = view.getFloat32(o, true); o += 4
+
+ const override = styleMap.get(styleIdx)
+ vertices.push({
+ x,
+ y,
+ handleMirroring: (override?.handleMirroring as HandleMirroring) ?? 'NONE'
+ })
+ }
+
+ const segments: VectorSegment[] = []
+ for (let i = 0; i < nS; i++) {
+ o += 4 // styleOverrideIdx (unused for segments currently)
+ const start = view.getUint32(o, true); o += 4
+ const tsX = view.getFloat32(o, true); o += 4
+ const tsY = view.getFloat32(o, true); o += 4
+ const end = view.getUint32(o, true); o += 4
+ const teX = view.getFloat32(o, true); o += 4
+ const teY = view.getFloat32(o, true); o += 4
+
+ segments.push({
+ start,
+ end,
+ tangentStart: { x: tsX, y: tsY },
+ tangentEnd: { x: teX, y: teY }
+ })
+ }
+
+ const regions: VectorRegion[] = []
+ for (let i = 0; i < nR; i++) {
+ const windingRuleU32 = view.getUint32(o, true); o += 4
+ const windingRule: WindingRule = windingRuleU32 === 0 ? 'EVENODD' : 'NONZERO'
+ const numLoops = view.getUint32(o, true); o += 4
+ const loops: number[][] = []
+ for (let j = 0; j < numLoops; j++) {
+ const numSegs = view.getUint32(o, true); o += 4
+ const loop: number[] = []
+ for (let k = 0; k < numSegs; k++) {
+ loop.push(view.getUint32(o, true)); o += 4
+ }
+ loops.push(loop)
+ }
+ regions.push({ windingRule, loops })
+ }
+
+ return { vertices, segments, regions }
+}
+
+export function encodeVectorNetworkBlob(network: VectorNetwork): Uint8Array {
+ const { vertices, segments, regions } = network
+
+ let regionBytes = 0
+ for (const region of regions) {
+ regionBytes += 8 // windingRule + numLoops
+ for (const loop of region.loops) {
+ regionBytes += 4 + loop.length * 4 // numSegs + indices
+ }
+ }
+
+ const totalBytes = 12 + vertices.length * 12 + segments.length * 28 + regionBytes
+ const buf = new ArrayBuffer(totalBytes)
+ const view = new DataView(buf)
+ let o = 0
+
+ view.setUint32(o, vertices.length, true); o += 4
+ view.setUint32(o, segments.length, true); o += 4
+ view.setUint32(o, regions.length, true); o += 4
+
+ for (const v of vertices) {
+ view.setUint32(o, 0, true); o += 4 // styleOverrideIdx (TODO: encode handleMirroring)
+ view.setFloat32(o, v.x, true); o += 4
+ view.setFloat32(o, v.y, true); o += 4
+ }
+
+ for (const seg of segments) {
+ view.setUint32(o, 0, true); o += 4 // styleOverrideIdx
+ view.setUint32(o, seg.start, true); o += 4
+ view.setFloat32(o, seg.tangentStart.x, true); o += 4
+ view.setFloat32(o, seg.tangentStart.y, true); o += 4
+ view.setUint32(o, seg.end, true); o += 4
+ view.setFloat32(o, seg.tangentEnd.x, true); o += 4
+ view.setFloat32(o, seg.tangentEnd.y, true); o += 4
+ }
+
+ for (const region of regions) {
+ view.setUint32(o, region.windingRule === 'EVENODD' ? 0 : 1, true); o += 4
+ view.setUint32(o, region.loops.length, true); o += 4
+ for (const loop of region.loops) {
+ view.setUint32(o, loop.length, true); o += 4
+ for (const segIdx of loop) {
+ view.setUint32(o, segIdx, true); o += 4
+ }
+ }
+ }
+
+ return new Uint8Array(buf)
+}
export function vectorNetworkToPath(ck: CanvasKit, network: VectorNetwork): Path {
const path = new ck.Path()
diff --git a/src/stores/editor.ts b/src/stores/editor.ts
index cfc0fd5f6..2a1e52156 100644
--- a/src/stores/editor.ts
+++ b/src/stores/editor.ts
@@ -598,8 +598,9 @@ export function createEditorStore() {
const src = graph.getNode(id)
if (!src) continue
const parentId = src.parentId ?? graph.rootId
+ const { id: _srcId, parentId: _srcParent, childIds: _srcChildren, ...srcRest } = src
const node = graph.createNode(src.type, parentId, {
- ...src,
+ ...srcRest,
name: src.name + ' copy',
x: src.x + 20,
y: src.y + 20
@@ -651,7 +652,7 @@ export function createEditorStore() {
parseFigmaClipboard(html).then((figma) => {
if (figma) {
- const created = importClipboardNodes(figma.nodes, graph, graph.rootId, 20, 20)
+ const created = importClipboardNodes(figma.nodes, graph, graph.rootId, 20, 20, figma.blobs)
if (created.length > 0) {
state.selectedIds = new Set(created)
requestRender()
@@ -670,8 +671,9 @@ export function createEditorStore() {
const created: Array<{ id: string; parentId: string; snapshot: SceneNode }> = []
function createTree(src: SceneNode & { children?: SceneNode[] }, pid: string, isTop: boolean) {
+ const { id: _srcId, parentId: _srcParent, childIds: _srcChildren, ...rest } = src
const node = graph.createNode(src.type, pid, {
- ...src,
+ ...rest,
x: src.x + (isTop ? 20 : 0),
y: src.y + (isTop ? 20 : 0)
})