Skip to content

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

Deduplicate fig-kiwi parsing, font weight mapping, layout, style runs, text editor

Danila Poyarkov20827a27d32e
diff --git a/packages/core/src/clipboard.ts b/packages/core/src/clipboard.ts
index 238159fa4..c8eff1f3c 100644
--- a/packages/core/src/clipboard.ts
+++ b/packages/core/src/clipboard.ts
@@ -2,7 +2,12 @@ import { inflateSync, deflateSync } from 'fflate'
import { initCodec, getCompiledSchema, getSchemaBytes } from './kiwi/codec'
import { decodeBinarySchema, compileSchema, ByteBuffer } from './kiwi/kiwi-schema'
-import { sceneNodeToKiwi, FIG_KIWI_VERSION } from './kiwi-serialize'
+import {
+ sceneNodeToKiwi,
+ buildFigKiwi,
+ parseFigKiwiChunks,
+ decompressFigKiwiDataAsync
+} from './kiwi-serialize'
import { decodeVectorNetworkBlob } from './vector'
@@ -29,89 +34,7 @@ export async function prefetchFigmaSchema(): Promise<void> {
await initCodec()
}
-function parseFigKiwi(
- binary: Uint8Array
-): { schemaDeflated: Uint8Array; dataRaw: Uint8Array } | null {
- const header = new TextDecoder().decode(binary.slice(0, 8))
- if (header !== 'fig-kiwi') return null
-
- const view = new DataView(binary.buffer, binary.byteOffset, binary.byteLength)
- let offset = 12
-
- const chunks: Uint8Array[] = []
- while (offset < binary.length) {
- const chunkLen = view.getUint32(offset, true)
- offset += 4
- chunks.push(binary.slice(offset, offset + chunkLen))
- offset += chunkLen
- }
- if (chunks.length < 2) return null
-
- const schemaDeflated = chunks[0]
- let dataRaw: Uint8Array
- try {
- dataRaw = inflateSync(chunks[1])
- } catch {
- // Zstd fallback (lazy import)
- return null
- }
-
- return { schemaDeflated, dataRaw }
-}
-
-async function parseFigKiwiWithZstd(
- binary: Uint8Array
-): Promise<{ schemaDeflated: Uint8Array; dataRaw: Uint8Array } | null> {
- const header = new TextDecoder().decode(binary.slice(0, 8))
- if (header !== 'fig-kiwi') return null
-
- const view = new DataView(binary.buffer, binary.byteOffset, binary.byteLength)
- let offset = 12
-
- const chunks: Uint8Array[] = []
- while (offset < binary.length) {
- const chunkLen = view.getUint32(offset, true)
- offset += 4
- chunks.push(binary.slice(offset, offset + chunkLen))
- offset += chunkLen
- }
- if (chunks.length < 2) return null
-
- let dataRaw: Uint8Array
- try {
- dataRaw = inflateSync(chunks[1])
- } catch {
- const fzstd = await import('fzstd')
- dataRaw = fzstd.decompress(chunks[1])
- }
-
- return { schemaDeflated: chunks[0], dataRaw }
-}
-
-function buildFigKiwi(schemaDeflated: Uint8Array, dataRaw: Uint8Array): Uint8Array {
- const dataDeflated = deflateSync(dataRaw)
-
- const total = 8 + 4 + 4 + schemaDeflated.length + 4 + dataDeflated.length
- const out = new Uint8Array(total)
- const view = new DataView(out.buffer)
-
- const magic = new TextEncoder().encode('fig-kiwi')
- out.set(magic, 0)
- view.setUint32(8, FIG_KIWI_VERSION, true)
-
- let offset = 12
- view.setUint32(offset, schemaDeflated.length, true)
- offset += 4
- out.set(schemaDeflated, offset)
- offset += schemaDeflated.length
-
- view.setUint32(offset, dataDeflated.length, true)
- offset += 4
- out.set(dataDeflated, offset)
-
- return out
-}
function binaryToBase64(bytes: Uint8Array): string {
let binary = ''
@@ -142,13 +65,14 @@ export async function parseFigmaClipboard(
const meta: FigmaClipboardMeta = JSON.parse(atob(metaMatch[1]))
const binary = base64ToBinary(bufMatch[1])
- const parsed = parseFigKiwi(binary) ?? (await parseFigKiwiWithZstd(binary))
- if (!parsed) return null
+ const chunks = parseFigKiwiChunks(binary)
+ if (!chunks) return null
- const schemaBytes = inflateSync(parsed.schemaDeflated)
+ const schemaBytes = inflateSync(chunks[0])
const schema = decodeBinarySchema(new ByteBuffer(schemaBytes))
const compiled = compileSchema(schema)
- const msg = compiled.decodeMessage(parsed.dataRaw) as {
+ const dataRaw = await decompressFigKiwiDataAsync(chunks[1])
+ const msg = compiled.decodeMessage(dataRaw) as {
nodeChanges?: KiwiNodeChange[]
blobs?: Array<{ bytes: Uint8Array | Record<string, number> }>
}
diff --git a/packages/core/src/fig-export.ts b/packages/core/src/fig-export.ts
index ca892f647..4adf55da7 100644
--- a/packages/core/src/fig-export.ts
+++ b/packages/core/src/fig-export.ts
@@ -2,7 +2,7 @@ import { zipSync, deflateSync } from 'fflate'
import { IS_TAURI } from './constants'
import { initCodec, getCompiledSchema, getSchemaBytes } from './kiwi/codec'
-import { sceneNodeToKiwi, fractionalPosition, FIG_KIWI_VERSION } from './kiwi-serialize'
+import { sceneNodeToKiwi, fractionalPosition, buildFigKiwi } from './kiwi-serialize'
import { renderThumbnail } from './render-image'
import type { SkiaRenderer } from './renderer'
@@ -19,28 +19,6 @@ const THUMBNAIL_1X1 = Uint8Array.from(
type KiwiNodeChange = NodeChange & Record<string, unknown>
-function buildFigKiwi(schemaDeflated: Uint8Array, dataCompressed: Uint8Array): Uint8Array {
-
- const total = 8 + 4 + 4 + schemaDeflated.length + 4 + dataCompressed.length
- const out = new Uint8Array(total)
- const view = new DataView(out.buffer)
-
- out.set(new TextEncoder().encode('fig-kiwi'), 0)
- view.setUint32(8, FIG_KIWI_VERSION, true)
-
- let offset = 12
- view.setUint32(offset, schemaDeflated.length, true)
- offset += 4
- out.set(schemaDeflated, offset)
- offset += schemaDeflated.length
-
- view.setUint32(offset, dataCompressed.length, true)
- offset += 4
- out.set(dataCompressed, offset)
-
- return out
-}
-
const THUMBNAIL_WIDTH = 400
const THUMBNAIL_HEIGHT = 225
@@ -141,7 +119,7 @@ export async function exportFigFile(
)
}
- const canvasData = buildFigKiwi(schemaDeflated, deflateSync(kiwiData))
+ const canvasData = buildFigKiwi(schemaDeflated, kiwiData)
return zipSync({
'canvas.fig': [canvasData, { level: 0 }],
'thumbnail.png': [thumbnailPng, { level: 0 }],
diff --git a/packages/core/src/fonts.ts b/packages/core/src/fonts.ts
index c811dcbeb..647a6687e 100644
--- a/packages/core/src/fonts.ts
+++ b/packages/core/src/fonts.ts
@@ -115,8 +115,8 @@ function registerFontInBrowser(family: string, style: string, data: ArrayBuffer)
face.load().then(() => document.fonts.add(face))
}
-function styleToWeight(style: string): number {
- const s = style.toLowerCase()
+export function styleToWeight(style: string): number {
+ const s = style.toLowerCase().replace(/[\s-_]/g, '')
if (s.includes('thin') || s.includes('hairline')) return 100
if (s.includes('extralight') || s.includes('ultralight')) return 200
if (s.includes('light')) return 300
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 544d1f434..534e8bc2f 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -51,7 +51,15 @@ export {
export { SkiaRenderer, type RenderOverlays } from './renderer'
export { computeLayout, computeAllLayouts } from './layout'
export { getCanvasKit, type CanvasKitOptions } from './canvaskit'
-export { loadFont, listFamilies, initFontService, getFontProvider, ensureNodeFont } from './fonts'
+export {
+ loadFont,
+ listFamilies,
+ initFontService,
+ getFontProvider,
+ ensureNodeFont,
+ styleToWeight,
+ weightToStyle
+} from './fonts'
export { parseColor, colorToHex, colorToHexRaw, colorToRgba255 } from './color'
export { vectorNetworkToPath, decodeVectorNetworkBlob, encodeVectorNetworkBlob, computeVectorBounds } from './vector'
export { computeSelectionBounds, computeSnap, type SnapGuide } from './snap'
@@ -66,6 +74,16 @@ export {
} from './style-runs'
export { renderNodesToImage, renderThumbnail, type ExportFormat } from './render-image'
export { exportFigFile } from './fig-export'
+export {
+ FIG_KIWI_VERSION,
+ buildFigKiwi,
+ parseFigKiwiChunks,
+ decompressFigKiwiData,
+ decompressFigKiwiDataAsync,
+ sceneNodeToKiwi,
+ fractionalPosition,
+ mapToFigmaType
+} from './kiwi-serialize'
export {
renderTree,
diff --git a/packages/core/src/kiwi-serialize.ts b/packages/core/src/kiwi-serialize.ts
index 6767fec73..a8993bc2d 100644
--- a/packages/core/src/kiwi-serialize.ts
+++ b/packages/core/src/kiwi-serialize.ts
@@ -1,5 +1,7 @@
export const FIG_KIWI_VERSION = 106
+import { deflateSync, inflateSync } from 'fflate'
+
import { encodeVectorNetworkBlob } from './vector'
import { weightToStyle } from './fonts'
@@ -8,6 +10,63 @@ import type { NodeChange, Paint } from './kiwi/codec'
type KiwiNodeChange = NodeChange & Record<string, unknown>
+export function parseFigKiwiChunks(binary: Uint8Array): Uint8Array[] | null {
+ const header = new TextDecoder().decode(binary.slice(0, 8))
+ if (header !== 'fig-kiwi') return null
+
+ const view = new DataView(binary.buffer, binary.byteOffset, binary.byteLength)
+ let offset = 12
+
+ const chunks: Uint8Array[] = []
+ while (offset < binary.length) {
+ const chunkLen = view.getUint32(offset, true)
+ offset += 4
+ chunks.push(binary.slice(offset, offset + chunkLen))
+ offset += chunkLen
+ }
+ return chunks.length >= 2 ? chunks : null
+}
+
+export function decompressFigKiwiData(compressed: Uint8Array): Uint8Array {
+ try {
+ return inflateSync(compressed)
+ } catch {
+ throw new Error('Failed to decompress fig-kiwi data (try async variant for Zstd)')
+ }
+}
+
+export async function decompressFigKiwiDataAsync(compressed: Uint8Array): Promise<Uint8Array> {
+ try {
+ return inflateSync(compressed)
+ } catch {
+ const fzstd = await import('fzstd')
+ return fzstd.decompress(compressed)
+ }
+}
+
+export function buildFigKiwi(schemaDeflated: Uint8Array, dataRaw: Uint8Array): Uint8Array {
+ const dataDeflated = deflateSync(dataRaw)
+
+ const total = 8 + 4 + 4 + schemaDeflated.length + 4 + dataDeflated.length
+ const out = new Uint8Array(total)
+ const view = new DataView(out.buffer)
+
+ out.set(new TextEncoder().encode('fig-kiwi'), 0)
+ view.setUint32(8, FIG_KIWI_VERSION, true)
+
+ let offset = 12
+ view.setUint32(offset, schemaDeflated.length, true)
+ offset += 4
+ out.set(schemaDeflated, offset)
+ offset += schemaDeflated.length
+
+ view.setUint32(offset, dataDeflated.length, true)
+ offset += 4
+ out.set(dataDeflated, offset)
+
+ return out
+}
+
export function mapToFigmaType(type: SceneNode['type']): string {
switch (type) {
case 'FRAME':
diff --git a/packages/core/src/kiwi/fig-import.ts b/packages/core/src/kiwi/fig-import.ts
index 263b61d4a..b7e40789e 100644
--- a/packages/core/src/kiwi/fig-import.ts
+++ b/packages/core/src/kiwi/fig-import.ts
@@ -1,4 +1,5 @@
import { SceneGraph } from '../scene-graph'
+import { styleToWeight } from '../fonts'
import { decodeVectorNetworkBlob } from '../vector'
import type { NodeChange, Paint, Effect as KiwiEffect, GUID } from './codec'
@@ -238,19 +239,7 @@ function mapStackCounterAlign(align?: string): LayoutCounterAlign {
}
}
-function mapFontWeight(style?: string): number {
- if (!style) return 400
- const s = style.toLowerCase().replace(/\s+/g, '')
- if (s.includes('thin') || s.includes('hairline')) return 100
- if (s.includes('extralight') || s.includes('ultralight')) return 200
- if (s.includes('light')) return 300
- if (s.includes('medium')) return 500
- if (s.includes('semibold') || s.includes('demibold')) return 600
- if (s.includes('extrabold') || s.includes('ultrabold')) return 800
- if (s.includes('black') || s.includes('heavy')) return 900
- if (s.includes('bold')) return 700
- return 400
-}
+
function mapConstraint(c?: string): ConstraintType {
switch (c) {
@@ -302,7 +291,7 @@ function importStyleRuns(nc: NodeChange): StyleRun[] {
const style: CharacterStyleOverride = {}
if (override.fontName) {
style.fontFamily = override.fontName.family
- style.fontWeight = mapFontWeight(override.fontName.style)
+ style.fontWeight = styleToWeight(override.fontName.style ?? "")
style.italic = override.fontName.style?.toLowerCase().includes('italic') ?? false
}
if (override.fontSize !== undefined) style.fontSize = override.fontSize
@@ -461,7 +450,7 @@ export function importNodeChanges(
text: nc.textData?.characters ?? '',
fontSize: nc.fontSize ?? 14,
fontFamily: nc.fontName?.family ?? 'Inter',
- fontWeight: mapFontWeight(nc.fontName?.style),
+ fontWeight: styleToWeight(nc.fontName?.style ?? ""),
italic: nc.fontName?.style?.toLowerCase().includes('italic') ?? false,
textAlignHorizontal:
(nc.textAlignHorizontal as 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED') ?? 'LEFT',
diff --git a/packages/core/src/layout.ts b/packages/core/src/layout.ts
index 5f2216488..cfde4f34d 100644
--- a/packages/core/src/layout.ts
+++ b/packages/core/src/layout.ts
@@ -203,46 +203,7 @@ function setSizing(
}
}
-function applyYogaLayout(graph: SceneGraph, frame: SceneNode, yogaRoot: YogaNode): void {
- if (frame.primaryAxisSizing === 'HUG' || frame.counterAxisSizing === 'HUG') {
- const computedW = yogaRoot.getComputedWidth()
- const computedH = yogaRoot.getComputedHeight()
- const updates: Partial<SceneNode> = {}
-
- if (frame.primaryAxisSizing === 'HUG') {
- if (frame.layoutMode === 'HORIZONTAL') updates.width = computedW
- else updates.height = computedH
- }
- if (frame.counterAxisSizing === 'HUG') {
- if (frame.layoutMode === 'HORIZONTAL') updates.height = computedH
- else updates.width = computedW
- }
-
- graph.updateNode(frame.id, updates)
- }
-
- const children = graph.getChildren(frame.id)
- let yogaIndex = 0
- for (const child of children) {
- if (child.layoutPositioning === 'ABSOLUTE') continue
-
- const yogaChild = yogaRoot.getChild(yogaIndex)
- yogaIndex++
-
- graph.updateNode(child.id, {
- x: yogaChild.getComputedLeft(),
- y: yogaChild.getComputedTop(),
- width: yogaChild.getComputedWidth(),
- height: yogaChild.getComputedHeight()
- })
-
- if (child.layoutMode !== 'NONE') {
- applyYogaLayoutNested(graph, child, yogaChild)
- }
- }
-}
-
-function applyYogaLayoutNested(graph: SceneGraph, frame: SceneNode, yogaNode: YogaNode): void {
+function applyYogaLayout(graph: SceneGraph, frame: SceneNode, yogaNode: YogaNode): void {
if (frame.primaryAxisSizing === 'HUG' || frame.counterAxisSizing === 'HUG') {
const computedW = yogaNode.getComputedWidth()
const computedH = yogaNode.getComputedHeight()
@@ -276,7 +237,7 @@ function applyYogaLayoutNested(graph: SceneGraph, frame: SceneNode, yogaNode: Yo
})
if (child.layoutMode !== 'NONE') {
- applyYogaLayoutNested(graph, child, yogaChild)
+ applyYogaLayout(graph, child, yogaChild)
}
}
}
diff --git a/packages/core/src/style-runs.ts b/packages/core/src/style-runs.ts
index bb8334905..68fd75137 100644
--- a/packages/core/src/style-runs.ts
+++ b/packages/core/src/style-runs.ts
@@ -9,20 +9,27 @@ export function getStyleAt(runs: StyleRun[], index: number): CharacterStyleOverr
return {}
}
-export function applyStyleToRange(
+function expandRuns(
runs: StyleRun[],
- start: number,
- end: number,
- patch: CharacterStyleOverride,
textLength: number
-): StyleRun[] {
+): (CharacterStyleOverride | null)[] {
const chars: (CharacterStyleOverride | null)[] = new Array(textLength).fill(null)
-
for (const run of runs) {
for (let i = run.start; i < run.start + run.length && i < textLength; i++) {
chars[i] = { ...(chars[i] ?? {}), ...run.style }
}
}
+ return chars
+}
+
+export function applyStyleToRange(
+ runs: StyleRun[],
+ start: number,
+ end: number,
+ patch: CharacterStyleOverride,
+ textLength: number
+): StyleRun[] {
+ const chars = expandRuns(runs, textLength)
for (let i = start; i < end && i < textLength; i++) {
chars[i] = { ...(chars[i] ?? {}), ...patch }
@@ -38,13 +45,7 @@ export function removeStyleFromRange(
keys: (keyof CharacterStyleOverride)[],
textLength: number
): StyleRun[] {
- const chars: (CharacterStyleOverride | null)[] = new Array(textLength).fill(null)
-
- for (const run of runs) {
- for (let i = run.start; i < run.start + run.length && i < textLength; i++) {
- chars[i] = { ...(chars[i] ?? {}), ...run.style }
- }
- }
+ const chars = expandRuns(runs, textLength)
for (let i = start; i < end && i < textLength; i++) {
if (chars[i]) {
diff --git a/packages/core/src/text-editor.ts b/packages/core/src/text-editor.ts
index f23167c69..216d994a5 100644
--- a/packages/core/src/text-editor.ts
+++ b/packages/core/src/text-editor.ts
@@ -27,6 +27,14 @@ export class TextEditor {
this.ck = ck
}
+ private prepareMove(extend: boolean): TextEditorState | null {
+ const s = this._state
+ if (!s) return null
+ if (extend && s.selectionAnchor === null) s.selectionAnchor = s.cursor
+ if (!extend) s.selectionAnchor = null
+ return s
+ }
+
get state(): TextEditorState | null {
return this._state
}
@@ -179,8 +187,7 @@ export class TextEditor {
s.selectionAnchor = null
return
}
- if (extend && s.selectionAnchor === null) s.selectionAnchor = s.cursor
- if (!extend) s.selectionAnchor = null
+ this.prepareMove(extend)
if (s.cursor > 0) s.cursor--
}
@@ -193,43 +200,34 @@ export class TextEditor {
s.selectionAnchor = null
return
}
- if (extend && s.selectionAnchor === null) s.selectionAnchor = s.cursor
- if (!extend) s.selectionAnchor = null
+ this.prepareMove(extend)
if (s.cursor < s.text.length) s.cursor++
}
moveUp(extend = false): void {
const s = this._state
if (!s?.paragraph) return
- if (extend && s.selectionAnchor === null) s.selectionAnchor = s.cursor
- if (!extend) s.selectionAnchor = null
-
+ this.prepareMove(extend)
const caret = this.getCaretRect()
if (!caret) return
const fontSize = s.paragraph.getLineMetrics()[0]?.height ?? 14
- const newPos = s.paragraph.getGlyphPositionAtCoordinate(caret.x, caret.y0 - fontSize / 2).pos
- s.cursor = newPos
+ s.cursor = s.paragraph.getGlyphPositionAtCoordinate(caret.x, caret.y0 - fontSize / 2).pos
}
moveDown(extend = false): void {
const s = this._state
if (!s?.paragraph) return
- if (extend && s.selectionAnchor === null) s.selectionAnchor = s.cursor
- if (!extend) s.selectionAnchor = null
-
+ this.prepareMove(extend)
const caret = this.getCaretRect()
if (!caret) return
const fontSize = s.paragraph.getLineMetrics()[0]?.height ?? 14
- const newPos = s.paragraph.getGlyphPositionAtCoordinate(caret.x, caret.y1 + fontSize / 2).pos
- s.cursor = newPos
+ s.cursor = s.paragraph.getGlyphPositionAtCoordinate(caret.x, caret.y1 + fontSize / 2).pos
}
moveToLineStart(extend = false): void {
const s = this._state
if (!s?.paragraph) return
- if (extend && s.selectionAnchor === null) s.selectionAnchor = s.cursor
- if (!extend) s.selectionAnchor = null
-
+ this.prepareMove(extend)
const lineNum = s.paragraph.getLineNumberAt(s.cursor)
if (lineNum < 0) return
const metrics = s.paragraph.getLineMetricsAt(lineNum)
@@ -239,9 +237,7 @@ export class TextEditor {
moveToLineEnd(extend = false): void {
const s = this._state
if (!s?.paragraph) return
- if (extend && s.selectionAnchor === null) s.selectionAnchor = s.cursor
- if (!extend) s.selectionAnchor = null
-
+ this.prepareMove(extend)
const lineNum = s.paragraph.getLineNumberAt(s.cursor)
if (lineNum < 0) return
const metrics = s.paragraph.getLineMetricsAt(lineNum)
@@ -249,11 +245,8 @@ export class TextEditor {
}
moveWordLeft(extend = false): void {
- const s = this._state
+ const s = this.prepareMove(extend)
if (!s) return
- if (extend && s.selectionAnchor === null) s.selectionAnchor = s.cursor
- if (!extend) s.selectionAnchor = null
-
let pos = s.cursor
while (pos > 0 && isWordBoundary(s.text[pos - 1])) pos--
while (pos > 0 && !isWordBoundary(s.text[pos - 1])) pos--
@@ -261,11 +254,8 @@ export class TextEditor {
}
moveWordRight(extend = false): void {
- const s = this._state
+ const s = this.prepareMove(extend)
if (!s) return
- if (extend && s.selectionAnchor === null) s.selectionAnchor = s.cursor
- if (!extend) s.selectionAnchor = null
-
let pos = s.cursor
while (pos < s.text.length && !isWordBoundary(s.text[pos])) pos++
while (pos < s.text.length && isWordBoundary(s.text[pos])) pos++
diff --git a/src/engine/fonts.ts b/src/engine/fonts.ts
index e6bcb9444..f5b7757cc 100644
--- a/src/engine/fonts.ts
+++ b/src/engine/fonts.ts
@@ -1,6 +1,6 @@
export { initFontService, getFontProvider, ensureNodeFont } from '@open-pencil/core'
-import { loadFont as loadFontCore, getFontProvider } from '@open-pencil/core'
+import { loadFont as loadFontCore, getFontProvider, styleToWeight } from '@open-pencil/core'
interface TauriFontFamily {
family: string
@@ -78,15 +78,4 @@ export async function loadFont(family: string, style = 'Regular'): Promise<Array
return loadFontCore(family, style)
}
-function styleToWeight(style: string): number {
- const s = style.toLowerCase()
- if (s.includes('thin') || s.includes('hairline')) return 100
- if (s.includes('extralight') || s.includes('ultralight')) return 200
- if (s.includes('light')) return 300
- if (s.includes('medium')) return 500
- if (s.includes('semibold') || s.includes('demibold')) return 600
- if (s.includes('extrabold') || s.includes('ultrabold')) return 800
- if (s.includes('black') || s.includes('heavy')) return 900
- if (s.includes('bold')) return 700
- return 400
-}
+