Skip to content

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

Deduplicate: 47 → 28 clones, 1.37% → 0.61% duplication

Danila Poyarkovfd44d7b853f0
diff --git a/packages/cli/src/commands/analyze/clusters.ts b/packages/cli/src/commands/analyze/clusters.ts
index 57112b0e0..49a576a86 100644
--- a/packages/cli/src/commands/analyze/clusters.ts
+++ b/packages/cli/src/commands/analyze/clusters.ts
@@ -3,25 +3,10 @@ import { defineCommand } from 'citty'
import { loadDocument } from '../../headless'
import { isAppMode, requireFile, rpc } from '../../app-client'
import { bold, fmtList, fmtSummary } from '../../format'
-import { executeRpcCommand } from '@open-pencil/core'
+import { executeRpcCommand, calcClusterConfidence } from '@open-pencil/core'
import type { AnalyzeClustersResult } from '@open-pencil/core'
-function calcConfidence(nodes: Array<{ width: number; height: number; childCount: number }>): number {
- if (nodes.length < 2) return 100
- const base = nodes[0]
- let score = 0
- for (const node of nodes.slice(1)) {
- const sizeDiff = Math.abs(node.width - base.width) + Math.abs(node.height - base.height)
- const childDiff = Math.abs(node.childCount - base.childCount)
- if (sizeDiff <= 4 && childDiff === 0) score++
- else if (sizeDiff <= 10 && childDiff <= 1) score += 0.8
- else if (sizeDiff <= 20 && childDiff <= 2) score += 0.6
- else score += 0.4
- }
- return Math.round((score / (nodes.length - 1)) * 100)
-}
-
function formatSignature(sig: string): string {
const [typeSize, children] = sig.split('|')
const type = typeSize.split(':')[0]
@@ -74,7 +59,7 @@ export default defineCommand({
const items = data.clusters.map((c) => {
const first = c.nodes[0]
- const confidence = calcConfidence(c.nodes)
+ const confidence = calcClusterConfidence(c.nodes)
const widths = c.nodes.map((n) => n.width)
const heights = c.nodes.map((n) => n.height)
diff --git a/packages/cli/src/commands/find.ts b/packages/cli/src/commands/find.ts
index 14f556e26..fdc143dfd 100644
--- a/packages/cli/src/commands/find.ts
+++ b/packages/cli/src/commands/find.ts
@@ -2,7 +2,7 @@ import { defineCommand } from 'citty'
import { loadDocument } from '../headless'
import { isAppMode, requireFile, rpc } from '../app-client'
-import { fmtList, bold, entity, formatType } from '../format'
+import { printNodeResults } from '../format'
import { executeRpcCommand } from '@open-pencil/core'
import type { FindNodeResult } from '@open-pencil/core'
@@ -32,21 +32,6 @@ export default defineCommand({
return
}
- if (results.length === 0) {
- console.log('No nodes found.')
- return
- }
-
- console.log('')
- console.log(bold(` Found ${results.length} node${results.length > 1 ? 's' : ''}`))
- console.log('')
- console.log(
- fmtList(
- results.map((n) => ({
- header: entity(formatType(n.type), n.name, n.id)
- }))
- )
- )
- console.log('')
+ printNodeResults(results)
}
})
diff --git a/packages/cli/src/commands/query.ts b/packages/cli/src/commands/query.ts
index cd9eca42b..ab2d70f79 100644
--- a/packages/cli/src/commands/query.ts
+++ b/packages/cli/src/commands/query.ts
@@ -2,7 +2,7 @@ import { defineCommand } from 'citty'
import { loadDocument } from '../headless'
import { isAppMode, requireFile, rpc } from '../app-client'
-import { fmtList, printError, bold, entity, formatType } from '../format'
+import { printNodeResults, printError } from '../format'
import { executeRpcCommand } from '@open-pencil/core'
import type { QueryNodeResult } from '@open-pencil/core'
@@ -66,25 +66,9 @@ Examples:
return
}
- if (results.length === 0) {
- console.log('No nodes found.')
- return
- }
-
- console.log('')
- console.log(bold(` Found ${results.length} node${results.length > 1 ? 's' : ''}`))
- console.log('')
- console.log(
- fmtList(
- results.map((n) => ({
- header: entity(
- formatType(n.type),
- `${n.name} ${n.width}×${n.height}`,
- n.id
- )
- }))
- )
- )
- console.log('')
+ printNodeResults(results, (n) => {
+ const q = n as { width?: number; height?: number; name: string }
+ return `${q.name} ${q.width}×${q.height}`
+ })
}
})
diff --git a/packages/cli/src/format.ts b/packages/cli/src/format.ts
index 8659a3c12..6c6a31fc4 100644
--- a/packages/cli/src/format.ts
+++ b/packages/cli/src/format.ts
@@ -18,6 +18,27 @@ import type { SceneNode, SceneGraph } from '@open-pencil/core'
export { ok, fail, dim, bold, cyan, entity, kv, fmtTree, fmtList, fmtNode, fmtHistogram, fmtSummary }
+export function printNodeResults(
+ results: Array<{ type: string; name: string; id: string }>,
+ formatLabel: (n: { type: string; name: string; id: string }) => string = (n) => n.name
+): void {
+ if (results.length === 0) {
+ console.log('No nodes found.')
+ return
+ }
+ console.log('')
+ console.log(bold(` Found ${results.length} node${results.length > 1 ? 's' : ''}`))
+ console.log('')
+ console.log(
+ fmtList(
+ results.map((n) => ({
+ header: entity(formatType(n.type), formatLabel(n), n.id)
+ }))
+ )
+ )
+ console.log('')
+}
+
const TYPE_LABELS: Record<string, string> = {
FRAME: 'frame',
RECTANGLE: 'rect',
diff --git a/packages/core/src/clipboard.ts b/packages/core/src/clipboard.ts
index 6e7bc1c49..37b01cb95 100644
--- a/packages/core/src/clipboard.ts
+++ b/packages/core/src/clipboard.ts
@@ -6,7 +6,9 @@ import {
sceneNodeToKiwi,
buildFigKiwi,
parseFigKiwiChunks,
- decompressFigKiwiDataAsync
+ decompressFigKiwiDataAsync,
+ makeDocumentNodeChange,
+ makeCanvasNodeChange
} from './kiwi/kiwi-serialize'
import { initCodec, getCompiledSchema, getSchemaBytes } from './kiwi/codec'
import { decodeBinarySchema, compileSchema, ByteBuffer } from './kiwi/kiwi-schema'
@@ -285,25 +287,8 @@ export function buildFigmaClipboardHTML(nodes: SceneNode[], graph: SceneGraph):
const localIdCounter = { value: 100 }
const nodeChanges: KiwiNodeChange[] = [
- {
- guid: docGuid,
- type: 'DOCUMENT',
- name: 'Document',
- visible: true,
- opacity: 1,
- phase: 'CREATED',
- transform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
- },
- {
- guid: canvasGuid,
- parentIndex: { guid: docGuid, position: '!' },
- type: 'CANVAS',
- name: 'Page 1',
- visible: true,
- opacity: 1,
- phase: 'CREATED',
- transform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
- }
+ makeDocumentNodeChange(docGuid),
+ makeCanvasNodeChange(canvasGuid, docGuid, '!', 'Page 1')
]
const blobs: Uint8Array[] = []
diff --git a/packages/core/src/editor/alignment.ts b/packages/core/src/editor/alignment.ts
index a9bf3c589..e436a66ff 100644
--- a/packages/core/src/editor/alignment.ts
+++ b/packages/core/src/editor/alignment.ts
@@ -1,3 +1,4 @@
+import { computeAbsoluteBounds } from '../geometry'
import type { Vector } from '../types'
import type { SceneNode } from '../scene-graph'
import type { EditorContext } from './types'
@@ -37,19 +38,14 @@ function alignMultipleNodes(
align: 'min' | 'center' | 'max'
) {
const absPositions = new Map<string, Vector>()
- let minX = Infinity
- let minY = Infinity
- let maxX = -Infinity
- let maxY = -Infinity
-
- for (const n of nodes) {
- const abs = ctx.graph.getAbsolutePosition(n.id)
- absPositions.set(n.id, abs)
- minX = Math.min(minX, abs.x)
- minY = Math.min(minY, abs.y)
- maxX = Math.max(maxX, abs.x + n.width)
- maxY = Math.max(maxY, abs.y + n.height)
- }
+ for (const n of nodes) absPositions.set(n.id, ctx.graph.getAbsolutePosition(n.id))
+
+ const getPos = (id: string) => absPositions.get(id) ?? { x: 0, y: 0 }
+ const b = computeAbsoluteBounds(nodes, getPos)
+ const minX = b.x
+ const minY = b.y
+ const maxX = b.x + b.width
+ const maxY = b.y + b.height
for (const n of nodes) {
const abs = absPositions.get(n.id)
diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.ts
index b87b0c82f..19ba87bb3 100644
--- a/packages/core/src/editor/create.ts
+++ b/packages/core/src/editor/create.ts
@@ -24,23 +24,10 @@ import type { SkiaRenderer } from '../renderer/renderer'
import type { CanvasKit } from 'canvaskit-wasm'
import type { EditorContext, EditorOptions, EditorState } from './types'
-export function createEditor(options?: EditorOptions) {
- let _graph = options?.graph ?? new SceneGraph()
- const undo = new UndoManager()
- const _loadFont = options?.loadFont ?? defaultLoadFont
- const _getViewportSize = options?.getViewportSize ?? (() => {
- if (IS_BROWSER) return { width: window.innerWidth, height: window.innerHeight }
- return { width: 800, height: 600 }
- })
- let _ck: CanvasKit | null = null
- let _renderer: SkiaRenderer | null = null
- let _textEditor: TextEditor | null = null
-
- void prefetchFigmaSchema()
-
- const state: EditorState = options?.state ?? {
+export function createDefaultEditorState(pageId: string): EditorState {
+ return {
activeTool: 'SELECT',
- currentPageId: _graph.getPages()[0].id,
+ currentPageId: pageId,
selectedIds: new Set<string>(),
marquee: null,
snapGuides: [],
@@ -63,6 +50,23 @@ export function createEditor(options?: EditorOptions) {
loading: false,
enteredContainerId: null
}
+}
+
+export function createEditor(options?: EditorOptions) {
+ let _graph = options?.graph ?? new SceneGraph()
+ const undo = new UndoManager()
+ const _loadFont = options?.loadFont ?? defaultLoadFont
+ const _getViewportSize = options?.getViewportSize ?? (() => {
+ if (IS_BROWSER) return { width: window.innerWidth, height: window.innerHeight }
+ return { width: 800, height: 600 }
+ })
+ let _ck: CanvasKit | null = null
+ let _renderer: SkiaRenderer | null = null
+ let _textEditor: TextEditor | null = null
+
+ void prefetchFigmaSchema()
+
+ const state: EditorState = options?.state ?? createDefaultEditorState(_graph.getPages()[0].id)
function requestRender() {
state.renderVersion++
diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.ts
index 7f1e60048..94c156adc 100644
--- a/packages/core/src/editor/index.ts
+++ b/packages/core/src/editor/index.ts
@@ -1,4 +1,4 @@
-export { createEditor } from './create'
+export { createDefaultEditorState, createEditor } from './create'
export type { Editor } from './create'
export {
EDITOR_TOOLS,
diff --git a/packages/core/src/editor/structure.ts b/packages/core/src/editor/structure.ts
index 2588fa47c..1fbac579d 100644
--- a/packages/core/src/editor/structure.ts
+++ b/packages/core/src/editor/structure.ts
@@ -1,3 +1,4 @@
+import { computeAbsoluteBounds } from '../geometry'
import { computeLayout } from '../layout'
import type { LayoutMode, SceneNode } from '../scene-graph'
@@ -117,17 +118,11 @@ export function createStructureActions(ctx: EditorContext) {
const nodeIds = selectedNodes.map((n) => n.id)
const origPositions = selectedNodes.map((n) => ({ id: n.id, x: n.x, y: n.y }))
- let minX = Infinity
- let minY = Infinity
- let maxX = -Infinity
- let maxY = -Infinity
- for (const n of selectedNodes) {
- const abs = ctx.graph.getAbsolutePosition(n.id)
- minX = Math.min(minX, abs.x)
- minY = Math.min(minY, abs.y)
- maxX = Math.max(maxX, abs.x + n.width)
- maxY = Math.max(maxY, abs.y + n.height)
- }
+ const { x: minX, y: minY, width: bw, height: bh } = computeAbsoluteBounds(
+ selectedNodes, (id) => ctx.graph.getAbsolutePosition(id)
+ )
+ const maxX = minX + bw
+ const maxY = minY + bh
const parentAbs = isTopLevel(parentId) ? { x: 0, y: 0 } : ctx.graph.getAbsolutePosition(parentId)
const firstIndex = Math.min(...nodeIds.map((id) => parent.childIds.indexOf(id)))
@@ -195,31 +190,21 @@ export function createStructureActions(ctx: EditorContext) {
const prevSelection = new Set(ctx.state.selectedIds)
const origPositions = selectedNodes.map((n) => ({ id: n.id, x: n.x, y: n.y, parentId }))
- let minX = Infinity
- let minY = Infinity
- let maxX = -Infinity
- let maxY = -Infinity
- for (const n of selectedNodes) {
- const abs = ctx.graph.getAbsolutePosition(n.id)
- minX = Math.min(minX, abs.x)
- minY = Math.min(minY, abs.y)
- maxX = Math.max(maxX, abs.x + n.width)
- maxY = Math.max(maxY, abs.y + n.height)
- }
+ const bounds = computeAbsoluteBounds(selectedNodes, (id) => ctx.graph.getAbsolutePosition(id))
const parentAbs = isTopLevel(parentId)
? { x: 0, y: 0 }
: ctx.graph.getAbsolutePosition(parentId)
const direction: LayoutMode =
- selectedNodes.length <= 1 || maxY - minY > maxX - minX ? 'VERTICAL' : 'HORIZONTAL'
+ selectedNodes.length <= 1 || bounds.height > bounds.width ? 'VERTICAL' : 'HORIZONTAL'
const frame = ctx.graph.createNode('FRAME', parentId, {
name: 'Frame',
- x: minX - parentAbs.x,
- y: minY - parentAbs.y,
- width: maxX - minX,
- height: maxY - minY,
+ x: bounds.x - parentAbs.x,
+ y: bounds.y - parentAbs.y,
+ width: bounds.width,
+ height: bounds.height,
layoutMode: direction,
primaryAxisSizing: 'HUG',
counterAxisSizing: 'HUG',
diff --git a/packages/core/src/editor/viewport.ts b/packages/core/src/editor/viewport.ts
index 2da475a1a..188481a23 100644
--- a/packages/core/src/editor/viewport.ts
+++ b/packages/core/src/editor/viewport.ts
@@ -1,5 +1,5 @@
import { ZOOM_DIVISOR, ZOOM_SCALE_MAX, ZOOM_SCALE_MIN } from '../constants'
-import { computeBounds } from '../geometry'
+import { computeBounds, computeAbsoluteBounds } from '../geometry'
import type { EditorContext } from './types'
@@ -65,22 +65,13 @@ export function createViewportActions(ctx: EditorContext) {
function zoomToSelection() {
if (ctx.state.selectedIds.size === 0) return
- let minX = Infinity
- let minY = Infinity
- let maxX = -Infinity
- let maxY = -Infinity
- for (const id of ctx.state.selectedIds) {
- const n = ctx.graph.getNode(id)
- if (!n) continue
- const abs = ctx.graph.getAbsolutePosition(id)
- minX = Math.min(minX, abs.x)
- minY = Math.min(minY, abs.y)
- maxX = Math.max(maxX, abs.x + n.width)
- maxY = Math.max(maxY, abs.y + n.height)
- }
- if (minX === Infinity) return
+ const nodes = [...ctx.state.selectedIds]
+ .map((id) => ctx.graph.getNode(id))
+ .filter((n): n is NonNullable<typeof n> => n != null)
+ if (nodes.length === 0) return
- zoomToBounds(minX, minY, maxX, maxY)
+ const b = computeAbsoluteBounds(nodes, (id) => ctx.graph.getAbsolutePosition(id))
+ zoomToBounds(b.x, b.y, b.x + b.width, b.y + b.height)
}
return { screenToCanvas, applyZoom, pan, zoomToBounds, zoomToFit, zoomTo100, zoomToSelection }
diff --git a/packages/core/src/fig-export.ts b/packages/core/src/fig-export.ts
index 3a87b8217..7dfce520b 100644
--- a/packages/core/src/fig-export.ts
+++ b/packages/core/src/fig-export.ts
@@ -8,7 +8,9 @@ import {
sceneNodeToKiwi,
fractionalPosition,
buildFontDigestMap,
- safeColor
+ safeColor,
+ makeDocumentNodeChange,
+ makeCanvasNodeChange
} from './kiwi/kiwi-serialize'
import { renderThumbnail } from './render-image'
@@ -82,21 +84,7 @@ export async function exportFigFile(
const docGuid = { sessionID: 0, localID: 0 }
const localIdCounter = { value: 2 }
- const nodeChanges: KiwiNodeChange[] = [
- {
- guid: docGuid,
- type: 'DOCUMENT',
- name: 'Document',
- visible: true,
- opacity: 1,
- phase: 'CREATED',
- transform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 },
- strokeWeight: 1,
- strokeAlign: 'CENTER',
- strokeJoin: 'MITER',
- documentColorProfile: 'SRGB'
- }
- ]
+ const nodeChanges: KiwiNodeChange[] = [makeDocumentNodeChange(docGuid)]
const blobs: Uint8Array[] = []
const pages = graph.getPages(true)
@@ -112,22 +100,11 @@ export async function exportFigFile(
if (page.internalOnly) internalCanvasGuid = canvasGuid
- const canvasNc: KiwiNodeChange = {
- guid: canvasGuid,
- parentIndex: { guid: docGuid, position: fractionalPosition(p) },
- type: 'CANVAS',
- name: page.name,
- visible: true,
- opacity: 1,
- phase: 'CREATED',
- transform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 },
- strokeWeight: 1,
- strokeAlign: 'CENTER',
- strokeJoin: 'MITER',
+ const canvasNc = makeCanvasNodeChange(canvasGuid, docGuid, fractionalPosition(p), page.name, {
backgroundOpacity: 1,
backgroundColor: { ...CANVAS_BG_COLOR },
backgroundEnabled: true
- }
+ })
if (page.internalOnly) canvasNc.internalOnly = true
nodeChanges.push(canvasNc)
@@ -153,20 +130,10 @@ export async function exportFigFile(
if (!internalCanvasGuid) {
const internalLocalID = localIdCounter.value++
internalCanvasGuid = { sessionID: 0, localID: internalLocalID }
- nodeChanges.push({
- guid: internalCanvasGuid,
- parentIndex: { guid: docGuid, position: fractionalPosition(pages.length) },
- type: 'CANVAS',
- name: 'Internal Only Canvas',
- visible: true,
- opacity: 1,
- phase: 'CREATED',
- transform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 },
- strokeWeight: 1,
- strokeAlign: 'CENTER',
- strokeJoin: 'MITER',
- internalOnly: true
- })
+ nodeChanges.push(makeCanvasNodeChange(
+ internalCanvasGuid, docGuid, fractionalPosition(pages.length), 'Internal Only Canvas',
+ { internalOnly: true }
+ ))
}
const modeIdToGuid = new Map<string, GUID>()
diff --git a/packages/core/src/fonts.ts b/packages/core/src/fonts.ts
index f3bc0e947..392fd5de9 100644
--- a/packages/core/src/fonts.ts
+++ b/packages/core/src/fonts.ts
@@ -68,6 +68,18 @@ export function normalizeFontFamily(family: string): string {
return family.replace(/\s+Variable$/i, '')
}
+async function retryWithNormalizedFamily(family: string): Promise<Record<string, string> | null> {
+ const normalized = normalizeFontFamily(family)
+ if (normalized === family) {
+ googleFontsFailed.add(family)
+ return null
+ }
+ const result = await fetchGoogleFontFiles(normalized)
+ if (result) googleFontsCache.set(family, result)
+ else googleFontsFailed.add(family)
+ return result
+}
+
async function fetchGoogleFontFiles(family: string): Promise<Record<string, string> | null> {
if (googleFontsCache.has(family)) return googleFontsCache.get(family) ?? null
if (googleFontsFailed.has(family)) return null
@@ -80,31 +92,11 @@ async function fetchGoogleFontFiles(family: string): Promise<Record<string, stri
googleFontsFailed.add(family)
return null
}
- if (!response.ok) {
- const normalized = normalizeFontFamily(family)
- if (normalized !== family) {
- const result = await fetchGoogleFontFiles(normalized)
- if (result) googleFontsCache.set(family, result)
- else googleFontsFailed.add(family)
- return result
- }
- googleFontsFailed.add(family)
- return null
- }
+ if (!response.ok) return retryWithNormalizedFamily(family)
const data = (await response.json()) as { items?: Array<{ files?: Record<string, string> }> }
const files = data.items?.[0]?.files
- if (!files) {
- const normalized = normalizeFontFamily(family)
- if (normalized !== family) {
- const result = await fetchGoogleFontFiles(normalized)
- if (result) googleFontsCache.set(family, result)
- else googleFontsFailed.add(family)
- return result
- }
- googleFontsFailed.add(family)
- return null
- }
+ if (!files) return retryWithNormalizedFamily(family)
googleFontsCache.set(family, files)
return files
diff --git a/packages/core/src/geometry.ts b/packages/core/src/geometry.ts
index e5d2c4889..e3c373682 100644
--- a/packages/core/src/geometry.ts
+++ b/packages/core/src/geometry.ts
@@ -83,3 +83,19 @@ export function computeBounds(items: Iterable<Rect>): Rect {
if (minX === Infinity) return { x: 0, y: 0, width: 0, height: 0 }
return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }
}
+
+export function computeAbsoluteBounds(
+ nodes: Iterable<{ id: string; width: number; height: number }>,
+ getAbsolutePosition: (id: string) => Vector
+): Rect {
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity
+ for (const n of nodes) {
+ const abs = getAbsolutePosition(n.id)
+ minX = Math.min(minX, abs.x)
+ minY = Math.min(minY, abs.y)
+ maxX = Math.max(maxX, abs.x + n.width)
+ maxY = Math.max(maxY, abs.y + n.height)
+ }
+ if (minX === Infinity) return { x: 0, y: 0, width: 0, height: 0 }
+ return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 688f854af..a803d2de6 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -1,10 +1,11 @@
export type { GUID, Color, Vector, Matrix, Rect } from './types'
-export { computeBounds, degToRad, radToDeg, rotatePoint, rotatedCorners, rotatedBBox } from './geometry'
+export { computeBounds, computeAbsoluteBounds, degToRad, radToDeg, rotatePoint, rotatedCorners, rotatedBBox } from './geometry'
export { randomHex, randomInt, randomIndex } from './random'
export * from './constants'
export {
+ createDefaultEditorState,
createEditor,
EDITOR_TOOLS,
TOOL_SHORTCUTS
@@ -67,7 +68,7 @@ export {
} from './scene-graph'
export { FigmaAPI, FigmaNodeProxy, computeImageHash, type FigmaFontName } from './figma-api'
-export { ALL_TOOLS, CORE_TOOLS, EXTENDED_TOOLS, defineTool, toolsToAI, buildDebugLog, requireNode, NodeNotFoundError } from './tools'
+export { ALL_TOOLS, CORE_TOOLS, EXTENDED_TOOLS, defineTool, toolsToAI, buildDebugLog, requireNode, NodeNotFoundError, calcClusterConfidence } from './tools'
export type { ToolDef, ParamDef, ParamType, ToolLogEntry, ToolDebugLog, AIAdapterOptions, StepBudget } from './tools'
export { executeRpcCommand, ALL_RPC_COMMANDS } from './rpc'
export { queryByXPath, matchByXPath } from './xpath'
diff --git a/packages/core/src/kiwi/fig-file.ts b/packages/core/src/kiwi/fig-file.ts
index ac2cfde2f..60e603475 100644
--- a/packages/core/src/kiwi/fig-file.ts
+++ b/packages/core/src/kiwi/fig-file.ts
@@ -1,108 +1,13 @@
-import { unzipSync, inflateSync } from 'fflate'
-import { decompress as zstdDecompress } from 'fzstd'
-
import { IS_BROWSER } from '../constants'
import { importNodeChanges } from './fig-import'
-import { decodeBinarySchema, compileSchema, ByteBuffer } from './kiwi-schema'
-import { isZstdCompressed } from './protocol'
+import { parseFigBuffer } from './fig-parse-core'
import type { SceneGraph } from '../scene-graph'
-import type { FigmaMessage } from './codec'
-import type { FigParseResult } from './fig-parse-worker'
-
-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 }
-}
+import type { FigParseResult } from './fig-parse-core'
function parseFigFileSync(buffer: ArrayBuffer): SceneGraph {
- const zip = unzipSync(new Uint8Array(buffer), {
- filter: (file) =>
- file.name === 'canvas.fig' ||
- file.name === 'canvas' ||
- (file.name.startsWith('images/') && file.name !== 'images/'),
- })
- const entries = Object.keys(zip)
-
- let canvasData: Uint8Array | null = null
- for (const name of entries) {
- if (name === 'canvas.fig' || name === 'canvas') {
- canvasData = zip[name]
- break
- }
- }
- if (!canvasData) {
- let maxSize = 0
- for (const name of entries) {
- const lower = name.toLowerCase()
- if (lower.endsWith('.png') || lower.endsWith('.jpg') || lower.endsWith('.json')) continue
- if (zip[name].byteLength > maxSize) {
- maxSize = zip[name].byteLength
- canvasData = zip[name]
- }
- }
- }
-
- if (!canvasData) {
- throw new Error(`No canvas data found in .fig file. Entries: ${entries.join(', ')}`)
- }
-
- 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')
- }
-
- const blobs: Uint8Array[] = (message.blobs ?? []).map((b) =>
- b.bytes instanceof Uint8Array ? b.bytes : new Uint8Array(Object.values(b.bytes))
- )
-
- const images = new Map<string, Uint8Array>()
- for (const name of entries) {
- if (name.startsWith('images/') && name !== 'images/') {
- images.set(name.replace('images/', ''), zip[name])
- }
- }
-
- return importNodeChanges(nodeChanges, blobs, images)
+ const { nodeChanges, blobs, images: imageEntries } = parseFigBuffer(buffer)
+ return importNodeChanges(nodeChanges, blobs, new Map(imageEntries))
}
function parseViaWorker(buffer: ArrayBuffer): Promise<SceneGraph> {
diff --git a/packages/core/src/kiwi/fig-parse-core.ts b/packages/core/src/kiwi/fig-parse-core.ts
new file mode 100644
index 000000000..09b1b6ff9
--- /dev/null
+++ b/packages/core/src/kiwi/fig-parse-core.ts
@@ -0,0 +1,108 @@
+import { unzipSync, inflateSync } from 'fflate'
+import { decompress as zstdDecompress } from 'fzstd'
+
+import { decodeBinarySchema, compileSchema, ByteBuffer } from './kiwi-schema'
+import { isZstdCompressed } from './protocol'
+
+import type { FigmaMessage, NodeChange } from './codec'
+
+interface FigKiwiPayload {
+ schemaDeflated: Uint8Array
+ dataRaw: Uint8Array
+}
+
+export 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 interface FigParseResult {
+ nodeChanges: NodeChange[]
+ blobs: Uint8Array[]
+ images: Array<[string, Uint8Array]>
+}
+
+export function parseFigBuffer(buffer: ArrayBuffer): FigParseResult {
+ const zip = unzipSync(new Uint8Array(buffer), {
+ filter: (file) =>
+ file.name === 'canvas.fig' ||
+ file.name === 'canvas' ||
+ (file.name.startsWith('images/') && file.name !== 'images/'),
+ })
+ const entries = Object.keys(zip)
+
+ let canvasData: Uint8Array | null = null
+ for (const name of entries) {
+ if (name === 'canvas.fig' || name === 'canvas') {
+ canvasData = zip[name]
+ break
+ }
+ }
+ if (!canvasData) {
+ let maxSize = 0
+ for (const name of entries) {
+ const lower = name.toLowerCase()
+ if (lower.endsWith('.png') || lower.endsWith('.jpg') || lower.endsWith('.json')) continue
+ if (zip[name].byteLength > maxSize) {
+ maxSize = zip[name].byteLength
+ canvasData = zip[name]
+ }
+ }
+ }
+
+ if (!canvasData) {
+ throw new Error(`No canvas data found in .fig file. Entries: ${entries.join(', ')}`)
+ }
+
+ 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')
+ }
+
+ const blobs: Uint8Array[] = (message.blobs ?? []).map((b) =>
+ b.bytes instanceof Uint8Array ? b.bytes : new Uint8Array(Object.values(b.bytes))
+ )
+
+ const images: Array<[string, Uint8Array]> = []
+ for (const name of entries) {
+ if (name.startsWith('images/') && name !== 'images/') {
+ images.push([name.replace('images/', ''), zip[name]])
+ }
+ }
+
+ return { nodeChanges, blobs, images }
+}
diff --git a/packages/core/src/kiwi/fig-parse-worker.ts b/packages/core/src/kiwi/fig-parse-worker.ts
index cae33879a..5cff4cfd4 100644
--- a/packages/core/src/kiwi/fig-parse-worker.ts
+++ b/packages/core/src/kiwi/fig-parse-worker.ts
@@ -1,114 +1,10 @@
-import { unzipSync, inflateSync } from 'fflate'
-import { decompress as zstdDecompress } from 'fzstd'
+import { parseFigBuffer } from './fig-parse-core'
-import { decodeBinarySchema, compileSchema, ByteBuffer } from './kiwi-schema'
-import { isZstdCompressed } from './protocol'
-
-import type { FigmaMessage, NodeChange } from './codec'
-
-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 interface FigParseResult {
- nodeChanges: NodeChange[]
- blobs: Uint8Array[]
- images: Array<[string, Uint8Array]>
-}
+export type { FigParseResult } from './fig-parse-core'
self.onmessage = (e: MessageEvent<ArrayBuffer>) => {
try {
- const buffer = e.data
-
- const zip = unzipSync(new Uint8Array(buffer), {
- filter: (file) =>
- file.name === 'canvas.fig' ||
- file.name === 'canvas' ||
- (file.name.startsWith('images/') && file.name !== 'images/'),
- })
- const entries = Object.keys(zip)
-
- let canvasData: Uint8Array | null = null
- for (const name of entries) {
- if (name === 'canvas.fig' || name === 'canvas') {
- canvasData = zip[name]
- break
- }
- }
- if (!canvasData) {
- let maxSize = 0
- for (const name of entries) {
- const lower = name.toLowerCase()
- if (lower.endsWith('.png') || lower.endsWith('.jpg') || lower.endsWith('.json')) continue
- if (zip[name].byteLength > maxSize) {
- maxSize = zip[name].byteLength
- canvasData = zip[name]
- }
- }
- }
-
- if (!canvasData) {
- throw new Error(`No canvas data found in .fig file. Entries: ${entries.join(', ')}`)
- }
-
- 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')
- }
-
- const blobs: Uint8Array[] = (message.blobs ?? []).map((b) =>
- b.bytes instanceof Uint8Array ? b.bytes : new Uint8Array(Object.values(b.bytes))
- )
-
- const images: Array<[string, Uint8Array]> = []
- for (const name of entries) {
- if (name.startsWith('images/') && name !== 'images/') {
- images.push([name.replace('images/', ''), zip[name]])
- }
- }
-
- const result: FigParseResult = { nodeChanges, blobs, images }
- self.postMessage(result)
+ self.postMessage(parseFigBuffer(e.data))
} catch (err) {
self.postMessage({ error: err instanceof Error ? err.message : String(err) })
}
diff --git a/packages/core/src/kiwi/kiwi-serialize.ts b/packages/core/src/kiwi/kiwi-serialize.ts
index 1164c2381..dc5fc82c9 100644
--- a/packages/core/src/kiwi/kiwi-serialize.ts
+++ b/packages/core/src/kiwi/kiwi-serialize.ts
@@ -493,3 +493,44 @@ export function sceneNodeToKiwi(
return result
}
+
+const IDENTITY_TRANSFORM = { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
+
+export function makeDocumentNodeChange(guid: GUID): NodeChange & Record<string, unknown> {
+ return {
+ guid,
+ type: 'DOCUMENT',
+ name: 'Document',
+ visible: true,
+ opacity: 1,
+ phase: 'CREATED',
+ transform: { ...IDENTITY_TRANSFORM },
+ strokeWeight: 1,
+ strokeAlign: 'CENTER',
+ strokeJoin: 'MITER',
+ documentColorProfile: 'SRGB'
+ }
+}
+
+export function makeCanvasNodeChange(
+ guid: GUID,
+ parentGuid: GUID,
+ position: string,
+ name: string,
+ extra?: Record<string, unknown>
+): NodeChange & Record<string, unknown> {
+ return {
+ guid,
+ parentIndex: { guid: parentGuid, position },
+ type: 'CANVAS',
+ name,
+ visible: true,
+ opacity: 1,
+ phase: 'CREATED',
+ transform: { ...IDENTITY_TRANSFORM },
+ strokeWeight: 1,
+ strokeAlign: 'CENTER',
+ strokeJoin: 'MITER',
+ ...extra
+ }
+}
diff --git a/packages/core/src/renderer/ai-overlays.ts b/packages/core/src/renderer/ai-overlays.ts
index d592f89a5..1e24b8495 100644
--- a/packages/core/src/renderer/ai-overlays.ts
+++ b/packages/core/src/renderer/ai-overlays.ts
@@ -1,62 +1,23 @@
import {
- FLASH_PADDING,
- FLASH_STROKE_WIDTH,
- FLASH_RADIUS,
AI_ACTIVE_COLOR,
AI_DONE_COLOR,
AI_PULSE_PERIOD_MS,
AI_DONE_DURATION_MS
} from '../constants'
+import { drawNodeHighlightRect } from './highlight-rect'
+
import type { SceneGraph } from '../scene-graph'
import type { Canvas } from 'canvaskit-wasm'
import type { SkiaRenderer } from './renderer'
-function drawAiNodeOverlay(
- r: SkiaRenderer,
- canvas: Canvas,
- graph: SceneGraph,
- nodeId: string,
- color: { r: number; g: number; b: number },
- opacity: number
-): void {
- const node = graph.getNode(nodeId)
- if (!node) return
- const ck = r.ck
- const abs = graph.getAbsolutePosition(nodeId)
- const cx = (abs.x + node.width / 2) * r.zoom + r.panX
- const cy = (abs.y + node.height / 2) * r.zoom + r.panY
- const hw = (node.width / 2) * r.zoom
- const hh = (node.height / 2) * r.zoom
- const pad = FLASH_PADDING
-
- if (!r._flashPaint) {
- r._flashPaint = new ck.Paint()
- r._flashPaint.setStyle(ck.PaintStyle.Stroke)
- r._flashPaint.setAntiAlias(true)
- }
-
- const paint = r._flashPaint
- paint.setColor(ck.Color4f(color.r, color.g, color.b, opacity))
- paint.setStrokeWidth(FLASH_STROKE_WIDTH)
-
- canvas.save()
- if (node.rotation !== 0) canvas.rotate(node.rotation, cx, cy)
- const rect = ck.RRectXY(
- ck.LTRBRect(cx - hw - pad, cy - hh - pad, cx + hw + pad, cy + hh + pad),
- FLASH_RADIUS, FLASH_RADIUS
- )
- canvas.drawRRect(rect, paint)
- canvas.restore()
-}
-
export function drawAiOverlays(r: SkiaRenderer, canvas: Canvas, graph: SceneGraph): void {
const now = performance.now()
for (const nodeId of r._aiActiveNodes) {
const phase = (now % AI_PULSE_PERIOD_MS) / AI_PULSE_PERIOD_MS
const opacity = 0.3 + 0.5 * (0.5 + 0.5 * Math.sin(phase * Math.PI * 2))
- drawAiNodeOverlay(r, canvas, graph, nodeId, AI_ACTIVE_COLOR, opacity)
+ drawNodeHighlightRect(r, canvas, graph, nodeId, AI_ACTIVE_COLOR, opacity)
}
for (let i = r._aiDoneFlashes.length - 1; i >= 0; i--) {
@@ -68,6 +29,6 @@ export function drawAiOverlays(r: SkiaRenderer, canvas: Canvas, graph: SceneGrap
}
const t = elapsed / AI_DONE_DURATION_MS
const opacity = t < 0.3 ? t / 0.3 : 1 - (t - 0.3) / 0.7
- drawAiNodeOverlay(r, canvas, graph, flash.nodeId, AI_DONE_COLOR, opacity)
+ drawNodeHighlightRect(r, canvas, graph, flash.nodeId, AI_DONE_COLOR, opacity)
}
}
diff --git a/packages/core/src/renderer/highlight-rect.ts b/packages/core/src/renderer/highlight-rect.ts
new file mode 100644
index 000000000..a2168f010
--- /dev/null
+++ b/packages/core/src/renderer/highlight-rect.ts
@@ -0,0 +1,48 @@
+import { FLASH_PADDING, FLASH_STROKE_WIDTH, FLASH_RADIUS } from '../constants'
+import type { SceneGraph } from '../scene-graph'
+import type { Canvas, Paint } from 'canvaskit-wasm'
+import type { SkiaRenderer } from './renderer'
+
+export function ensureFlashPaint(r: SkiaRenderer): Paint {
+ if (!r._flashPaint) {
+ r._flashPaint = new r.ck.Paint()
+ r._flashPaint.setStyle(r.ck.PaintStyle.Stroke)
+ r._flashPaint.setAntiAlias(true)
+ }
+ return r._flashPaint
+}
+
+export function drawNodeHighlightRect(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ graph: SceneGraph,
+ nodeId: string,
+ color: { r: number; g: number; b: number },
+ opacity: number,
+ extraPad = 0
+): boolean {
+ const node = graph.getNode(nodeId)
+ if (!node) return false
+
+ const abs = graph.getAbsolutePosition(nodeId)
+ const cx = (abs.x + node.width / 2) * r.zoom + r.panX
+ const cy = (abs.y + node.height / 2) * r.zoom + r.panY
+ const hw = (node.width / 2) * r.zoom
+ const hh = (node.height / 2) * r.zoom
+ const pad = FLASH_PADDING + extraPad
+
+ const paint = ensureFlashPaint(r)
+ paint.setColor(r.ck.Color4f(color.r, color.g, color.b, opacity))
+ paint.setStrokeWidth(FLASH_STROKE_WIDTH)
+
+ canvas.save()
+ if (node.rotation !== 0) canvas.rotate(node.rotation, cx, cy)
+ const rect = r.ck.RRectXY(
+ r.ck.LTRBRect(cx - hw - pad, cy - hh - pad, cx + hw + pad, cy + hh + pad),
+ FLASH_RADIUS,
+ FLASH_RADIUS
+ )
+ canvas.drawRRect(rect, paint)
+ canvas.restore()
+ return true
+}
diff --git a/packages/core/src/renderer/label-cache.ts b/packages/core/src/renderer/label-cache.ts
index 169ba75a1..f0ba31382 100644
--- a/packages/core/src/renderer/label-cache.ts
+++ b/packages/core/src/renderer/label-cache.ts
@@ -23,6 +23,10 @@ interface Viewport {
const LABEL_TYPES = new Set(['COMPONENT', 'COMPONENT_SET'])
+function isInViewport(absX: number, absY: number, w: number, h: number, vp: Viewport): boolean {
+ return absX + w >= vp.x && absY + h >= vp.y && absX <= vp.x + vp.w && absY <= vp.y + vp.h
+}
+
export class LabelCache {
private sections: CachedSection[] = []
private components: CachedComponent[] = []
@@ -47,15 +51,8 @@ export class LabelCache {
const result: Array<{ node: SceneNode; absX: number; absY: number; nested: boolean }> = []
for (const cached of this.sections) {
const node = graph.getNode(cached.nodeId)
- if (!node) continue
- if (
- cached.absX + node.width >= viewport.x &&
- cached.absY + node.height >= viewport.y &&
- cached.absX <= viewport.x + viewport.w &&
- cached.absY <= viewport.y + viewport.h
- ) {
- result.push({ node, absX: cached.absX, absY: cached.absY, nested: cached.nested })
- }
+ if (!node || !isInViewport(cached.absX, cached.absY, node.width, node.height, viewport)) continue
+ result.push({ node, absX: cached.absX, absY: cached.absY, nested: cached.nested })
}
return result
}
@@ -64,15 +61,8 @@ export class LabelCache {
const result: Array<{ node: SceneNode; absX: number; absY: number; inside: boolean }> = []
for (const cached of this.components) {
const node = graph.getNode(cached.nodeId)
- if (!node) continue
- if (
- cached.absX + node.width >= viewport.x &&
- cached.absY + node.height >= viewport.y &&
- cached.absX <= viewport.x + viewport.w &&
- cached.absY <= viewport.y + viewport.h
- ) {
- result.push({ node, absX: cached.absX, absY: cached.absY, inside: cached.parentType === 'COMPONENT_SET' })
- }
+ if (!node || !isInViewport(cached.absX, cached.absY, node.width, node.height, viewport)) continue
+ result.push({ node, absX: cached.absX, absY: cached.absY, inside: cached.parentType === 'COMPONENT_SET' })
}
return result
}
diff --git a/packages/core/src/renderer/overlays.ts b/packages/core/src/renderer/overlays.ts
index e0a473b45..2f6a3e40c 100644
--- a/packages/core/src/renderer/overlays.ts
+++ b/packages/core/src/renderer/overlays.ts
@@ -17,11 +17,10 @@ import {
FLASH_ATTACK_MS,
FLASH_HOLD_MS,
FLASH_RELEASE_MS,
- FLASH_STROKE_WIDTH,
- FLASH_PADDING,
- FLASH_OVERSHOOT,
- FLASH_RADIUS
+ FLASH_OVERSHOOT
} from '../constants'
+import { rotatedCorners } from '../geometry'
+import { drawNodeHighlightRect } from './highlight-rect'
import type { SceneNode, SceneGraph } from '../scene-graph'
import type { SnapGuide } from '../snap'
import type { TextEditor } from '../text-editor'
@@ -148,12 +147,13 @@ export function drawSelection(
r.drawSelectionLabels(canvas, graph, selectedIds)
}
-export function drawNodeSelection(
+function withNodeBounds(
r: SkiaRenderer,
canvas: Canvas,
node: SceneNode,
rotation: number,
- graph: SceneGraph
+ graph: SceneGraph,
+ draw: (x1: number, y1: number, x2: number, y2: number) => void
): void {
const abs = graph.getAbsolutePosition(node.id)
const cx = (abs.x + node.width / 2) * r.zoom + r.panX
@@ -166,28 +166,34 @@ export function drawNodeSelection(
canvas.rotate(rotation, cx, cy)
}
- const x1 = cx - hw
- const y1 = cy - hh
- const x2 = cx + hw
- const y2 = cy + hh
-
- canvas.drawRect(r.ck.LTRBRect(x1, y1, x2, y2), r.selectionPaint)
-
- r.drawHandle(canvas, x1, y1)
- r.drawHandle(canvas, x2, y1)
- r.drawHandle(canvas, x1, y2)
- r.drawHandle(canvas, x2, y2)
-
- const mx = (x1 + x2) / 2
- const my = (y1 + y2) / 2
- r.drawHandle(canvas, mx, y1)
- r.drawHandle(canvas, mx, y2)
- r.drawHandle(canvas, x1, my)
- r.drawHandle(canvas, x2, my)
-
+ draw(cx - hw, cy - hh, cx + hw, cy + hh)
canvas.restore()
}
+export function drawNodeSelection(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ rotation: number,
+ graph: SceneGraph
+): void {
+ withNodeBounds(r, canvas, node, rotation, graph, (x1, y1, x2, y2) => {
+ canvas.drawRect(r.ck.LTRBRect(x1, y1, x2, y2), r.selectionPaint)
+
+ r.drawHandle(canvas, x1, y1)
+ r.drawHandle(canvas, x2, y1)
+ r.drawHandle(canvas, x1, y2)
+ r.drawHandle(canvas, x2, y2)
+
+ const mx = (x1 + x2) / 2
+ const my = (y1 + y2) / 2
+ r.drawHandle(canvas, mx, y1)
+ r.drawHandle(canvas, mx, y2)
+ r.drawHandle(canvas, x1, my)
+ r.drawHandle(canvas, x2, my)
+ })
+}
+
export function drawSelectionLabels(
r: SkiaRenderer,
canvas: Canvas,
@@ -308,19 +314,9 @@ export function drawNodeOutline(
rotation: number,
graph: SceneGraph
): void {
- const abs = graph.getAbsolutePosition(node.id)
- const cx = (abs.x + node.width / 2) * r.zoom + r.panX
- const cy = (abs.y + node.height / 2) * r.zoom + r.panY
- const hw = (node.width / 2) * r.zoom
- const hh = (node.height / 2) * r.zoom
-
- canvas.save()
- if (rotation !== 0) {
- canvas.rotate(rotation, cx, cy)
- }
-
- canvas.drawRect(r.ck.LTRBRect(cx - hw, cy - hh, cx + hw, cy + hh), r.selectionPaint)
- canvas.restore()
+ withNodeBounds(r, canvas, node, rotation, graph, (x1, y1, x2, y2) => {
+ canvas.drawRect(r.ck.LTRBRect(x1, y1, x2, y2), r.selectionPaint)
+ })
}
export function drawGroupBounds(
@@ -383,16 +379,7 @@ export function getRotatedCorners(
const cy = (abs.y + n.height / 2) * r.zoom + r.panY
const hw = (n.width / 2) * r.zoom
const hh = (n.height / 2) * r.zoom
- const rad = (n.rotation * Math.PI) / 180
- const cos = Math.cos(rad)
- const sin = Math.sin(rad)
-
- return [
- { x: cx + -hw * cos - -hh * sin, y: cy + -hw * sin + -hh * cos },
- { x: cx + hw * cos - -hh * sin, y: cy + hw * sin + -hh * cos },
- { x: cx + hw * cos - hh * sin, y: cy + hw * sin + hh * cos },
- { x: cx + -hw * cos - hh * sin, y: cy + -hw * sin + hh * cos }
- ]
+ return rotatedCorners(cx, cy, hw, hh, n.rotation)
}
export function drawHandle(r: SkiaRenderer, canvas: Canvas, x: number, y: number): void {
@@ -447,18 +434,8 @@ export function drawFlashes(r: SkiaRenderer, canvas: Canvas, graph: SceneGraph):
if (r._flashes.length === 0) return
const now = performance.now()
- const ck = r.ck
const totalMs = FLASH_ATTACK_MS + FLASH_HOLD_MS + FLASH_RELEASE_MS
- if (!r._flashPaint) {
- r._flashPaint = new ck.Paint()
- r._flashPaint.setStyle(ck.PaintStyle.Stroke)
- r._flashPaint.setAntiAlias(true)
- }
-
- const paint = r._flashPaint
- const zoom = r.zoom
-
for (let i = r._flashes.length - 1; i >= 0; i--) {
const flash = r._flashes[i]
const elapsed = now - flash.startTime
@@ -467,18 +444,6 @@ export function drawFlashes(r: SkiaRenderer, canvas: Canvas, graph: SceneGraph):
continue
}
- const node = graph.getNode(flash.nodeId)
- if (!node) {
- r._flashes.splice(i, 1)
- continue
- }
-
- const abs = graph.getAbsolutePosition(flash.nodeId)
- const cx = (abs.x + node.width / 2) * zoom + r.panX
- const cy = (abs.y + node.height / 2) * zoom + r.panY
- const hw = (node.width / 2) * zoom
- const hh = (node.height / 2) * zoom
-
let opacity: number
let extraPad: number
@@ -496,22 +461,9 @@ export function drawFlashes(r: SkiaRenderer, canvas: Canvas, graph: SceneGraph):
extraPad = 0
}
- const pad = FLASH_PADDING + extraPad
- const rad = FLASH_RADIUS
-
- paint.setColor(ck.Color4f(FLASH_COLOR.r, FLASH_COLOR.g, FLASH_COLOR.b, opacity))
- paint.setStrokeWidth(FLASH_STROKE_WIDTH)
-
- canvas.save()
- if (node.rotation !== 0) canvas.rotate(node.rotation, cx, cy)
-
- const rect = ck.RRectXY(
- ck.LTRBRect(cx - hw - pad, cy - hh - pad, cx + hw + pad, cy + hh + pad),
- rad,
- rad
- )
- canvas.drawRRect(rect, paint)
- canvas.restore()
+ if (!drawNodeHighlightRect(r, canvas, graph, flash.nodeId, FLASH_COLOR, opacity, extraPad)) {
+ r._flashes.splice(i, 1)
+ }
}
}
diff --git a/packages/core/src/renderer/rulers.ts b/packages/core/src/renderer/rulers.ts
index 9d8434e33..41d9f3605 100644
--- a/packages/core/src/renderer/rulers.ts
+++ b/packages/core/src/renderer/rulers.ts
@@ -11,6 +11,7 @@ import {
RULER_TARGET_PIXEL_SPACING,
RULER_MAJOR_TOLERANCE
} from '../constants'
+import { computeAbsoluteBounds } from '../geometry'
import type { SceneNode, SceneGraph } from '../scene-graph'
import type { Canvas, CanvasKit } from 'canvaskit-wasm'
import type { SkiaRenderer } from './renderer'
@@ -27,22 +28,12 @@ function getSelectionScreenBounds(
graph: SceneGraph,
selNodes: SceneNode[]
): SelectionScreenBounds {
- let minX = Infinity,
- minY = Infinity,
- maxX = -Infinity,
- maxY = -Infinity
- for (const n of selNodes) {
- const abs = graph.getAbsolutePosition(n.id)
- minX = Math.min(minX, abs.x)
- minY = Math.min(minY, abs.y)
- maxX = Math.max(maxX, abs.x + n.width)
- maxY = Math.max(maxY, abs.y + n.height)
- }
+ const b = computeAbsoluteBounds(selNodes, (id) => graph.getAbsolutePosition(id))
return {
- sx1: minX * r.zoom + r.panX,
- sx2: maxX * r.zoom + r.panX,
- sy1: minY * r.zoom + r.panY,
- sy2: maxY * r.zoom + r.panY
+ sx1: b.x * r.zoom + r.panX,
+ sx2: (b.x + b.width) * r.zoom + r.panX,
+ sy1: b.y * r.zoom + r.panY,
+ sy2: (b.y + b.height) * r.zoom + r.panY
}
}
diff --git a/packages/core/src/tools/analyze.ts b/packages/core/src/tools/analyze.ts
index 7251fc4cf..88b9d3f07 100644
--- a/packages/core/src/tools/analyze.ts
+++ b/packages/core/src/tools/analyze.ts
@@ -9,6 +9,27 @@ import type { Color } from '../types'
import type { SceneNode } from '../scene-graph'
import type { FigmaAPI } from '../figma-api'
+interface SizedItem {
+ width: number
+ height: number
+ childCount: number
+}
+
+export function calcClusterConfidence(nodes: SizedItem[]): number {
+ if (nodes.length < 2) return 100
+ const base = nodes[0]
+ let score = 0
+ for (const n of nodes.slice(1)) {
+ const sizeDiff = Math.abs(n.width - base.width) + Math.abs(n.height - base.height)
+ const childDiff = Math.abs(n.childCount - base.childCount)
+ if (sizeDiff <= 4 && childDiff === 0) score++
+ else if (sizeDiff <= 10 && childDiff <= 1) score += 0.8
+ else if (sizeDiff <= 20 && childDiff <= 2) score += 0.6
+ else score += 0.4
+ }
+ return Math.round((score / (nodes.length - 1)) * 100)
+}
+
interface ColorEntry {
hex: string
color: Color
@@ -428,20 +449,7 @@ export const analyzeClusters = defineTool({
const widthRange = Math.max(...widths) - Math.min(...widths)
const heightRange = Math.max(...heights) - Math.min(...heights)
- let confidence = 100
- if (nodes.length >= 2) {
- const base = nodes[0]
- let score = 0
- for (const n of nodes.slice(1)) {
- const sizeDiff = Math.abs(n.width - base.width) + Math.abs(n.height - base.height)
- const childDiff = Math.abs(n.childCount - base.childCount)
- if (sizeDiff <= 4 && childDiff === 0) score++
- else if (sizeDiff <= 10 && childDiff <= 1) score += 0.8
- else if (sizeDiff <= 20 && childDiff <= 2) score += 0.6
- else score += 0.4
- }
- confidence = Math.round((score / (nodes.length - 1)) * 100)
- }
+ const confidence = calcClusterConfidence(nodes)
return {
signature,
diff --git a/packages/core/src/tools/index.ts b/packages/core/src/tools/index.ts
index d64560701..4104b93cc 100644
--- a/packages/core/src/tools/index.ts
+++ b/packages/core/src/tools/index.ts
@@ -4,3 +4,4 @@ export { defineTool, nodeToResult, nodeSummary, requireNode, NodeNotFoundError }
export type { ToolDef, ParamDef, ParamType } from './schema'
export { toolsToAI, buildDebugLog } from './ai-adapter'
export type { ToolLogEntry, ToolDebugLog, AIAdapterOptions, StepBudget } from './ai-adapter'
+export { calcClusterConfidence } from './analyze'
diff --git a/packages/core/src/tools/structure.ts b/packages/core/src/tools/structure.ts
index 68f439b7f..3114cdddb 100644
--- a/packages/core/src/tools/structure.ts
+++ b/packages/core/src/tools/structure.ts
@@ -193,7 +193,7 @@ export const nodeAncestors = defineTool({
let current = node.parent
let d = 0
while (current && (!args.depth || d < args.depth)) {
- ancestors.push({ id: current.id, name: current.name, type: current.type })
+ ancestors.push(nodeSummary(current))
current = current.parent
d++
}
@@ -212,7 +212,7 @@ export const nodeChildren = defineTool({
if (!node) return { error: `Node "${id}" not found` }
return {
id,
- children: node.children.map((c) => ({ id: c.id, name: c.name, type: c.type }))
+ children: node.children.map(nodeSummary)
}
}
})
diff --git a/packages/core/src/tools/vector.ts b/packages/core/src/tools/vector.ts
index 2f333983d..94632f034 100644
--- a/packages/core/src/tools/vector.ts
+++ b/packages/core/src/tools/vector.ts
@@ -1,5 +1,18 @@
import { defineTool, nodeSummary } from './schema'
+import type { FigmaAPI } from '../figma-api'
+import type { SceneNode, VectorNetwork } from '../scene-graph'
+
+function getVectorNode(
+ figma: FigmaAPI,
+ id: string
+): { node: SceneNode; vn: VectorNetwork } | { error: string } {
+ const node = figma.graph.getNode(id)
+ if (!node) return { error: `Node "${id}" not found` }
+ if (!node.vectorNetwork) return { error: `Node "${id}" has no vector data` }
+ return { node, vn: structuredClone(node.vectorNetwork) }
+}
+
const CHUNK_SIZE = 0x8000
function uint8ArrayToBase64(bytes: Uint8Array): string {
@@ -106,10 +119,9 @@ export const pathScale = defineTool({
factor: { type: 'number', description: 'Scale factor (e.g. 2 for double)', required: true }
},
execute: (figma, { id, factor }) => {
- const raw = figma.graph.getNode(id)
- if (!raw) return { error: `Node "${id}" not found` }
- if (!raw.vectorNetwork) return { error: `Node "${id}" has no vector data` }
- const vn = structuredClone(raw.vectorNetwork)
+ const result = getVectorNode(figma, id)
+ if ('error' in result) return result
+ const { node: raw, vn } = result
const cx = raw.width / 2
const cy = raw.height / 2
for (const v of vn.vertices) {
@@ -142,10 +154,9 @@ export const pathFlip = defineTool({
}
},
execute: (figma, { id, axis }) => {
- const raw = figma.graph.getNode(id)
- if (!raw) return { error: `Node "${id}" not found` }
- if (!raw.vectorNetwork) return { error: `Node "${id}" has no vector data` }
- const vn = structuredClone(raw.vectorNetwork)
+ const result = getVectorNode(figma, id)
+ if ('error' in result) return result
+ const { node: raw, vn } = result
const w = raw.width
const h = raw.height
for (const v of vn.vertices) {
@@ -174,10 +185,9 @@ export const pathMove = defineTool({
dy: { type: 'number', description: 'Y offset', required: true }
},
execute: (figma, { id, dx, dy }) => {
- const raw = figma.graph.getNode(id)
- if (!raw) return { error: `Node "${id}" not found` }
- if (!raw.vectorNetwork) return { error: `Node "${id}" has no vector data` }
- const vn = structuredClone(raw.vectorNetwork)
+ const result = getVectorNode(figma, id)
+ if ('error' in result) return result
+ const { vn } = result
for (const v of vn.vertices) {
v.x += dx
v.y += dy
diff --git a/src/ai/acp-transport.ts b/src/ai/acp-transport.ts
index 5e1e546f4..8b5d83e46 100644
--- a/src/ai/acp-transport.ts
+++ b/src/ai/acp-transport.ts
@@ -1,6 +1,7 @@
import { ClientSideConnection, ndJsonStream, PROTOCOL_VERSION } from '@agentclientprotocol/sdk'
import SYSTEM_PROMPT from '@/ai/system-prompt.md?raw'
+import { decodeTauriStderr } from '@/utils/tauri'
import { mapUpdate } from './acp-map-update'
@@ -219,11 +220,7 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
})
command.stderr.on('data', (raw: Uint8Array | number[] | string) => {
- const text =
- typeof raw === 'string'
- ? raw
- : new TextDecoder().decode(raw instanceof Uint8Array ? raw : new Uint8Array(raw))
- console.error(`[ACP ${this.agentDef.id}]`, text)
+ console.error(`[ACP ${this.agentDef.id}]`, decodeTauriStderr(raw))
})
command.on('close', () => {
diff --git a/src/automation/spawn-mcp.ts b/src/automation/spawn-mcp.ts
index 9651fd019..e3d2255b5 100644
--- a/src/automation/spawn-mcp.ts
+++ b/src/automation/spawn-mcp.ts
@@ -1,3 +1,4 @@
+import { decodeTauriStderr } from '@/utils/tauri'
import { AUTOMATION_HTTP_PORT, IS_TAURI } from '@open-pencil/core'
async function checkHealth(): Promise<boolean> {
@@ -28,11 +29,7 @@ export async function spawnMCPIfNeeded(): Promise<(() => void) | null> {
const command = Command.create('openpencil-mcp', [])
command.stderr.on('data', (raw: Uint8Array | number[] | string) => {
- const text =
- typeof raw === 'string'
- ? raw
- : new TextDecoder().decode(raw instanceof Uint8Array ? raw : new Uint8Array(raw))
- console.error('[MCP]', text)
+ console.error('[MCP]', decodeTauriStderr(raw))
})
command.on('close', (data: { code: number | null }) => {
diff --git a/src/stores/editor.ts b/src/stores/editor.ts
index 122311e29..350c8f29d 100644
--- a/src/stores/editor.ts
+++ b/src/stores/editor.ts
@@ -4,6 +4,7 @@ import { IS_TAURI, CANVAS_BG_COLOR } from '@/constants'
import { loadFont } from '@/engine/fonts'
import {
computeAllLayouts,
+ createDefaultEditorState,
createEditor,
exportFigFile,
readFigFile,
@@ -35,29 +36,7 @@ export function createEditorStore() {
cursorCanvasY: number | null
}
>({
- activeTool: 'SELECT',
- currentPageId: graph.getPages()[0].id,
- selectedIds: new Set<string>(),
- marquee: null,
- snapGuides: [],
- rotationPreview: null,
- dropTargetId: null,
- layoutInsertIndicator: null,
- hoveredNodeId: null,
- editingTextId: null,
- penState: null,
- penCursorX: null,
- penCursorY: null,
- remoteCursors: [],
- documentName: 'Untitled',
- panX: 0,
- pageColor: { ...CANVAS_BG_COLOR },
- panY: 0,
- zoom: 1,
- renderVersion: 0,
- sceneVersion: 0,
- loading: false,
- enteredContainerId: null,
+ ...createDefaultEditorState(graph.getPages()[0].id),
showUI: true,
activeRibbonTab: 'panels',
panelMode: 'design',
diff --git a/src/utils/tauri.ts b/src/utils/tauri.ts
new file mode 100644
index 000000000..68a67ebd8
--- /dev/null
+++ b/src/utils/tauri.ts
@@ -0,0 +1,4 @@
+export function decodeTauriStderr(raw: Uint8Array | number[] | string): string {
+ if (typeof raw === 'string') return raw
+ return new TextDecoder().decode(raw instanceof Uint8Array ? raw : new Uint8Array(raw))
+}