AI-native design editor. Open-source Figma alternative.
Extract @open-pencil/core package
Danila Poyarkov6d1cec16060c
diff --git a/bun.lock b/bun.lockindex 8218e2019..06c4bd56d 100644--- a/bun.lock+++ b/bun.lock@@ -5,6 +5,7 @@"": {"name": "open-pencil-app","dependencies": {+ "@open-pencil/core": "workspace:*","@tailwindcss/vite": "^4.2.1","@tauri-apps/api": "^2","@tauri-apps/plugin-dialog": "^2.6.0",@@ -36,6 +37,20 @@"vite": "^7.0.4",},},+ "packages/core": {+ "name": "@open-pencil/core",+ "version": "0.1.0",+ "dependencies": {+ "canvaskit-wasm": "^0.40.0",+ "culori": "^4.0.2",+ "fflate": "^0.8.2",+ "fzstd": "^0.1.1",+ "yoga-layout": "^3.2.1",+ },+ "devDependencies": {+ "@types/culori": "^4.0.1",+ },+ },},"packages": {"@antfu/install-pkg": ["@antfu/[email protected]", "", { "dependencies": { "package-manager-detector": "^1.3.0", "tinyexec": "^1.0.1" } }, "sha512-MGQsmw10ZyI+EJo45CdSER4zEb+p31LpDAFp2Z3gkSd1yqVZGi0Ebx++YTEMonJy4oChEMLsxZ64j8FH6sSqtQ=="],@@ -128,6 +143,8 @@"@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],+ "@open-pencil/core": ["@open-pencil/core@workspace:packages/core"],+"@oxfmt/binding-android-arm-eabi": ["@oxfmt/[email protected]", "", { "os": "android", "cpu": "arm" }, "sha512-BaRKlM3DyG81y/xWTsE6gZiv89F/3pHe2BqX2H4JbiB8HNVlWWtplzgATAE5IDSdwChdeuWLDTQzJ92Lglw3ZA=="],"@oxfmt/binding-android-arm64": ["@oxfmt/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-/O+EbuAJYs6nde/anv+aID6uHsGQApyE9JtYBo/79KyU8e6RBN3DMbT0ix97y1SOnCglurmL2iZ+hlohjP2PnQ=="],diff --git a/package.json b/package.jsonindex e63f9c49e..926d6f962 100644--- a/package.json+++ b/package.json@@ -3,6 +3,7 @@"private": true,"version": "0.1.0","type": "module",+ "workspaces": ["packages/*"],"scripts": {"dev": "vite","build": "tsc && vite build",@@ -24,6 +25,7 @@"@tauri-apps/plugin-dialog": "^2.6.0","@tauri-apps/plugin-fs": "^2.4.5","@tauri-apps/plugin-opener": "^2",+ "@open-pencil/core": "workspace:*","@vueuse/core": "^14.2.1","canvaskit-wasm": "^0.40.0","culori": "^4.0.2",diff --git a/packages/core/package.json b/packages/core/package.jsonnew file mode 100644index 000000000..f903eae41--- /dev/null+++ b/packages/core/package.json@@ -0,0 +1,18 @@+{+ "name": "@open-pencil/core",+ "version": "0.1.0",+ "type": "module",+ "exports": {+ ".": "./src/index.ts"+ },+ "dependencies": {+ "canvaskit-wasm": "^0.40.0",+ "culori": "^4.0.2",+ "fflate": "^0.8.2",+ "fzstd": "^0.1.1",+ "yoga-layout": "^3.2.1"+ },+ "devDependencies": {+ "@types/culori": "^4.0.1"+ }+}diff --git a/packages/core/src/canvaskit.ts b/packages/core/src/canvaskit.tsnew file mode 100644index 000000000..56833af08--- /dev/null+++ b/packages/core/src/canvaskit.ts@@ -0,0 +1,18 @@+import CanvasKitInit, { type CanvasKit } from 'canvaskit-wasm'++let instance: CanvasKit | null = null++export interface CanvasKitOptions {+ locateFile?: (file: string) => string+}++export async function getCanvasKit(options?: CanvasKitOptions): Promise<CanvasKit> {+ if (instance) return instance+ instance = await CanvasKitInit({+ locateFile: options?.locateFile ?? ((file) => {+ if (typeof window !== 'undefined') return `/${file}`+ return file+ })+ })+ return instance+}diff --git a/packages/core/src/clipboard.ts b/packages/core/src/clipboard.tsnew file mode 100644index 000000000..abf68f769--- /dev/null+++ b/packages/core/src/clipboard.ts@@ -0,0 +1,653 @@+import { inflateSync, deflateSync } from 'fflate'++import { initCodec, getCompiledSchema, getSchemaBytes } from './kiwi/codec'+import { decodeBinarySchema, compileSchema, ByteBuffer } from './kiwi/kiwi-schema'++import { decodeVectorNetworkBlob, encodeVectorNetworkBlob } from './vector'++import type {+ SceneGraph,+ SceneNode,+ Fill,+ Stroke,+ LayoutMode,+ LayoutSizing,+ LayoutAlign,+ LayoutCounterAlign,+ VectorNetwork+} from './scene-graph'+import type { NodeChange as KiwiNodeChange } from './kiwi/codec'++interface FigmaClipboardMeta {+ fileKey: string+ pasteID: number+ dataType: string+}++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 FIG_KIWI_VERSION = 106++ 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 = ''+ for (let i = 0; i < bytes.length; i++) {+ binary += String.fromCharCode(bytes[i])+ }+ return btoa(binary)+}++function base64ToBinary(b64: string): Uint8Array {+ const raw = atob(b64)+ const bytes = new Uint8Array(raw.length)+ for (let i = 0; i < raw.length; i++) {+ bytes[i] = raw.charCodeAt(i)+ }+ return bytes+}++// --- Paste from Figma ---++export async function parseFigmaClipboard(+ html: string+): 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++ 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 schemaBytes = inflateSync(parsed.schemaDeflated)+ const schema = decodeBinarySchema(new ByteBuffer(schemaBytes))+ const compiled = compileSchema(schema)+ 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, 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(+ nodeChanges: KiwiNodeChange[],+ graph: SceneGraph,+ targetParentId: string,+ offsetX = 0,+ offsetY = 0,+ blobs: Uint8Array[] = []+): string[] {+ const guidMap = new Map<string, KiwiNodeChange>()+ const parentMap = new Map<string, string>()+ for (const nc of nodeChanges) {+ if (!nc.guid) continue+ const id = `${nc.guid.sessionID}:${nc.guid.localID}`+ guidMap.set(id, nc)+ if (nc.parentIndex?.guid) {+ parentMap.set(id, `${nc.parentIndex.guid.sessionID}:${nc.parentIndex.guid.localID}`)+ }+ }++ const skipTypes = new Set(['DOCUMENT', 'CANVAS'])+ const topLevel: string[] = []+ for (const [id, nc] of guidMap) {+ if (skipTypes.has(nc.type ?? '')) continue+ const parentId = parentMap.get(id)+ if (!parentId || !guidMap.has(parentId) || skipTypes.has(guidMap.get(parentId)?.type ?? '')) {+ topLevel.push(id)+ }+ }++ const created = new Map<string, string>()+ const createdIds: string[] = []++ function createNode(figmaId: string, ourParentId: string) {+ if (created.has(figmaId)) return+ const nc = guidMap.get(figmaId)+ if (!nc) return++ const x = (nc.transform?.m02 ?? 0) + (ourParentId === targetParentId ? offsetX : 0)+ const y = (nc.transform?.m12 ?? 0) + (ourParentId === targetParentId ? offsetY : 0)++ let rotation = 0+ if (nc.transform) {+ rotation = Math.atan2(nc.transform.m10, nc.transform.m00) * (180 / Math.PI)+ }++ const fills: Fill[] = (nc.fillPaints ?? [])+ .filter((p) => p.type === 'SOLID' && p.color)+ .map((p) => ({+ type: 'SOLID' as const,+ color: p.color ?? { r: 0, g: 0, b: 0, a: 1 },+ opacity: p.opacity ?? 1,+ visible: p.visible ?? true+ }))++ const strokes: Stroke[] = (nc.strokePaints ?? [])+ .filter((p) => p.type === 'SOLID' && p.color)+ .map((p) => ({+ color: p.color ?? { r: 0, g: 0, b: 0, a: 1 },+ weight: nc.strokeWeight ?? 1,+ opacity: p.opacity ?? 1,+ visible: p.visible ?? true,+ align: 'CENTER' as const+ }))++ const nodeType = mapNodeType(nc.type)+ const node = graph.createNode(nodeType, ourParentId, {+ name: nc.name ?? nodeType,+ x,+ y,+ width: nc.size?.x ?? 100,+ height: nc.size?.y ?? 100,+ rotation,+ opacity: nc.opacity ?? 1,+ visible: nc.visible ?? true,+ fills,+ strokes,+ cornerRadius: nc.cornerRadius ?? 0,+ independentCorners: nc.rectangleCornerRadiiIndependent ?? false,+ topLeftRadius: nc.rectangleTopLeftCornerRadius ?? 0,+ topRightRadius: nc.rectangleTopRightCornerRadius ?? 0,+ bottomLeftRadius: nc.rectangleBottomLeftCornerRadius ?? 0,+ bottomRightRadius: nc.rectangleBottomRightCornerRadius ?? 0,+ text: nc.textData?.characters ?? '',+ fontSize: nc.fontSize ?? 14,+ fontFamily: nc.fontName?.family ?? 'Inter',+ textAlignHorizontal:+ (nc.textAlignHorizontal as 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED') ?? 'LEFT',+ layoutMode: mapLayoutMode(nc.stackMode as string),+ itemSpacing: (nc.stackSpacing as number) ?? 0,+ paddingTop: (nc.stackVerticalPadding as number) ?? (nc.stackPadding as number) ?? 0,+ paddingBottom:+ (nc.stackPaddingBottom as number) ??+ (nc.stackVerticalPadding as number) ??+ (nc.stackPadding as number) ??+ 0,+ paddingLeft: (nc.stackHorizontalPadding as number) ?? (nc.stackPadding as number) ?? 0,+ paddingRight:+ (nc.stackPaddingRight as number) ??+ (nc.stackHorizontalPadding as number) ??+ (nc.stackPadding as number) ??+ 0,+ primaryAxisSizing: mapSizing(nc.stackPrimarySizing as string),+ counterAxisSizing: mapSizing(nc.stackCounterSizing as string),+ primaryAxisAlign: mapPrimaryAlign(+ (nc.stackPrimaryAlignItems as string) ?? (nc.stackJustify as string)+ ),+ counterAxisAlign: mapCounterAlign(+ (nc.stackCounterAlignItems as string) ?? (nc.stackCounterAlign as string)+ ),+ 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,+ vectorNetwork: decodeVectorData(nc, blobs)+ })++ created.set(figmaId, node.id)+ if (ourParentId === targetParentId) createdIds.push(node.id)++ const children: string[] = []+ for (const [childId, pid] of parentMap) {+ if (pid === figmaId && !skipTypes.has(guidMap.get(childId)?.type ?? '')) {+ children.push(childId)+ }+ }+ children.sort((a, b) => {+ const aPos = guidMap.get(a)?.parentIndex?.position ?? ''+ const bPos = guidMap.get(b)?.parentIndex?.position ?? ''+ return aPos.localeCompare(bPos)+ })+ for (const childId of children) {+ createNode(childId, node.id)+ }+ }++ for (const id of topLevel) {+ createNode(id, targetParentId)+ }++ return createdIds+}++function mapLayoutMode(mode?: string): LayoutMode {+ if (mode === 'HORIZONTAL') return 'HORIZONTAL'+ if (mode === 'VERTICAL') return 'VERTICAL'+ return 'NONE'+}++function mapSizing(sizing?: string): LayoutSizing {+ if (sizing === 'RESIZE_TO_FIT' || sizing === 'RESIZE_TO_FIT_WITH_IMPLICIT_SIZE') return 'HUG'+ if (sizing === 'FILL') return 'FILL'+ return 'FIXED'+}++function mapPrimaryAlign(align?: string): LayoutAlign {+ if (align === 'CENTER') return 'CENTER'+ if (align === 'MAX') return 'MAX'+ if (align === 'SPACE_BETWEEN' || align === 'SPACE_EVENLY') return 'SPACE_BETWEEN'+ return 'MIN'+}++function mapCounterAlign(align?: string): LayoutCounterAlign {+ if (align === 'CENTER') return 'CENTER'+ if (align === 'MAX') return 'MAX'+ if (align === 'STRETCH') return 'STRETCH'+ if (align === 'BASELINE') return 'BASELINE'+ return 'MIN'+}++function mapNodeType(type?: string): SceneNode['type'] {+ switch (type) {+ case 'FRAME':+ return 'FRAME'+ case 'COMPONENT':+ return 'COMPONENT'+ case 'COMPONENT_SET':+ return 'COMPONENT_SET'+ case 'INSTANCE':+ return 'INSTANCE'+ case 'RECTANGLE':+ case 'ROUNDED_RECTANGLE':+ return 'RECTANGLE'+ case 'ELLIPSE':+ return 'ELLIPSE'+ case 'TEXT':+ return 'TEXT'+ case 'LINE':+ return 'LINE'+ case 'STAR':+ return 'STAR'+ case 'REGULAR_POLYGON':+ return 'POLYGON'+ case 'VECTOR':+ case 'BOOLEAN_OPERATION':+ return 'VECTOR'+ case 'GROUP':+ return 'GROUP'+ case 'SECTION':+ return 'SECTION'+ default:+ return 'RECTANGLE'+ }+}++// --- Copy to Figma-compatible fig-kiwi ---++function mapToFigmaType(type: SceneNode['type']): string {+ switch (type) {+ case 'FRAME':+ return 'FRAME'+ case 'RECTANGLE':+ return 'RECTANGLE'+ case 'ELLIPSE':+ return 'ELLIPSE'+ case 'TEXT':+ return 'TEXT'+ case 'LINE':+ return 'LINE'+ case 'STAR':+ return 'STAR'+ case 'POLYGON':+ return 'REGULAR_POLYGON'+ case 'VECTOR':+ return 'VECTOR'+ case 'GROUP':+ return 'FRAME'+ case 'SECTION':+ return 'SECTION'+ default:+ return 'RECTANGLE'+ }+}++function fractionalPosition(index: number): string {+ const base = '!'+ return String.fromCharCode(base.charCodeAt(0) + index)+}++function sceneNodeToKiwi(+ node: SceneNode,+ parentGuid: { sessionID: number; localID: number },+ childIndex: number,+ localIdCounter: { value: number },+ graph: SceneGraph,+ blobs: Uint8Array[]+): KiwiNodeChange[] {+ const localID = localIdCounter.value+++ const guid = { sessionID: 1, localID }+ const cos = Math.cos((node.rotation * Math.PI) / 180)+ const sin = Math.sin((node.rotation * Math.PI) / 180)++ const fillPaints = node.fills+ .filter((f) => f.type === 'SOLID')+ .map((f) => ({+ type: 'SOLID' as const,+ color: f.color,+ opacity: f.opacity,+ visible: f.visible,+ blendMode: 'NORMAL' as const+ }))++ const strokePaints = node.strokes+ .filter((s) => s.visible)+ .map((s) => ({+ type: 'SOLID' as const,+ color: s.color,+ opacity: s.opacity,+ visible: true,+ blendMode: 'NORMAL' as const+ }))++ const nc: KiwiNodeChange = {+ guid,+ parentIndex: { guid: parentGuid, position: fractionalPosition(childIndex) },+ type: mapToFigmaType(node.type),+ name: node.name,+ visible: node.visible,+ opacity: node.opacity,+ phase: 'CREATED',+ size: { x: node.width, y: node.height },+ transform: { m00: cos, m01: -sin, m02: node.x, m10: sin, m11: cos, m12: node.y },+ strokeWeight: node.strokes.length > 0 ? node.strokes[0].weight : 1,+ strokeAlign: 'INSIDE'+ }++ if (fillPaints.length > 0) nc.fillPaints = fillPaints+ if (strokePaints.length > 0) nc.strokePaints = strokePaints++ if (node.cornerRadius > 0) {+ nc.cornerRadius = node.cornerRadius+ nc.rectangleTopLeftCornerRadius = node.independentCorners+ ? node.topLeftRadius+ : node.cornerRadius+ nc.rectangleTopRightCornerRadius = node.independentCorners+ ? node.topRightRadius+ : node.cornerRadius+ nc.rectangleBottomLeftCornerRadius = node.independentCorners+ ? node.bottomLeftRadius+ : node.cornerRadius+ nc.rectangleBottomRightCornerRadius = node.independentCorners+ ? node.bottomRightRadius+ : node.cornerRadius+ }++ if (node.type === 'TEXT') {+ nc.fontSize = node.fontSize+ nc.fontName = { family: node.fontFamily, style: 'Regular', postscript: '' }+ nc.textData = {+ characters: node.text,+ lines: [+ {+ lineType: 'PLAIN',+ styleId: 0,+ indentationLevel: 0,+ sourceDirectionality: 'AUTO',+ listStartOffset: 0,+ isFirstLineOfList: false+ }+ ]+ }+ nc.textAutoResize = 'WIDTH_AND_HEIGHT'+ nc.textAlignHorizontal = node.textAlignHorizontal+ }++ if (node.type === 'FRAME' || node.type === 'GROUP') {+ nc.frameMaskDisabled = node.type === 'GROUP'+ }++ if (node.layoutMode !== 'NONE') {+ nc.stackMode = node.layoutMode+ nc.stackSpacing = node.itemSpacing+ nc.stackVerticalPadding = node.paddingTop+ nc.stackHorizontalPadding = node.paddingLeft+ nc.stackPaddingBottom = node.paddingBottom+ nc.stackPaddingRight = node.paddingRight+ nc.stackPrimarySizing = node.primaryAxisSizing === 'HUG' ? 'RESIZE_TO_FIT' : 'FIXED'+ nc.stackCounterSizing =+ node.counterAxisSizing === 'HUG' ? 'RESIZE_TO_FIT_WITH_IMPLICIT_SIZE' : undefined+ }++ if (node.layoutPositioning === 'ABSOLUTE') {+ nc.stackPositioning = 'ABSOLUTE'+ }+ if (node.layoutGrow > 0) {+ 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, blobs))+ }++ return result+}++export function buildFigmaClipboardHTML(nodes: SceneNode[], graph: SceneGraph): string | null {+ const compiled = getCompiledSchema()+ const schemaDeflated = deflateSync(getSchemaBytes())++ const docGuid = { sessionID: 0, localID: 0 }+ const canvasGuid = { sessionID: 0, localID: 1 }+ 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 }+ }+ ]++ const blobs: Uint8Array[] = []+ for (let i = 0; i < nodes.length; i++) {+ nodeChanges.push(...sceneNodeToKiwi(nodes[i], canvasGuid, i, localIdCounter, graph, blobs))+ }++ const msg: Record<string, unknown> = {+ type: 'NODE_CHANGES',+ sessionID: 0,+ ackID: 0,+ pasteID: Math.floor(Math.random() * 2147483647),+ pasteFileKey: 'openpencil',+ 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 as number,+ dataType: 'scene'+ }+ const metaB64 = btoa(JSON.stringify(meta))++ return (+ `<meta charset='utf-8'>` ++ `<span data-metadata="<!--(figmeta)${metaB64}(/figmeta)-->"></span>` ++ `<span data-buffer="<!--(figma)${bufferB64}(/figma)-->"></span>`+ )+}++// --- Internal copy/paste (OpenPencil ↔ OpenPencil) ---++export function parseOpenPencilClipboard(+ html: string+): Array<SceneNode & { children?: SceneNode[] }> | null {+ const match = html.match(/<!--\(openpencil\)(.*?)\(\/openpencil\)-->/s)+ if (!match) return null++ try {+ const decoded = JSON.parse(atob(match[1]))+ if (decoded.format === 'openpencil/v1' && Array.isArray(decoded.nodes)) {+ return decoded.nodes+ }+ } catch {+ // Not our format+ }+ return null+}++export function buildOpenPencilClipboardHTML(nodes: SceneNode[], graph: SceneGraph): string {+ const data = {+ format: 'openpencil/v1',+ nodes: collectNodeTree(nodes, graph)+ }+ return `<!--(openpencil)${btoa(JSON.stringify(data))}(/openpencil)-->`+}++function collectNodeTree(+ nodes: SceneNode[],+ graph: SceneGraph+): Array<SceneNode & { children?: SceneNode[] }> {+ return nodes.map((node) => {+ const children = graph.getChildren(node.id)+ return {+ ...node,+ children: children.length > 0 ? collectNodeTree(children, graph) : undefined+ }+ })+}diff --git a/packages/core/src/color.ts b/packages/core/src/color.tsnew file mode 100644index 000000000..b0abd006d--- /dev/null+++ b/packages/core/src/color.ts@@ -0,0 +1,48 @@+import { parse, formatHex, converter } from 'culori'++import type { Color } from './types'++const toRgb = converter('rgb')++export function parseColor(input: string): Color {+ const parsed = parse(input)+ if (!parsed) return { r: 0, g: 0, b: 0, a: 1 }+ const rgb = toRgb(parsed)+ return {+ r: rgb?.r ?? 0,+ g: rgb?.g ?? 0,+ b: rgb?.b ?? 0,+ a: parsed.alpha ?? 1+ }+}++export function colorToHex(color: Color): string {+ return (formatHex({ mode: 'rgb', r: color.r, g: color.g, b: color.b }) ?? '#000000').toUpperCase()+}++export function colorToHexRaw(color: Color): string {+ return colorToHex(color).slice(1)+}++export function colorToRgba255(color: Color) {+ return {+ r: Math.round(color.r * 255),+ g: Math.round(color.g * 255),+ b: Math.round(color.b * 255),+ a: color.a+ }+}++export function rgba255ToColor(rgba: { r: number; g: number; b: number; a: number }): Color {+ return { r: rgba.r / 255, g: rgba.g / 255, b: rgba.b / 255, a: rgba.a }+}++export function colorToFill(color: string | Color) {+ const rgba = typeof color === 'string' ? parseColor(color) : color+ return {+ type: 'SOLID' as const,+ color: { r: rgba.r, g: rgba.g, b: rgba.b, a: rgba.a },+ opacity: rgba.a,+ visible: true+ }+}diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.tsnew file mode 100644index 000000000..392ef04d1--- /dev/null+++ b/packages/core/src/constants.ts@@ -0,0 +1,70 @@+import type { Color } from './types'++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 COMPONENT_COLOR = { r: 0.592, g: 0.278, b: 1, a: 1 } satisfies Color+export const SNAP_COLOR = { r: 1.0, g: 0.0, b: 0.56, a: 1 } satisfies Color+export const CANVAS_BG_COLOR = { r: 0.96, g: 0.96, b: 0.96, a: 1 } satisfies Color++export const ROTATION_HANDLE_OFFSET = 20+export const SNAP_THRESHOLD = 5++export const RULER_SIZE = 20+export const RULER_BG_COLOR = { r: 0.14, g: 0.14, b: 0.14, a: 1 } satisfies Color+export const RULER_TICK_COLOR = { r: 0.4, g: 0.4, b: 0.4, a: 1 } satisfies Color+export const RULER_TEXT_COLOR = { r: 0.55, g: 0.55, b: 0.55, a: 1 } satisfies Color+export const RULER_BADGE_HEIGHT = 14+export const RULER_BADGE_PADDING = 3+export const RULER_BADGE_RADIUS = 2+export const RULER_BADGE_EXCLUSION = 30+export const RULER_TEXT_BASELINE = 0.65+export const RULER_MAJOR_TICK = 0.5+export const RULER_MINOR_TICK = 0.25+export const RULER_HIGHLIGHT_ALPHA = 0.3++export const PEN_HANDLE_RADIUS = 3+export const PEN_VERTEX_RADIUS = 4+export const PEN_CLOSE_RADIUS_BOOST = 2+export const PEN_PATH_STROKE_WIDTH = 2+export const PARENT_OUTLINE_ALPHA = 0.5+export const PARENT_OUTLINE_DASH = 4+export const DEFAULT_FONT_SIZE = 14+export const LABEL_FONT_SIZE = 11+export const SIZE_FONT_SIZE = 10++export const ROTATION_HANDLE_RADIUS = 4++export const HANDLE_HALF_SIZE = 3++export const LABEL_OFFSET_Y = 8+export const SIZE_PILL_PADDING_X = 6+export const SIZE_PILL_PADDING_Y = 6+export const SIZE_PILL_HEIGHT = 18+export const SIZE_PILL_RADIUS = 4+export const SIZE_PILL_TEXT_OFFSET_Y = 13++export const MARQUEE_FILL_ALPHA = 0.08+export const SELECTION_DASH_ALPHA = 0.6+export const DROP_HIGHLIGHT_ALPHA = 0.8+export const DROP_HIGHLIGHT_STROKE = 2++export const LAYOUT_INDICATOR_STROKE = 2++export const SECTION_CORNER_RADIUS = 5+export const SECTION_TITLE_HEIGHT = 24+export const SECTION_TITLE_PADDING_X = 8+export const SECTION_TITLE_RADIUS = 5+export const SECTION_TITLE_FONT_SIZE = 12+export const SECTION_TITLE_GAP = 6++export const COMPONENT_SET_DASH = 6+export const COMPONENT_SET_DASH_GAP = 4+export const COMPONENT_SET_BORDER_WIDTH = 1.5+export const COMPONENT_LABEL_FONT_SIZE = 11+export const COMPONENT_LABEL_GAP = 6+export const COMPONENT_LABEL_ICON_SIZE = 10+export const COMPONENT_LABEL_ICON_GAP = 4++export const RULER_TARGET_PIXEL_SPACING = 100+export const RULER_MAJOR_TOLERANCE = 0.01diff --git a/packages/core/src/fig-export.ts b/packages/core/src/fig-export.tsnew file mode 100644index 000000000..ffa2f36a2--- /dev/null+++ b/packages/core/src/fig-export.ts@@ -0,0 +1,337 @@+import { zipSync, deflateSync } from 'fflate'++import { IS_TAURI } from './constants'+import { initCodec, getCompiledSchema, getSchemaBytes } from './kiwi/codec'++import { renderThumbnail } from './render-image'+import { encodeVectorNetworkBlob } from './vector'++import type { SkiaRenderer } from './renderer'+import type { SceneGraph, SceneNode } from './scene-graph'+import type { NodeChange, Paint } from './kiwi/codec'+import type { CanvasKit } from 'canvaskit-wasm'++const THUMBNAIL_1X1 = Uint8Array.from(+ atob(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=='+ ),+ (c) => c.charCodeAt(0)+)++type KiwiNodeChange = NodeChange & Record<string, unknown>++function mapToFigmaType(type: SceneNode['type']): string {+ switch (type) {+ case 'FRAME':+ return 'FRAME'+ case 'RECTANGLE':+ return 'RECTANGLE'+ case 'ROUNDED_RECTANGLE':+ return 'ROUNDED_RECTANGLE'+ case 'ELLIPSE':+ return 'ELLIPSE'+ case 'TEXT':+ return 'TEXT'+ case 'LINE':+ return 'LINE'+ case 'STAR':+ return 'STAR'+ case 'POLYGON':+ return 'REGULAR_POLYGON'+ case 'VECTOR':+ return 'VECTOR'+ case 'GROUP':+ return 'FRAME'+ case 'SECTION':+ return 'SECTION'+ case 'COMPONENT':+ return 'COMPONENT'+ case 'COMPONENT_SET':+ return 'COMPONENT_SET'+ case 'INSTANCE':+ return 'INSTANCE'+ case 'CONNECTOR':+ return 'CONNECTOR'+ case 'SHAPE_WITH_TEXT':+ return 'SHAPE_WITH_TEXT'+ default:+ return 'RECTANGLE'+ }+}++function fractionalPosition(index: number): string {+ return String.fromCharCode('!'.charCodeAt(0) + index)+}++function sceneNodeToKiwi(+ node: SceneNode,+ parentGuid: { sessionID: number; localID: number },+ childIndex: number,+ localIdCounter: { value: number },+ graph: SceneGraph,+ blobs: Uint8Array[]+): KiwiNodeChange[] {+ const localID = localIdCounter.value+++ const guid = { sessionID: 1, localID }+ const cos = Math.cos((node.rotation * Math.PI) / 180)+ const sin = Math.sin((node.rotation * Math.PI) / 180)++ const fillPaints = node.fills.map((f) => {+ const paint: Paint = {+ type: f.type,+ color: f.color,+ opacity: f.opacity,+ visible: f.visible,+ blendMode: f.blendMode ?? 'NORMAL'+ }+ if (f.gradientStops) {+ paint.stops = f.gradientStops.map((s) => ({ color: s.color, position: s.position }))+ }+ if (f.gradientTransform) paint.transform = f.gradientTransform+ if (f.imageHash) paint.image = { hash: f.imageHash }+ if (f.imageScaleMode) paint.imageScaleMode = f.imageScaleMode+ if (f.imageTransform) paint.transform = f.imageTransform+ return paint+ })++ const strokePaints = node.strokes.map((s) => ({+ type: 'SOLID' as const,+ color: s.color,+ opacity: s.opacity,+ visible: s.visible,+ blendMode: 'NORMAL' as const+ }))++ const nc: KiwiNodeChange = {+ guid,+ parentIndex: { guid: parentGuid, position: fractionalPosition(childIndex) },+ type: mapToFigmaType(node.type),+ name: node.name,+ visible: node.visible,+ opacity: node.opacity,+ phase: 'CREATED',+ size: { x: node.width, y: node.height },+ transform: { m00: cos, m01: -sin, m02: node.x, m10: sin, m11: cos, m12: node.y },+ strokeWeight: node.strokes.length > 0 ? node.strokes[0].weight : 1,+ strokeAlign: 'INSIDE'+ }++ if (fillPaints.length > 0) nc.fillPaints = fillPaints+ if (strokePaints.length > 0) nc.strokePaints = strokePaints++ if (node.cornerRadius > 0 || node.independentCorners) {+ nc.cornerRadius = node.cornerRadius+ nc.rectangleCornerRadiiIndependent = node.independentCorners+ nc.rectangleTopLeftCornerRadius = node.independentCorners+ ? node.topLeftRadius+ : node.cornerRadius+ nc.rectangleTopRightCornerRadius = node.independentCorners+ ? node.topRightRadius+ : node.cornerRadius+ nc.rectangleBottomLeftCornerRadius = node.independentCorners+ ? node.bottomLeftRadius+ : node.cornerRadius+ nc.rectangleBottomRightCornerRadius = node.independentCorners+ ? node.bottomRightRadius+ : node.cornerRadius+ }++ if (node.cornerSmoothing > 0) {+ nc.cornerSmoothing = node.cornerSmoothing+ }++ if (node.effects.length > 0) {+ nc.effects = node.effects.map((e) => ({+ type: e.type,+ color: e.color,+ offset: e.offset,+ radius: e.radius,+ spread: e.spread,+ visible: e.visible+ }))+ }++ if (node.type === 'TEXT') {+ nc.fontSize = node.fontSize+ nc.fontName = {+ family: node.fontFamily,+ style: node.fontWeight >= 700 ? 'Bold' : 'Regular',+ postscript: ''+ }+ nc.textData = { characters: node.text }+ nc.textAutoResize = 'WIDTH_AND_HEIGHT'+ nc.textAlignHorizontal = node.textAlignHorizontal+ if (node.lineHeight != null) nc.lineHeight = { value: node.lineHeight, units: 'PIXELS' }+ if (node.letterSpacing !== 0) nc.letterSpacing = { value: node.letterSpacing, units: 'PIXELS' }+ }++ if (node.type === 'FRAME' || node.type === 'GROUP') {+ nc.frameMaskDisabled = node.type === 'GROUP'+ if (node.clipsContent) nc.clipsContent = true+ }++ if (node.layoutMode !== 'NONE') {+ nc.stackMode = node.layoutMode+ nc.stackSpacing = node.itemSpacing+ nc.stackVerticalPadding = node.paddingTop+ nc.stackHorizontalPadding = node.paddingLeft+ nc.stackPaddingBottom = node.paddingBottom+ nc.stackPaddingRight = node.paddingRight+ nc.stackPrimarySizing = node.primaryAxisSizing === 'HUG' ? 'RESIZE_TO_FIT' : 'FIXED'+ nc.stackCounterSizing = node.counterAxisSizing === 'HUG' ? 'RESIZE_TO_FIT' : 'FIXED'+ nc.stackPrimaryAlignItems = node.primaryAxisAlign+ nc.stackCounterAlignItems = node.counterAxisAlign+ if (node.layoutWrap === 'WRAP') nc.stackWrap = 'WRAP'+ if (node.counterAxisSpacing > 0) nc.stackCounterSpacing = node.counterAxisSpacing+ }++ if (node.layoutPositioning === 'ABSOLUTE') nc.stackPositioning = 'ABSOLUTE'+ if (node.layoutGrow > 0) 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, blobs))+ }++ return result+}++function buildFigKiwi(schemaDeflated: Uint8Array, dataCompressed: Uint8Array): Uint8Array {+ const FIG_KIWI_VERSION = 106+ 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++export async function exportFigFile(+ graph: SceneGraph,+ ck?: CanvasKit,+ renderer?: SkiaRenderer,+ pageId?: string+): Promise<Uint8Array> {+ await initCodec()+ const compiled = getCompiledSchema()+ const schemaDeflated = deflateSync(getSchemaBytes())++ 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 blobs: Uint8Array[] = []+ const pages = graph.getPages()++ for (let p = 0; p < pages.length; p++) {+ const page = pages[p]+ const canvasLocalID = localIdCounter.value+++ const canvasGuid = { sessionID: 0, localID: canvasLocalID }++ nodeChanges.push({+ 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',+ backgroundOpacity: 1,+ backgroundColor: { r: 0.96, g: 0.96, b: 0.96, a: 1 },+ backgroundEnabled: true+ })++ const children = graph.getChildren(page.id)+ for (let i = 0; i < children.length; i++) {+ nodeChanges.push(...sceneNodeToKiwi(children[i], canvasGuid, i, localIdCounter, graph, blobs))+ }+ }++ const msg: Record<string, unknown> = {+ type: 'NODE_CHANGES',+ sessionID: 0,+ ackID: 0,+ nodeChanges+ }++ if (blobs.length > 0) {+ msg.blobs = blobs.map((bytes) => ({ bytes }))+ }++ const kiwiData = compiled.encodeMessage(msg)++ const currentPageId = pageId ?? pages[0]?.id+ const thumbnailPng =+ (ck && renderer && currentPageId+ ? renderThumbnail(ck, renderer, graph, currentPageId, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT)+ : null) ?? THUMBNAIL_1X1++ const metaJson = JSON.stringify({+ version: 1,+ app: 'OpenPencil',+ createdAt: new Date().toISOString()+ })++ if (IS_TAURI) {+ const { invoke } = await import('@tauri-apps/api/core')+ return new Uint8Array(+ await invoke<number[]>('build_fig_file', {+ schemaDeflated: Array.from(schemaDeflated),+ kiwiData: Array.from(kiwiData),+ thumbnailPng: Array.from(thumbnailPng),+ metaJson+ })+ )+ }++ const canvasData = buildFigKiwi(schemaDeflated, deflateSync(kiwiData))+ return zipSync({+ 'canvas.fig': [canvasData, { level: 0 }],+ 'thumbnail.png': [thumbnailPng, { level: 0 }],+ 'meta.json': new TextEncoder().encode(metaJson)+ })+}diff --git a/packages/core/src/fonts.ts b/packages/core/src/fonts.tsnew file mode 100644index 000000000..bce9df6cb--- /dev/null+++ b/packages/core/src/fonts.ts@@ -0,0 +1,145 @@+import type { CanvasKit, TypefaceFontProvider } from 'canvaskit-wasm'++export interface FontInfo {+ family: string+ fullName: string+ style: string+ postscriptName: string+}++const loadedFamilies = new Map<string, ArrayBuffer>()+let fontProvider: TypefaceFontProvider | null = null++export function initFontService(_canvasKit: CanvasKit, provider: TypefaceFontProvider) {+ fontProvider = provider+}++export function getFontProvider(): TypefaceFontProvider | null {+ return fontProvider+}++export async function queryFonts(): Promise<FontInfo[]> {+ if (!window.queryLocalFonts) return []+ try {+ const fonts = await window.queryLocalFonts()+ const seen = new Set<string>()+ const result: FontInfo[] = []+ for (const f of fonts) {+ const key = `${f.family}|${f.style}`+ if (seen.has(key)) continue+ seen.add(key)+ result.push({+ family: f.family,+ fullName: f.fullName,+ style: f.style,+ postscriptName: f.postscriptName+ })+ }+ return result+ } catch {+ return []+ }+}++export async function listFamilies(): Promise<string[]> {+ const fonts = await queryFonts()+ return [...new Set(fonts.map((f) => f.family))].sort()+}++const BUNDLED_FONTS: Record<string, string> = {+ 'Inter|Regular': '/Inter-Regular.ttf'+}++export async function loadFont(family: string, style = 'Regular'): Promise<ArrayBuffer | null> {+ const cacheKey = `${family}|${style}`+ if (loadedFamilies.has(cacheKey)) {+ const cached = loadedFamilies.get(cacheKey)+ if (!cached) return null+ registerFontInCanvasKit(family, cached)+ return cached+ }++ // Try local font access API first+ if (window.queryLocalFonts) {+ try {+ const fonts = await window.queryLocalFonts()+ const match =+ fonts.find((f: FontInfo) => f.family === family && f.style === style) ??+ fonts.find((f: FontInfo) => f.family === family)+ if (match) {+ const blob: Blob = await match.blob()+ const buffer = await blob.arrayBuffer()++ loadedFamilies.set(cacheKey, buffer)+ registerFontInCanvasKit(family, buffer)+ registerFontInBrowser(family, style, buffer)+ return buffer+ }+ } catch {+ /* fall through to bundled */+ }+ }++ // Fall back to bundled font+ const bundledUrl = BUNDLED_FONTS[cacheKey]+ if (bundledUrl) {+ try {+ const response = await fetch(bundledUrl)+ const buffer = await response.arrayBuffer()++ loadedFamilies.set(cacheKey, buffer)+ registerFontInCanvasKit(family, buffer)+ registerFontInBrowser(family, style, buffer)+ return buffer+ } catch {+ /* no bundled font available */+ }+ }++ return null+}++function registerFontInCanvasKit(family: string, data: ArrayBuffer) {+ if (!fontProvider) return+ fontProvider.registerFont(data, family)+}++function registerFontInBrowser(family: string, style: string, data: ArrayBuffer) {+ const weight = styleToWeight(style)+ const italic = style.toLowerCase().includes('italic') ? 'italic' : 'normal'+ const face = new FontFace(family, data, {+ weight: String(weight),+ style: italic+ })+ face.load().then(() => document.fonts.add(face))+}++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+}++export async function ensureNodeFont(family: string, weight: number): Promise<void> {+ const style = weightToStyle(weight)+ await loadFont(family, style)+}++function weightToStyle(weight: number): string {+ if (weight <= 100) return 'Thin'+ if (weight <= 200) return 'ExtraLight'+ if (weight <= 300) return 'Light'+ if (weight <= 400) return 'Regular'+ if (weight <= 500) return 'Medium'+ if (weight <= 600) return 'SemiBold'+ if (weight <= 700) return 'Bold'+ if (weight <= 800) return 'ExtraBold'+ return 'Black'+}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsnew file mode 100644index 000000000..ce8f2aa60--- /dev/null+++ b/packages/core/src/index.ts@@ -0,0 +1,75 @@+export type {+ GUID,+ Color,+ Vector,+ Matrix,+ Rect+} from './types'++export * from './constants'++export {+ SceneGraph,+ type SceneNode,+ type NodeType,+ type Fill,+ type FillType,+ type Stroke,+ type StrokeCap,+ type StrokeJoin,+ type Effect,+ type BlendMode,+ type ImageScaleMode,+ type GradientStop,+ type GradientTransform,+ type LayoutMode,+ type LayoutSizing,+ type LayoutAlign,+ type LayoutCounterAlign,+ type LayoutWrap,+ type ConstraintType,+ type TextAutoResize,+ type TextAlignVertical,+ type TextCase,+ type TextDecoration,+ type ArcData,+ type VectorNetwork,+ type VectorVertex,+ type VectorSegment,+ type VectorRegion,+ type HandleMirroring,+ type WindingRule+} from './scene-graph'++export { SkiaRenderer, type RenderOverlays } from './renderer'+export { computeLayout, computeAllLayouts } from './layout'+export { getCanvasKit, type CanvasKitOptions } from './canvaskit'+export { loadFont, listFamilies } from './fonts'+export { parseColor, colorToHex, colorToHexRaw, colorToRgba255 } from './color'+export { vectorNetworkToPath, decodeVectorNetworkBlob, encodeVectorNetworkBlob, computeVectorBounds } from './vector'+export { computeSelectionBounds, computeSnap, type SnapGuide } from './snap'+export { UndoManager } from './undo'+export { renderNodesToImage, renderThumbnail, type ExportFormat } from './render-image'+export { exportFigFile } from './fig-export'+export {+ parseFigmaClipboard,+ importClipboardNodes,+ parseOpenPencilClipboard,+ buildFigmaClipboardHTML,+ buildOpenPencilClipboardHTML,+ prefetchFigmaSchema+} from './clipboard'++export { readFigFile } from './kiwi/fig-file'+export { importNodeChanges } from './kiwi/fig-import'+export {+ initCodec,+ encodeMessage,+ decodeMessage,+ getCompiledSchema,+ getSchemaBytes,+ type NodeChange,+ type Paint as KiwiPaint,+ type Effect as KiwiEffect,+ type FigmaMessage+} from './kiwi/codec'diff --git a/packages/core/src/kiwi/codec.ts b/packages/core/src/kiwi/codec.tsnew file mode 100644index 000000000..68116b8bc--- /dev/null+++ b/packages/core/src/kiwi/codec.ts@@ -0,0 +1,557 @@+/**+ * Message Encoding/Decoding for Figma Multiplayer+ *+ * Uses:+ * - kiwi-schema: Binary serialization (by Evan Wallace, Figma co-founder)+ * - fzstd: Browser-compatible Zstd decompression+ */++import { decompress as zstdDecompress } from 'fzstd'++import { parseColor } from '../color'++import { compileSchema, encodeBinarySchema } from './kiwi-schema'+import { isZstdCompressed, getKiwiMessageType } from './protocol.ts'+import figmaSchema from './schema.ts'++import type { Schema } from './kiwi-schema'++interface CompiledSchema {+ encodeMessage(message: unknown): Uint8Array+ decodeMessage(data: Uint8Array): unknown+ encodePaint(paint: unknown): Uint8Array+ encodeNodeChange(nodeChange: unknown): Uint8Array+}++let compiledSchema: CompiledSchema | null = null++/**+ * Initialize the codec (compiles Kiwi schema)+ */+export async function initCodec(): Promise<void> {+ if (compiledSchema) return+ 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+ */+export function isCodecReady(): boolean {+ return compiledSchema !== null+}++/**+ * Compress data using Zstd (Bun native)+ */+export function compress(data: Uint8Array): Uint8Array {+ return data+}++/**+ * Decompress Zstd data (Bun native)+ */+export function decompress(data: Uint8Array): Uint8Array {+ if (!isZstdCompressed(data)) return data+ return zstdDecompress(data)+}++/**+ * Encode a message for sending to Figma+ * Handles variable bindings in fillPaints which require custom encoding+ */+export function encodeMessage(message: FigmaMessage): Uint8Array {+ if (!compiledSchema) {+ throw new Error('Codec not initialized. Call initCodec() first.')+ }++ // Check if any nodeChange has variable bindings (fill or stroke)+ const hasVariables = message.nodeChanges?.some(+ (nc) =>+ nc.fillPaints?.some((p) => p.colorVariableBinding) ||+ nc.strokePaints?.some((p) => p.colorVariableBinding)+ )++ if (!hasVariables) {+ // Standard encoding+ const encoded = compiledSchema.encodeMessage(message)+ return compress(encoded)+ }++ // Need custom encoding for variable bindings+ // Strategy: encode each nodeChange separately, then combine+ const messageWithoutNodes = { ...message, nodeChanges: [] }+ const baseEncoded = compiledSchema.encodeMessage(messageWithoutNodes)+ const baseHex = Buffer.from(baseEncoded).toString('hex')++ // Encode nodeChanges with variable support+ const nodeChangeBytes: Uint8Array[] = []+ for (const nc of message.nodeChanges || []) {+ const encoded = encodeNodeChangeWithVariables(nc)+ nodeChangeBytes.push(encoded)+ }++ // Combine: base message + nodeChanges+ // Message structure: type, sessionID, ackID, reconnectSeqNum, nodeChanges[]+ // nodeChanges is field 5++ // Message structure in kiwi:+ // - Field 1 (type): enum MessageType+ // - Field 2 (sessionID): uint+ // - Field 3 (ackID): uint+ // - Field 4 (nodeChanges): NodeChange[] - this is what we need to replace+ // - Field 25 (reconnectSequenceNumber): uint+ //+ // Empty array: "04 00" (field 4, length 0)+ // We need to replace "04 00" with "04 <count> <nodes>"++ const emptyArrayPattern = '0400' // field 4, length 0+ const emptyArrayIdx = baseHex.indexOf(emptyArrayPattern)++ if (emptyArrayIdx === -1) {+ // Fallback to standard encoding+ const encoded = compiledSchema.encodeMessage(message)+ return compress(encoded)+ }++ // Build nodeChanges array with our encoded nodes+ const ncBytes: number[] = [0x04] // field 4+ ncBytes.push(...encodeVarint(nodeChangeBytes.length)) // array length+ for (const ncArr of nodeChangeBytes) {+ ncBytes.push(...Array.from(ncArr))+ }++ // Replace "0400" with our nodeChanges+ const beforeArray = baseHex.slice(0, emptyArrayIdx)+ const afterArray = baseHex.slice(emptyArrayIdx + 4) // skip "0400"++ const ncHex = Buffer.from(ncBytes).toString('hex')+ const finalHex = beforeArray + ncHex + afterArray++ const finalBytes = new Uint8Array(finalHex.match(/.{2}/g)?.map((b) => parseInt(b, 16)) ?? [])+ return compress(finalBytes)+}++/**+ * Decode a message received from Figma+ */+export function decodeMessage(data: Uint8Array): FigmaMessage {+ if (!compiledSchema) {+ throw new Error('Codec not initialized. Call initCodec() first.')+ }++ const decompressed = decompress(data)+ return compiledSchema.decodeMessage(decompressed) as FigmaMessage+}++/**+ * Quick peek at message type without full decoding+ */+export function peekMessageType(data: Uint8Array): number | null {+ try {+ const decompressed = decompress(data)+ return getKiwiMessageType(decompressed)+ } catch {+ return null+ }+}++// Type definitions++export type { GUID, Color } from '../types'++import type { Color, GUID, Matrix, Vector } from '../types'++export type { Matrix, Vector }++export interface ParentIndex {+ guid: GUID+ position: string+}++export interface VariableBinding {+ variableID: GUID+}++export interface Paint {+ type:+ | 'SOLID'+ | 'GRADIENT_LINEAR'+ | 'GRADIENT_RADIAL'+ | 'GRADIENT_ANGULAR'+ | 'GRADIENT_DIAMOND'+ | 'IMAGE'+ color?: Color+ opacity?: number+ visible?: boolean+ blendMode?: string+ stops?: { color: Color; position: number }[]+ transform?: { m00: number; m01: number; m02: number; m10: number; m11: number; m12: number }+ image?: { hash: string }+ imageScaleMode?: string+ colorVariableBinding?: VariableBinding+}++export interface Effect {+ type: 'DROP_SHADOW' | 'INNER_SHADOW' | 'LAYER_BLUR' | 'BACKGROUND_BLUR' | 'FOREGROUND_BLUR'+ color?: Color+ offset?: Vector+ radius?: number+ visible?: boolean+ spread?: number+ blendMode?: string+}++export interface NodeChange {+ guid: GUID+ phase?: 'CREATED' | 'REMOVED'+ parentIndex?: ParentIndex+ type?: string+ name?: string+ visible?: boolean+ locked?: boolean+ opacity?: number+ blendMode?: string+ size?: Vector+ transform?: Matrix+ cornerRadius?: number+ fillPaints?: Paint[]+ strokePaints?: Paint[]+ strokeWeight?: number+ strokeAlign?: string+ strokeCap?: string+ strokeJoin?: string+ dashPattern?: number[]+ effects?: Effect[]+ // Layout+ stackMode?: 'NONE' | 'HORIZONTAL' | 'VERTICAL'+ stackSpacing?: number+ stackPadding?: number+ stackPaddingRight?: number+ stackPaddingBottom?: number+ stackCounterAlign?: string+ stackJustify?: string+ stackCounterAlignItems?: string+ stackPrimaryAlignItems?: string+ stackPrimarySizing?: 'FIXED' | 'RESIZE_TO_FIT' | 'RESIZE_TO_FIT_WITH_IMPLICIT_SIZE'+ stackCounterSizing?: 'FIXED' | 'RESIZE_TO_FIT' | 'RESIZE_TO_FIT_WITH_IMPLICIT_SIZE'+ stackVerticalPadding?: number+ stackHorizontalPadding?: number+ stackWrap?: string+ stackPositioning?: string+ stackChildPrimaryGrow?: number+ stackCounterSpacing?: number+ // Frame+ clipsContent?: boolean+ frameMaskDisabled?: boolean+ // Vector+ vectorData?: unknown+ // Text+ fontSize?: number+ fontName?: { family: string; style: string; postscript?: string }+ textAlignHorizontal?: string+ textAlignVertical?: string+ textAutoResize?: string+ textData?: { characters: string; lines?: unknown[] }+ lineHeight?: { value: number; units: string }+ letterSpacing?: { value: number; units: string }+ // Symbol/Instance+ symbolData?: { symbolID: GUID }+ // ComponentSet+ isStateGroup?: boolean+ stateGroupPropertyValueOrders?: Array<{ property: string; values: string[] }>+ // Corners+ rectangleTopLeftCornerRadius?: number+ rectangleTopRightCornerRadius?: number+ rectangleBottomLeftCornerRadius?: number+ rectangleBottomRightCornerRadius?: number+ rectangleCornerRadiiIndependent?: boolean+ cornerSmoothing?: number+ // Constraints+ horizontalConstraint?: string+ verticalConstraint?: string+}++export interface FigmaMessage {+ type: string+ sessionID?: number+ ackID?: number+ reconnectSequenceNumber?: number+ nodeChanges?: NodeChange[]+}++/**+ * Create a NODE_CHANGES message+ */+export function createNodeChangesMessage(+ sessionID: number,+ reconnectSequenceNumber: number,+ nodeChanges: NodeChange[],+ ackID = 1+): FigmaMessage {+ return {+ type: 'NODE_CHANGES',+ sessionID,+ ackID,+ reconnectSequenceNumber,+ nodeChanges+ }+}++/**+ * Create a node change for a new shape+ */+export function createNodeChange(opts: {+ sessionID: number+ localID: number+ parentSessionID: number+ parentLocalID: number+ position?: string+ type: string+ name: string+ x: number+ y: number+ width: number+ height: number+ fill?: Color | string+ stroke?: Color | string+ strokeWeight?: number+ cornerRadius?: number+ opacity?: number+}): NodeChange {+ const change: NodeChange = {+ guid: { sessionID: opts.sessionID, localID: opts.localID },+ phase: 'CREATED',+ parentIndex: {+ guid: { sessionID: opts.parentSessionID, localID: opts.parentLocalID },+ position: opts.position || '!'+ },+ type: opts.type,+ name: opts.name,+ visible: true,+ opacity: opts.opacity ?? 1.0,+ size: { x: opts.width, y: opts.height },+ transform: {+ m00: 1,+ m01: 0,+ m02: opts.x,+ m10: 0,+ m11: 1,+ m12: opts.y+ }+ }++ if (opts.fill) {+ const color = typeof opts.fill === 'string' ? parseColor(opts.fill) : opts.fill+ change.fillPaints = [+ {+ type: 'SOLID',+ color,+ opacity: 1.0,+ visible: true,+ blendMode: 'NORMAL'+ }+ ]+ }++ if (opts.stroke) {+ const color = typeof opts.stroke === 'string' ? parseColor(opts.stroke) : opts.stroke+ change.strokePaints = [+ {+ type: 'SOLID',+ color,+ opacity: 1.0,+ visible: true,+ blendMode: 'NORMAL'+ }+ ]+ change.strokeWeight = opts.strokeWeight ?? 1+ }++ if (opts.cornerRadius !== undefined) {+ change.cornerRadius = opts.cornerRadius+ }++ return change+}++/**+ * Encode a varint (variable-length integer)+ */+function encodeVarint(value: number): number[] {+ const bytes: number[] = []+ while (value > 0x7f) {+ bytes.push((value & 0x7f) | 0x80)+ value >>>= 7+ }+ bytes.push(value)+ return bytes+}++/**+ * Encode a Paint with optional variable binding+ *+ * Figma's variable binding format (discovered via WS traffic analysis):+ * - Field 21 = 1 (binding type)+ * - Field 4 = 1 (flag)+ * - Raw sessionID varint (no field number)+ * - Raw localID varint (no field number)+ * - Terminators: 00 00 02 03 03 04 00 00+ */+export function encodePaintWithVariableBinding(+ paint: Paint,+ variableSessionID: number,+ variableLocalID: number+): Uint8Array {+ if (!compiledSchema) {+ throw new Error('Codec not initialized. Call initCodec() first.')+ }++ const { colorVariableBinding: _, ...basePaint } = paint++ const baseBytes = compiledSchema.encodePaint(basePaint)+ const baseArray = Array.from(baseBytes) as number[]++ // Remove trailing 00+ if (baseArray[baseArray.length - 1] === 0) {+ baseArray.pop()+ }++ // Add variable binding in Figma's exact format:+ // Field 21 (0x15) = 1 (binding type)+ baseArray.push(0x15, 0x01)+ // Field 4 = 1 (flag)+ baseArray.push(0x04, 0x01)+ // Raw varints: sessionID, localID (no field numbers!)+ baseArray.push(...encodeVarint(variableSessionID))+ baseArray.push(...encodeVarint(variableLocalID))+ // Terminators observed in Figma traffic+ baseArray.push(0x00, 0x00, 0x02, 0x03, 0x03, 0x04)+ // Final terminators+ baseArray.push(0x00, 0x00)++ return new Uint8Array(baseArray)+}++/**+ * Parse a variable ID string (e.g., "VariableID:38448:122296")+ * Returns sessionID and localID+ */+export function parseVariableId(variableId: string): { sessionID: number; localID: number } | null {+ const match = variableId.match(/VariableID:(\d+):(\d+)/)+ if (!match) return null+ return {+ sessionID: parseInt(match[1] ?? '0', 10),+ localID: parseInt(match[2] ?? '0', 10)+ }+}++/**+ * Encode a NodeChange with variable bindings in fillPaints and/or strokePaints+ * This is needed because kiwi-schema cannot produce Figma's exact variable binding format+ */+export function encodeNodeChangeWithVariables(nodeChange: NodeChange): Uint8Array {+ if (!compiledSchema) {+ throw new Error('Codec not initialized. Call initCodec() first.')+ }++ const hasFillBinding = nodeChange.fillPaints?.some((p) => p.colorVariableBinding)+ const hasStrokeBinding = nodeChange.strokePaints?.some((p) => p.colorVariableBinding)++ if (!hasFillBinding && !hasStrokeBinding) {+ return compiledSchema.encodeNodeChange(nodeChange)+ }++ // Create a copy without variable bindings for base encoding+ const cleanNodeChange = { ...nodeChange }+ if (cleanNodeChange.fillPaints) {+ cleanNodeChange.fillPaints = cleanNodeChange.fillPaints.map(+ ({ colorVariableBinding: _, ...rest }) => rest+ )+ }+ if (cleanNodeChange.strokePaints) {+ cleanNodeChange.strokePaints = cleanNodeChange.strokePaints.map(+ ({ colorVariableBinding: _, ...rest }) => rest+ )+ }++ // Encode clean version+ const baseBytes = compiledSchema.encodeNodeChange(cleanNodeChange)+ let hex = Buffer.from(baseBytes).toString('hex')++ // Inject fill variable binding (field 38 = 0x26)+ const fillBinding = nodeChange.fillPaints?.[0]?.colorVariableBinding+ if (hasFillBinding && fillBinding) {+ hex = injectVariableBinding(hex, '2601', fillBinding)+ }++ // Inject stroke variable binding (field 39 = 0x27)+ const strokeBinding = nodeChange.strokePaints?.[0]?.colorVariableBinding+ if (hasStrokeBinding && strokeBinding) {+ hex = injectVariableBinding(hex, '2701', strokeBinding)+ }++ return new Uint8Array(hex.match(/.{2}/g)?.map((b) => parseInt(b, 16)) ?? [])+}++/**+ * Inject variable binding into a paint at the specified marker+ */+function injectVariableBinding(+ hex: string,+ marker: string,+ binding: { variableID: { sessionID: number; localID: number } }+): string {+ const markerIdx = hex.indexOf(marker)+ if (markerIdx === -1) return hex++ // Find visible=true pattern (04 01) after the marker+ const visiblePattern = '0401'+ let patternIdx = hex.indexOf(visiblePattern, markerIdx)+ if (patternIdx === -1) return hex++ // Move past 0401 to find where to insert+ let insertPoint = patternIdx + visiblePattern.length++ // Check if blendMode follows (05 01)+ if (hex.slice(insertPoint, insertPoint + 4) === '0501') {+ insertPoint += 4+ }++ // Build variable binding bytes+ const varBytes = [+ 0x15,+ 0x01, // Field 21 (variableBinding) = 1+ 0x04,+ 0x01, // Nested field 4 = 1+ ...encodeVarint(binding.variableID.sessionID),+ ...encodeVarint(binding.variableID.localID),+ 0x00,+ 0x00,+ 0x02,+ 0x03,+ 0x03,+ 0x04,+ 0x00,+ 0x00 // Terminators+ ]+ const varHex = Buffer.from(varBytes).toString('hex')++ const beforeVar = hex.slice(0, insertPoint)+ // Skip original paint terminator (00) - our varHex includes terminators+ let afterIdx = insertPoint+ if (hex.slice(afterIdx, afterIdx + 2) === '00') {+ afterIdx += 2+ }+ const afterVar = hex.slice(afterIdx)++ return beforeVar + varHex + afterVar+}diff --git a/packages/core/src/kiwi/fig-file.ts b/packages/core/src/kiwi/fig-file.tsnew file mode 100644index 000000000..643dfa115--- /dev/null+++ b/packages/core/src/kiwi/fig-file.ts@@ -0,0 +1,109 @@+import { unzipSync, inflateSync } from 'fflate'+import { decompress as zstdDecompress } from 'fzstd'++import { importNodeChanges } from './fig-import'+import { decodeBinarySchema, compileSchema, ByteBuffer } from './kiwi-schema'+import { isZstdCompressed } from './protocol'++import type { FigmaMessage } from './codec'+import type { SceneGraph } from '../scene-graph'++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)++ 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 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[])+ )++ 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)+}++/**+ * Read a .fig File object and parse it+ */+export async function readFigFile(file: File): Promise<SceneGraph> {+ const buffer = await file.arrayBuffer()+ return parseFigFile(buffer)+}diff --git a/packages/core/src/kiwi/fig-import.ts b/packages/core/src/kiwi/fig-import.tsnew file mode 100644index 000000000..5d4ceda3c--- /dev/null+++ b/packages/core/src/kiwi/fig-import.ts@@ -0,0 +1,491 @@+import { SceneGraph } from '../scene-graph'+import { decodeVectorNetworkBlob } from '../vector'++import type { NodeChange, Paint, Effect as KiwiEffect, GUID } from './codec'+import type {+ NodeType,+ Fill,+ FillType,+ Stroke,+ Effect,+ Color,+ BlendMode,+ ImageScaleMode,+ GradientTransform,+ StrokeCap,+ StrokeJoin,+ LayoutMode,+ LayoutSizing,+ LayoutAlign,+ LayoutCounterAlign,+ ConstraintType,+ TextAutoResize,+ TextAlignVertical,+ TextCase,+ TextDecoration,+ ArcData,+ VectorNetwork+} from '../scene-graph'++function ext(nc: NodeChange): Record<string, unknown> {+ return nc as unknown as Record<string, unknown>+}++function guidToString(guid: GUID): string {+ return `${guid.sessionID}:${guid.localID}`+}++function convertColor(color?: { r: number; g: number; b: number; a: number }): Color {+ if (!color) return { r: 0, g: 0, b: 0, a: 1 }+ return { r: color.r, g: color.g, b: color.b, a: color.a }+}++function imageHashToString(hash: Record<string, number>): string {+ const bytes = Object.keys(hash)+ .sort((a, b) => Number(a) - Number(b))+ .map((k) => hash[Number(k)])+ return bytes.map((b) => b.toString(16).padStart(2, '0')).join('')+}++function convertGradientTransform(t?: {+ m00: number+ m01: number+ m02: number+ m10: number+ m11: number+ m12: number+}): GradientTransform | undefined {+ if (!t) return undefined+ return { m00: t.m00, m01: t.m01, m02: t.m02, m10: t.m10, m11: t.m11, m12: t.m12 }+}++function convertFills(paints?: Paint[]): Fill[] {+ if (!paints) return []+ return paints.map((p) => {+ const base: Fill = {+ type: (p.type ?? 'SOLID') as FillType,+ color: convertColor(p.color),+ opacity: p.opacity ?? 1,+ visible: p.visible ?? true,+ blendMode: (p.blendMode ?? 'NORMAL') as BlendMode+ }++ if (p.type?.startsWith('GRADIENT') && p.stops) {+ base.gradientStops = p.stops.map((s) => ({+ color: convertColor(s.color),+ position: s.position+ }))+ if (p.transform) {+ base.gradientTransform = convertGradientTransform(p.transform)+ }+ }++ if (p.type === 'IMAGE') {+ if (p.image && typeof p.image === 'object') {+ const img = p.image as { hash: string | Record<string, number> }+ if (typeof img.hash === 'object') {+ base.imageHash = imageHashToString(img.hash)+ } else if (typeof img.hash === 'string') {+ base.imageHash = img.hash+ }+ }+ base.imageScaleMode = (p.imageScaleMode as ImageScaleMode) ?? 'FILL'+ if (p.transform) {+ base.imageTransform = convertGradientTransform(p.transform)+ }+ }++ return base+ })+}++function convertStrokes(+ paints?: Paint[],+ weight?: number,+ align?: string,+ cap?: string,+ join?: string,+ dashPattern?: number[]+): Stroke[] {+ if (!paints) return []+ return paints.map((p) => ({+ color: convertColor(p.color),+ weight: weight ?? 1,+ opacity: p.opacity ?? 1,+ visible: p.visible ?? true,+ align: (align === 'INSIDE'+ ? 'INSIDE'+ : align === 'OUTSIDE'+ ? 'OUTSIDE'+ : 'CENTER') as Stroke['align'],+ cap: (cap ?? 'NONE') as StrokeCap,+ join: (join ?? 'MITER') as StrokeJoin,+ dashPattern: dashPattern ?? []+ }))+}++function convertEffects(effects?: KiwiEffect[]): Effect[] {+ if (!effects) return []+ return effects.map((e) => ({+ type: e.type as Effect['type'],+ color: convertColor(e.color),+ offset: e.offset ?? { x: 0, y: 0 },+ radius: e.radius ?? 0,+ spread: e.spread ?? 0,+ visible: e.visible ?? true,+ blendMode: (e.blendMode as BlendMode) ?? 'NORMAL'+ }))+}++function mapNodeType(type?: string): NodeType | 'DOCUMENT' {+ switch (type) {+ case 'DOCUMENT':+ return 'DOCUMENT'+ case 'CANVAS':+ return 'CANVAS'+ case 'FRAME':+ return 'FRAME'+ case 'RECTANGLE':+ return 'RECTANGLE'+ case 'ROUNDED_RECTANGLE':+ return 'ROUNDED_RECTANGLE'+ case 'ELLIPSE':+ return 'ELLIPSE'+ case 'TEXT':+ return 'TEXT'+ case 'LINE':+ return 'LINE'+ case 'STAR':+ return 'STAR'+ case 'REGULAR_POLYGON':+ return 'POLYGON'+ case 'VECTOR':+ return 'VECTOR'+ case 'GROUP':+ return 'GROUP'+ case 'SECTION':+ return 'SECTION'+ case 'COMPONENT':+ return 'COMPONENT'+ case 'COMPONENT_SET':+ return 'COMPONENT_SET'+ case 'INSTANCE':+ return 'INSTANCE'+ case 'SYMBOL':+ return 'COMPONENT'+ case 'CONNECTOR':+ return 'CONNECTOR'+ case 'SHAPE_WITH_TEXT':+ return 'SHAPE_WITH_TEXT'+ default:+ return 'RECTANGLE'+ }+}++function mapStackMode(mode?: string): LayoutMode {+ switch (mode) {+ case 'HORIZONTAL':+ return 'HORIZONTAL'+ case 'VERTICAL':+ return 'VERTICAL'+ default:+ return 'NONE'+ }+}++function mapStackSizing(sizing?: string): LayoutSizing {+ switch (sizing) {+ case 'RESIZE_TO_FIT':+ case 'RESIZE_TO_FIT_WITH_IMPLICIT_SIZE':+ return 'HUG'+ case 'FILL':+ return 'FILL'+ default:+ return 'FIXED'+ }+}++function mapStackJustify(justify?: string): LayoutAlign {+ switch (justify) {+ case 'CENTER':+ return 'CENTER'+ case 'MAX':+ return 'MAX'+ case 'SPACE_BETWEEN':+ case 'SPACE_EVENLY':+ return 'SPACE_BETWEEN'+ default:+ return 'MIN'+ }+}++function mapStackCounterAlign(align?: string): LayoutCounterAlign {+ switch (align) {+ case 'CENTER':+ return 'CENTER'+ case 'MAX':+ return 'MAX'+ case 'STRETCH':+ return 'STRETCH'+ case 'BASELINE':+ return 'BASELINE'+ default:+ return 'MIN'+ }+}++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) {+ case 'CENTER':+ return 'CENTER'+ case 'MAX':+ return 'MAX'+ case 'STRETCH':+ return 'STRETCH'+ case 'SCALE':+ return 'SCALE'+ default:+ return 'MIN'+ }+}++function mapTextDecoration(d?: string): TextDecoration {+ switch (d) {+ case 'UNDERLINE':+ return 'UNDERLINE'+ case 'STRIKETHROUGH':+ return 'STRIKETHROUGH'+ default:+ return 'NONE'+ }+}++function mapArcData(data?: Record<string, number>): ArcData | null {+ if (!data) return null+ return {+ startingAngle: data.startingAngle ?? 0,+ endingAngle: data.endingAngle ?? 2 * Math.PI,+ innerRadius: data.innerRadius ?? 0+ }+}++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[] = [],+ images?: Map<string, Uint8Array>+): SceneGraph {+ const graph = new SceneGraph()++ if (images) {+ for (const [hash, data] of images) {+ graph.images.set(hash, data)+ }+ }++ // Remove the default page created by constructor — we'll create pages from the file+ for (const page of graph.getPages()) {+ graph.deleteNode(page.id)+ }++ const changeMap = new Map<string, NodeChange>()+ const parentMap = new Map<string, string>()++ for (const nc of nodeChanges) {+ if (!nc.guid) continue+ if (nc.phase === 'REMOVED') continue+ const id = guidToString(nc.guid)+ changeMap.set(id, nc)++ if (nc.parentIndex?.guid) {+ parentMap.set(id, guidToString(nc.parentIndex.guid))+ }+ }++ function getChildren(ncId: string): string[] {+ const children: string[] = []+ for (const [childId, pid] of parentMap) {+ if (pid === ncId) children.push(childId)+ }+ children.sort((a, b) => {+ const aPos = changeMap.get(a)?.parentIndex?.position ?? ''+ const bPos = changeMap.get(b)?.parentIndex?.position ?? ''+ return aPos.localeCompare(bPos)+ })+ return children+ }++ const created = new Set<string>()++ function createSceneNode(ncId: string, graphParentId: string) {+ if (created.has(ncId)) return+ created.add(ncId)++ const nc = changeMap.get(ncId)+ if (!nc) return++ const nodeType = mapNodeType(nc.type)+ if (nodeType === 'DOCUMENT') return++ const x = nc.transform?.m02 ?? 0+ const y = nc.transform?.m12 ?? 0+ const width = nc.size?.x ?? 100+ const height = nc.size?.y ?? 100++ let rotation = 0+ if (nc.transform) {+ rotation = Math.atan2(nc.transform.m10, nc.transform.m00) * (180 / Math.PI)+ }++ const dashPattern = (ext(nc).dashPattern as number[]) ?? []++ const node = graph.createNode(nodeType, graphParentId, {+ name: nc.name ?? nodeType,+ x,+ y,+ width,+ height,+ rotation,+ opacity: nc.opacity ?? 1,+ visible: nc.visible ?? true,+ locked: nc.locked ?? false,+ blendMode: (ext(nc).blendMode as Fill['blendMode']) ?? 'PASS_THROUGH',+ fills: convertFills(nc.fillPaints),+ strokes: convertStrokes(+ nc.strokePaints,+ nc.strokeWeight,+ nc.strokeAlign,+ nc.strokeCap,+ nc.strokeJoin,+ dashPattern+ ),+ effects: convertEffects(nc.effects),+ cornerRadius: nc.cornerRadius ?? 0,+ topLeftRadius: nc.rectangleTopLeftCornerRadius ?? nc.cornerRadius ?? 0,+ topRightRadius: nc.rectangleTopRightCornerRadius ?? nc.cornerRadius ?? 0,+ bottomRightRadius: nc.rectangleBottomRightCornerRadius ?? nc.cornerRadius ?? 0,+ bottomLeftRadius: nc.rectangleBottomLeftCornerRadius ?? nc.cornerRadius ?? 0,+ independentCorners: nc.rectangleCornerRadiiIndependent ?? false,+ cornerSmoothing: nc.cornerSmoothing ?? 0,+ text: nc.textData?.characters ?? '',+ fontSize: nc.fontSize ?? 14,+ fontFamily: nc.fontName?.family ?? 'Inter',+ fontWeight: mapFontWeight(nc.fontName?.style),+ textAlignHorizontal:+ (nc.textAlignHorizontal as 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED') ?? 'LEFT',+ textAlignVertical: (ext(nc).textAlignVertical as TextAlignVertical) ?? 'TOP',+ textAutoResize: (ext(nc).textAutoResize as TextAutoResize) ?? 'NONE',+ textCase: (ext(nc).textCase as TextCase) ?? 'ORIGINAL',+ textDecoration: mapTextDecoration(ext(nc).textDecoration as string),+ lineHeight: nc.lineHeight?.value ?? null,+ letterSpacing: nc.letterSpacing?.value ?? 0,+ maxLines: (ext(nc).maxLines as number) ?? null,+ horizontalConstraint: mapConstraint(ext(nc).horizontalConstraint as string),+ verticalConstraint: mapConstraint(ext(nc).verticalConstraint as string),+ layoutMode: mapStackMode(nc.stackMode),+ itemSpacing: nc.stackSpacing ?? 0,+ paddingTop: nc.stackVerticalPadding ?? nc.stackPadding ?? 0,+ paddingBottom: nc.stackPaddingBottom ?? nc.stackVerticalPadding ?? nc.stackPadding ?? 0,+ paddingLeft: nc.stackHorizontalPadding ?? nc.stackPadding ?? 0,+ paddingRight: nc.stackPaddingRight ?? nc.stackHorizontalPadding ?? nc.stackPadding ?? 0,+ primaryAxisSizing: mapStackSizing(nc.stackPrimarySizing),+ counterAxisSizing: mapStackSizing(nc.stackCounterSizing),+ primaryAxisAlign: mapStackJustify(nc.stackPrimaryAlignItems ?? nc.stackJustify),+ counterAxisAlign: mapStackCounterAlign(nc.stackCounterAlignItems ?? nc.stackCounterAlign),+ 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,+ vectorNetwork: resolveVectorNetwork(nc, blobs),+ arcData: mapArcData(ext(nc).arcData as Record<string, number> | undefined),+ strokeCap: (nc.strokeCap ?? 'NONE') as StrokeCap,+ strokeJoin: (nc.strokeJoin ?? 'MITER') as StrokeJoin,+ dashPattern,+ borderTopWeight: (ext(nc).borderTopWeight as number) ?? 0,+ borderRightWeight: (ext(nc).borderRightWeight as number) ?? 0,+ borderBottomWeight: (ext(nc).borderBottomWeight as number) ?? 0,+ borderLeftWeight: (ext(nc).borderLeftWeight as number) ?? 0,+ independentStrokeWeights: (ext(nc).borderStrokeWeightsIndependent as boolean) ?? false+ })++ for (const childId of getChildren(ncId)) {+ createSceneNode(childId, node.id)+ }+ }++ // Find the document node (type=DOCUMENT or guid 0:0)+ let docId: string | null = null+ for (const [id, nc] of changeMap) {+ if (nc.type === 'DOCUMENT' || id === '0:0') {+ docId = id+ break+ }+ }++ if (docId) {+ // Import pages (CANVAS nodes) and their children+ for (const canvasId of getChildren(docId)) {+ const canvasNc = changeMap.get(canvasId)+ if (!canvasNc) continue+ if (canvasNc.type === 'CANVAS') {+ const page = graph.addPage(canvasNc.name ?? 'Page')+ created.add(canvasId)+ for (const childId of getChildren(canvasId)) {+ createSceneNode(childId, page.id)+ }+ } else {+ createSceneNode(canvasId, graph.getPages()[0]?.id ?? graph.rootId)+ }+ }+ } else {+ // No document structure — treat all roots as children of the first page+ const roots: string[] = []+ for (const [id] of changeMap) {+ const pid = parentMap.get(id)+ if (!pid || !changeMap.has(pid)) roots.push(id)+ }+ const page = graph.getPages()[0] ?? graph.addPage('Page 1')+ for (const rootId of roots) {+ createSceneNode(rootId, page.id)+ }+ }++ // Ensure at least one page exists+ if (graph.getPages().length === 0) {+ graph.addPage('Page 1')+ }++ return graph+}diff --git a/packages/core/src/kiwi/kiwi-schema/bb.ts b/packages/core/src/kiwi/kiwi-schema/bb.tsnew file mode 100644index 000000000..84f703c84--- /dev/null+++ b/packages/core/src/kiwi/kiwi-schema/bb.ts@@ -0,0 +1,281 @@+let int32 = new Int32Array(1)+let float32 = new Float32Array(int32.buffer)++export class ByteBuffer {+ private _data: Uint8Array+ private _index: number+ length: number++ constructor(data?: Uint8Array) {+ if (data && !(data instanceof Uint8Array)) {+ throw new Error('Must initialize a ByteBuffer with a Uint8Array')+ }+ this._data = data || new Uint8Array(256)+ this._index = 0+ this.length = data ? data.length : 0+ }++ toUint8Array(): Uint8Array {+ return this._data.subarray(0, this.length)+ }++ readByte(): number {+ if (this._index + 1 > this._data.length) {+ throw new Error('Index out of bounds')+ }+ return this._data[this._index++]+ }++ readByteArray(): Uint8Array {+ let length = this.readVarUint()+ let start = this._index+ let end = start + length+ if (end > this._data.length) {+ throw new Error('Read array out of bounds')+ }+ this._index = end+ // Copy into a new array instead of just creating another view.+ let result = new Uint8Array(length)+ result.set(this._data.subarray(start, end))+ return result+ }++ readVarFloat(): number {+ let index = this._index+ let data = this._data+ let length = data.length++ // Optimization: use a single byte to store zero+ if (index + 1 > length) {+ throw new Error('Index out of bounds')+ }+ let first = data[index]+ if (first === 0) {+ this._index = index + 1+ return 0+ }++ // Endian-independent 32-bit read+ if (index + 4 > length) {+ throw new Error('Index out of bounds')+ }+ let bits = first | (data[index + 1] << 8) | (data[index + 2] << 16) | (data[index + 3] << 24)+ this._index = index + 4++ // Move the exponent back into place+ bits = (bits << 23) | (bits >>> 9)++ // Reinterpret as a floating-point number+ int32[0] = bits+ return float32[0]+ }++ readVarUint(): number {+ let value = 0+ let shift = 0+ do {+ var byte = this.readByte()+ value |= (byte & 127) << shift+ shift += 7+ } while (byte & 128 && shift < 35)+ return value >>> 0+ }++ readVarInt(): number {+ let value = this.readVarUint() | 0+ return value & 1 ? ~(value >>> 1) : value >>> 1+ }++ readVarUint64(): bigint {+ let value = BigInt(0)+ let shift = BigInt(0)+ let seven = BigInt(7)+ let byte: number+ while ((byte = this.readByte()) & 128 && shift < 56) {+ value |= BigInt(byte & 127) << shift+ shift += seven+ }+ value |= BigInt(byte) << shift+ return value+ }++ readVarInt64(): bigint {+ let value = this.readVarUint64()+ let one = BigInt(1)+ let sign = value & one+ value >>= one+ return sign ? ~value : value+ }++ readString(): string {+ let result = ''++ while (true) {+ let codePoint++ // Decode UTF-8+ let a = this.readByte()+ if (a < 0xc0) {+ codePoint = a+ } else {+ let b = this.readByte()+ if (a < 0xe0) {+ codePoint = ((a & 0x1f) << 6) | (b & 0x3f)+ } else {+ let c = this.readByte()+ if (a < 0xf0) {+ codePoint = ((a & 0x0f) << 12) | ((b & 0x3f) << 6) | (c & 0x3f)+ } else {+ let d = this.readByte()+ codePoint = ((a & 0x07) << 18) | ((b & 0x3f) << 12) | ((c & 0x3f) << 6) | (d & 0x3f)+ }+ }+ }++ // Strings are null-terminated+ if (codePoint === 0) {+ break+ }++ // Encode UTF-16+ if (codePoint < 0x10000) {+ result += String.fromCharCode(codePoint)+ } else {+ codePoint -= 0x10000+ result += String.fromCharCode(+ (codePoint >> 10) + 0xd800,+ (codePoint & ((1 << 10) - 1)) + 0xdc00+ )+ }+ }++ return result+ }++ private _growBy(amount: number): void {+ if (this.length + amount > this._data.length) {+ let data = new Uint8Array((this.length + amount) << 1)+ data.set(this._data)+ this._data = data+ }+ this.length += amount+ }++ writeByte(value: number): void {+ let index = this.length+ this._growBy(1)+ this._data[index] = value+ }++ writeByteArray(value: Uint8Array): void {+ this.writeVarUint(value.length)+ let index = this.length+ this._growBy(value.length)+ this._data.set(value, index)+ }++ writeVarFloat(value: number): void {+ let index = this.length++ // Reinterpret as an integer+ float32[0] = value+ let bits = int32[0]++ // Move the exponent to the first 8 bits+ bits = (bits >>> 23) | (bits << 9)++ // Optimization: use a single byte to store zero and denormals (check for an exponent of 0)+ if ((bits & 255) === 0) {+ this.writeByte(0)+ return+ }++ // Endian-independent 32-bit write+ this._growBy(4)+ let data = this._data+ data[index] = bits+ data[index + 1] = bits >> 8+ data[index + 2] = bits >> 16+ data[index + 3] = bits >> 24+ }++ writeVarUint(value: number): void {+ if (value < 0 || value > 0xffff_ffff) throw new Error('Outside uint range: ' + value)+ do {+ let byte = value & 127+ value >>>= 7+ this.writeByte(value ? byte | 128 : byte)+ } while (value)+ }++ writeVarInt(value: number): void {+ if (value < -0x8000_0000 || value > 0x7fff_ffff) throw new Error('Outside int range: ' + value)+ this.writeVarUint(((value << 1) ^ (value >> 31)) >>> 0)+ }++ writeVarUint64(value: bigint | string): void {+ if (typeof value === 'string') value = BigInt(value)+ else if (typeof value !== 'bigint')+ throw new Error('Expected bigint but got ' + typeof value + ': ' + value)+ if (value < 0 || value > BigInt('0xFFFFFFFFFFFFFFFF'))+ throw new Error('Outside uint64 range: ' + value)+ let mask = BigInt(127)+ let seven = BigInt(7)+ for (let i = 0; value > mask && i < 8; i++) {+ this.writeByte(Number(value & mask) | 128)+ value >>= seven+ }+ this.writeByte(Number(value))+ }++ writeVarInt64(value: bigint | string): void {+ if (typeof value === 'string') value = BigInt(value)+ else if (typeof value !== 'bigint')+ throw new Error('Expected bigint but got ' + typeof value + ': ' + value)+ if (value < -BigInt('0x8000000000000000') || value > BigInt('0x7FFFFFFFFFFFFFFF'))+ throw new Error('Outside int64 range: ' + value)+ let one = BigInt(1)+ this.writeVarUint64(value < 0 ? ~(value << one) : value << one)+ }++ writeString(value: string): void {+ let codePoint++ for (let i = 0; i < value.length; i++) {+ // Decode UTF-16+ let a = value.charCodeAt(i)+ if (i + 1 === value.length || a < 0xd800 || a >= 0xdc00) {+ codePoint = a+ } else {+ let b = value.charCodeAt(++i)+ codePoint = (a << 10) + b + (0x10000 - (0xd800 << 10) - 0xdc00)+ }++ // Strings are null-terminated+ if (codePoint === 0) {+ throw new Error('Cannot encode a string containing the null character')+ }++ // Encode UTF-8+ if (codePoint < 0x80) {+ this.writeByte(codePoint)+ } else {+ if (codePoint < 0x800) {+ this.writeByte(((codePoint >> 6) & 0x1f) | 0xc0)+ } else {+ if (codePoint < 0x10000) {+ this.writeByte(((codePoint >> 12) & 0x0f) | 0xe0)+ } else {+ this.writeByte(((codePoint >> 18) & 0x07) | 0xf0)+ this.writeByte(((codePoint >> 12) & 0x3f) | 0x80)+ }+ this.writeByte(((codePoint >> 6) & 0x3f) | 0x80)+ }+ this.writeByte((codePoint & 0x3f) | 0x80)+ }+ }++ // Strings are null-terminated+ this.writeByte(0)+ }+}diff --git a/packages/core/src/kiwi/kiwi-schema/binary.ts b/packages/core/src/kiwi/kiwi-schema/binary.tsnew file mode 100644index 000000000..9e6af4691--- /dev/null+++ b/packages/core/src/kiwi/kiwi-schema/binary.ts@@ -0,0 +1,102 @@+import { ByteBuffer } from './bb'+import { Schema, Field, Definition, DefinitionKind } from './schema'++let types: (string | null)[] = ['bool', 'byte', 'int', 'uint', 'float', 'string', 'int64', 'uint64']+let kinds: DefinitionKind[] = ['ENUM', 'STRUCT', 'MESSAGE']++export function decodeBinarySchema(buffer: Uint8Array | ByteBuffer): Schema {+ let bb = buffer instanceof ByteBuffer ? buffer : new ByteBuffer(buffer)+ let definitionCount = bb.readVarUint()+ let definitions: Definition[] = []++ // Read in the schema+ for (let i = 0; i < definitionCount; i++) {+ let definitionName = bb.readString()+ let kind = bb.readByte()+ let fieldCount = bb.readVarUint()+ let fields: Field[] = []++ for (let j = 0; j < fieldCount; j++) {+ let fieldName = bb.readString()+ let type = bb.readVarInt()+ let isArray = !!(bb.readByte() & 1)+ let value = bb.readVarUint()++ fields.push({+ name: fieldName,+ line: 0,+ column: 0,+ type: kinds[kind] === 'ENUM' ? null : (type as any),+ isArray: isArray,+ isDeprecated: false,+ value: value+ })+ }++ definitions.push({+ name: definitionName,+ line: 0,+ column: 0,+ kind: kinds[kind],+ fields: fields+ })+ }++ // Bind type names afterwards+ for (let i = 0; i < definitionCount; i++) {+ let fields = definitions[i].fields+ for (let j = 0; j < fields.length; j++) {+ let field = fields[j]+ let type = field.type as any as number | null++ if (type !== null && type < 0) {+ if (~type >= types.length) {+ throw new Error('Invalid type ' + type)+ }+ field.type = types[~type]+ } else {+ if (type !== null && type >= definitions.length) {+ throw new Error('Invalid type ' + type)+ }+ field.type = type === null ? null : definitions[type].name+ }+ }+ }++ return {+ package: null,+ definitions: definitions+ }+}++export function encodeBinarySchema(schema: Schema): Uint8Array {+ let bb = new ByteBuffer()+ let definitions = schema.definitions+ let definitionIndex: { [name: string]: number } = {}++ bb.writeVarUint(definitions.length)++ for (let i = 0; i < definitions.length; i++) {+ definitionIndex[definitions[i].name] = i+ }++ for (let i = 0; i < definitions.length; i++) {+ let definition = definitions[i]++ bb.writeString(definition.name)+ bb.writeByte(kinds.indexOf(definition.kind))+ bb.writeVarUint(definition.fields.length)++ for (let j = 0; j < definition.fields.length; j++) {+ let field = definition.fields[j]+ let type = types.indexOf(field.type)++ bb.writeString(field.name)+ bb.writeVarInt(type === -1 ? definitionIndex[field.type!] : ~type)+ bb.writeByte(field.isArray ? 1 : 0)+ bb.writeVarUint(field.value)+ }+ }++ return bb.toUint8Array()+}diff --git a/packages/core/src/kiwi/kiwi-schema/index.ts b/packages/core/src/kiwi/kiwi-schema/index.tsnew file mode 100644index 000000000..7d45da2f9--- /dev/null+++ b/packages/core/src/kiwi/kiwi-schema/index.ts@@ -0,0 +1,5 @@+export type { Schema, Definition, Field } from './schema'+export { ByteBuffer } from './bb'+export { compileSchema } from './js'+export { decodeBinarySchema, encodeBinarySchema } from './binary'+export { parseSchema } from './parser'diff --git a/packages/core/src/kiwi/kiwi-schema/js.ts b/packages/core/src/kiwi/kiwi-schema/js.tsnew file mode 100644index 000000000..63649e7e8--- /dev/null+++ b/packages/core/src/kiwi/kiwi-schema/js.ts@@ -0,0 +1,339 @@+import { ByteBuffer } from './bb'+import { Schema, Definition } from './schema'+import { error, quote } from './util'++function compileDecode(+ definition: Definition,+ definitions: { [name: string]: Definition }+): string {+ let lines: string[] = []+ let indent = ' '++ lines.push('function (bb) {')+ lines.push(' var result = {};')+ lines.push(' if (!(bb instanceof this.ByteBuffer)) {')+ lines.push(' bb = new this.ByteBuffer(bb);')+ lines.push(' }')+ lines.push('')++ if (definition.kind === 'MESSAGE') {+ lines.push(' while (true) {')+ lines.push(' switch (bb.readVarUint()) {')+ lines.push(' case 0:')+ lines.push(' return result;')+ lines.push('')+ indent = ' '+ }++ for (let i = 0; i < definition.fields.length; i++) {+ let field = definition.fields[i]+ let code: string++ switch (field.type) {+ case 'bool': {+ code = '!!bb.readByte()'+ break+ }++ case 'byte': {+ code = 'bb.readByte()' // only used if not array+ break+ }++ case 'int': {+ code = 'bb.readVarInt()'+ break+ }++ case 'uint': {+ code = 'bb.readVarUint()'+ break+ }++ case 'float': {+ code = 'bb.readVarFloat()'+ break+ }++ case 'string': {+ code = 'bb.readString()'+ break+ }++ case 'int64': {+ code = 'bb.readVarInt64()'+ break+ }++ case 'uint64': {+ code = 'bb.readVarUint64()'+ break+ }++ default: {+ let type = definitions[field.type!]+ if (!type) {+ error(+ 'Invalid type ' + quote(field.type!) + ' for field ' + quote(field.name),+ field.line,+ field.column+ )+ } else if (type.kind === 'ENUM') {+ code = 'this[' + quote(type.name) + '][bb.readVarUint()]'+ } else {+ code = 'this[' + quote('decode' + type.name) + '](bb)'+ }+ }+ }++ if (definition.kind === 'MESSAGE') {+ lines.push(' case ' + field.value + ':')+ }++ if (field.isArray) {+ if (field.isDeprecated) {+ if (field.type === 'byte') {+ lines.push(indent + 'bb.readByteArray();')+ } else {+ lines.push(indent + 'var length = bb.readVarUint();')+ lines.push(indent + 'while (length-- > 0) ' + code + ';')+ }+ } else {+ if (field.type === 'byte') {+ lines.push(indent + 'result[' + quote(field.name) + '] = bb.readByteArray();')+ } else {+ lines.push(indent + 'var length = bb.readVarUint();')+ lines.push(indent + 'var values = result[' + quote(field.name) + '] = Array(length);')+ lines.push(indent + 'for (var i = 0; i < length; i++) values[i] = ' + code + ';')+ }+ }+ } else {+ if (field.isDeprecated) {+ lines.push(indent + code + ';')+ } else {+ lines.push(indent + 'result[' + quote(field.name) + '] = ' + code + ';')+ }+ }++ if (definition.kind === 'MESSAGE') {+ lines.push(' break;')+ lines.push('')+ }+ }++ if (definition.kind === 'MESSAGE') {+ lines.push(' default:')+ lines.push(' throw new Error("Attempted to parse invalid message");')+ lines.push(' }')+ lines.push(' }')+ } else {+ lines.push(' return result;')+ }++ lines.push('}')++ return lines.join('\n')+}++function compileEncode(+ definition: Definition,+ definitions: { [name: string]: Definition }+): string {+ let lines: string[] = []++ lines.push('function (message, bb) {')+ lines.push(' var isTopLevel = !bb;')+ lines.push(' if (isTopLevel) bb = new this.ByteBuffer();')++ for (let j = 0; j < definition.fields.length; j++) {+ let field = definition.fields[j]+ let code: string++ if (field.isDeprecated) {+ continue+ }++ switch (field.type) {+ case 'bool': {+ code = 'bb.writeByte(value);'+ break+ }++ case 'byte': {+ code = 'bb.writeByte(value);' // only used if not array+ break+ }++ case 'int': {+ code = 'bb.writeVarInt(value);'+ break+ }++ case 'uint': {+ code = 'bb.writeVarUint(value);'+ break+ }++ case 'float': {+ code = 'bb.writeVarFloat(value);'+ break+ }++ case 'string': {+ code = 'bb.writeString(value);'+ break+ }++ case 'int64': {+ code = 'bb.writeVarInt64(value);'+ break+ }++ case 'uint64': {+ code = 'bb.writeVarUint64(value);'+ break+ }++ default: {+ let type = definitions[field.type!]+ if (!type) {+ throw new Error('Invalid type ' + quote(field.type!) + ' for field ' + quote(field.name))+ } else if (type.kind === 'ENUM') {+ code =+ 'var encoded = this[' ++ quote(type.name) ++ '][value]; ' ++ 'if (encoded === void 0) throw new Error("Invalid value " + JSON.stringify(value) + ' ++ quote(' for enum ' + quote(type.name)) ++ '); ' ++ 'bb.writeVarUint(encoded);'+ } else {+ code = 'this[' + quote('encode' + type.name) + '](value, bb);'+ }+ }+ }++ lines.push('')+ lines.push(' var value = message[' + quote(field.name) + '];')+ lines.push(' if (value != null) {') // Comparing with null using "!=" also checks for undefined++ if (definition.kind === 'MESSAGE') {+ lines.push(' bb.writeVarUint(' + field.value + ');')+ }++ if (field.isArray) {+ if (field.type === 'byte') {+ lines.push(' bb.writeByteArray(value);')+ } else {+ lines.push(' var values = value, n = values.length;')+ lines.push(' bb.writeVarUint(n);')+ lines.push(' for (var i = 0; i < n; i++) {')+ lines.push(' value = values[i];')+ lines.push(' ' + code)+ lines.push(' }')+ }+ } else {+ lines.push(' ' + code)+ }++ if (definition.kind === 'STRUCT') {+ lines.push(' } else {')+ lines.push(+ ' throw new Error(' + quote('Missing required field ' + quote(field.name)) + ');'+ )+ }++ lines.push(' }')+ }++ // A field id of zero is reserved to indicate the end of the message+ if (definition.kind === 'MESSAGE') {+ lines.push(' bb.writeVarUint(0);')+ }++ lines.push('')+ lines.push(' if (isTopLevel) return bb.toUint8Array();')+ lines.push('}')++ return lines.join('\n')+}++export function compileSchemaJS(schema: Schema): string {+ let definitions: { [name: string]: Definition } = {}+ let name = schema.package+ let js: string[] = []++ if (name !== null) {+ js.push('var ' + name + ' = exports || ' + name + ' || {}, exports;')+ } else {+ js.push('var exports = exports || {};')+ name = 'exports'+ }++ js.push(name + '.ByteBuffer = ' + name + '.ByteBuffer || require("kiwi-schema").ByteBuffer;')++ for (let i = 0; i < schema.definitions.length; i++) {+ let definition = schema.definitions[i]+ definitions[definition.name] = definition+ }++ for (let i = 0; i < schema.definitions.length; i++) {+ let definition = schema.definitions[i]++ switch (definition.kind) {+ case 'ENUM': {+ let value: any = {}+ for (let j = 0; j < definition.fields.length; j++) {+ let field = definition.fields[j]+ value[field.name] = field.value+ value[field.value] = field.name+ }+ js.push(name + '[' + quote(definition.name) + '] = ' + JSON.stringify(value, null, 2) + ';')+ break+ }++ case 'STRUCT':+ case 'MESSAGE': {+ js.push('')+ js.push(+ name ++ '[' ++ quote('decode' + definition.name) ++ '] = ' ++ compileDecode(definition, definitions) ++ ';'+ )+ js.push('')+ js.push(+ name ++ '[' ++ quote('encode' + definition.name) ++ '] = ' ++ compileEncode(definition, definitions) ++ ';'+ )+ break+ }++ default: {+ error(+ 'Invalid definition kind ' + quote(definition.kind),+ definition.line,+ definition.column+ )+ break+ }+ }+ }++ js.push('')+ return js.join('\n')+}++export function compileSchema(schema: Schema): any {+ let result = {+ ByteBuffer: ByteBuffer+ }+ new Function('exports', compileSchemaJS(schema))(result)+ return result+}diff --git a/packages/core/src/kiwi/kiwi-schema/parser.ts b/packages/core/src/kiwi/kiwi-schema/parser.tsnew file mode 100644index 000000000..c2a0a80ff--- /dev/null+++ b/packages/core/src/kiwi/kiwi-schema/parser.ts@@ -0,0 +1,287 @@+import { Schema, Definition, Field, DefinitionKind } from './schema'+import { error, quote } from './util'++export let nativeTypes = ['bool', 'byte', 'float', 'int', 'int64', 'string', 'uint', 'uint64']++// These are special names on the object returned by compileSchema()+export let reservedNames = ['ByteBuffer', 'package']++let regex = /((?:-|\b)\d+\b|[=;{}]|\[\]|\[deprecated\]|\b[A-Za-z_][A-Za-z0-9_]*\b|\/\/.*|\s+)/g+let identifier = /^[A-Za-z_][A-Za-z0-9_]*$/+let whitespace = /^\/\/.*|\s+$/+let equals = /^=$/+let endOfFile = /^$/+let semicolon = /^;$/+let integer = /^-?\d+$/+let leftBrace = /^\{$/+let rightBrace = /^\}$/+let arrayToken = /^\[\]$/+let enumKeyword = /^enum$/+let structKeyword = /^struct$/+let messageKeyword = /^message$/+let packageKeyword = /^package$/+let deprecatedToken = /^\[deprecated\]$/++interface Token {+ text: string+ line: number+ column: number+}++function tokenize(text: string): Token[] {+ let parts = text.split(regex)+ let tokens = []+ let column = 0+ let line = 0++ for (let i = 0; i < parts.length; i++) {+ let part = parts[i]++ // Keep non-whitespace tokens+ if (i & 1) {+ if (!whitespace.test(part)) {+ tokens.push({+ text: part,+ line: line + 1,+ column: column + 1+ })+ }+ }++ // Detect syntax errors+ else if (part !== '') {+ error('Syntax error ' + quote(part), line + 1, column + 1)+ }++ // Keep track of the line and column counts+ let lines = part.split('\n')+ if (lines.length > 1) column = 0+ line += lines.length - 1+ column += lines[lines.length - 1].length+ }++ // End-of-file token+ tokens.push({+ text: '',+ line: line,+ column: column+ })++ return tokens+}++function parse(tokens: Token[]): Schema {+ function current(): Token {+ return tokens[index]+ }++ function eat(test: RegExp): boolean {+ if (test.test(current().text)) {+ index+++ return true+ }+ return false+ }++ function expect(test: RegExp, expected: string): void {+ if (!eat(test)) {+ let token = current()+ error('Expected ' + expected + ' but found ' + quote(token.text), token.line, token.column)+ }+ }++ function unexpectedToken(): never {+ let token = current()+ error('Unexpected token ' + quote(token.text), token.line, token.column)+ }++ let definitions: Definition[] = []+ let packageText = null+ let index = 0++ if (eat(packageKeyword)) {+ packageText = current().text+ expect(identifier, 'identifier')+ expect(semicolon, '";"')+ }++ while (index < tokens.length && !eat(endOfFile)) {+ let fields: Field[] = []+ let kind: DefinitionKind++ if (eat(enumKeyword)) kind = 'ENUM'+ else if (eat(structKeyword)) kind = 'STRUCT'+ else if (eat(messageKeyword)) kind = 'MESSAGE'+ else unexpectedToken()++ // All definitions start off the same+ let name = current()+ expect(identifier, 'identifier')+ expect(leftBrace, '"{"')++ // Parse fields+ while (!eat(rightBrace)) {+ let type: string | null = null+ let isArray = false+ let isDeprecated = false++ // Enums don't have types+ if (kind !== 'ENUM') {+ type = current().text+ expect(identifier, 'identifier')+ isArray = eat(arrayToken)+ }++ let field = current()+ expect(identifier, 'identifier')++ // Structs don't have explicit values+ let value: Token | null = null+ if (kind !== 'STRUCT') {+ expect(equals, '"="')+ value = current()+ expect(integer, 'integer')++ if ((+value.text | 0) + '' !== value.text) {+ error('Invalid integer ' + quote(value.text), value.line, value.column)+ }+ }++ let deprecated = current()+ if (eat(deprecatedToken)) {+ if (kind !== 'MESSAGE') {+ error('Cannot deprecate this field', deprecated.line, deprecated.column)+ }++ isDeprecated = true+ }++ expect(semicolon, '";"')++ fields.push({+ name: field.text,+ line: field.line,+ column: field.column,+ type: type,+ isArray: isArray,+ isDeprecated: isDeprecated,+ value: value !== null ? +value.text | 0 : fields.length + 1+ })+ }++ definitions.push({+ name: name.text,+ line: name.line,+ column: name.column,+ kind: kind,+ fields: fields+ })+ }++ return {+ package: packageText,+ definitions: definitions+ }+}++function verify(root: Schema): void {+ let definedTypes = nativeTypes.slice()+ let definitions: { [name: string]: Definition } = {}++ // Define definitions+ for (let i = 0; i < root.definitions.length; i++) {+ let definition = root.definitions[i]+ if (definedTypes.indexOf(definition.name) !== -1) {+ error(+ 'The type ' + quote(definition.name) + ' is defined twice',+ definition.line,+ definition.column+ )+ }+ if (reservedNames.indexOf(definition.name) !== -1) {+ error(+ 'The type name ' + quote(definition.name) + ' is reserved',+ definition.line,+ definition.column+ )+ }+ definedTypes.push(definition.name)+ definitions[definition.name] = definition+ }++ // Check fields+ for (let i = 0; i < root.definitions.length; i++) {+ let definition = root.definitions[i]+ let fields = definition.fields++ if (definition.kind === 'ENUM' || fields.length === 0) {+ continue+ }++ // Check types+ for (let j = 0; j < fields.length; j++) {+ let field = fields[j]+ if (definedTypes.indexOf(field.type!) === -1) {+ error(+ 'The type ' + quote(field.type!) + ' is not defined for field ' + quote(field.name),+ field.line,+ field.column+ )+ }+ }++ // Check values+ let values: number[] = []+ for (let j = 0; j < fields.length; j++) {+ let field = fields[j]+ if (values.indexOf(field.value) !== -1) {+ error('The id for field ' + quote(field.name) + ' is used twice', field.line, field.column)+ }+ if (field.value <= 0) {+ error(+ 'The id for field ' + quote(field.name) + ' must be positive',+ field.line,+ field.column+ )+ }+ // Figma schema uses sparse field IDs (up to 435), so skip sequential check+ values.push(field.value)+ }+ }++ // Check that structs don't contain themselves+ let state: { [name: string]: number } = {}+ let check = (name: string): boolean => {+ let definition = definitions[name]+ if (definition && definition.kind === 'STRUCT') {+ if (state[name] === 1) {+ error(+ 'Recursive nesting of ' + quote(name) + ' is not allowed',+ definition.line,+ definition.column+ )+ }+ if (state[name] !== 2 && definition) {+ state[name] = 1+ let fields = definition.fields+ for (let i = 0; i < fields.length; i++) {+ let field = fields[i]+ if (!field.isArray) {+ check(field.type!)+ }+ }+ state[name] = 2+ }+ }+ return true+ }+ for (let i = 0; i < root.definitions.length; i++) {+ check(root.definitions[i].name)+ }+}++export function parseSchema(text: string): Schema {+ let schema = parse(tokenize(text))+ verify(schema)+ return schema+}diff --git a/packages/core/src/kiwi/kiwi-schema/schema.ts b/packages/core/src/kiwi/kiwi-schema/schema.tsnew file mode 100644index 000000000..82786ef59--- /dev/null+++ b/packages/core/src/kiwi/kiwi-schema/schema.ts@@ -0,0 +1,24 @@+export interface Schema {+ package: string | null+ definitions: Definition[]+}++export type DefinitionKind = 'ENUM' | 'STRUCT' | 'MESSAGE'++export interface Definition {+ name: string+ line: number+ column: number+ kind: DefinitionKind+ fields: Field[]+}++export interface Field {+ name: string+ line: number+ column: number+ type: string | null+ isArray: boolean+ isDeprecated: boolean+ value: number+}diff --git a/packages/core/src/kiwi/kiwi-schema/util.ts b/packages/core/src/kiwi/kiwi-schema/util.tsnew file mode 100644index 000000000..2925ed6dd--- /dev/null+++ b/packages/core/src/kiwi/kiwi-schema/util.ts@@ -0,0 +1,10 @@+export function quote(text: string): string {+ return JSON.stringify(text)+}++export function error(text: string, line: number, column: number): never {+ var error = new Error(text)+ ;(error as any).line = line+ ;(error as any).column = column+ throw error+}diff --git a/packages/core/src/kiwi/protocol.ts b/packages/core/src/kiwi/protocol.tsnew file mode 100644index 000000000..d44aee9c9--- /dev/null+++ b/packages/core/src/kiwi/protocol.ts@@ -0,0 +1,238 @@+/**+ * Figma Multiplayer Protocol+ *+ * This module handles the low-level WebSocket communication with Figma's+ * multiplayer server. The protocol uses:+ *+ * - Kiwi binary serialization (schema-based, like Protocol Buffers)+ * - Zstd compression for all messages+ * - Session-based authentication via cookies+ *+ * Message types (from Figma's schema):+ * 0 = JOIN_START - Server sends session info+ * 1 = NODE_CHANGES - Create/update/delete nodes+ * 2 = USER_CHANGES - User presence updates+ * 3 = JOIN_END - Initial sync complete+ * 4 = SIGNAL - Various metadata (reconnect info, etc.)+ * 5 = STYLE - Style updates+ * ...and more+ *+ * Wire format:+ * All messages are Zstd-compressed Kiwi-encoded binary data.+ * Zstd magic bytes: 0x28 0xB5 0x2F 0xFD+ */++export const MESSAGE_TYPES = {+ JOIN_START: 0,+ NODE_CHANGES: 1,+ USER_CHANGES: 2,+ JOIN_END: 3,+ SIGNAL: 4,+ STYLE: 5,+ STYLE_SET: 6,+ JOIN_START_SKIP_RELOAD: 7,+ NOTIFY_SHOULD_UPGRADE: 8,+ UPGRADE_DONE: 9,+ UPGRADE_REFRESH: 10,+ SCENE_GRAPH_QUERY: 11,+ SCENE_GRAPH_REPLY: 12,+ DIFF: 13,+ CLIENT_BROADCAST: 14+} as const++export const NODE_TYPES = {+ NONE: 0,+ DOCUMENT: 1,+ CANVAS: 2,+ GROUP: 3,+ FRAME: 4,+ BOOLEAN_OPERATION: 5,+ VECTOR: 6,+ STAR: 7,+ LINE: 8,+ ELLIPSE: 9,+ RECTANGLE: 10,+ REGULAR_POLYGON: 11,+ ROUNDED_RECTANGLE: 12,+ TEXT: 13,+ SLICE: 14,+ SYMBOL: 15,+ INSTANCE: 16,+ STICKY: 17,+ SHAPE_WITH_TEXT: 18,+ CONNECTOR: 19,+ CODE_BLOCK: 20,+ WIDGET: 21,+ STAMP: 22,+ MEDIA: 23,+ HIGHLIGHT: 24,+ SECTION: 25,+ SECTION_OVERLAY: 26,+ WASHI_TAPE: 27,+ VARIABLE: 28+} as const++export const NODE_PHASES = {+ CREATED: 0,+ REMOVED: 1+} as const++export const BLEND_MODES = {+ PASS_THROUGH: 0,+ NORMAL: 1,+ DARKEN: 2,+ MULTIPLY: 3,+ LINEAR_BURN: 4,+ COLOR_BURN: 5,+ LIGHTEN: 6,+ SCREEN: 7,+ LINEAR_DODGE: 8,+ COLOR_DODGE: 9,+ OVERLAY: 10,+ SOFT_LIGHT: 11,+ HARD_LIGHT: 12,+ DIFFERENCE: 13,+ EXCLUSION: 14,+ HUE: 15,+ SATURATION: 16,+ COLOR: 17,+ LUMINOSITY: 18+} as const++export const PAINT_TYPES = {+ SOLID: 0,+ GRADIENT_LINEAR: 1,+ GRADIENT_RADIAL: 2,+ GRADIENT_ANGULAR: 3,+ GRADIENT_DIAMOND: 4,+ IMAGE: 5,+ EMOJI: 6,+ VIDEO: 7+} as const++/**+ * Zstd magic bytes+ */+export const ZSTD_MAGIC = new Uint8Array([0x28, 0xb5, 0x2f, 0xfd])++// ============================================================================+// Kiwi Binary Format Constants+// ============================================================================++/**+ * Kiwi uses field numbers to identify message fields.+ * Field 1 with value = message type indicates the message kind.+ */+export const KIWI = {+ /** First byte of valid Kiwi messages (field number 1) */+ MESSAGE_MARKER: 1,++ /** Field number for sessionID in JOIN_START message */+ SESSION_ID_FIELD: 2,++ /** Varint continuation bit (MSB set = more bytes follow) */+ VARINT_CONTINUE_BIT: 0x80,++ /** Varint value mask (lower 7 bits contain data) */+ VARINT_VALUE_MASK: 0x7f,++ /** Bits per varint byte */+ VARINT_BITS_PER_BYTE: 7+} as const++/**+ * Valid session ID range (based on observed Figma behavior)+ */+export const SESSION_ID = {+ MIN: 10000,+ MAX: 1000000+} as const++/**+ * Parse a varint from a Uint8Array at given position+ * Returns [value, newPosition]+ */+export function parseVarint(data: Uint8Array, pos: number): [number, number] {+ let value = 0+ let shift = 0++ while (pos < data.length) {+ const byte = data[pos]+ if (byte === undefined) break+ pos+++ value |= (byte & KIWI.VARINT_VALUE_MASK) << shift++ if (!(byte & KIWI.VARINT_CONTINUE_BIT)) {+ break+ }+ shift += KIWI.VARINT_BITS_PER_BYTE+ }++ return [value, pos]+}++/**+ * Check if data is a valid Kiwi message+ */+export function isKiwiMessage(data: Uint8Array): boolean {+ return data.length >= 2 && data[0] === KIWI.MESSAGE_MARKER+}++/**+ * Get message type from Kiwi message+ */+export function getKiwiMessageType(data: Uint8Array): number | null {+ if (!isKiwiMessage(data)) return null+ return data[1] ?? null+}++/**+ * fig-wire header magic (first 8 bytes of some messages)+ */+export const FIG_WIRE_MAGIC = 'fig-wire'++/**+ * Check if data is Zstd-compressed+ */+export function isZstdCompressed(data: Uint8Array): boolean {+ return (+ data.length >= 4 && data[0] === 0x28 && data[1] === 0xb5 && data[2] === 0x2f && data[3] === 0xfd+ )+}++/**+ * Check if data has fig-wire header+ */+export function hasFigWireHeader(data: Uint8Array): boolean {+ if (data.length < 8) return false+ const header = new TextDecoder().decode(data.slice(0, 8))+ return header === FIG_WIRE_MAGIC+}++/**+ * Skip fig-wire header and find zstd data+ * Header format: "fig-wire" (8 bytes) + version (4 bytes LE) + zstd data+ */+export function skipFigWireHeader(data: Uint8Array): Uint8Array {+ if (!hasFigWireHeader(data)) return data+ // Skip 8 bytes header + 4 bytes version+ return data.slice(12)+}++/**+ * Current multiplayer protocol version+ */+export const PROTOCOL_VERSION = 151++/**+ * Build WebSocket URL for Figma multiplayer+ */+export function buildMultiplayerUrl(fileKey: string, trackingId?: string): string {+ const params = new URLSearchParams({+ role: 'editor',+ version: String(PROTOCOL_VERSION),+ recentReload: '0',+ tracking_session_id: trackingId || `ws-${Date.now()}`+ })+ return `wss://www.figma.com/api/multiplayer/${fileKey}?${params}`+}diff --git a/packages/core/src/kiwi/schema.ts b/packages/core/src/kiwi/schema.tsnew file mode 100644index 000000000..c9d56990d--- /dev/null+++ b/packages/core/src/kiwi/schema.ts@@ -0,0 +1,2178 @@+import { parseSchema } from './kiwi-schema'++const schemaText = `+package Fig;++enum MessageType {+ JOIN_START = 0;+ NODE_CHANGES = 1;+ USER_CHANGES = 2;+ JOIN_END = 3;+ SIGNAL = 4;+ STYLE = 5;+ STYLE_SET = 6;+ JOIN_START_SKIP_RELOAD = 7;+ NOTIFY_SHOULD_UPGRADE = 8;+ UPGRADE_DONE = 9;+ UPGRADE_REFRESH = 10;+ SCENE_GRAPH_QUERY = 11;+ SCENE_GRAPH_REPLY = 12;+ DIFF = 13;+ CLIENT_BROADCAST = 14;+}++enum Axis {+ X = 0;+ Y = 1;+}++enum Access {+ READ_ONLY = 0;+ READ_WRITE = 1;+}++enum NodePhase {+ CREATED = 0;+ REMOVED = 1;+}++enum WindingRule {+ NONZERO = 0;+ ODD = 1;+}++enum NodeType {+ NONE = 0;+ DOCUMENT = 1;+ CANVAS = 2;+ GROUP = 3;+ FRAME = 4;+ BOOLEAN_OPERATION = 5;+ VECTOR = 6;+ STAR = 7;+ LINE = 8;+ ELLIPSE = 9;+ RECTANGLE = 10;+ REGULAR_POLYGON = 11;+ ROUNDED_RECTANGLE = 12;+ TEXT = 13;+ SLICE = 14;+ SYMBOL = 15;+ INSTANCE = 16;+ STICKY = 17;+ SHAPE_WITH_TEXT = 18;+ CONNECTOR = 19;+ CODE_BLOCK = 20;+ WIDGET = 21;+ STAMP = 22;+ MEDIA = 23;+ HIGHLIGHT = 24;+ SECTION = 25;+ SECTION_OVERLAY = 26;+ WASHI_TAPE = 27;+ VARIABLE = 28;+}++enum ShapeWithTextType {+ SQUARE = 0;+ ELLIPSE = 1;+ DIAMOND = 2;+ TRIANGLE_UP = 3;+ TRIANGLE_DOWN = 4;+ ROUNDED_RECTANGLE = 5;+ PARALLELOGRAM_RIGHT = 6;+ PARALLELOGRAM_LEFT = 7;+ ENG_DATABASE = 8;+ ENG_QUEUE = 9;+ ENG_FILE = 10;+ ENG_FOLDER = 11;+}++enum BlendMode {+ PASS_THROUGH = 0;+ NORMAL = 1;+ DARKEN = 2;+ MULTIPLY = 3;+ LINEAR_BURN = 4;+ COLOR_BURN = 5;+ LIGHTEN = 6;+ SCREEN = 7;+ LINEAR_DODGE = 8;+ COLOR_DODGE = 9;+ OVERLAY = 10;+ SOFT_LIGHT = 11;+ HARD_LIGHT = 12;+ DIFFERENCE = 13;+ EXCLUSION = 14;+ HUE = 15;+ SATURATION = 16;+ COLOR = 17;+ LUMINOSITY = 18;+}++enum PaintType {+ SOLID = 0;+ GRADIENT_LINEAR = 1;+ GRADIENT_RADIAL = 2;+ GRADIENT_ANGULAR = 3;+ GRADIENT_DIAMOND = 4;+ IMAGE = 5;+ EMOJI = 6;+}++enum ImageScaleMode {+ STRETCH = 0;+ FIT = 1;+ FILL = 2;+ TILE = 3;+}++enum EffectType {+ INNER_SHADOW = 0;+ DROP_SHADOW = 1;+ FOREGROUND_BLUR = 2;+ BACKGROUND_BLUR = 3;+}++enum TextCase {+ ORIGINAL = 0;+ UPPER = 1;+ LOWER = 2;+ TITLE = 3;+ SMALL_CAPS = 4;+ SMALL_CAPS_FORCED = 5;+}++enum TextDecoration {+ NONE = 0;+ UNDERLINE = 1;+ STRIKETHROUGH = 2;+}++enum NumberUnits {+ RAW = 0;+ PIXELS = 1;+ PERCENT = 2;+}++enum ConstraintType {+ MIN = 0;+ CENTER = 1;+ MAX = 2;+ STRETCH = 3;+ SCALE = 4;+ FIXED_MIN = 5;+ FIXED_MAX = 6;+}++enum StrokeAlign {+ CENTER = 0;+ INSIDE = 1;+ OUTSIDE = 2;+}++enum StrokeCap {+ NONE = 0;+ ROUND = 1;+ SQUARE = 2;+ ARROW_LINES = 3;+ ARROW_EQUILATERAL = 4;+ DIAMOND_FILLED = 5;+ TRIANGLE_FILLED = 6;+ HIGHLIGHT = 7;+ WASHI_TAPE_1 = 8;+ WASHI_TAPE_2 = 9;+ WASHI_TAPE_3 = 10;+ WASHI_TAPE_4 = 11;+ WASHI_TAPE_5 = 12;+ WASHI_TAPE_6 = 13;+ CIRCLE_FILLED = 14;+}++enum StrokeJoin {+ MITER = 0;+ BEVEL = 1;+ ROUND = 2;+}++enum BooleanOperation {+ UNION = 0;+ INTERSECT = 1;+ SUBTRACT = 2;+ XOR = 3;+}++enum TextAlignHorizontal {+ LEFT = 0;+ CENTER = 1;+ RIGHT = 2;+ JUSTIFIED = 3;+}++enum TextAlignVertical {+ TOP = 0;+ CENTER = 1;+ BOTTOM = 2;+}++enum MouseCursor {+ DEFAULT = 0;+ CROSSHAIR = 1;+ EYEDROPPER = 2;+ HAND = 3;+ PAINT_BUCKET = 4;+ PEN = 5;+ PENCIL = 6;+ MARKER = 7;+ ERASER = 8;+ HIGHLIGHTER = 9;+}++enum VectorMirror {+ NONE = 0;+ ANGLE = 1;+ ANGLE_AND_LENGTH = 2;+}++enum DashMode {+ CLIP = 0;+ STRETCH = 1;+}++enum ImageType {+ PNG = 0;+ JPEG = 1;+ SVG = 2;+ PDF = 3;+}++enum ExportConstraintType {+ CONTENT_SCALE = 0;+ CONTENT_WIDTH = 1;+ CONTENT_HEIGHT = 2;+}++enum LayoutGridType {+ MIN = 0;+ CENTER = 1;+ STRETCH = 2;+ MAX = 3;+}++enum LayoutGridPattern {+ STRIPES = 0;+ GRID = 1;+}++enum TextAutoResize {+ NONE = 0;+ WIDTH_AND_HEIGHT = 1;+ HEIGHT = 2;+}++enum TextTruncation {+ DISABLED = 0;+ ENDING = 1;+}++enum StyleSetType {+ PERSONAL = 0;+ TEAM = 1;+ CUSTOM = 2;+ FREQUENCY = 3;+ TEMPORARY = 4;+}++enum StyleSetContentType {+ SOLID = 0;+ GRADIENT = 1;+ IMAGE = 2;+}++enum StackMode {+ NONE = 0;+ HORIZONTAL = 1;+ VERTICAL = 2;+ GRID = 3;+}++enum GridTrackSizeType {+ FIXED = 0;+ FLEX = 1;+ HUG = 2;+}++message GridTrackSize {+ GridTrackSizeType type = 1;+ float value = 2;+}++enum StackAlign {+ MIN = 0;+ CENTER = 1;+ MAX = 2;+ BASELINE = 3;+}++enum StackCounterAlign {+ MIN = 0;+ CENTER = 1;+ MAX = 2;+ STRETCH = 3;+ AUTO = 4;+ BASELINE = 5;+}++enum StackJustify {+ MIN = 0;+ CENTER = 1;+ MAX = 2;+ SPACE_BETWEEN = 3;+}++enum StackSize {+ FIXED = 0;+ RESIZE_TO_FIT = 1;+ RESIZE_TO_FIT_WITH_IMPLICIT_SIZE = 2;+}++enum StackPositioning {+ AUTO = 0;+ ABSOLUTE = 1;+}++enum ConnectionType {+ NONE = 0;+ INTERNAL_NODE = 1;+ URL = 2;+ BACK = 3;+ CLOSE = 4;+ SET_VARIABLE = 5;+}++enum InteractionType {+ ON_CLICK = 0;+ AFTER_TIMEOUT = 1;+ MOUSE_IN = 2;+ MOUSE_OUT = 3;+ ON_HOVER = 4;+ MOUSE_DOWN = 5;+ MOUSE_UP = 6;+ ON_PRESS = 7;+ NONE = 8;+ DRAG = 9;+ ON_KEY_DOWN = 10;+ ON_VOICE = 11;+}++enum TransitionType {+ INSTANT_TRANSITION = 0;+ DISSOLVE = 1;+ FADE = 2;+ SLIDE_FROM_LEFT = 3;+ SLIDE_FROM_RIGHT = 4;+ SLIDE_FROM_TOP = 5;+ SLIDE_FROM_BOTTOM = 6;+ PUSH_FROM_LEFT = 7;+ PUSH_FROM_RIGHT = 8;+ PUSH_FROM_TOP = 9;+ PUSH_FROM_BOTTOM = 10;+ MOVE_FROM_LEFT = 11;+ MOVE_FROM_RIGHT = 12;+ MOVE_FROM_TOP = 13;+ MOVE_FROM_BOTTOM = 14;+ SLIDE_OUT_TO_LEFT = 15;+ SLIDE_OUT_TO_RIGHT = 16;+ SLIDE_OUT_TO_TOP = 17;+ SLIDE_OUT_TO_BOTTOM = 18;+ MOVE_OUT_TO_LEFT = 19;+ MOVE_OUT_TO_RIGHT = 20;+ MOVE_OUT_TO_TOP = 21;+ MOVE_OUT_TO_BOTTOM = 22;+ MAGIC_MOVE = 23;+ SMART_ANIMATE = 24;+ SCROLL_ANIMATE = 25;+}++enum EasingType {+ IN_CUBIC = 0;+ OUT_CUBIC = 1;+ INOUT_CUBIC = 2;+ LINEAR = 3;+ IN_BACK_CUBIC = 4;+ OUT_BACK_CUBIC = 5;+ INOUT_BACK_CUBIC = 6;+ CUSTOM_CUBIC = 7;+ SPRING = 8;+ GENTLE_SPRING = 9;+ CUSTOM_SPRING = 10;+ SPRING_PRESET_ONE = 11;+ SPRING_PRESET_TWO = 12;+ SPRING_PRESET_THREE = 13;+}++enum ScrollDirection {+ NONE = 0;+ HORIZONTAL = 1;+ VERTICAL = 2;+ BOTH = 3;+}++enum ScrollContractedState {+ EXPANDED = 0;+ CONTRACTED = 1;+}++struct GUID {+ uint sessionID;+ uint localID;+}++struct Color {+ float r;+ float g;+ float b;+ float a;+}++struct Vector {+ float x;+ float y;+}++struct Rect {+ float x;+ float y;+ float w;+ float h;+}++struct ColorStop {+ Color color;+ float position;+}++struct Matrix {+ float m00;+ float m01;+ float m02;+ float m10;+ float m11;+ float m12;+}++struct ParentIndex {+ GUID guid;+ string position;+}++struct Number {+ float value;+ NumberUnits units;+}++struct FontName {+ string family;+ string style;+ string postscript;+}++enum FontVariantNumericFigure {+ NORMAL = 0;+ LINING = 1;+ OLDSTYLE = 2;+}++enum FontVariantNumericSpacing {+ NORMAL = 0;+ PROPORTIONAL = 1;+ TABULAR = 2;+}++enum FontVariantNumericFraction {+ NORMAL = 0;+ DIAGONAL = 1;+ STACKED = 2;+}++enum FontVariantCaps {+ NORMAL = 0;+ SMALL = 1;+ ALL_SMALL = 2;+ PETITE = 3;+ ALL_PETITE = 4;+ UNICASE = 5;+ TITLING = 6;+}++enum FontVariantPosition {+ NORMAL = 0;+ SUB = 1;+ SUPER = 2;+}++enum FontStyle {+ NORMAL = 0;+ ITALIC = 1;+}++enum OpenTypeFeature {+ PCAP = 0;+ C2PC = 1;+ CASE = 2;+ CPSP = 3;+ TITL = 4;+ UNIC = 5;+ ZERO = 6;+ SINF = 7;+ ORDN = 8;+ AFRC = 9;+ DNOM = 10;+ NUMR = 11;+ LIGA = 12;+ CLIG = 13;+ DLIG = 14;+ HLIG = 15;+ RLIG = 16;+ AALT = 17;+ CALT = 18;+ RCLT = 19;+ SALT = 20;+ RVRN = 21;+ VERT = 22;+ SWSH = 23;+ CSWH = 24;+ NALT = 25;+ CCMP = 26;+ STCH = 27;+ HIST = 28;+ SIZE = 29;+ ORNM = 30;+ ITAL = 31;+ RAND = 32;+ DTLS = 33;+ FLAC = 34;+ MGRK = 35;+ SSTY = 36;+ KERN = 37;+ FWID = 38;+ HWID = 39;+ HALT = 40;+ TWID = 41;+ QWID = 42;+ PWID = 43;+ JUST = 44;+ LFBD = 45;+ OPBD = 46;+ RTBD = 47;+ PALT = 48;+ PKNA = 49;+ LTRA = 50;+ LTRM = 51;+ RTLA = 52;+ RTLM = 53;+ ABRV = 54;+ ABVM = 55;+ ABVS = 56;+ VALT = 57;+ VHAL = 58;+ BLWF = 59;+ BLWM = 60;+ BLWS = 61;+ AKHN = 62;+ CJCT = 63;+ CFAR = 64;+ CPCT = 65;+ CURS = 66;+ DIST = 67;+ EXPT = 68;+ FALT = 69;+ FINA = 70;+ FIN2 = 71;+ FIN3 = 72;+ HALF = 73;+ HALN = 74;+ HKNA = 75;+ HNGL = 76;+ HOJO = 77;+ INIT = 78;+ ISOL = 79;+ JP78 = 80;+ JP83 = 81;+ JP90 = 82;+ JP04 = 83;+ LJMO = 84;+ LOCL = 85;+ MARK = 86;+ MEDI = 87;+ MED2 = 88;+ MKMK = 89;+ NLCK = 90;+ NUKT = 91;+ PREF = 92;+ PRES = 93;+ VPAL = 94;+ PSTF = 95;+ PSTS = 96;+ RKRF = 97;+ RPHF = 98;+ RUBY = 99;+ SMPL = 100;+ TJMO = 101;+ TNAM = 102;+ TRAD = 103;+ VATU = 104;+ VJMO = 105;+ VKNA = 106;+ VKRN = 107;+ VRTR = 108;+ VRT2 = 109;+ SS01 = 110;+ SS02 = 111;+ SS03 = 112;+ SS04 = 113;+ SS05 = 114;+ SS06 = 115;+ SS07 = 116;+ SS08 = 117;+ SS09 = 118;+ SS10 = 119;+ SS11 = 120;+ SS12 = 121;+ SS13 = 122;+ SS14 = 123;+ SS15 = 124;+ SS16 = 125;+ SS17 = 126;+ SS18 = 127;+ SS19 = 128;+ SS20 = 129;+ CV01 = 130;+ CV02 = 131;+ CV03 = 132;+ CV04 = 133;+ CV05 = 134;+ CV06 = 135;+ CV07 = 136;+ CV08 = 137;+ CV09 = 138;+ CV10 = 139;+ CV11 = 140;+ CV12 = 141;+ CV13 = 142;+ CV14 = 143;+ CV15 = 144;+ CV16 = 145;+ CV17 = 146;+ CV18 = 147;+ CV19 = 148;+ CV20 = 149;+ CV21 = 150;+ CV22 = 151;+ CV23 = 152;+ CV24 = 153;+ CV25 = 154;+ CV26 = 155;+ CV27 = 156;+ CV28 = 157;+ CV29 = 158;+ CV30 = 159;+ CV31 = 160;+ CV32 = 161;+ CV33 = 162;+ CV34 = 163;+ CV35 = 164;+ CV36 = 165;+ CV37 = 166;+ CV38 = 167;+ CV39 = 168;+ CV40 = 169;+ CV41 = 170;+ CV42 = 171;+ CV43 = 172;+ CV44 = 173;+ CV45 = 174;+ CV46 = 175;+ CV47 = 176;+ CV48 = 177;+ CV49 = 178;+ CV50 = 179;+ CV51 = 180;+ CV52 = 181;+ CV53 = 182;+ CV54 = 183;+ CV55 = 184;+ CV56 = 185;+ CV57 = 186;+ CV58 = 187;+ CV59 = 188;+ CV60 = 189;+ CV61 = 190;+ CV62 = 191;+ CV63 = 192;+ CV64 = 193;+ CV65 = 194;+ CV66 = 195;+ CV67 = 196;+ CV68 = 197;+ CV69 = 198;+ CV70 = 199;+ CV71 = 200;+ CV72 = 201;+ CV73 = 202;+ CV74 = 203;+ CV75 = 204;+ CV76 = 205;+ CV77 = 206;+ CV78 = 207;+ CV79 = 208;+ CV80 = 209;+ CV81 = 210;+ CV82 = 211;+ CV83 = 212;+ CV84 = 213;+ CV85 = 214;+ CV86 = 215;+ CV87 = 216;+ CV88 = 217;+ CV89 = 218;+ CV90 = 219;+ CV91 = 220;+ CV92 = 221;+ CV93 = 222;+ CV94 = 223;+ CV95 = 224;+ CV96 = 225;+ CV97 = 226;+ CV98 = 227;+ CV99 = 228;+}++struct ExportConstraint {+ ExportConstraintType type;+ float value;+}++struct GUIDMapping {+ GUID from;+ GUID to;+}++struct Blob {+ byte[] bytes;+}++message Image {+ byte[] hash = 1;+ string name = 2;+ uint dataBlob = 3;+}++message Video {+ byte[] hash = 1;+ string s3Url = 2;+}++struct FilterColorAdjust {+ float tint;+ float shadows;+ float highlights;+ float detail;+ float exposure;+ float vignette;+ float temperature;+ float vibrance;+}++message PaintFilterMessage {+ float tint = 1;+ float shadows = 2;+ float highlights = 3;+ float detail = 4 [deprecated];+ float exposure = 5;+ float vignette = 6 [deprecated];+ float temperature = 7;+ float vibrance = 8;+ float contrast = 9;+ float brightness = 10 [deprecated];+}++// Variable binding embedded in Paint - discovered via WS sniffing 2026-01+// Figma wire format: 15 01 04 01 {sessionID varint} {localID varint}+// - 15 = field 21 in Paint+// - 01 = always 1 (binding type for color)+// - 04 = field 4+// - 01 = always 1 (flag)+// - then GUID as raw sessionID + localID varints (no field numbers)+// NOTE: kiwi-schema cannot produce this exact format, handled manually in codec+message PaintVariableBinding {+ uint bindingType = 1; // Always 1 for color+ uint flag = 2; // Placeholder+ uint flag2 = 3; // Placeholder+ GUID variableID = 4; // Variable GUID+}++message Paint {+ PaintType type = 1;+ Color color = 2;+ float opacity = 3;+ bool visible = 4;+ BlendMode blendMode = 5;+ ColorStop[] stops = 6;+ Matrix transform = 7;+ Image image = 8;+ Image imageThumbnail = 9;+ Image animatedImage = 16;+ uint animationFrame = 17;+ ImageScaleMode imageScaleMode = 10;+ float rotation = 11;+ float scale = 12;+ FilterColorAdjust filterColorAdjust = 13 [deprecated];+ PaintFilterMessage paintFilter = 14;+ uint[] emojiCodePoints = 15;+ Video video = 18;+ uint originalImageWidth = 19;+ uint originalImageHeight = 20;+ PaintVariableBinding variableBinding = 21; // Not in fig-kiwi. Discovered via WS sniffing 2026-01+}++message FontMetaData {+ FontName key = 1;+ float fontLineHeight = 2;+ byte[] fontDigest = 3;+ FontStyle fontStyle = 4;+ int fontWeight = 5;+}++message FontVariation {+ uint axisTag = 1;+ string axisName = 2;+ float value = 3;+}++message TextData {+ string characters = 1;+ uint[] characterStyleIDs = 2;+ NodeChange[] styleOverrideTable = 3;+ Vector layoutSize = 4;+ Baseline[] baselines = 5;+ Glyph[] glyphs = 6;+ Decoration[] decorations = 7;+ uint layoutVersion = 8;+ FontMetaData[] fontMetaData = 9;+ FontName[] fallbackFonts = 10;+ HyperlinkBox[] hyperlinkBoxes = 11;+ TextLineData[] lines = 12;+ int truncationStartIndex = 13;+ float truncatedHeight = 14;+}++message HyperlinkBox {+ Rect bounds = 1;+ string url = 2;+ GUID guid = 3;+ int hyperlinkID = 4;+}++message Baseline {+ Vector position = 1;+ float width = 2;+ float lineY = 3;+ float lineHeight = 4;+ float lineAscent = 7;+ uint firstCharacter = 5;+ uint endCharacter = 6;+}++message Glyph {+ uint commandsBlob = 1;+ Vector position = 2;+ uint styleID = 3;+ float fontSize = 4;+ uint firstCharacter = 5;+ float advance = 6;+}++message Decoration {+ Rect[] rects = 1;+ uint styleID = 2;+}++message VectorData {+ uint vectorNetworkBlob = 1;+ Vector normalizedSize = 2;+ NodeChange[] styleOverrideTable = 3;+}++message GUIDPath {+ GUID[] guids = 1;+}++message SymbolData {+ GUID symbolID = 1;+ NodeChange[] symbolOverrides = 2;+ float uniformScaleFactor = 3;+}++message GUIDPathMapping {+ GUID id = 1;+ GUIDPath path = 2;+}++message NodeGenerationData {+ NodeChange[] overrides = 1;+}++message DerivedImmutableFrameData {+ NodeChange[] overrides = 1;+ uint version = 2;+}++message SharedSymbolReference {+ string fileKey = 1;+ GUID symbolID = 2;+ string versionHash = 3;+ GUIDPathMapping[] guidPathMappings = 4;+ byte[] bytes = 5;+ GUIDMapping[] libraryGUIDToSubscribingGUID = 6 [deprecated];+ string componentKey = 7;+ GUIDPathMapping[] unflatteningMappings = 8;+ bool isUnflattened = 9;+}++message SharedComponentMasterData {+ string componentKey = 1;+ GUIDPathMapping[] publishingGUIDPathToTeamLibraryGUID = 2;+ bool isUnflattened = 3;+}++message InstanceOverrideStash {+ GUIDPath overridePathOfSwappedInstance = 1;+ string componentKey = 2;+ NodeChange[] overrides = 3;+}++message InstanceOverrideStashV2 {+ GUIDPath overridePathOfSwappedInstance = 1;+ GUID localSymbolID = 2;+ NodeChange[] overrides = 3;+}++message Effect {+ EffectType type = 1;+ Color color = 2;+ Vector offset = 3;+ float radius = 4;+ bool visible = 5;+ BlendMode blendMode = 6;+ float spread = 7;+ bool showShadowBehindNode = 8;+}++message TransitionInfo {+ TransitionType type = 1;+ float duration = 2;+}++enum PrototypeDeviceType {+ NONE = 0;+ PRESET = 1;+ CUSTOM = 2;+ PRESENTATION = 3;+}++enum DeviceRotation {+ NONE = 0;+ CCW_90 = 1;+}++message PrototypeDevice {+ PrototypeDeviceType type = 1;+ Vector size = 2;+ string presetIdentifier = 3;+ DeviceRotation rotation = 4;+}++enum OverlayPositionType {+ CENTER = 0;+ TOP_LEFT = 1;+ TOP_CENTER = 2;+ TOP_RIGHT = 3;+ BOTTOM_LEFT = 4;+ BOTTOM_CENTER = 5;+ BOTTOM_RIGHT = 6;+ MANUAL = 7;+}++enum OverlayBackgroundInteraction {+ NONE = 0;+ CLOSE_ON_CLICK_OUTSIDE = 1;+}++enum OverlayBackgroundType {+ NONE = 0;+ SOLID_COLOR = 1;+}++message OverlayBackgroundAppearance {+ OverlayBackgroundType backgroundType = 1;+ Color backgroundColor = 2;+}++enum NavigationType {+ NAVIGATE = 0;+ OVERLAY = 1;+ SWAP = 2;+ SWAP_STATE = 3;+ SCROLL_TO = 4;+}++message ExportSettings {+ string suffix = 1;+ ImageType imageType = 2;+ ExportConstraint constraint = 3;+ bool svgDataName = 4;+ ExportSVGIDMode svgIDMode = 5;+ bool svgOutlineText = 6;+ bool contentsOnly = 7;+ bool svgForceStrokeMasks = 8;+ bool useAbsoluteBounds = 9;+}++enum ExportSVGIDMode {+ IF_NEEDED = 0;+ ALWAYS = 1;+}++message LayoutGrid {+ LayoutGridType type = 1;+ Axis axis = 2;+ bool visible = 3;+ int numSections = 4;+ float offset = 5;+ float sectionSize = 6;+ float gutterSize = 7;+ Color color = 8;+ LayoutGridPattern pattern = 9;+}++message Guide {+ Axis axis = 1;+ float offset = 2;+ GUID guid = 3;+}++message Path {+ WindingRule windingRule = 1;+ uint commandsBlob = 2;+ uint styleID = 3;+}++enum StyleType {+ NONE = 0;+ FILL = 1;+ STROKE = 2;+ TEXT = 3;+ EFFECT = 4;+ EXPORT = 5;+ GRID = 6;+}++message SharedStyleReference {+ string styleKey = 1;+ string versionHash = 2;+}++message SharedStyleMasterData {+ string styleKey = 1;+ string sortPosition = 2;+ string fileKey = 3;+}++enum ScrollBehavior {+ SCROLLS = 0;+ FIXED_WHEN_CHILD_OF_SCROLLING_FRAME = 1;+}++message ArcData {+ float startingAngle = 1;+ float endingAngle = 2;+ float innerRadius = 3;+}++message SymbolLink {+ string uri = 1;+ string displayName = 2;+ string displayText = 3;+}++message PluginData {+ string pluginID = 1;+ string value = 2;+ string key = 3;+}++message PluginRelaunchData {+ string pluginID = 1;+ string message = 2;+ string command = 3;+ bool isDeleted = 4;+}++enum ConnectorMagnet {+ NONE = 0;+ AUTO = 1;+ TOP = 2;+ LEFT = 3;+ BOTTOM = 4;+ RIGHT = 5;+}++message ConnectorEndpoint {+ GUID endpointNodeID = 1;+ Vector position = 2;+ ConnectorMagnet magnet = 3;+}++message ConnectorControlPoint {+ Vector position = 1;+ Vector axis = 2;+}++enum ConnectorTextSection {+ MIDDLE_TO_START = 0;+ MIDDLE_TO_END = 1;+}++message ConnectorTextMidpoint {+ ConnectorTextSection section = 1;+ float offset = 2;+}++enum ConnectorLineStyle {+ ELBOWED = 0;+ STRAIGHT = 1;+}++message LibraryMoveInfo {+ string oldKey = 1;+ string pasteFileKey = 2;+}++message LibraryMoveHistoryItem {+ GUID sourceNodeId = 1;+ string sourceComponentKey = 2;+}++message WidgetPointer {+ GUID nodeId = 1;+}++enum EditorType {+ DESIGN = 0;+ WHITEBOARD = 1;+}++message NodeChange {+ GUID guid = 1;+ uint guidTag = 53 [deprecated];+ NodePhase phase = 2;+ uint phaseTag = 54 [deprecated];+ ParentIndex parentIndex = 3;+ uint parentIndexTag = 55 [deprecated];+ NodeType type = 4;+ uint typeTag = 56 [deprecated];+ string name = 5;+ uint nameTag = 57 [deprecated];+ bool visible = 6;+ uint visibleTag = 58 [deprecated];+ bool locked = 7;+ uint lockedTag = 59 [deprecated];+ float opacity = 8;+ uint opacityTag = 60 [deprecated];+ BlendMode blendMode = 9;+ uint blendModeTag = 61 [deprecated];+ uint count = 10;+ uint countTag = 62 [deprecated];+ Vector size = 11;+ uint sizeTag = 63 [deprecated];+ Matrix transform = 12;+ uint transformTag = 64 [deprecated];+ float[] dashPattern = 13;+ uint dashPatternTag = 65 [deprecated];+ bool autoRename = 14;+ uint autoRenameTag = 66 [deprecated];+ bool backgroundEnabled = 15;+ uint backgroundEnabledTag = 67 [deprecated];+ bool mask = 16;+ uint maskTag = 68 [deprecated];+ bool exportContentsOnly = 17;+ uint exportContentsOnlyTag = 69 [deprecated];+ bool maskIsOutline = 18;+ uint maskIsOutlineTag = 70 [deprecated];+ float backgroundOpacity = 19;+ uint backgroundOpacityTag = 71 [deprecated];+ float cornerRadius = 20;+ uint cornerRadiusTag = 72 [deprecated];+ float fontSize = 21;+ uint fontSizeTag = 73 [deprecated];+ float paragraphIndent = 22;+ uint paragraphIndentTag = 74 [deprecated];+ float paragraphSpacing = 23;+ uint paragraphSpacingTag = 75 [deprecated];+ float starInnerScale = 24;+ uint starInnerScaleTag = 76 [deprecated];+ float miterLimit = 25;+ uint miterLimitTag = 77 [deprecated];+ float strokeWeight = 26;+ uint strokeWeightTag = 78 [deprecated];+ float textTracking = 27;+ uint textTrackingTag = 79 [deprecated];+ ConstraintType horizontalConstraint = 28;+ uint horizontalConstraintTag = 80 [deprecated];+ StrokeAlign strokeAlign = 29;+ uint strokeAlignTag = 81 [deprecated];+ StrokeCap strokeCap = 30;+ uint strokeCapTag = 82 [deprecated];+ StrokeJoin strokeJoin = 31;+ uint strokeJoinTag = 83 [deprecated];+ TextAlignHorizontal textAlignHorizontal = 32;+ uint textAlignHorizontalTag = 84 [deprecated];+ TextAlignVertical textAlignVertical = 33;+ uint textAlignVerticalTag = 85 [deprecated];+ TextCase textCase = 34;+ uint textCaseTag = 86 [deprecated];+ TextDecoration textDecoration = 35;+ uint textDecorationTag = 87 [deprecated];+ BooleanOperation booleanOperation = 36;+ uint booleanOperationTag = 88 [deprecated];+ ConstraintType verticalConstraint = 37;+ uint verticalConstraintTag = 89 [deprecated];+ Paint[] fillPaints = 38;+ uint fillPaintsTag = 90 [deprecated];+ Paint[] strokePaints = 39;+ uint strokePaintsTag = 91 [deprecated];+ Number lineHeight = 40;+ uint lineHeightTag = 92 [deprecated];+ FontName fontName = 41;+ uint fontNameTag = 93 [deprecated];+ TextData textData = 42;+ uint textDataTag = 94 [deprecated];+ Effect[] effects = 43;+ uint effectsTag = 95 [deprecated];+ VectorMirror handleMirroring = 44;+ uint handleMirroringTag = 96 [deprecated];+ ExportSettings[] exportSettings = 45;+ uint exportSettingsTag = 97 [deprecated];+ TextAutoResize textAutoResize = 46;+ uint textAutoResizeTag = 98 [deprecated];+ LayoutGrid[] layoutGrids = 47;+ uint layoutGridsTag = 99 [deprecated];+ VectorData vectorData = 48;+ uint vectorDataTag = 100 [deprecated];+ uint styleID = 49;+ uint styleIDTag = 101 [deprecated];+ Color backgroundColor = 50;+ uint backgroundColorTag = 102 [deprecated];+ Path[] fillGeometry = 51;+ uint fillGeometryTag = 103 [deprecated];+ Path[] strokeGeometry = 52;+ uint strokeGeometryTag = 104 [deprecated];+ StackMode stackMode = 105;+ uint stackModeTag = 106 [deprecated];+ float stackSpacing = 107;+ uint stackSpacingTag = 108 [deprecated];+ float stackPadding = 109;+ uint stackPaddingTag = 110 [deprecated];+ GUIDPath guidPath = 111;+ uint guidPathTag = 112 [deprecated];+ SymbolData symbolData = 113;+ uint symbolDataTag = 114 [deprecated];+ bool frameMaskDisabled = 115;+ uint frameMaskDisabledTag = 116 [deprecated];+ bool resizeToFit = 117;+ uint resizeToFitTag = 118 [deprecated];+ bool exportBackgroundDisabled = 119;+ StackCounterAlign stackCounterAlign = 120;+ StackJustify stackJustify = 121;+ SharedSymbolReference sharedSymbolReference = 122;+ bool isSymbolPublishable = 123;+ GUIDPathMapping[] sharedSymbolMappings = 124;+ NodeChange[] derivedSymbolData = 125;+ string sharedSymbolVersion = 126;+ bool fontVariantCommonLigatures = 127;+ bool fontVariantContextualLigatures = 128;+ bool fontVariantDiscretionaryLigatures = 129;+ bool fontVariantHistoricalLigatures = 130;+ bool fontVariantOrdinal = 131;+ bool fontVariantSlashedZero = 132;+ FontVariantNumericFigure fontVariantNumericFigure = 133;+ FontVariantNumericSpacing fontVariantNumericSpacing = 134;+ FontVariantNumericFraction fontVariantNumericFraction = 135;+ FontVariantCaps fontVariantCaps = 136;+ FontVariantPosition fontVariantPosition = 137;+ Guide[] guides = 138;+ GUID transitionNodeID = 139;+ GUID prototypeStartNodeID = 140;+ Color prototypeBackgroundColor = 141;+ bool internalOnly = 142;+ GUID overriddenSymbolID = 143;+ string symbolDescription = 144;+ float rectangleTopLeftCornerRadius = 145;+ float rectangleTopRightCornerRadius = 146;+ float rectangleBottomLeftCornerRadius = 147;+ float rectangleBottomRightCornerRadius = 148;+ bool rectangleCornerRadiiIndependent = 149;+ bool rectangleCornerToolIndependent = 150;+ bool proportionsConstrained = 151;+ SharedComponentMasterData sharedComponentMasterData = 152;+ TransitionInfo transitionInfo = 153 [deprecated];+ TransitionType transitionType = 154;+ float transitionDuration = 155;+ EasingType easingType = 156;+ ScrollDirection scrollDirection = 159;+ float cornerSmoothing = 160;+ GUID inheritFillStyleID = 158;+ GUID inheritStrokeStyleID = 162;+ GUID inheritTextStyleID = 167;+ GUID inheritExportStyleID = 168;+ GUID inheritEffectStyleID = 169;+ GUID inheritGridStyleID = 170;+ GUID inheritFillStyleIDForStroke = 185;+ bool isFillStyle = 157 [deprecated];+ bool isStrokeStyle = 161 [deprecated];+ StyleType styleType = 163;+ string styleDescription = 191;+ GUIDPathMapping[] unflatteningMappings = 164;+ Number letterSpacing = 165;+ Vector scrollOffset = 166 [deprecated];+ string version = 171;+ SharedStyleMasterData sharedStyleMasterData = 172;+ SharedStyleReference sharedStyleReference = 173;+ bool isPublishable = 174;+ bool exportTextAsSVGText = 175;+ bool isSoftDeletedStyle = 176;+ bool isNonUpdateable = 177;+ ScrollContractedState scrollContractedState = 178 [deprecated];+ Vector contractedSize = 179 [deprecated];+ string fixedChildrenDivider = 180 [deprecated];+ bool transitionPreserveScroll = 181;+ ConnectionType connectionType = 182;+ string connectionURL = 183;+ PrototypeDevice prototypeDevice = 184;+ ScrollBehavior scrollBehavior = 186;+ InteractionType interactionType = 187;+ float transitionTimeout = 188;+ bool interactionMaintained = 189;+ float interactionDuration = 190;+ bool destinationIsOverlay = 192 [deprecated];+ Paint[] backgroundPaints = 193;+ GUID inheritFillStyleIDForBackground = 194;+ ArcData arcData = 195;+ int derivedSymbolDataLayoutVersion = 196;+ NavigationType navigationType = 197;+ OverlayPositionType overlayPositionType = 198;+ Vector overlayRelativePosition = 199;+ OverlayBackgroundInteraction overlayBackgroundInteraction = 200;+ OverlayBackgroundAppearance overlayBackgroundAppearance = 201;+ string fontVersion = 202;+ uint textUserLayoutVersion = 203;+ PluginData[] pluginData = 204;+ OpenTypeFeature[] toggledOnOTFeatures = 205;+ OpenTypeFeature[] toggledOffOTFeatures = 206;+ bool transitionShouldSmartAnimate = 207;+ StackAlign stackAlign = 208 [deprecated];+ float stackHorizontalPadding = 209;+ float stackVerticalPadding = 210;+ StackSize stackWidth = 211 [deprecated];+ StackSize stackHeight = 212 [deprecated];+ GUID overrideKey = 213;+ string publishFile = 214;+ GUID publishID = 215;+ string componentKey = 216;+ bool isC2 = 217;+ string publishedVersion = 218;+ PluginRelaunchData[] pluginRelaunchData = 219;+ bool containerSupportsFillStrokeAndCorners = 220;+ StackSize stackCounterSizing = 221;+ bool containersSupportFillStrokeAndCorners = 222 [deprecated];+ Hyperlink hyperlink = 223;+ KeyTrigger keyTrigger = 224;+ bool isStateGroup = 225;+ PrototypeInteraction[] prototypeInteractions = 226;+ string voiceEventPhrase = 227;+ GUIDPathMapping[] forceUnflatteningMappings = 228;+ StackSize stackPrimarySizing = 229;+ StackJustify stackPrimaryAlignItems = 230;+ StackAlign stackCounterAlignItems = 231;+ float stackChildPrimaryGrow = 232;+ float stackPaddingRight = 233;+ float stackPaddingBottom = 234;+ GUID[] ancestorPathBeforeDeletion = 235;+ StackCounterAlign stackChildAlignSelf = 236;+ SymbolLink[] symbolLinks = 237;+ StateGroupPropertyValueOrder[] stateGroupPropertyValueOrders = 238;+ TextListData textListData = 239;+ NodeGenerationData nodeGenerationData = 240;+ ShapeWithTextType shapeWithTextType = 241;+ ConnectorEndpoint connectorStart = 242;+ ConnectorEndpoint connectorEnd = 243;+ ConnectorLineStyle connectorLineStyle = 244;+ StrokeCap connectorStartCap = 245;+ StrokeCap connectorEndCap = 246;+ float shapeUserHeight = 247;+ InstanceOverrideStash[] overrideStash = 248;+ PrototypeStartingPoint prototypeStartingPoint = 249;+ InstanceOverrideStashV2[] overrideStashV2 = 250 [deprecated];+ InternalEnumForTest internalEnumForTest = 251;+ string originComponentKey = 252 [deprecated];+ ConnectorControlPoint[] connectorControlPoints = 253;+ DerivedImmutableFrameData derivedImmutableFrameData = 254;+ ConnectorTextMidpoint connectorTextMidpoint = 255;+ LibraryMoveInfo libraryMoveInfo = 256;+ InternalDataForTest internalDataForTest = 257;+ bool useAbsoluteBounds = 258 [deprecated];+ CodeBlockLanguage codeBlockLanguage = 259;+ FontVariation[] fontVariations = 260;+ bool detachOpticalSizeFromFontSize = 261;+ WidgetMetadata widgetMetadata = 262;+ WidgetEvent[] widgetEvents = 263;+ float listSpacing = 264;+ WidgetPropertyMenuItem[] widgetPropertyMenuItems = 265;+ ComponentPropDef[] componentPropDefs = 266;+ ComponentPropRef[] componentPropRefs = 267;+ ComponentPropAssignment[] componentPropAssignments = 268;+ StackPositioning stackPositioning = 269;+ EmbedData embedData = 270;+ bool stackReverseZIndex = 271;+ RichMediaData richMediaData = 272;+ MultiplayerMap widgetSyncedState = 273;+ uint widgetSyncCursor = 274 [deprecated];+ WidgetDerivedSubtreeCursor widgetDerivedSubtreeCursor = 275 [deprecated];+ WidgetPointer widgetCachedAncestor = 276;+ MultiplayerMap renderedSyncedState = 277;+ LinkPreviewData linkPreviewData = 278;+ uint textBidiVersion = 279;+ TextTruncation textTruncation = 280;+ LibraryMoveHistoryItem[] libraryMoveHistory = 281;+ bool shapeTruncates = 282;+ bool sectionContentsHidden = 283;+ bool simplifyInstancePanels = 284;+ WidgetInputBehavior widgetInputBehavior = 285;+ string widgetTooltip = 286;+ bool borderTopHidden = 287 [deprecated];+ bool borderBottomHidden = 288 [deprecated];+ bool borderLeftHidden = 289 [deprecated];+ bool borderRightHidden = 290 [deprecated];+ WidgetHoverStyle widgetHoverStyle = 291;+ bool hasHadRTLText = 292;+ bool isWidgetStickable = 293;+ bool bordersTakeSpace = 294;+ float borderTopWeight = 295;+ float borderBottomWeight = 296;+ float borderLeftWeight = 297;+ float borderRightWeight = 298;+ bool borderStrokeWeightsIndependent = 299;+ VideoPlayback videoPlayback = 300;+ StampData stampData = 301;+ HTMLTag htmlTag = 302;+ ARIARole ariaRole = 303;+ string accessibleLabel = 304;+ bool propsAreBubbled = 305;+ VariableData variableData = 306;+ uint gridRowCount = 435;+ uint gridColumnCount = 436;+ float gridRowGap = 437;+ float gridColumnGap = 438;+ GridTrackSize[] gridColumnSizes = 474;+ GridTrackSize[] gridRowSizes = 475;+}++message VideoPlayback {+ bool autoplay = 1;+ bool mediaLoop = 2;+ bool muted = 3;+}++message WidgetHoverStyle {+ Paint[] fillPaints = 1;+ Paint[] strokePaints = 2;+ float opacity = 3;+ bool areFillPaintsSet = 4;+ bool areStrokePaintsSet = 5;+ bool isOpacitySet = 6;+}++message WidgetDerivedSubtreeCursor {+ uint sessionID = 1;+ uint counter = 2;+}++message MultiplayerMap {+ MultiplayerMapEntry[] entries = 1;+}++message MultiplayerMapEntry {+ string key = 1;+ string value = 2;+}++message ComponentPropRef {+ uint nodeField = 1;+ GUID defID = 2;+ string zombieFallbackName = 3;+ ComponentPropNodeField componentPropNodeField = 4;+ bool isDeleted = 5;+}++enum ComponentPropNodeField {+ VISIBLE = 0;+ TEXT_DATA = 1;+ OVERRIDDEN_SYMBOL_ID = 2;+ INHERIT_FILL_STYLE_ID = 3;+}++message ComponentPropAssignment {+ GUID defID = 1;+ ComponentPropValue value = 2;+}++message ComponentPropDef {+ GUID id = 1;+ string name = 2;+ ComponentPropValue initialValue = 3;+ string sortPosition = 4;+ GUID parentPropDefId = 5;+ ComponentPropType type = 6;+ bool isDeleted = 7;+ ComponentPropPreferredValues preferredValues = 8;+}++message ComponentPropValue {+ bool boolValue = 1;+ TextData textValue = 2;+ GUID guidValue = 3;+}++enum ComponentPropType {+ BOOL = 0;+ TEXT = 1;+ COLOR = 2;+ INSTANCE_SWAP = 3;+}++message ComponentPropPreferredValues {+ string[] stringValues = 1;+}++enum WidgetEvent {+ MOUSE_DOWN = 0;+ CLICK = 1;+ TEXT_EDIT_END = 2;+ ATTACHED_STICKABLES_CHANGED = 3;+ STUCK_STATUS_CHANGED = 4;+}++enum WidgetInputBehavior {+ WRAP = 0;+ TRUNCATE = 1;+ MULTILINE = 2;+}++message WidgetMetadata {+ string pluginID = 1;+ string pluginVersionID = 2;+ string widgetName = 3;+}++enum WidgetPropertyMenuItemType {+ ACTION = 0;+ SEPARATOR = 1;+ COLOR = 2;+ DROPDOWN = 3;+ COLOR_SELECTOR = 4;+ TOGGLE = 5;+ LINK = 6;+}++message WidgetPropertyMenuSelectorOption {+ string option = 1;+ string tooltip = 2;+}++message WidgetPropertyMenuItem {+ string propertyName = 1;+ string tooltip = 2;+ WidgetPropertyMenuItemType itemType = 3;+ string icon = 4;+ WidgetPropertyMenuSelectorOption[] options = 5;+ string selectedOption = 6;+ bool isToggled = 7;+ string href = 8;+}++enum CodeBlockLanguage {+ TYPESCRIPT = 0;+ CPP = 1;+ RUBY = 2;+ CSS = 3;+ JAVASCRIPT = 4;+ HTML = 5;+ JSON = 6;+ GRAPHQL = 7;+ PYTHON = 8;+ GO = 9;+ SQL = 10;+ SWIFT = 11;+ KOTLIN = 12;+ RUST = 13;+}++enum InternalEnumForTest {+ OLD = 1;+}++message InternalDataForTest {+ int testFieldA = 1;+}++message StateGroupPropertyValueOrder {+ string property = 1;+ string[] values = 2;+}++message TextListData {+ int listID = 1 [deprecated];+ BulletType bulletType = 2;+ int indentationLevel = 3;+ int lineNumber = 4 [deprecated];+}++message TextLineData {+ LineType lineType = 1;+ int indentationLevel = 2;+ Directionality directionality = 3;+ DirectionalityIntent directionalityIntent = 4;+}++enum BulletType {+ ORDERED = 0;+ UNORDERED = 1;+ INDENT = 2;+ NO_LIST = 3;+}++enum LineType {+ PLAIN = 0;+ ORDERED_LIST = 1;+ UNORDERED_LIST = 2;+}++enum Directionality {+ LTR = 0;+ RTL = 1;+}++enum DirectionalityIntent {+ IMPLICIT = 0;+ EXPLICIT = 1;+}++message PrototypeInteraction {+ GUID id = 1;+ PrototypeEvent event = 2;+ PrototypeAction[] actions = 3;+ bool isDeleted = 4;+}++message PrototypeEvent {+ InteractionType interactionType = 1;+ bool interactionMaintained = 2;+ float interactionDuration = 3;+ KeyTrigger keyTrigger = 4;+ string voiceEventPhrase = 5;+ float transitionTimeout = 6;+}++message PrototypeAction {+ GUID transitionNodeID = 1;+ TransitionType transitionType = 2;+ float transitionDuration = 3;+ EasingType easingType = 4;+ float transitionTimeout = 5 [deprecated];+ bool transitionShouldSmartAnimate = 6;+ ConnectionType connectionType = 7;+ string connectionURL = 8;+ Vector overlayRelativePosition = 9;+ NavigationType navigationType = 10;+ bool transitionPreserveScroll = 11;+ float[] easingFunction = 12;+ Vector extraScrollOffset = 13;+ GUID targetVariableID = 14;+}++message PrototypeStartingPoint {+ string name = 1;+ string description = 2;+ string position = 3;+}++enum TriggerDevice {+ KEYBOARD = 0;+ UNKNOWN_CONTROLLER = 1;+ XBOX_ONE = 2;+ PS4 = 3;+ SWITCH_PRO = 4;+}++message KeyTrigger {+ int[] keyCodes = 1;+ TriggerDevice triggerDevice = 2;+}++message Hyperlink {+ string url = 1;+ GUID guid = 2;+}++message EmbedData {+ string url = 1;+ string srcUrl = 2;+ string title = 3;+ string thumbnailUrl = 4;+ float width = 5;+ float height = 6;+ string embedType = 7;+ string thumbnailImageHash = 8;+ string faviconImageHash = 9;+ string provider = 10;+ string originalText = 11;+ string description = 12;+}++message StampData {+ string userId = 1;+}++message LinkPreviewData {+ string url = 1;+ string title = 2;+ string provider = 3;+ string description = 4;+ string thumbnailImageHash = 5;+ string faviconImageHash = 6;+ float thumbnailImageWidth = 7;+ float thumbnailImageHeight = 8;+}++message Viewport {+ Rect canvasSpaceBounds = 1;+ bool pixelPreview = 2;+ float pixelDensity = 3;+ GUID canvasGuid = 4;+}++message Mouse {+ MouseCursor cursor = 1;+ Vector canvasSpaceLocation = 2;+ Rect canvasSpaceSelectionBox = 3;+ GUID canvasGuid = 4;+}++struct Click {+ uint id;+ Vector point;+}++struct ScrollPosition {+ GUID node;+ Vector scrollOffset;+}++struct TriggeredOverlay {+ GUID overlayGuid;+ GUID hotspotGuid;+ GUID swapGuid;+}++message TriggeredOverlayData {+ GUID overlayGuid = 1;+ GUID hotspotGuid = 2;+ GUID swapGuid = 3;+ GUID prototypeInteractionGuid = 4;+ GUIDPath hotspotBlueprintId = 5;+}++message PresentedState {+ GUID baseScreenID = 1;+ TriggeredOverlayData[] overlays = 2;+}++enum TransitionDirection {+ FORWARD = 0;+ REVERSE = 1;+}++message TopLevelPlaybackChange {+ PresentedState oldState = 1;+ PresentedState newState = 2;+ GUIDPath hotspotBlueprintID = 3;+ GUID interactionID = 4;+ bool isHotspotInNewPresentedState = 5;+ TransitionDirection direction = 6;+ GUIDPath instanceStablePath = 7;+}++message InstanceStateChange {+ GUID stateID = 1;+ GUID interactionID = 2;+ GUIDPath hotspotStablePath = 3;+ GUIDPath instanceStablePath = 4;+ PlaybackChangePhase phase = 5;+}++enum PlaybackChangePhase {+ INITIATED = 0;+ ABORTED = 1;+ COMMITTED = 2;+}++message PlaybackChangeKeyframe {+ PlaybackChangePhase phase = 1;+ float progress = 2;+ float timestamp = 3;+}++message StateMapping {+ GUIDPath stablePath = 1;+ TopLevelPlaybackChange lastTopLevelChange = 2;+ PlaybackChangeKeyframe lastTopLevelChangeStatus = 3;+ float timestamp = 4;+}++message ScrollMapping {+ GUIDPath blueprintID = 1;+ uint overlayIndex = 2;+ Vector scrollOffset = 3;+}++message PlaybackUpdate {+ TopLevelPlaybackChange lastTopLevelChange = 1;+ PlaybackChangeKeyframe lastTopLevelChangeStatus = 2;+ ScrollMapping[] scrollMappings = 3;+ float timestamp = 4;+ Vector pointerLocation = 5;+ bool isTopLevelFrameChange = 6;+ StateMapping[] stateMappings = 7;+}++message ChatMessage {+ string text = 1;+ string previousText = 2;+}++message VoiceMetadata {+ string connectedCallId = 1;+}++message UserChange {+ uint sessionID = 1;+ bool connected = 2;+ string name = 3;+ Color color = 4;+ string imageURL = 5;+ Viewport viewport = 6;+ Mouse mouse = 7;+ GUID[] selection = 8;+ uint[] observing = 9;+ string deviceName = 10;+ Click[] recentClicks = 11;+ ScrollPosition[] scrollPositions = 12;+ TriggeredOverlay[] triggeredOverlays = 13 [deprecated];+ string userID = 14;+ GUID lastTriggeredHotspot = 15;+ GUID lastTriggeredPrototypeInteractionID = 16;+ TriggeredOverlayData[] triggeredOverlaysData = 17;+ PlaybackUpdate[] playbackUpdates = 18 [deprecated];+ ChatMessage chatMessage = 19;+ VoiceMetadata voiceMetadata = 20;+ bool canWrite = 21;+ bool highFiveStatus = 22;+ InstanceStateChange[] instanceStateChanges = 23;+}++message SceneGraphQuery {+ GUID startingNode = 1;+ uint depth = 2;+}++message NodeChangesMetadata {+ uint blobsFieldOffset = 1;+}++message CursorReaction {+ string imageUrl = 1;+}++message TimerInfo {+ bool isPaused = 1;+ uint timeRemainingMs = 2;+ uint totalTimeMs = 3;+ uint timerID = 4;+ string setBy = 5;+}++message PresenterInfo {+ uint sessionID = 1;+}++message ClientBroadcast {+ uint sessionID = 1;+ CursorReaction cursorReaction = 2;+ TimerInfo timer = 3;+ PresenterInfo presenter = 4;+}++message Message {+ MessageType type = 1;+ uint sessionID = 2;+ uint ackID = 3;+ NodeChange[] nodeChanges = 4;+ UserChange[] userChanges = 5;+ Blob[] blobs = 6;+ string signalName = 7;+ Access access = 8;+ string styleSetName = 9;+ StyleSetType styleSetType = 10;+ StyleSetContentType styleSetContentType = 11;+ int pasteID = 12;+ Vector pasteOffset = 13;+ string pasteFileKey = 14;+ string signalPayload = 15;+ SceneGraphQuery[] sceneGraphQueries = 16;+ NodeChangesMetadata nodeChangesMetadata = 17 [deprecated];+ uint fileVersion = 18;+ bool pasteIsPartiallyOutsideEnclosingFrame = 19;+ GUID pastePageId = 20;+ bool isCut = 21;+ Message[] localUndoStack = 22;+ Message[] localRedoStack = 23;+ ClientBroadcast[] broadcasts = 24;+ uint reconnectSequenceNumber = 25;+ string pasteBranchSourceFileKey = 26;+ EditorType pasteEditorType = 27;+ uint reserved28 = 28;+ uint64 timestamp = 38;+}++message DiffChunk {+ uint[] nodeChanges = 1;+ NodePhase phase = 2 [deprecated];+ NodeChange displayNode = 3;+ GUID canvasId = 4;+ string canvasName = 5;+ bool canvasIsInternal = 6;+ uint[] chunksAffectingThisChunk = 7;+ NodeChange[] basisParentHierarchy = 8;+ NodeChange[] parentHierarchy = 9;+}++message DiffPayload {+ NodeChange[] nodeChanges = 1;+ Blob[] blobs = 2;+ DiffChunk[] diffChunks = 3;+ NodeChange[] diffBasis = 4;+}++enum RichMediaType {+ ANIMATED_IMAGE = 0;+}++message RichMediaData {+ string mediaHash = 1;+ RichMediaType richMediaType = 2;+}++enum VariableDataType {+ BOOLEAN = 0;+ FLOAT = 1;+ STRING = 2;+}++message VariableAnyValue {+ bool boolValue = 1;+ string textValue = 2;+ float floatValue = 3;+}++message VariableData {+ VariableAnyValue value = 1;+ VariableDataType dataType = 2;+}++enum HTMLTag {+ AUTO = 0;+ ARTICLE = 1;+ SECTION = 2;+ NAV = 3;+ ASIDE = 4;+ H1 = 5;+ H2 = 6;+ H3 = 7;+ H4 = 8;+ H5 = 9;+ H6 = 10;+ HGROUP = 11;+ HEADER = 12;+ FOOTER = 13;+ ADDRESS = 14;+ P = 15;+ HR = 16;+ PRE = 17;+ BLOCKQUOTE = 18;+ OL = 19;+ UL = 20;+ MENU = 21;+ LI = 22;+ DL = 23;+ DT = 24;+ DD = 25;+ FIGURE = 26;+ FIGCAPTION = 27;+ MAIN = 28;+ DIV = 29;+ A = 30;+ EM = 31;+ STRONG = 32;+ SMALL = 33;+ S = 34;+ CITE = 35;+ Q = 36;+ DFN = 37;+ ABBR = 38;+ RUBY = 39;+ RT = 40;+ RP = 41;+ DATA = 42;+ TIME = 43;+ CODE = 44;+ VAR = 45;+ SAMP = 46;+ KBD = 47;+ SUB = 48;+ SUP = 49;+ I = 50;+ B = 51;+ U = 52;+ MARK = 53;+ BDI = 54;+ BDO = 55;+ SPAN = 56;+ BR = 57;+ WBR = 58;+ PICTURE = 59;+ SOURCE = 60;+ IMG = 61;+ FORM = 62;+ LABEL = 63;+ INPUT = 64;+ BUTTON = 65;+ SELECT = 66;+ DATALIST = 67;+ OPTGROUP = 68;+ OPTION = 69;+ TEXTAREA = 70;+ OUTPUT = 71;+ PROGRESS = 72;+ METER = 73;+ FIELDSET = 74;+ LEGEND = 75;+}++enum ARIARole {+ AUTO = 0;+ BUTTON = 1;+ CHECKBOX = 2;+ GRIDCELL = 3;+ LINK = 4;+ MENUITEM = 5;+ MENUITEMCHECKBOX = 6;+ MENUITEMRADIO = 7;+ OPTION = 8;+ PROGRESSBAR = 9;+ RADIO = 10;+ SCROLLBAR = 11;+ SEARCHBOX = 12;+ SEPARATOR = 13;+ SLIDER = 14;+ SPINBUTTON = 15;+ SWITCH = 16;+ TAB = 17;+ TABPANEL = 18;+ TEXTBOX = 19;+ TREEITEM = 20;+ COMBOBOX = 21;+ GRID = 22;+ LISTBOX = 23;+ MENU = 24;+ MENUBAR = 25;+ RADIOGROUP = 26;+ TABLIST = 27;+ TREE = 28;+ TREEGRID = 29;+ APPLICATION = 30;+ ARTICLE = 31;+ BLOCKQUOTE = 32;+ CAPTION = 33;+ CELL = 34;+ COLUMNHEADER = 35;+ DEFINITION = 36;+ DELETION = 37;+ DIRECTORY = 38;+ DOCUMENT = 39;+ EMPHASIS = 40;+ FEED = 41;+ FIGURE = 42;+ GENERIC = 43;+ GROUP = 44;+ HEADING = 45;+ IMG = 46;+ INSERTION = 47;+ LIST = 48;+ LISTITEM = 49;+ MATH = 50;+ METER = 51;+ NONE = 52;+ NOTE = 53;+ PARAGRAPH = 54;+ PRESENTATION = 55;+ ROW = 56;+ ROWGROUP = 57;+ ROWHEADER = 58;+ STRONG = 59;+ SUBSCRIPT = 60;+ SUPERSCRIPT = 61;+ TABLE = 62;+ TERM = 63;+ TIME = 64;+ TOOLBAR = 65;+ TOOLTIP = 66;+ BANNER = 67;+ COMPLEMENTARY = 68;+ CONTENTINFO = 69;+ FORM = 70;+ MAIN = 71;+ NAVIGATION = 72;+ REGION = 73;+ SEARCH = 74;+ ALERT = 75;+ LOG = 76;+ MARQUEE = 77;+ STATUS = 78;+ TIMER = 79;+ ALERTDIALOG = 80;+ DIALOG = 81;+}+`++export default parseSchema(schemaText)diff --git a/packages/core/src/layout.ts b/packages/core/src/layout.tsnew file mode 100644index 000000000..5f2216488--- /dev/null+++ b/packages/core/src/layout.ts@@ -0,0 +1,317 @@+import Yoga, {+ Align,+ Direction,+ FlexDirection,+ Gutter,+ Justify,+ Edge,+ Wrap,+ type Node as YogaNode+} from 'yoga-layout'++import type { SceneGraph, SceneNode } from './scene-graph'++export function computeLayout(graph: SceneGraph, frameId: string): void {+ const frame = graph.getNode(frameId)+ if (!frame || frame.layoutMode === 'NONE') return++ const yogaRoot = buildYogaTree(graph, frame)+ yogaRoot.calculateLayout(undefined, undefined, Direction.LTR)+ applyYogaLayout(graph, frame, yogaRoot)+ freeYogaTree(yogaRoot)+}++export function computeAllLayouts(graph: SceneGraph): void {+ const visited = new Set<string>()+ computeLayoutsBottomUp(graph, graph.rootId, visited)+}++function computeLayoutsBottomUp(graph: SceneGraph, nodeId: string, visited: Set<string>): void {+ const node = graph.getNode(nodeId)+ if (!node || visited.has(nodeId)) return+ visited.add(nodeId)++ for (const childId of node.childIds) {+ computeLayoutsBottomUp(graph, childId, visited)+ }++ if (node.layoutMode !== 'NONE') {+ computeLayout(graph, nodeId)+ }+}++function buildYogaTree(graph: SceneGraph, frame: SceneNode): YogaNode {+ const root = Yoga.Node.create()++ if (frame.primaryAxisSizing === 'FIXED') {+ if (frame.layoutMode === 'HORIZONTAL') root.setWidth(frame.width)+ else root.setHeight(frame.height)+ }+ if (frame.counterAxisSizing === 'FIXED') {+ if (frame.layoutMode === 'HORIZONTAL') root.setHeight(frame.height)+ else root.setWidth(frame.width)+ }++ root.setFlexDirection(+ frame.layoutMode === 'HORIZONTAL' ? FlexDirection.Row : FlexDirection.Column+ )+ root.setFlexWrap(frame.layoutWrap === 'WRAP' ? Wrap.Wrap : Wrap.NoWrap)+ root.setJustifyContent(mapJustify(frame.primaryAxisAlign))+ root.setAlignItems(mapAlign(frame.counterAxisAlign))++ root.setPadding(Edge.Top, frame.paddingTop)+ root.setPadding(Edge.Right, frame.paddingRight)+ root.setPadding(Edge.Bottom, frame.paddingBottom)+ root.setPadding(Edge.Left, frame.paddingLeft)++ root.setGap(+ Gutter.Column,+ frame.layoutMode === 'HORIZONTAL' ? frame.itemSpacing : frame.counterAxisSpacing+ )+ root.setGap(+ Gutter.Row,+ frame.layoutMode === 'HORIZONTAL' ? frame.counterAxisSpacing : frame.itemSpacing+ )++ const children = graph.getChildren(frame.id)+ for (let i = 0; i < children.length; i++) {+ const child = children[i]++ if (child.layoutPositioning === 'ABSOLUTE') continue++ const yogaChild = Yoga.Node.create()++ if (child.layoutMode !== 'NONE') {+ configureChildAsAutoLayout(yogaChild, child, frame, graph)+ } else {+ configureChildAsLeaf(yogaChild, child, frame)+ }++ root.insertChild(yogaChild, root.getChildCount())+ }++ return root+}++function configureChildAsAutoLayout(+ yogaChild: YogaNode,+ child: SceneNode,+ parent: SceneNode,+ graph: SceneGraph+): void {+ const isParentRow = parent.layoutMode === 'HORIZONTAL'+ const isChildRow = child.layoutMode === 'HORIZONTAL'++ const widthSizing = isChildRow ? child.primaryAxisSizing : child.counterAxisSizing+ const heightSizing = isChildRow ? child.counterAxisSizing : child.primaryAxisSizing++ if (isParentRow) {+ setSizing(yogaChild, 'width', widthSizing, child.width, child.layoutGrow)+ setSizing(yogaChild, 'height', heightSizing, child.height, 0)+ } else {+ setSizing(yogaChild, 'width', widthSizing, child.width, 0)+ setSizing(yogaChild, 'height', heightSizing, child.height, child.layoutGrow)+ }++ if (child.layoutAlignSelf === 'STRETCH') {+ yogaChild.setAlignSelf(Align.Stretch)+ }++ yogaChild.setFlexDirection(+ child.layoutMode === 'HORIZONTAL' ? FlexDirection.Row : FlexDirection.Column+ )+ yogaChild.setFlexWrap(child.layoutWrap === 'WRAP' ? Wrap.Wrap : Wrap.NoWrap)+ yogaChild.setJustifyContent(mapJustify(child.primaryAxisAlign))+ yogaChild.setAlignItems(mapAlign(child.counterAxisAlign))++ yogaChild.setPadding(Edge.Top, child.paddingTop)+ yogaChild.setPadding(Edge.Right, child.paddingRight)+ yogaChild.setPadding(Edge.Bottom, child.paddingBottom)+ yogaChild.setPadding(Edge.Left, child.paddingLeft)++ yogaChild.setGap(+ Gutter.Column,+ child.layoutMode === 'HORIZONTAL' ? child.itemSpacing : child.counterAxisSpacing+ )+ yogaChild.setGap(+ Gutter.Row,+ child.layoutMode === 'HORIZONTAL' ? child.counterAxisSpacing : child.itemSpacing+ )++ const grandchildren = graph.getChildren(child.id)+ for (const gc of grandchildren) {+ if (gc.layoutPositioning === 'ABSOLUTE') continue+ const yogaGC = Yoga.Node.create()+ if (gc.layoutMode !== 'NONE') {+ configureChildAsAutoLayout(yogaGC, gc, child, graph)+ } else {+ configureChildAsLeaf(yogaGC, gc, child)+ }+ yogaChild.insertChild(yogaGC, yogaChild.getChildCount())+ }+}++function configureChildAsLeaf(yogaChild: YogaNode, child: SceneNode, parent: SceneNode): void {+ const isRow = parent.layoutMode === 'HORIZONTAL'+ const stretchCross = child.layoutAlignSelf === 'STRETCH' || parent.counterAxisAlign === 'STRETCH'++ if (child.layoutGrow > 0) {+ yogaChild.setFlexGrow(child.layoutGrow)+ if (!stretchCross) {+ if (isRow) yogaChild.setHeight(child.height)+ else yogaChild.setWidth(child.width)+ }+ } else {+ if (isRow) {+ yogaChild.setWidth(child.width)+ if (!stretchCross) yogaChild.setHeight(child.height)+ } else {+ yogaChild.setHeight(child.height)+ if (!stretchCross) yogaChild.setWidth(child.width)+ }+ }++ if (child.layoutAlignSelf === 'STRETCH') {+ yogaChild.setAlignSelf(Align.Stretch)+ }+}++function setSizing(+ yogaNode: YogaNode,+ axis: 'width' | 'height',+ sizing: string,+ fixedValue: number,+ grow: number+): void {+ if (grow > 0) {+ yogaNode.setFlexGrow(grow)+ yogaNode.setFlexShrink(1)+ return+ }++ switch (sizing) {+ case 'FIXED':+ if (axis === 'width') yogaNode.setWidth(fixedValue)+ else yogaNode.setHeight(fixedValue)+ break+ case 'HUG':+ break+ case 'FILL':+ yogaNode.setFlexGrow(1)+ yogaNode.setFlexShrink(1)+ break+ }+}++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 {+ if (frame.primaryAxisSizing === 'HUG' || frame.counterAxisSizing === 'HUG') {+ const computedW = yogaNode.getComputedWidth()+ const computedH = yogaNode.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 = yogaNode.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 freeYogaTree(node: YogaNode): void {+ for (let i = node.getChildCount() - 1; i >= 0; i--) {+ freeYogaTree(node.getChild(i))+ }+ node.free()+}++function mapJustify(align: string): Justify {+ switch (align) {+ case 'CENTER':+ return Justify.Center+ case 'MAX':+ return Justify.FlexEnd+ case 'SPACE_BETWEEN':+ return Justify.SpaceBetween+ default:+ return Justify.FlexStart+ }+}++function mapAlign(align: string): Align {+ switch (align) {+ case 'CENTER':+ return Align.Center+ case 'MAX':+ return Align.FlexEnd+ case 'STRETCH':+ return Align.Stretch+ case 'BASELINE':+ return Align.Baseline+ default:+ return Align.FlexStart+ }+}diff --git a/packages/core/src/render-image.ts b/packages/core/src/render-image.tsnew file mode 100644index 000000000..ac731e1db--- /dev/null+++ b/packages/core/src/render-image.ts@@ -0,0 +1,158 @@+import type { SkiaRenderer } from './renderer'+import type { SceneGraph } from './scene-graph'+import type { CanvasKit } from 'canvaskit-wasm'++export type ExportFormat = 'PNG' | 'JPG' | 'WEBP'++interface RenderOptions {+ scale: number+ format: ExportFormat+ quality?: number+}++function computeContentBounds(+ graph: SceneGraph,+ nodeIds: string[]+): { minX: number; minY: number; maxX: number; maxY: number } | null {+ let minX = Infinity,+ minY = Infinity,+ maxX = -Infinity,+ maxY = -Infinity++ for (const id of nodeIds) {+ const node = graph.getNode(id)+ if (!node || !node.visible) continue+ const abs = graph.getAbsolutePosition(id)+ minX = Math.min(minX, abs.x)+ minY = Math.min(minY, abs.y)+ maxX = Math.max(maxX, abs.x + node.width)+ maxY = Math.max(maxY, abs.y + node.height)+ }++ if (!isFinite(minX)) return null+ return { minX, minY, maxX, maxY }+}++function renderToSurface(+ ck: CanvasKit,+ renderer: SkiaRenderer,+ graph: SceneGraph,+ pageId: string,+ width: number,+ height: number,+ setup: (canvas: import('canvaskit-wasm').Canvas) => void+): Uint8Array | null {+ const surface = ck.MakeSurface(width, height)+ if (!surface) return null++ try {+ const canvas = surface.getCanvas()+ setup(canvas)+ renderer.renderSceneToCanvas(canvas, graph, pageId)+ surface.flush()+ const image = surface.makeImageSnapshot()+ const encoded = image.encodeToBytes(ck.ImageFormat.PNG, 100)+ image.delete()+ return encoded ? new Uint8Array(encoded) : null+ } finally {+ surface.delete()+ }+}++function mimeForFormat(format: ExportFormat): string {+ switch (format) {+ case 'JPG':+ return 'image/jpeg'+ case 'WEBP':+ return 'image/webp'+ default:+ return 'image/png'+ }+}++async function reencodeImage(+ pngBytes: Uint8Array,+ format: ExportFormat,+ quality: number+): Promise<Uint8Array> {+ if (format === 'PNG') return pngBytes++ const blob = new Blob([new Uint8Array(pngBytes)], { type: 'image/png' })+ const bitmap = await createImageBitmap(blob)+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height)+ const ctx = canvas.getContext('2d')+ if (!ctx) return pngBytes++ if (format === 'JPG') {+ ctx.fillStyle = '#ffffff'+ ctx.fillRect(0, 0, bitmap.width, bitmap.height)+ }++ ctx.drawImage(bitmap, 0, 0)+ bitmap.close()++ const outBlob = await canvas.convertToBlob({+ type: mimeForFormat(format),+ quality: quality / 100+ })+ return new Uint8Array(await outBlob.arrayBuffer())+}++export async function renderNodesToImage(+ ck: CanvasKit,+ renderer: SkiaRenderer,+ graph: SceneGraph,+ pageId: string,+ nodeIds: string[],+ options: RenderOptions+): Promise<Uint8Array | null> {+ const bounds = computeContentBounds(graph, nodeIds)+ if (!bounds) return null++ const contentW = bounds.maxX - bounds.minX+ const contentH = bounds.maxY - bounds.minY+ if (contentW <= 0 || contentH <= 0) return null++ const pixelW = Math.ceil(contentW * options.scale)+ const pixelH = Math.ceil(contentH * options.scale)+ if (pixelW <= 0 || pixelH <= 0) return null++ const png = renderToSurface(ck, renderer, graph, pageId, pixelW, pixelH, (canvas) => {+ canvas.clear(ck.TRANSPARENT)+ canvas.scale(options.scale, options.scale)+ canvas.translate(-bounds.minX, -bounds.minY)+ })+ if (!png) return null++ const quality = options.quality ?? (options.format === 'PNG' ? 100 : 90)+ return reencodeImage(png, options.format, quality)+}++export function renderThumbnail(+ ck: CanvasKit,+ renderer: SkiaRenderer,+ graph: SceneGraph,+ pageId: string,+ width: number,+ height: number+): Uint8Array | null {+ const page = graph.getNode(pageId)+ if (!page || page.childIds.length === 0) return null++ const bounds = computeContentBounds(graph, page.childIds)+ if (!bounds) return null++ const contentW = bounds.maxX - bounds.minX+ const contentH = bounds.maxY - bounds.minY+ if (contentW <= 0 || contentH <= 0) return null++ const scale = Math.min(width / contentW, height / contentH, 2)++ return renderToSurface(ck, renderer, graph, pageId, width, height, (canvas) => {+ canvas.clear(ck.Color4f(renderer.pageColor.r, renderer.pageColor.g, renderer.pageColor.b, 1))+ const offsetX = (width - contentW * scale) / 2 - bounds.minX * scale+ const offsetY = (height - contentH * scale) / 2 - bounds.minY * scale+ canvas.translate(offsetX, offsetY)+ canvas.scale(scale, scale)+ })+}diff --git a/packages/core/src/renderer.ts b/packages/core/src/renderer.tsnew file mode 100644index 000000000..75a9caa7f--- /dev/null+++ b/packages/core/src/renderer.ts@@ -0,0 +1,2102 @@+import {+ SELECTION_COLOR,+ COMPONENT_COLOR,+ SNAP_COLOR,+ CANVAS_BG_COLOR,+ ROTATION_HANDLE_OFFSET,+ RULER_SIZE,+ RULER_BG_COLOR,+ RULER_TICK_COLOR,+ RULER_TEXT_COLOR,+ RULER_BADGE_HEIGHT,+ RULER_BADGE_PADDING,+ RULER_BADGE_RADIUS,+ RULER_BADGE_EXCLUSION,+ RULER_TEXT_BASELINE,+ RULER_MAJOR_TICK,+ RULER_MINOR_TICK,+ RULER_HIGHLIGHT_ALPHA,+ PEN_HANDLE_RADIUS,+ PEN_VERTEX_RADIUS,+ PEN_CLOSE_RADIUS_BOOST,+ PEN_PATH_STROKE_WIDTH,+ PARENT_OUTLINE_ALPHA,+ PARENT_OUTLINE_DASH,+ DEFAULT_FONT_SIZE,+ LABEL_FONT_SIZE,+ SIZE_FONT_SIZE,+ ROTATION_HANDLE_RADIUS,+ HANDLE_HALF_SIZE,+ LABEL_OFFSET_Y,+ SIZE_PILL_PADDING_X,+ SIZE_PILL_PADDING_Y,+ SIZE_PILL_HEIGHT,+ SIZE_PILL_RADIUS,+ SIZE_PILL_TEXT_OFFSET_Y,+ MARQUEE_FILL_ALPHA,+ SELECTION_DASH_ALPHA,+ DROP_HIGHLIGHT_ALPHA,+ DROP_HIGHLIGHT_STROKE,+ LAYOUT_INDICATOR_STROKE,+ SECTION_CORNER_RADIUS,+ SECTION_TITLE_HEIGHT,+ SECTION_TITLE_PADDING_X,+ SECTION_TITLE_RADIUS,+ SECTION_TITLE_FONT_SIZE,+ SECTION_TITLE_GAP,+ COMPONENT_SET_DASH,+ COMPONENT_SET_DASH_GAP,+ COMPONENT_SET_BORDER_WIDTH,+ COMPONENT_LABEL_FONT_SIZE,+ COMPONENT_LABEL_GAP,+ COMPONENT_LABEL_ICON_SIZE,+ COMPONENT_LABEL_ICON_GAP,+ RULER_TARGET_PIXEL_SPACING,+ RULER_MAJOR_TOLERANCE+} from './constants'++import { vectorNetworkToPath } from './vector'++import type { SceneNode, SceneGraph, Fill } from './scene-graph'+import type { SnapGuide } from './snap'+import type { Rect } from './types'+import type { EmbindEnumEntity, Image as CKImage, Path } from 'canvaskit-wasm'+import type {+ CanvasKit,+ Surface,+ Canvas,+ Paint,+ Font,+ FontMgr,+ FontWeight,+ TypefaceFontProvider+} from 'canvaskit-wasm'++export interface RenderOverlays {+ hoveredNodeId?: string | null+ editingTextId?: string | null+ marquee?: Rect | null+ snapGuides?: SnapGuide[]+ rotationPreview?: { nodeId: string; angle: number } | null+ dropTargetId?: string | null+ layoutInsertIndicator?: {+ x: number+ y: number+ length: number+ direction: 'HORIZONTAL' | 'VERTICAL'+ } | null+ penState?: {+ vertices: Array<{ x: number; y: number }>+ segments: Array<{+ start: number+ end: number+ tangentStart: { x: number; y: number }+ tangentEnd: { x: number; y: number }+ }>+ dragTangent: { x: number; y: number } | null+ closingToFirst: boolean+ cursorX?: number+ cursorY?: number+ } | null+}++export class SkiaRenderer {+ private ck: CanvasKit+ private surface: Surface+ private fillPaint: Paint+ private strokePaint: Paint+ private selectionPaint: Paint+ private parentOutlinePaint: Paint+ private snapPaint: Paint+ private auxFill: Paint+ private auxStroke: Paint+ private opacityPaint: Paint+ private textFont: Font | null = null+ private labelFont: Font | null = null+ private sizeFont: Font | null = null+ private sectionTitleFont: Font | null = null+ private componentLabelFont: Font | null = null+ private fontMgr: FontMgr | null = null+ private fontProvider: TypefaceFontProvider | null = null+ private fontsLoaded = false+ private imageCache = new Map<string, CKImage>()++ panX = 0+ panY = 0+ zoom = 1+ dpr = 1+ viewportWidth = 0+ viewportHeight = 0+ showRulers = true+ pageColor = CANVAS_BG_COLOR+ pageId: string | null = null++ private worldViewport = { x: 0, y: 0, w: 0, h: 0 }++ private selColor(alpha = 1) {+ return this.ck.Color4f(SELECTION_COLOR.r, SELECTION_COLOR.g, SELECTION_COLOR.b, alpha)+ }++ private compColor(alpha = 1) {+ return this.ck.Color4f(COMPONENT_COLOR.r, COMPONENT_COLOR.g, COMPONENT_COLOR.b, alpha)+ }++ private isComponentType(type: string): boolean {+ return type === 'COMPONENT' || type === 'COMPONENT_SET' || type === 'INSTANCE'+ }++ constructor(ck: CanvasKit, surface: Surface) {+ this.ck = ck+ this.surface = surface++ this.fillPaint = new ck.Paint()+ this.fillPaint.setStyle(ck.PaintStyle.Fill)+ this.fillPaint.setAntiAlias(true)++ this.strokePaint = new ck.Paint()+ this.strokePaint.setStyle(ck.PaintStyle.Stroke)+ this.strokePaint.setAntiAlias(true)++ this.selectionPaint = new ck.Paint()+ this.selectionPaint.setStyle(ck.PaintStyle.Stroke)+ this.selectionPaint.setStrokeWidth(1)+ this.selectionPaint.setColor(this.selColor())+ this.selectionPaint.setAntiAlias(true)++ this.parentOutlinePaint = new ck.Paint()+ this.parentOutlinePaint.setStyle(ck.PaintStyle.Stroke)+ this.parentOutlinePaint.setStrokeWidth(1)+ this.parentOutlinePaint.setColor(this.selColor(PARENT_OUTLINE_ALPHA))+ this.parentOutlinePaint.setAntiAlias(true)+ this.parentOutlinePaint.setPathEffect(+ ck.PathEffect.MakeDash([PARENT_OUTLINE_DASH, PARENT_OUTLINE_DASH], 0)+ )++ this.snapPaint = new ck.Paint()+ this.snapPaint.setStyle(ck.PaintStyle.Stroke)+ this.snapPaint.setStrokeWidth(1)+ this.snapPaint.setColor(this.ck.Color4f(SNAP_COLOR.r, SNAP_COLOR.g, SNAP_COLOR.b, 1))+ this.snapPaint.setAntiAlias(true)++ this.auxFill = new ck.Paint()+ this.auxFill.setStyle(ck.PaintStyle.Fill)+ this.auxFill.setAntiAlias(true)++ this.auxStroke = new ck.Paint()+ this.auxStroke.setStyle(ck.PaintStyle.Stroke)+ this.auxStroke.setAntiAlias(true)++ this.opacityPaint = new ck.Paint()++ this.textFont = new ck.Font(null, DEFAULT_FONT_SIZE)+ }++ async loadFonts(): Promise<void> {+ this.fontProvider = this.ck.TypefaceFontProvider.Make()++ const { initFontService, loadFont } = await import('./fonts')+ initFontService(this.ck, this.fontProvider)++ const fontData = await loadFont('Inter', 'Regular')+ if (fontData) {+ const typeface = this.ck.Typeface.MakeFreeTypeFaceFromData(fontData)+ if (typeface) {+ this.textFont?.delete()+ this.labelFont?.delete()+ this.sizeFont?.delete()+ this.sectionTitleFont?.delete()+ this.componentLabelFont?.delete()+ this.textFont = new this.ck.Font(typeface, DEFAULT_FONT_SIZE)+ this.labelFont = new this.ck.Font(typeface, LABEL_FONT_SIZE)+ this.sizeFont = new this.ck.Font(typeface, SIZE_FONT_SIZE)+ this.sectionTitleFont = new this.ck.Font(typeface, SECTION_TITLE_FONT_SIZE)+ this.componentLabelFont = new this.ck.Font(typeface, COMPONENT_LABEL_FONT_SIZE)+ }+ this.fontMgr = this.ck.FontMgr.FromData(fontData) ?? null+ }++ this.fontsLoaded = true+ }++ hitTestSectionTitle(graph: SceneGraph, canvasX: number, canvasY: number): SceneNode | null {+ if (!this.sectionTitleFont) return null++ const pageNode = graph.getNode(this.pageId ?? graph.rootId)+ if (!pageNode) return null++ const font = this.sectionTitleFont+ let result: SceneNode | null = null++ const check = (parentId: string, ox: number, oy: number, insideSection: boolean) => {+ const parent = graph.getNode(parentId)+ if (!parent) return+ for (let i = parent.childIds.length - 1; i >= 0; i--) {+ if (result) return+ const childId = parent.childIds[i]+ const child = graph.getNode(childId)+ if (!child || !child.visible) continue+ const ax = ox + child.x+ const ay = oy + child.y+ if (child.type === 'SECTION') {+ // Compute pill width from font metrics+ const glyphIds = font.getGlyphIDs(child.name)+ const widths = font.getGlyphWidths(glyphIds)+ let textW = 0+ for (const w of widths) textW += w+ const pillW =+ Math.min(textW + SECTION_TITLE_PADDING_X * 2, child.width * this.zoom) / this.zoom+ const pillH = SECTION_TITLE_HEIGHT / this.zoom+ const gap = SECTION_TITLE_GAP / this.zoom++ let pillX = ax+ let pillY: number+ if (insideSection) {+ pillY = ay + gap+ } else {+ pillY = ay - pillH - gap+ }++ if (+ canvasX >= pillX &&+ canvasX <= pillX + pillW &&+ canvasY >= pillY &&+ canvasY <= pillY + pillH+ ) {+ result = child+ return+ }++ check(childId, ax, ay, true)+ } else if (child.childIds.length > 0) {+ check(childId, ax, ay, insideSection)+ }+ }+ }++ check(pageNode.id, 0, 0, false)+ return result+ }++ hitTestComponentLabel(graph: SceneGraph, canvasX: number, canvasY: number): SceneNode | null {+ if (!this.componentLabelFont) return null++ const pageNode = graph.getNode(this.pageId ?? graph.rootId)+ if (!pageNode) return null++ const font = this.componentLabelFont+ const LABEL_TYPES = new Set(['COMPONENT', 'COMPONENT_SET', 'INSTANCE'])+ let result: SceneNode | null = null++ const check = (parentId: string, ox: number, oy: number) => {+ const parent = graph.getNode(parentId)+ if (!parent) return+ for (let i = parent.childIds.length - 1; i >= 0; i--) {+ if (result) return+ const childId = parent.childIds[i]+ const child = graph.getNode(childId)+ if (!child || !child.visible) continue+ const ax = ox + child.x+ const ay = oy + child.y+ if (LABEL_TYPES.has(child.type)) {+ const glyphIds = font.getGlyphIDs(child.name)+ const widths = font.getGlyphWidths(glyphIds)+ let textW = 0+ for (const w of widths) textW += w+ const labelW = (COMPONENT_LABEL_ICON_SIZE + COMPONENT_LABEL_ICON_GAP + textW) / this.zoom+ const labelH = COMPONENT_LABEL_FONT_SIZE / this.zoom+ const gap = COMPONENT_LABEL_GAP / this.zoom++ const isInsideSet = parent.type === 'COMPONENT_SET'+ const labelX = ax+ let labelY: number+ if (isInsideSet) {+ labelY = ay + gap+ } else {+ labelY = ay - labelH - gap+ }++ if (+ canvasX >= labelX &&+ canvasX <= labelX + labelW &&+ canvasY >= labelY &&+ canvasY <= labelY + labelH+ ) {+ result = child+ return+ }+ }+ if (child.childIds.length > 0) {+ check(childId, ax, ay)+ }+ }+ }++ check(pageNode.id, 0, 0)+ return result+ }++ renderSceneToCanvas(canvas: Canvas, graph: SceneGraph, pageId: string): void {+ // Disable culling for export — render everything+ const prevViewport = this.worldViewport+ this.worldViewport = { x: -1e9, y: -1e9, w: 2e9, h: 2e9 }+ const pageNode = graph.getNode(pageId)+ if (pageNode) {+ for (const childId of pageNode.childIds) {+ this.renderNode(canvas, graph, childId, {})+ }+ }+ this.worldViewport = prevViewport+ }++ render(graph: SceneGraph, selectedIds: Set<string>, overlays: RenderOverlays = {}): void {+ const canvas = this.surface.getCanvas()+ canvas.clear(this.ck.Color4f(this.pageColor.r, this.pageColor.g, this.pageColor.b, 1))++ // Compute world-space viewport for culling+ this.worldViewport = {+ x: -this.panX / this.zoom,+ y: -this.panY / this.zoom,+ w: this.viewportWidth / this.zoom,+ h: this.viewportHeight / this.zoom+ }++ // Scene layer (world coordinates)+ canvas.save()+ canvas.scale(this.dpr, this.dpr)+ canvas.translate(this.panX, this.panY)+ canvas.scale(this.zoom, this.zoom)++ const pageNode = graph.getNode(this.pageId ?? graph.rootId)+ if (pageNode) {+ for (const childId of pageNode.childIds) {+ this.renderNode(canvas, graph, childId, overlays, 0, 0)+ }+ }++ canvas.restore()++ // Section titles + component labels (screen coordinates, zoom-independent)+ canvas.save()+ canvas.scale(this.dpr, this.dpr)+ this.drawSectionTitles(canvas, graph)+ this.drawComponentLabels(canvas, graph)+ canvas.restore()++ // UI overlay layer (screen coordinates, zoom-independent)+ canvas.save()+ canvas.scale(this.dpr, this.dpr)++ this.drawSelection(canvas, graph, selectedIds, overlays)+ this.drawSnapGuides(canvas, overlays.snapGuides)+ this.drawMarquee(canvas, overlays.marquee)+ this.drawLayoutInsertIndicator(canvas, overlays.layoutInsertIndicator)+ this.drawPenOverlay(canvas, overlays.penState)+ if (this.showRulers) this.drawRulers(canvas, graph, selectedIds)++ canvas.restore()+ this.surface.flush()+ }++ // --- Selection UI ---++ private drawSelection(+ canvas: Canvas,+ graph: SceneGraph,+ selectedIds: Set<string>,+ overlays: RenderOverlays+ ): void {+ if (selectedIds.size === 0) return++ this.drawParentFrameOutlines(canvas, graph, selectedIds)++ if (selectedIds.size === 1) {+ const id = [...selectedIds][0]+ if (overlays.editingTextId === id) return+ const node = graph.getNode(id)+ if (!node) return++ const useComponentColor = this.isComponentType(node.type)+ this.selectionPaint.setColor(useComponentColor ? this.compColor() : this.selColor())+ this.selectionPaint.setStrokeWidth(1)++ const rotation =+ overlays.rotationPreview?.nodeId === id ? overlays.rotationPreview.angle : node.rotation+ this.drawNodeSelection(canvas, node, rotation, graph)+ this.drawSelectionLabels(canvas, graph, selectedIds)++ this.selectionPaint.setColor(this.selColor())+ return+ }++ for (const id of selectedIds) {+ const node = graph.getNode(id)+ if (!node) continue++ const useComponentColor = this.isComponentType(node.type)+ this.selectionPaint.setColor(useComponentColor ? this.compColor() : this.selColor())+ this.selectionPaint.setStrokeWidth(1)++ const rotation =+ overlays.rotationPreview?.nodeId === id ? overlays.rotationPreview.angle : node.rotation+ this.drawNodeOutline(canvas, node, rotation, graph)+ }++ this.selectionPaint.setColor(this.selColor())++ const nodes = [...selectedIds]+ .map((id) => graph.getNode(id))+ .filter((n): n is SceneNode => n !== undefined)+ this.drawGroupBounds(canvas, nodes, graph)++ this.drawSelectionLabels(canvas, graph, selectedIds)+ }++ private drawNodeSelection(+ canvas: Canvas,+ node: SceneNode,+ rotation: number,+ graph: SceneGraph+ ): void {+ const abs = graph.getAbsolutePosition(node.id)+ const cx = (abs.x + node.width / 2) * this.zoom + this.panX+ const cy = (abs.y + node.height / 2) * this.zoom + this.panY+ const hw = (node.width / 2) * this.zoom+ const hh = (node.height / 2) * this.zoom++ canvas.save()+ if (rotation !== 0) {+ canvas.rotate(rotation, cx, cy)+ }++ const x1 = cx - hw+ const y1 = cy - hh+ const x2 = cx + hw+ const y2 = cy + hh++ canvas.drawRect(this.ck.LTRBRect(x1, y1, x2, y2), this.selectionPaint)++ // Corner handles+ this.drawHandle(canvas, x1, y1)+ this.drawHandle(canvas, x2, y1)+ this.drawHandle(canvas, x1, y2)+ this.drawHandle(canvas, x2, y2)++ // Edge handles+ const mx = (x1 + x2) / 2+ const my = (y1 + y2) / 2+ this.drawHandle(canvas, mx, y1)+ this.drawHandle(canvas, mx, y2)+ this.drawHandle(canvas, x1, my)+ this.drawHandle(canvas, x2, my)++ // Rotation handle (line extending above + circle)+ const rotHandleY = y1 - ROTATION_HANDLE_OFFSET - ROTATION_HANDLE_RADIUS+ this.auxStroke.setStrokeWidth(1)+ this.auxStroke.setColor(this.selColor())+ this.auxStroke.setPathEffect(null)+ canvas.drawLine(mx, y1, mx, rotHandleY, this.auxStroke)++ this.auxFill.setColor(this.ck.WHITE)+ canvas.drawCircle(mx, rotHandleY, ROTATION_HANDLE_RADIUS, this.auxFill)+ canvas.drawCircle(mx, rotHandleY, ROTATION_HANDLE_RADIUS, this.auxStroke)++ canvas.restore()+ }++ private drawSelectionLabels(canvas: Canvas, graph: SceneGraph, selectedIds: Set<string>): void {+ if (!this.labelFont || !this.sizeFont) return++ // Compute bounding box of all selected nodes+ let minX = Infinity+ let minY = Infinity+ let maxX = -Infinity+ let maxY = -Infinity+ const nodes: SceneNode[] = []++ for (const id of selectedIds) {+ const node = graph.getNode(id)+ if (!node) continue+ nodes.push(node)+ const abs = graph.getAbsolutePosition(id)+ minX = Math.min(minX, abs.x)+ minY = Math.min(minY, abs.y)+ maxX = Math.max(maxX, abs.x + node.width)+ maxY = Math.max(maxY, abs.y + node.height)+ }++ if (nodes.length === 0) return++ const sx1 = minX * this.zoom + this.panX+ const sy1 = minY * this.zoom + this.panY+ const sx2 = maxX * this.zoom + this.panX+ const sy2 = maxY * this.zoom + this.panY+ const smx = (sx1 + sx2) / 2++ if (nodes.length === 1) {+ const node = nodes[0]+ const parentNode = node.parentId ? graph.getNode(node.parentId) : null+ const isTopLevel =+ !parentNode || parentNode.type === 'CANVAS' || parentNode.type === 'SECTION'+ if (node.type === 'FRAME' && isTopLevel) {+ this.auxFill.setColor(this.selColor())+ canvas.drawText(node.name, sx1, sy1 - LABEL_OFFSET_Y, this.auxFill, this.labelFont)+ }+ }++ // Size widget — blue pill below selection+ const w = Math.round(maxX - minX)+ const h = Math.round(maxY - minY)+ const sizeText = `${w} × ${h}`+ const glyphIds = this.sizeFont.getGlyphIDs(sizeText)+ const widths = this.sizeFont.getGlyphWidths(glyphIds)+ let textWidth = 0+ for (let i = 0; i < widths.length; i++) textWidth += widths[i]+ const pillW = textWidth + SIZE_PILL_PADDING_X * 2+ const pillH = SIZE_PILL_HEIGHT+ const pillX = smx - pillW / 2+ const pillY = sy2 + SIZE_PILL_PADDING_Y++ const allComponents = nodes.length > 0 && nodes.every((n) => this.isComponentType(n.type))+ const pillColor = allComponents ? this.compColor() : this.selColor()++ this.auxFill.setColor(pillColor)+ const rrect = this.ck.RRectXY(+ this.ck.LTRBRect(pillX, pillY, pillX + pillW, pillY + pillH),+ SIZE_PILL_RADIUS,+ SIZE_PILL_RADIUS+ )+ canvas.drawRRect(rrect, this.auxFill)++ this.auxFill.setColor(this.ck.WHITE)+ canvas.drawText(+ sizeText,+ pillX + SIZE_PILL_PADDING_X,+ pillY + SIZE_PILL_TEXT_OFFSET_Y,+ this.auxFill,+ this.sizeFont+ )+ }++ private drawParentFrameOutlines(+ canvas: Canvas,+ graph: SceneGraph,+ selectedIds: Set<string>+ ): void {+ const drawn = new Set<string>()+ for (const id of selectedIds) {+ const node = graph.getNode(id)+ if (!node?.parentId) continue+ const nodeParent = graph.getNode(node.parentId)+ if (!nodeParent || nodeParent.type === 'CANVAS') continue+ if (drawn.has(node.parentId) || selectedIds.has(node.parentId)) continue++ const parent = nodeParent++ // Skip dashed outline for top-level frames (direct children of page)+ const grandparent = parent.parentId ? graph.getNode(parent.parentId) : null+ if (!grandparent || grandparent.type === 'CANVAS') continue++ drawn.add(node.parentId)++ const abs = graph.getAbsolutePosition(parent.id)+ const x = abs.x * this.zoom + this.panX+ const y = abs.y * this.zoom + this.panY+ const w = parent.width * this.zoom+ const h = parent.height * this.zoom++ canvas.save()+ if (parent.rotation !== 0) {+ canvas.rotate(parent.rotation, x + w / 2, y + h / 2)+ }+ canvas.drawRect(this.ck.LTRBRect(x, y, x + w, y + h), this.parentOutlinePaint)+ canvas.restore()+ }+ }++ private drawNodeOutline(+ canvas: Canvas,+ node: SceneNode,+ rotation: number,+ graph: SceneGraph+ ): void {+ const abs = graph.getAbsolutePosition(node.id)+ const cx = (abs.x + node.width / 2) * this.zoom + this.panX+ const cy = (abs.y + node.height / 2) * this.zoom + this.panY+ const hw = (node.width / 2) * this.zoom+ const hh = (node.height / 2) * this.zoom++ canvas.save()+ if (rotation !== 0) {+ canvas.rotate(rotation, cx, cy)+ }++ canvas.drawRect(this.ck.LTRBRect(cx - hw, cy - hh, cx + hw, cy + hh), this.selectionPaint)+ canvas.restore()+ }++ private drawGroupBounds(canvas: Canvas, nodes: SceneNode[], graph: SceneGraph): void {+ let minX = Infinity+ let minY = Infinity+ let maxX = -Infinity+ let maxY = -Infinity++ for (const n of nodes) {+ const abs = graph.getAbsolutePosition(n.id)+ if (n.rotation !== 0) {+ const corners = this.getRotatedCorners(n, abs)+ for (const c of corners) {+ minX = Math.min(minX, c.x)+ minY = Math.min(minY, c.y)+ maxX = Math.max(maxX, c.x)+ maxY = Math.max(maxY, c.y)+ }+ } else {+ const x1 = abs.x * this.zoom + this.panX+ const y1 = abs.y * this.zoom + this.panY+ const x2 = (abs.x + n.width) * this.zoom + this.panX+ const y2 = (abs.y + n.height) * this.zoom + this.panY+ minX = Math.min(minX, x1)+ minY = Math.min(minY, y1)+ maxX = Math.max(maxX, x2)+ maxY = Math.max(maxY, y2)+ }+ }++ // Dashed bounding box+ this.auxStroke.setStrokeWidth(1)+ this.auxStroke.setColor(this.selColor(SELECTION_DASH_ALPHA))+ this.auxStroke.setPathEffect(null)++ canvas.drawRect(this.ck.LTRBRect(minX, minY, maxX, maxY), this.auxStroke)++ // Group resize handles+ this.drawHandle(canvas, minX, minY)+ this.drawHandle(canvas, maxX, minY)+ this.drawHandle(canvas, minX, maxY)+ this.drawHandle(canvas, maxX, maxY)+ const gmx = (minX + maxX) / 2+ const gmy = (minY + maxY) / 2+ this.drawHandle(canvas, gmx, minY)+ this.drawHandle(canvas, gmx, maxY)+ this.drawHandle(canvas, minX, gmy)+ this.drawHandle(canvas, maxX, gmy)+ }++ private getRotatedCorners(n: SceneNode, abs: { x: number; y: number }) {+ const cx = (abs.x + n.width / 2) * this.zoom + this.panX+ const cy = (abs.y + n.height / 2) * this.zoom + this.panY+ const hw = (n.width / 2) * this.zoom+ const hh = (n.height / 2) * this.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 }+ ]+ }++ private drawHandle(canvas: Canvas, x: number, y: number): void {+ this.auxFill.setColor(this.ck.WHITE)+ const rect = this.ck.LTRBRect(+ x - HANDLE_HALF_SIZE,+ y - HANDLE_HALF_SIZE,+ x + HANDLE_HALF_SIZE,+ y + HANDLE_HALF_SIZE+ )+ canvas.drawRect(rect, this.auxFill)+ canvas.drawRect(rect, this.selectionPaint)+ }++ // --- Snap guides ---++ private drawSnapGuides(canvas: Canvas, guides?: SnapGuide[]): void {+ if (!guides || guides.length === 0) return++ for (const guide of guides) {+ if (guide.axis === 'x') {+ const x = guide.position * this.zoom + this.panX+ const y1 = guide.from * this.zoom + this.panY+ const y2 = guide.to * this.zoom + this.panY+ canvas.drawLine(x, y1, x, y2, this.snapPaint)+ } else {+ const y = guide.position * this.zoom + this.panY+ const x1 = guide.from * this.zoom + this.panX+ const x2 = guide.to * this.zoom + this.panX+ canvas.drawLine(x1, y, x2, y, this.snapPaint)+ }+ }+ }++ // --- Marquee ---++ private drawMarquee(canvas: Canvas, marquee?: Rect | null): void {+ if (!marquee || marquee.width <= 0 || marquee.height <= 0) return++ const x1 = marquee.x * this.zoom + this.panX+ const y1 = marquee.y * this.zoom + this.panY+ const x2 = (marquee.x + marquee.width) * this.zoom + this.panX+ const y2 = (marquee.y + marquee.height) * this.zoom + this.panY+ const rect = this.ck.LTRBRect(x1, y1, x2, y2)++ this.auxFill.setColor(this.selColor(MARQUEE_FILL_ALPHA))+ canvas.drawRect(rect, this.auxFill)+ canvas.drawRect(rect, this.selectionPaint)+ }++ // --- Layout insert indicator ---++ private drawLayoutInsertIndicator(+ canvas: Canvas,+ indicator?: RenderOverlays['layoutInsertIndicator']+ ): void {+ if (!indicator) return++ this.auxStroke.setStrokeWidth(LAYOUT_INDICATOR_STROKE)+ this.auxStroke.setColor(this.selColor())+ this.auxStroke.setPathEffect(null)++ if (indicator.direction === 'HORIZONTAL') {+ const y = indicator.y * this.zoom + this.panY+ const x1 = indicator.x * this.zoom + this.panX+ const x2 = (indicator.x + indicator.length) * this.zoom + this.panX+ canvas.drawLine(x1, y, x2, y, this.auxStroke)+ } else {+ const x = indicator.x * this.zoom + this.panX+ const y1 = indicator.y * this.zoom + this.panY+ const y2 = (indicator.y + indicator.length) * this.zoom + this.panY+ canvas.drawLine(x, y1, x, y2, this.auxStroke)+ }+ }++ // --- Scene rendering ---++ private renderNode(+ canvas: Canvas,+ graph: SceneGraph,+ nodeId: string,+ overlays: RenderOverlays,+ parentAbsX = 0,+ parentAbsY = 0+ ): void {+ const node = graph.getNode(nodeId)+ if (!node || !node.visible) return++ const absX = parentAbsX + node.x+ const absY = parentAbsY + node.y++ // Viewport culling: skip nodes entirely outside the visible area.+ // Only cull leaf nodes and clipped containers — unclipped containers+ // may have children that extend beyond the parent's bounds.+ const canCull =+ node.childIds.length === 0 ||+ ((node.type === 'FRAME' || node.type === 'COMPONENT' || node.type === 'INSTANCE') &&+ node.clipsContent)+ if (canCull) {+ const vp = this.worldViewport+ // Expand bounds for rotation (diagonal is the max extent)+ let bw = node.width+ let bh = node.height+ if (node.rotation !== 0) {+ const diag = Math.sqrt(bw * bw + bh * bh)+ const cx = absX + bw / 2+ const cy = absY + bh / 2+ if (+ cx - diag / 2 > vp.x + vp.w ||+ cy - diag / 2 > vp.y + vp.h ||+ cx + diag / 2 < vp.x ||+ cy + diag / 2 < vp.y+ ) {+ return+ }+ } else if (absX > vp.x + vp.w || absY > vp.y + vp.h || absX + bw < vp.x || absY + bh < vp.y) {+ return+ }+ }++ canvas.save()+ canvas.translate(node.x, node.y)++ if (node.opacity < 1) {+ this.opacityPaint.setAlphaf(node.opacity)+ canvas.saveLayer(this.opacityPaint)+ }++ const rotation =+ overlays.rotationPreview?.nodeId === nodeId ? overlays.rotationPreview.angle : node.rotation++ if (rotation !== 0) {+ canvas.rotate(rotation, node.width / 2, node.height / 2)+ }++ if (node.type === 'SECTION') {+ this.renderSection(canvas, node, graph)+ } else if (node.type === 'COMPONENT_SET') {+ this.renderComponentSet(canvas, node, graph)+ } else if (overlays.editingTextId !== nodeId) {+ this.renderShape(canvas, node, graph)+ }++ // Drop target highlight+ if (overlays.dropTargetId === nodeId) {+ this.auxStroke.setStrokeWidth(DROP_HIGHLIGHT_STROKE / this.zoom)+ this.auxStroke.setColor(this.selColor(DROP_HIGHLIGHT_ALPHA))+ canvas.drawRect(this.ck.LTRBRect(0, 0, node.width, node.height), this.auxStroke)+ }++ // Hover highlight — shape-aware outline+ if (overlays.hoveredNodeId === nodeId) {+ this.auxStroke.setStrokeWidth(1 / this.zoom)+ this.auxStroke.setColor(this.isComponentType(node.type) ? this.compColor() : this.selColor())+ this.auxStroke.setPathEffect(null)+ this.strokeNodeShape(canvas, node, this.auxStroke)+ }++ // Clip + render children for containers+ const isClippableContainer =+ node.type === 'FRAME' || node.type === 'COMPONENT' || node.type === 'INSTANCE'+ if (isClippableContainer && node.clipsContent && node.childIds.length > 0) {+ canvas.save()+ canvas.clipRect(+ this.ck.LTRBRect(0, 0, node.width, node.height),+ this.ck.ClipOp.Intersect,+ true+ )+ for (const childId of node.childIds) {+ this.renderNode(canvas, graph, childId, overlays, absX, absY)+ }+ canvas.restore()+ } else {+ for (const childId of node.childIds) {+ this.renderNode(canvas, graph, childId, overlays, absX, absY)+ }+ }++ if (node.opacity < 1) {+ canvas.restore()+ }+ canvas.restore()+ }++ private strokeNodeShape(canvas: Canvas, node: SceneNode, paint: Paint): void {+ const rect = this.ck.LTRBRect(0, 0, node.width, node.height)++ switch (node.type) {+ case 'ELLIPSE':+ canvas.drawOval(rect, paint)+ return+ case 'VECTOR':+ if (node.vectorNetwork) {+ const vp = vectorNetworkToPath(this.ck, node.vectorNetwork)+ canvas.drawPath(vp, paint)+ vp.delete()+ }+ return+ case 'LINE':+ canvas.drawLine(0, 0, node.width, node.height, paint)+ return+ case 'POLYGON':+ case 'STAR': {+ const path = this.makePolygonPath(node)+ canvas.drawPath(path, paint)+ path.delete()+ return+ }+ }++ const hasRadius =+ node.cornerRadius > 0 ||+ (node.independentCorners &&+ (node.topLeftRadius > 0 ||+ node.topRightRadius > 0 ||+ node.bottomRightRadius > 0 ||+ node.bottomLeftRadius > 0))++ if (hasRadius) {+ if (node.independentCorners) {+ const rrect = new Float32Array([+ 0,+ 0,+ node.width,+ node.height,+ node.topLeftRadius,+ node.topLeftRadius,+ node.topRightRadius,+ node.topRightRadius,+ node.bottomRightRadius,+ node.bottomRightRadius,+ node.bottomLeftRadius,+ node.bottomLeftRadius+ ])+ canvas.drawRRect(rrect, paint)+ } else {+ canvas.drawRRect(this.ck.RRectXY(rect, node.cornerRadius, node.cornerRadius), paint)+ }+ } else {+ canvas.drawRect(rect, paint)+ }+ }++ private renderSection(canvas: Canvas, node: SceneNode, graph: SceneGraph): void {+ const rect = this.ck.LTRBRect(0, 0, node.width, node.height)+ const rrect = this.ck.RRectXY(rect, SECTION_CORNER_RADIUS, SECTION_CORNER_RADIUS)++ // Fill+ for (const fill of node.fills) {+ if (!fill.visible) continue+ this.applyFill(fill, node, graph)+ this.fillPaint.setAlphaf(fill.opacity)+ canvas.drawRRect(rrect, this.fillPaint)+ this.fillPaint.setShader(null)+ }++ // Stroke+ for (const stroke of node.strokes) {+ if (!stroke.visible) continue+ this.strokePaint.setColor(+ this.ck.Color4f(stroke.color.r, stroke.color.g, stroke.color.b, stroke.color.a)+ )+ this.strokePaint.setStrokeWidth(stroke.weight)+ this.strokePaint.setAlphaf(stroke.opacity)+ canvas.drawRRect(rrect, this.strokePaint)+ }+ }++ private drawSectionTitles(canvas: Canvas, graph: SceneGraph): void {+ if (!this.sectionTitleFont) return++ const pageNode = graph.getNode(this.pageId ?? graph.rootId)+ if (!pageNode) return++ const sections: { node: SceneNode; absX: number; absY: number; nested: boolean }[] = []+ const collectSections = (parentId: string, ox: number, oy: number, insideSection: boolean) => {+ const parent = graph.getNode(parentId)+ if (!parent) return+ for (const childId of parent.childIds) {+ const child = graph.getNode(childId)+ if (!child || !child.visible) continue+ const ax = ox + child.x+ const ay = oy + child.y+ if (child.type === 'SECTION') {+ const vp = this.worldViewport+ if (+ ax + child.width >= vp.x &&+ ay + child.height >= vp.y &&+ ax <= vp.x + vp.w &&+ ay <= vp.y + vp.h+ ) {+ sections.push({ node: child, absX: ax, absY: ay, nested: insideSection })+ }+ collectSections(childId, ax, ay, true)+ } else if (child.childIds.length > 0) {+ collectSections(childId, ax, ay, insideSection)+ }+ }+ }+ collectSections(pageNode.id, 0, 0, false)++ const font = this.sectionTitleFont+ const ellipsis = '…'+ const ellipsisGlyphs = font.getGlyphIDs(ellipsis)+ const ellipsisWidth = font.getGlyphWidths(ellipsisGlyphs)[0]++ for (const { node, absX, absY, nested } of sections) {+ const screenX = absX * this.zoom + this.panX+ const screenY = absY * this.zoom + this.panY+ const screenW = node.width * this.zoom+ const maxPillW = Math.max(screenW, 0)++ const glyphIds = font.getGlyphIDs(node.name)+ const widths = font.getGlyphWidths(glyphIds)++ let fullTextWidth = 0+ for (const w of widths) fullTextWidth += w++ const maxTextW = maxPillW - SECTION_TITLE_PADDING_X * 2+ let displayText = node.name+ let textWidth = fullTextWidth++ if (textWidth > maxTextW && maxTextW > ellipsisWidth) {+ let truncW = 0+ let truncIdx = 0+ for (let i = 0; i < widths.length; i++) {+ if (truncW + widths[i] + ellipsisWidth > maxTextW) break+ truncW += widths[i]+ truncIdx = i + 1+ }+ displayText = node.name.slice(0, truncIdx) + ellipsis+ textWidth = truncW + ellipsisWidth+ } else if (maxTextW <= ellipsisWidth) {+ displayText = ellipsis+ textWidth = ellipsisWidth+ }++ const pillW = Math.min(textWidth + SECTION_TITLE_PADDING_X * 2, maxPillW)+ const pillH = SECTION_TITLE_HEIGHT+ const pillX = screenX+ const pillY = nested ? screenY + SECTION_TITLE_GAP : screenY - pillH - SECTION_TITLE_GAP++ if (node.fills.length > 0 && node.fills[0].visible) {+ const c = node.fills[0].color+ this.auxFill.setColor(this.ck.Color4f(c.r, c.g, c.b, node.fills[0].opacity))+ } else {+ this.auxFill.setColor(this.ck.Color4f(0.37, 0.37, 0.37, 1))+ }+ const pillRect = this.ck.LTRBRect(pillX, pillY, pillX + pillW, pillY + pillH)+ canvas.drawRRect(+ this.ck.RRectXY(pillRect, SECTION_TITLE_RADIUS, SECTION_TITLE_RADIUS),+ this.auxFill+ )++ const pillColor =+ node.fills.length > 0 && node.fills[0].visible+ ? node.fills[0].color+ : { r: 0.37, g: 0.37, b: 0.37 }+ const lum = 0.299 * pillColor.r + 0.587 * pillColor.g + 0.114 * pillColor.b+ this.auxFill.setColor(lum > 0.5 ? this.ck.BLACK : this.ck.WHITE)+ const textY = pillY + pillH * 0.7+ canvas.drawText(displayText, pillX + SECTION_TITLE_PADDING_X, textY, this.auxFill, font)+ }+ }++ private drawComponentLabels(canvas: Canvas, graph: SceneGraph): void {+ if (!this.componentLabelFont) return++ const pageNode = graph.getNode(this.pageId ?? graph.rootId)+ if (!pageNode) return++ const font = this.componentLabelFont+ const LABEL_TYPES = new Set(['COMPONENT', 'COMPONENT_SET', 'INSTANCE'])++ const nodes: { node: SceneNode; absX: number; absY: number; inside: boolean }[] = []+ const collect = (parentId: string, ox: number, oy: number) => {+ const parent = graph.getNode(parentId)+ if (!parent) return+ for (const childId of parent.childIds) {+ const child = graph.getNode(childId)+ if (!child || !child.visible) continue+ const ax = ox + child.x+ const ay = oy + child.y+ if (LABEL_TYPES.has(child.type)) {+ const vp = this.worldViewport+ if (+ ax + child.width >= vp.x &&+ ay + child.height >= vp.y &&+ ax <= vp.x + vp.w &&+ ay <= vp.y + vp.h+ ) {+ const isInsideSet = parent.type === 'COMPONENT_SET'+ nodes.push({ node: child, absX: ax, absY: ay, inside: isInsideSet })+ }+ }+ if (child.childIds.length > 0) {+ collect(childId, ax, ay)+ }+ }+ }+ collect(pageNode.id, 0, 0)++ const compColor = this.compColor()++ // Diamond icon path points (scaled to COMPONENT_LABEL_ICON_SIZE)+ const iconS = COMPONENT_LABEL_ICON_SIZE++ for (const { node, absX, absY, inside } of nodes) {+ const screenX = absX * this.zoom + this.panX+ const screenY = absY * this.zoom + this.panY++ // Position: inside top-left for variants in a set, above top-left otherwise+ const labelX = screenX+ let labelY: number+ if (inside) {+ labelY = screenY + COMPONENT_LABEL_GAP + COMPONENT_LABEL_FONT_SIZE+ } else {+ labelY = screenY - COMPONENT_LABEL_GAP+ }++ // Draw diamond icon+ const iconX = labelX+ const iconY = labelY - COMPONENT_LABEL_FONT_SIZE * 0.75+ const iconCx = iconX + iconS / 2+ const iconCy = iconY + iconS / 2+ const iconR = iconS / 2++ this.auxFill.setColor(compColor)++ if (node.type === 'COMPONENT_SET') {+ const s = iconR * 0.45+ const gap = iconR * 0.2+ const path = new this.ck.Path()+ for (const [dx, dy] of [+ [-1, -1],+ [1, -1],+ [-1, 1],+ [1, 1]+ ]) {+ const cx = iconCx + dx * (s + gap)+ const cy = iconCy + dy * (s + gap)+ path.moveTo(cx, cy - s)+ path.lineTo(cx + s, cy)+ path.lineTo(cx, cy + s)+ path.lineTo(cx - s, cy)+ path.close()+ }+ canvas.drawPath(path, this.auxFill)+ path.delete()+ } else {+ const path = new this.ck.Path()+ path.moveTo(iconCx, iconCy - iconR)+ path.lineTo(iconCx + iconR, iconCy)+ path.lineTo(iconCx, iconCy + iconR)+ path.lineTo(iconCx - iconR, iconCy)+ path.close()+ canvas.drawPath(path, this.auxFill)+ path.delete()+ }++ canvas.drawText(+ node.name,+ labelX + iconS + COMPONENT_LABEL_ICON_GAP,+ labelY,+ this.auxFill,+ font+ )+ }+ }++ private renderComponentSet(canvas: Canvas, node: SceneNode, graph: SceneGraph): void {+ const rect = this.ck.LTRBRect(0, 0, node.width, node.height)+ const rrect = this.ck.RRectXY(rect, 5, 5)++ for (const fill of node.fills) {+ if (!fill.visible) continue+ this.applyFill(fill, node, graph)+ this.fillPaint.setAlphaf(fill.opacity)+ canvas.drawRRect(rrect, this.fillPaint)+ this.fillPaint.setShader(null)+ }++ this.auxStroke.setStrokeWidth(COMPONENT_SET_BORDER_WIDTH / this.zoom)+ this.auxStroke.setColor(this.compColor())+ this.auxStroke.setPathEffect(+ this.ck.PathEffect.MakeDash(+ [COMPONENT_SET_DASH / this.zoom, COMPONENT_SET_DASH_GAP / this.zoom],+ 0+ )+ )+ canvas.drawRRect(rrect, this.auxStroke)+ this.auxStroke.setPathEffect(null)+ }++ private renderShape(canvas: Canvas, node: SceneNode, graph: SceneGraph): void {+ const rect = this.ck.LTRBRect(0, 0, node.width, node.height)++ const hasRadius =+ node.cornerRadius > 0 ||+ (node.independentCorners &&+ (node.topLeftRadius > 0 ||+ node.topRightRadius > 0 ||+ node.bottomRightRadius > 0 ||+ node.bottomLeftRadius > 0))++ // Fills+ for (const fill of node.fills) {+ if (!fill.visible) continue+ this.applyFill(fill, node, graph)+ this.fillPaint.setAlphaf(fill.opacity)++ this.drawNodeFill(canvas, node, rect, hasRadius)+ this.fillPaint.setShader(null)+ }++ // Effects (behind: drop shadow)+ this.renderEffects(canvas, node, rect, hasRadius, 'behind')++ // Strokes+ for (const stroke of node.strokes) {+ if (!stroke.visible) continue+ this.strokePaint.setColor(+ this.ck.Color4f(stroke.color.r, stroke.color.g, stroke.color.b, stroke.color.a)+ )+ this.strokePaint.setStrokeWidth(stroke.weight)+ this.strokePaint.setAlphaf(stroke.opacity)++ if (stroke.cap) {+ const capMap: Record<string, EmbindEnumEntity> = {+ NONE: this.ck.StrokeCap.Butt,+ ROUND: this.ck.StrokeCap.Round,+ SQUARE: this.ck.StrokeCap.Square+ }+ this.strokePaint.setStrokeCap(capMap[stroke.cap] ?? this.ck.StrokeCap.Butt)+ }+ if (stroke.join) {+ const joinMap: Record<string, EmbindEnumEntity> = {+ MITER: this.ck.StrokeJoin.Miter,+ ROUND: this.ck.StrokeJoin.Round,+ BEVEL: this.ck.StrokeJoin.Bevel+ }+ this.strokePaint.setStrokeJoin(joinMap[stroke.join] ?? this.ck.StrokeJoin.Miter)+ }+ if (stroke.dashPattern && stroke.dashPattern.length > 0) {+ this.strokePaint.setPathEffect(this.ck.PathEffect.MakeDash(stroke.dashPattern, 0))+ } else {+ this.strokePaint.setPathEffect(null)+ }++ this.drawNodeStroke(canvas, node, rect, hasRadius)+ }++ // Effects (front: inner shadow, blur)+ this.renderEffects(canvas, node, rect, hasRadius, 'front')+ }++ private drawNodeFill(+ canvas: Canvas,+ node: SceneNode,+ rect: Float32Array,+ hasRadius: boolean+ ): void {+ switch (node.type) {+ case 'VECTOR':+ if (node.vectorNetwork) {+ const vp = vectorNetworkToPath(this.ck, node.vectorNetwork)+ canvas.drawPath(vp, this.fillPaint)+ vp.delete()+ }+ break+ case 'ELLIPSE':+ if (node.arcData) {+ this.drawArc(canvas, node, this.fillPaint)+ } else {+ canvas.drawOval(rect, this.fillPaint)+ }+ break+ case 'TEXT':+ this.renderText(canvas, node)+ break+ case 'LINE':+ canvas.drawLine(0, 0, node.width, node.height, this.fillPaint)+ break+ case 'POLYGON':+ case 'STAR': {+ const path = this.makePolygonPath(node)+ canvas.drawPath(path, this.fillPaint)+ path.delete()+ break+ }+ default:+ if (hasRadius) {+ canvas.drawRRect(this.makeRRect(node), this.fillPaint)+ } else {+ canvas.drawRect(rect, this.fillPaint)+ }+ }+ }++ private drawNodeStroke(+ canvas: Canvas,+ node: SceneNode,+ rect: Float32Array,+ hasRadius: boolean+ ): void {+ switch (node.type) {+ case 'VECTOR':+ if (node.vectorNetwork) {+ const vp = vectorNetworkToPath(this.ck, node.vectorNetwork)+ canvas.drawPath(vp, this.strokePaint)+ vp.delete()+ }+ break+ case 'ELLIPSE':+ if (node.arcData) {+ this.drawArc(canvas, node, this.strokePaint)+ } else {+ canvas.drawOval(rect, this.strokePaint)+ }+ break+ case 'POLYGON':+ case 'STAR': {+ const path = this.makePolygonPath(node)+ canvas.drawPath(path, this.strokePaint)+ path.delete()+ break+ }+ default:+ if (hasRadius) {+ canvas.drawRRect(this.makeRRect(node), this.strokePaint)+ } else {+ canvas.drawRect(rect, this.strokePaint)+ }+ }+ }++ private makePolygonPath(node: SceneNode): Path {+ const path = new this.ck.Path()+ const cx = node.width / 2+ const cy = node.height / 2+ const rx = node.width / 2+ const ry = node.height / 2+ const n = Math.max(3, node.pointCount)+ const isStar = node.type === 'STAR'+ const innerRatio = isStar ? node.starInnerRadius : 1+ const totalPoints = isStar ? n * 2 : n+ const angleOffset = -Math.PI / 2++ for (let i = 0; i < totalPoints; i++) {+ const angle = angleOffset + (2 * Math.PI * i) / totalPoints+ const isInner = isStar && i % 2 === 1+ const r = isInner ? innerRatio : 1+ const px = cx + rx * r * Math.cos(angle)+ const py = cy + ry * r * Math.sin(angle)+ if (i === 0) path.moveTo(px, py)+ else path.lineTo(px, py)+ }+ path.close()+ return path+ }++ private makeRRect(node: SceneNode): Float32Array {+ if (node.independentCorners) {+ return new Float32Array([+ 0,+ 0,+ node.width,+ node.height,+ node.topLeftRadius,+ node.topLeftRadius,+ node.topRightRadius,+ node.topRightRadius,+ node.bottomRightRadius,+ node.bottomRightRadius,+ node.bottomLeftRadius,+ node.bottomLeftRadius+ ])+ }+ return this.ck.RRectXY(+ this.ck.LTRBRect(0, 0, node.width, node.height),+ node.cornerRadius,+ node.cornerRadius+ )+ }++ private drawArc(canvas: Canvas, node: SceneNode, paint: Paint): void {+ const arc = node.arcData+ if (!arc) return+ const cx = node.width / 2+ const cy = node.height / 2+ const rx = node.width / 2+ const ry = node.height / 2+ const innerRx = rx * arc.innerRadius+ const innerRy = ry * arc.innerRadius++ const startDeg = arc.startingAngle * (180 / Math.PI)+ const endDeg = arc.endingAngle * (180 / Math.PI)+ const sweepDeg = endDeg - startDeg++ const path = new this.ck.Path()+ const oval = this.ck.LTRBRect(0, 0, node.width, node.height)++ if (arc.innerRadius > 0) {+ // Donut shape+ path.addArc(oval, startDeg, sweepDeg)+ const innerOval = this.ck.LTRBRect(cx - innerRx, cy - innerRy, cx + innerRx, cy + innerRy)+ const innerPath = new this.ck.Path()+ innerPath.addArc(innerOval, startDeg + sweepDeg, -sweepDeg)+ path.addPath(innerPath)+ path.close()+ innerPath.delete()+ } else {+ const isFullCircle = Math.abs(sweepDeg) >= 359.99+ if (isFullCircle) {+ path.addOval(oval)+ } else {+ path.moveTo(cx, cy)+ path.addArc(oval, startDeg, sweepDeg)+ path.close()+ }+ }++ canvas.drawPath(path, paint)+ path.delete()+ }++ private renderEffects(+ canvas: Canvas,+ node: SceneNode,+ rect: Float32Array,+ hasRadius: boolean,+ pass: 'behind' | 'front'+ ): void {+ for (const effect of node.effects) {+ if (!effect.visible) continue++ if (pass === 'behind' && effect.type === 'DROP_SHADOW') {+ this.auxFill.setColor(+ this.ck.Color4f(effect.color.r, effect.color.g, effect.color.b, effect.color.a)+ )+ this.auxFill.setImageFilter(+ this.ck.ImageFilter.MakeBlur(effect.radius, effect.radius, this.ck.TileMode.Decal, null)+ )++ canvas.save()+ canvas.translate(effect.offset.x, effect.offset.y)+ if (node.type === 'ELLIPSE') {+ canvas.drawOval(rect, this.auxFill)+ } else if (hasRadius) {+ canvas.drawRRect(this.makeRRect(node), this.auxFill)+ } else {+ canvas.drawRect(rect, this.auxFill)+ }+ canvas.restore()+ this.auxFill.setImageFilter(null)+ }++ if (pass === 'front' && effect.type === 'LAYER_BLUR') {+ // Layer blur applied as save layer with blur filter — already applied via opacity layer+ }++ if (pass === 'front' && effect.type === 'INNER_SHADOW') {+ // Inner shadow: draw a shadow clipped to the node shape+ this.auxFill.setColor(+ this.ck.Color4f(effect.color.r, effect.color.g, effect.color.b, effect.color.a)+ )+ this.auxFill.setImageFilter(+ this.ck.ImageFilter.MakeBlur(effect.radius, effect.radius, this.ck.TileMode.Decal, null)+ )++ canvas.save()+ if (node.type === 'ELLIPSE') {+ const path = new this.ck.Path()+ path.addOval(rect)+ canvas.clipPath(path, this.ck.ClipOp.Intersect, true)+ path.delete()+ } else if (hasRadius) {+ canvas.clipRRect(this.makeRRect(node), this.ck.ClipOp.Intersect, true)+ } else {+ canvas.clipRect(rect, this.ck.ClipOp.Intersect, true)+ }++ // Draw inverted shape offset by shadow offset+ const big = this.ck.LTRBRect(+ -effect.radius * 2 + effect.offset.x,+ -effect.radius * 2 + effect.offset.y,+ node.width + effect.radius * 2 + effect.offset.x,+ node.height + effect.radius * 2 + effect.offset.y+ )+ const bigPath = new this.ck.Path()+ bigPath.addRect(big)+ if (node.type === 'ELLIPSE') {+ const innerPath = new this.ck.Path()+ const offsetRect = this.ck.LTRBRect(+ effect.offset.x,+ effect.offset.y,+ node.width + effect.offset.x,+ node.height + effect.offset.y+ )+ innerPath.addOval(offsetRect)+ bigPath.op(innerPath, this.ck.PathOp.Difference)+ innerPath.delete()+ } else {+ const innerPath = new this.ck.Path()+ innerPath.addRect(+ this.ck.LTRBRect(+ effect.offset.x,+ effect.offset.y,+ node.width + effect.offset.x,+ node.height + effect.offset.y+ )+ )+ bigPath.op(innerPath, this.ck.PathOp.Difference)+ innerPath.delete()+ }+ canvas.drawPath(bigPath, this.auxFill)+ bigPath.delete()+ canvas.restore()+ this.auxFill.setImageFilter(null)+ }+ }+ }++ private renderText(canvas: Canvas, node: SceneNode): void {+ const text = node.text+ if (!text) return++ if (this.fontsLoaded && this.fontProvider) {+ const paraStyle = new this.ck.ParagraphStyle({+ textAlign: this.getTextAlign(node.textAlignHorizontal),+ textStyle: {+ color: this.fillPaint.getColor(),+ fontFamilies: [node.fontFamily || 'Inter'],+ fontSize: node.fontSize || DEFAULT_FONT_SIZE,+ fontStyle: { weight: { value: node.fontWeight || 400 } as FontWeight },+ letterSpacing: node.letterSpacing || 0,+ heightMultiplier: node.lineHeight+ ? node.lineHeight / (node.fontSize || DEFAULT_FONT_SIZE)+ : undefined+ }+ })+ const builder = this.ck.ParagraphBuilder.MakeFromFontProvider(paraStyle, this.fontProvider)+ builder.addText(text)+ const paragraph = builder.build()+ paragraph.layout(node.width || 1e6)+ canvas.drawParagraph(paragraph, 0, 0)+ paragraph.delete()+ builder.delete()+ } else if (this.textFont) {+ canvas.drawText(text, 0, node.fontSize || DEFAULT_FONT_SIZE, this.fillPaint, this.textFont)+ }+ }++ private getTextAlign(align: string) {+ switch (align) {+ case 'CENTER':+ return this.ck.TextAlign.Center+ case 'RIGHT':+ return this.ck.TextAlign.Right+ case 'JUSTIFIED':+ return this.ck.TextAlign.Justify+ default:+ return this.ck.TextAlign.Left+ }+ }++ private applyFill(fill: Fill, node: SceneNode, graph: SceneGraph): void {+ this.fillPaint.setShader(null)++ if (fill.type === 'SOLID') {+ this.fillPaint.setColor(+ this.ck.Color4f(fill.color.r, fill.color.g, fill.color.b, fill.color.a)+ )+ return+ }++ if (fill.type.startsWith('GRADIENT') && fill.gradientStops && fill.gradientTransform) {+ this.applyGradientFill(fill, node)+ return+ }++ if (fill.type === 'IMAGE' && fill.imageHash) {+ this.applyImageFill(fill, node, graph)+ return+ }+ }++ private applyGradientFill(fill: Fill, node: SceneNode): void {+ const stops = fill.gradientStops+ const t = fill.gradientTransform+ if (!stops || !t) return+ const colors = stops.map((s) => this.ck.Color4f(s.color.r, s.color.g, s.color.b, s.color.a))+ const positions = stops.map((s) => s.position)++ // Figma gradient transform maps unit square to node bounds+ // Convert transform to canvas coordinates+ const w = node.width+ const h = node.height++ if (fill.type === 'GRADIENT_LINEAR') {+ // Start and end points derived from transform+ const startX = t.m02 * w+ const startY = t.m12 * h+ const endX = (t.m00 + t.m02) * w+ const endY = (t.m10 + t.m12) * h+ const shader = this.ck.Shader.MakeLinearGradient(+ [startX, startY],+ [endX, endY],+ colors,+ positions,+ this.ck.TileMode.Clamp+ )+ this.fillPaint.setShader(shader)+ } else if (fill.type === 'GRADIENT_RADIAL') {+ const cx = t.m02 * w+ const cy = t.m12 * h+ const radius = Math.sqrt(t.m00 * t.m00 + t.m10 * t.m10) * Math.max(w, h)+ const shader = this.ck.Shader.MakeRadialGradient(+ [cx, cy],+ radius,+ colors,+ positions,+ this.ck.TileMode.Clamp+ )+ this.fillPaint.setShader(shader)+ } else if (fill.type === 'GRADIENT_ANGULAR') {+ const cx = t.m02 * w+ const cy = t.m12 * h+ const shader = this.ck.Shader.MakeSweepGradient(+ cx,+ cy,+ colors,+ positions,+ this.ck.TileMode.Clamp,+ // Figma angular gradients start from right (0°), CanvasKit sweep from right too+ undefined+ )+ this.fillPaint.setShader(shader)+ } else if (fill.type === 'GRADIENT_DIAMOND') {+ // Diamond gradient approximated as radial+ const cx = t.m02 * w+ const cy = t.m12 * h+ const radius = Math.sqrt(t.m00 * t.m00 + t.m10 * t.m10) * Math.max(w, h)+ const shader = this.ck.Shader.MakeRadialGradient(+ [cx, cy],+ radius,+ colors,+ positions,+ this.ck.TileMode.Clamp+ )+ this.fillPaint.setShader(shader)+ }+ }++ private applyImageFill(fill: Fill, node: SceneNode, graph: SceneGraph): void {+ const hash = fill.imageHash+ if (!hash) return+ let img = this.imageCache.get(hash)+ if (!img) {+ const data = graph.images.get(hash)+ if (!data) return+ img = this.ck.MakeImageFromEncoded(data) ?? undefined+ if (img) this.imageCache.set(hash, img)+ else return+ }++ const imgW = img.width()+ const imgH = img.height()+ const scaleMode = fill.imageScaleMode ?? 'FILL'++ let sx: number, sy: number, sw: number, sh: number+ if (scaleMode === 'FILL') {+ const scale = Math.max(node.width / imgW, node.height / imgH)+ sw = node.width / scale+ sh = node.height / scale+ sx = (imgW - sw) / 2+ sy = (imgH - sh) / 2+ } else if (scaleMode === 'FIT') {+ sw = imgW+ sh = imgH+ sx = 0+ sy = 0+ // FIT: image centered within bounds — handled by shader matrix+ } else {+ sx = 0+ sy = 0+ sw = imgW+ sh = imgH+ }++ const shader = img.makeShaderCubic(+ this.ck.TileMode.Clamp,+ this.ck.TileMode.Clamp,+ 1 / 3,+ 1 / 3,+ this.ck.Matrix.multiply(+ this.ck.Matrix.scaled(node.width / sw, node.height / sh),+ this.ck.Matrix.translated(-sx, -sy)+ )+ )+ this.fillPaint.setShader(shader)+ }++ screenToCanvas(sx: number, sy: number): { x: number; y: number } {+ return {+ x: (sx - this.panX) / this.zoom,+ y: (sy - this.panY) / this.zoom+ }+ }++ private drawPenOverlay(canvas: Canvas, penState: RenderOverlays['penState']): void {+ if (!penState || penState.vertices.length === 0) return++ const { vertices, segments, dragTangent, cursorX, cursorY } = penState+ const pathPaint = new this.ck.Paint()+ pathPaint.setStyle(this.ck.PaintStyle.Stroke)+ pathPaint.setStrokeWidth(PEN_PATH_STROKE_WIDTH)+ pathPaint.setColor(this.selColor())+ pathPaint.setAntiAlias(true)++ const handlePaint = new this.ck.Paint()+ handlePaint.setStyle(this.ck.PaintStyle.Stroke)+ handlePaint.setStrokeWidth(1)+ handlePaint.setColor(this.selColor(PARENT_OUTLINE_ALPHA))+ handlePaint.setAntiAlias(true)++ const vertexFill = new this.ck.Paint()+ vertexFill.setStyle(this.ck.PaintStyle.Fill)+ vertexFill.setColor(this.ck.WHITE)+ vertexFill.setAntiAlias(true)++ const vertexStroke = new this.ck.Paint()+ vertexStroke.setStyle(this.ck.PaintStyle.Stroke)+ vertexStroke.setStrokeWidth(PEN_PATH_STROKE_WIDTH)+ vertexStroke.setColor(this.selColor())+ vertexStroke.setAntiAlias(true)++ const toScreen = (x: number, y: number) => ({+ x: x * this.zoom + this.panX,+ y: y * this.zoom + this.panY+ })++ // Draw existing segments+ const path = new this.ck.Path()+ for (const seg of segments) {+ const s = toScreen(vertices[seg.start].x, vertices[seg.start].y)+ const e = toScreen(vertices[seg.end].x, vertices[seg.end].y)+ path.moveTo(s.x, s.y)++ const isLine =+ seg.tangentStart.x === 0 &&+ seg.tangentStart.y === 0 &&+ seg.tangentEnd.x === 0 &&+ seg.tangentEnd.y === 0+ if (isLine) {+ path.lineTo(e.x, e.y)+ } else {+ const cp1 = toScreen(+ vertices[seg.start].x + seg.tangentStart.x,+ vertices[seg.start].y + seg.tangentStart.y+ )+ const cp2 = toScreen(+ vertices[seg.end].x + seg.tangentEnd.x,+ vertices[seg.end].y + seg.tangentEnd.y+ )+ path.cubicTo(cp1.x, cp1.y, cp2.x, cp2.y, e.x, e.y)+ }+ }++ // Preview line from last vertex to cursor+ if (vertices.length > 0 && cursorX != null && cursorY != null) {+ const last = toScreen(vertices[vertices.length - 1].x, vertices[vertices.length - 1].y)+ const cursor = toScreen(cursorX, cursorY)+ path.moveTo(last.x, last.y)+ if (dragTangent) {+ const cp1 = toScreen(+ vertices[vertices.length - 1].x + dragTangent.x,+ vertices[vertices.length - 1].y + dragTangent.y+ )+ path.cubicTo(cp1.x, cp1.y, cursor.x, cursor.y, cursor.x, cursor.y)+ } else {+ path.lineTo(cursor.x, cursor.y)+ }+ }++ canvas.drawPath(path, pathPaint)+ path.delete()++ // Draw tangent handle lines+ for (const seg of segments) {+ const ts = seg.tangentStart+ const te = seg.tangentEnd+ if (ts.x !== 0 || ts.y !== 0) {+ const s = toScreen(vertices[seg.start].x, vertices[seg.start].y)+ const cp = toScreen(vertices[seg.start].x + ts.x, vertices[seg.start].y + ts.y)+ canvas.drawLine(s.x, s.y, cp.x, cp.y, handlePaint)+ canvas.drawCircle(cp.x, cp.y, PEN_HANDLE_RADIUS, vertexFill)+ canvas.drawCircle(cp.x, cp.y, PEN_HANDLE_RADIUS, handlePaint)+ }+ if (te.x !== 0 || te.y !== 0) {+ const e = toScreen(vertices[seg.end].x, vertices[seg.end].y)+ const cp = toScreen(vertices[seg.end].x + te.x, vertices[seg.end].y + te.y)+ canvas.drawLine(e.x, e.y, cp.x, cp.y, handlePaint)+ canvas.drawCircle(cp.x, cp.y, PEN_HANDLE_RADIUS, vertexFill)+ canvas.drawCircle(cp.x, cp.y, PEN_HANDLE_RADIUS, handlePaint)+ }+ }++ // Draw current drag tangent handles+ if (dragTangent && vertices.length > 0) {+ const last = vertices[vertices.length - 1]+ const cp1 = toScreen(last.x + dragTangent.x, last.y + dragTangent.y)+ const cp2 = toScreen(last.x - dragTangent.x, last.y - dragTangent.y)+ canvas.drawLine(cp2.x, cp2.y, cp1.x, cp1.y, handlePaint)+ canvas.drawCircle(cp1.x, cp1.y, PEN_HANDLE_RADIUS, vertexFill)+ canvas.drawCircle(cp1.x, cp1.y, PEN_HANDLE_RADIUS, handlePaint)+ canvas.drawCircle(cp2.x, cp2.y, PEN_HANDLE_RADIUS, vertexFill)+ canvas.drawCircle(cp2.x, cp2.y, PEN_HANDLE_RADIUS, handlePaint)+ }++ // Draw vertices+ for (let i = 0; i < vertices.length; i++) {+ const v = toScreen(vertices[i].x, vertices[i].y)+ const radius =+ i === 0 && penState.closingToFirst+ ? PEN_VERTEX_RADIUS + PEN_CLOSE_RADIUS_BOOST+ : PEN_VERTEX_RADIUS+ canvas.drawCircle(v.x, v.y, radius, vertexFill)+ canvas.drawCircle(v.x, v.y, radius, vertexStroke)+ }++ pathPaint.delete()+ handlePaint.delete()+ vertexFill.delete()+ vertexStroke.delete()+ }++ // --- Rulers ---++ private drawRulers(canvas: Canvas, graph: SceneGraph, selectedIds: Set<string>): void {+ const R = RULER_SIZE+ const vw = this.viewportWidth+ const vh = this.viewportHeight+ if (vw === 0 || vh === 0) return++ const bg = RULER_BG_COLOR+ const bgPaint = new this.ck.Paint()+ bgPaint.setColor(this.ck.Color4f(bg.r, bg.g, bg.b, 1))++ canvas.drawRect(this.ck.LTRBRect(0, 0, vw, R), bgPaint)+ canvas.drawRect(this.ck.LTRBRect(0, R, R, vh), bgPaint)++ // Corner square+ canvas.drawRect(this.ck.LTRBRect(0, 0, R, R), bgPaint)++ const tickPaint = new this.ck.Paint()+ tickPaint.setColor(+ this.ck.Color4f(RULER_TICK_COLOR.r, RULER_TICK_COLOR.g, RULER_TICK_COLOR.b, 1)+ )+ tickPaint.setStrokeWidth(1)+ tickPaint.setAntiAlias(true)++ const textColor = RULER_TEXT_COLOR+ const textPaint = new this.ck.Paint()+ textPaint.setColor(this.ck.Color4f(textColor.r, textColor.g, textColor.b, 1))+ textPaint.setAntiAlias(true)++ const font = this.sizeFont ?? this.textFont+ if (!font) {+ bgPaint.delete()+ tickPaint.delete()+ textPaint.delete()+ return+ }++ const step = this.rulerStep()+ const minorStep = step / 5++ // Compute selection bounds for badge exclusion zones+ let sx1 = -Infinity,+ sx2 = -Infinity,+ sy1 = -Infinity,+ sy2 = -Infinity+ const selNodes = [...selectedIds]+ .map((id) => graph.getNode(id))+ .filter((n): n is SceneNode => n !== undefined)+ if (selNodes.length > 0) {+ 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)+ }+ sx1 = minX * this.zoom + this.panX+ sx2 = maxX * this.zoom + this.panX+ sy1 = minY * this.zoom + this.panY+ sy2 = maxY * this.zoom + this.panY+ }++ const badgeW = RULER_BADGE_EXCLUSION++ // Horizontal ruler (clipped)+ canvas.save()+ canvas.clipRect(this.ck.LTRBRect(R, 0, vw, R), this.ck.ClipOp.Intersect, false)+ const worldLeft = -this.panX / this.zoom+ const worldRight = (vw - this.panX) / this.zoom+ const startX = Math.floor(worldLeft / step) * step++ for (let wx = startX; wx <= worldRight; wx += minorStep) {+ const sx = wx * this.zoom + this.panX+ if (sx < R) continue+ const isMajor = Math.abs(wx % step) < RULER_MAJOR_TOLERANCE+ const tickLen = isMajor ? R * RULER_MAJOR_TICK : R * RULER_MINOR_TICK+ canvas.drawLine(sx, R - tickLen, sx, R, tickPaint)++ if (isMajor && selNodes.length > 0) {+ const tooClose = Math.abs(sx - sx1) < badgeW || Math.abs(sx - sx2) < badgeW+ if (!tooClose) {+ canvas.drawText(this.rulerLabel(wx), sx + 2, R * RULER_TEXT_BASELINE, textPaint, font)+ }+ } else if (isMajor) {+ canvas.drawText(this.rulerLabel(wx), sx + 2, R * RULER_TEXT_BASELINE, textPaint, font)+ }+ }+ canvas.restore()++ // Vertical ruler (clipped)+ canvas.save()+ canvas.clipRect(this.ck.LTRBRect(0, R, R, vh), this.ck.ClipOp.Intersect, false)+ const worldTop = -this.panY / this.zoom+ const worldBottom = (vh - this.panY) / this.zoom+ const startY = Math.floor(worldTop / step) * step++ for (let wy = startY; wy <= worldBottom; wy += minorStep) {+ const sy = wy * this.zoom + this.panY+ if (sy < R) continue+ const isMajor = Math.abs(wy % step) < RULER_MAJOR_TOLERANCE+ const tickLen = isMajor ? R * RULER_MAJOR_TICK : R * RULER_MINOR_TICK+ canvas.drawLine(R - tickLen, sy, R, sy, tickPaint)++ if (isMajor && selNodes.length > 0) {+ const tooClose = Math.abs(sy - sy1) < badgeW || Math.abs(sy - sy2) < badgeW+ if (!tooClose) {+ canvas.save()+ canvas.translate(R * RULER_TEXT_BASELINE, sy - 2)+ canvas.rotate(-90, 0, 0)+ canvas.drawText(this.rulerLabel(wy), 0, 3, textPaint, font)+ canvas.restore()+ }+ } else if (isMajor) {+ canvas.save()+ canvas.translate(R * RULER_TEXT_BASELINE, sy - 2)+ canvas.rotate(-90, 0, 0)+ canvas.drawText(this.rulerLabel(wy), 0, 3, textPaint, font)+ canvas.restore()+ }+ }+ canvas.restore()++ // Selection highlight + badges+ if (selNodes.length > 0) {+ const hlPaint = new this.ck.Paint()+ hlPaint.setColor(this.selColor(RULER_HIGHLIGHT_ALPHA))++ canvas.drawRect(this.ck.LTRBRect(Math.max(R, sx1), 0, sx2, R), hlPaint)+ canvas.drawRect(this.ck.LTRBRect(0, Math.max(R, sy1), R, sy2), hlPaint)++ this.drawRulerBadge(+ canvas,+ font,+ Math.round((sx1 - this.panX) / this.zoom).toString(),+ Math.max(R, sx1),+ 0,+ 'horizontal'+ )+ this.drawRulerBadge(+ canvas,+ font,+ Math.round((sx2 - this.panX) / this.zoom).toString(),+ sx2,+ 0,+ 'horizontal'+ )+ this.drawRulerBadge(+ canvas,+ font,+ Math.round((sy1 - this.panY) / this.zoom).toString(),+ 0,+ Math.max(R, sy1),+ 'vertical'+ )+ this.drawRulerBadge(+ canvas,+ font,+ Math.round((sy2 - this.panY) / this.zoom).toString(),+ 0,+ sy2,+ 'vertical'+ )++ hlPaint.delete()+ }++ bgPaint.delete()+ tickPaint.delete()+ textPaint.delete()+ }++ private drawRulerBadge(+ canvas: Canvas,+ font: InstanceType<CanvasKit['Font']>,+ label: string,+ x: number,+ y: number,+ axis: 'horizontal' | 'vertical'+ ): void {+ const R = RULER_SIZE+ const glyphIds = font.getGlyphIDs(label)+ const widths = font.getGlyphWidths(glyphIds)+ const textW = widths.reduce((s, w) => s + w, 0)+ const pad = RULER_BADGE_PADDING+ const h = RULER_BADGE_HEIGHT++ const badgePaint = new this.ck.Paint()+ badgePaint.setColor(this.selColor())+ const labelPaint = new this.ck.Paint()+ labelPaint.setColor(this.ck.Color4f(1, 1, 1, 1))+ labelPaint.setAntiAlias(true)++ if (axis === 'horizontal') {+ const bx = x - (textW + pad * 2) / 2+ const by = (R - h) / 2+ canvas.drawRRect(+ this.ck.RRectXY(+ this.ck.LTRBRect(bx, by, bx + textW + pad * 2, by + h),+ RULER_BADGE_RADIUS,+ RULER_BADGE_RADIUS+ ),+ badgePaint+ )+ canvas.drawText(label, bx + pad, R * RULER_TEXT_BASELINE, labelPaint, font)+ } else {+ const bw = textW + pad * 2+ const bx = (R - h) / 2+ const by = y - bw / 2+ canvas.save()+ canvas.translate(bx + h / 2, by + bw / 2)+ canvas.rotate(-90, 0, 0)+ canvas.drawRRect(+ this.ck.RRectXY(+ this.ck.LTRBRect(-bw / 2, -h / 2, bw / 2, h / 2),+ RULER_BADGE_RADIUS,+ RULER_BADGE_RADIUS+ ),+ badgePaint+ )+ canvas.drawText(label, -bw / 2 + pad, h / 2 - 3, labelPaint, font)+ canvas.restore()+ }++ badgePaint.delete()+ labelPaint.delete()+ }++ private rulerStep(): number {+ const pixelsPerUnit = this.zoom+ const rawStep = RULER_TARGET_PIXEL_SPACING / pixelsPerUnit+ const magnitude = Math.pow(10, Math.floor(Math.log10(rawStep)))+ const normalized = rawStep / magnitude++ if (normalized <= 1) return magnitude+ if (normalized <= 2) return 2 * magnitude+ if (normalized <= 5) return 5 * magnitude+ return 10 * magnitude+ }++ private rulerLabel(value: number): string {+ return Math.round(value).toString()+ }++ destroy(): void {+ for (const img of this.imageCache.values()) img.delete()+ this.imageCache.clear()+ this.fillPaint.delete()+ this.strokePaint.delete()+ this.selectionPaint.delete()+ this.snapPaint.delete()+ this.auxFill.delete()+ this.auxStroke.delete()+ this.opacityPaint.delete()+ this.textFont?.delete()+ this.labelFont?.delete()+ this.sizeFont?.delete()+ this.fontMgr?.delete()+ this.fontProvider?.delete()+ this.surface.delete()+ }+}diff --git a/packages/core/src/scene-graph.ts b/packages/core/src/scene-graph.tsnew file mode 100644index 000000000..ff3d8004f--- /dev/null+++ b/packages/core/src/scene-graph.ts@@ -0,0 +1,802 @@+export type { GUID, Color } from './types'++export type HandleMirroring = 'NONE' | 'ANGLE' | 'ANGLE_AND_LENGTH'+export type WindingRule = 'NONZERO' | 'EVENODD'++export interface VectorVertex {+ x: number+ y: number+ strokeCap?: string+ strokeJoin?: string+ cornerRadius?: number+ handleMirroring?: HandleMirroring+}++export interface VectorSegment {+ start: number+ end: number+ tangentStart: { x: number; y: number }+ tangentEnd: { x: number; y: number }+}++export interface VectorRegion {+ windingRule: WindingRule+ loops: number[][]+}++export interface VectorNetwork {+ vertices: VectorVertex[]+ segments: VectorSegment[]+ regions: VectorRegion[]+}++export type NodeType =+ | 'CANVAS'+ | 'FRAME'+ | 'RECTANGLE'+ | 'ROUNDED_RECTANGLE'+ | 'ELLIPSE'+ | 'TEXT'+ | 'LINE'+ | 'STAR'+ | 'POLYGON'+ | 'VECTOR'+ | 'GROUP'+ | 'SECTION'+ | 'COMPONENT'+ | 'COMPONENT_SET'+ | 'INSTANCE'+ | 'CONNECTOR'+ | 'SHAPE_WITH_TEXT'++import type { Color, Matrix, Rect } from './types'++export type FillType =+ | 'SOLID'+ | 'GRADIENT_LINEAR'+ | 'GRADIENT_RADIAL'+ | 'GRADIENT_ANGULAR'+ | 'GRADIENT_DIAMOND'+ | 'IMAGE'+export type BlendMode =+ | 'NORMAL'+ | 'DARKEN'+ | 'MULTIPLY'+ | 'COLOR_BURN'+ | 'LIGHTEN'+ | 'SCREEN'+ | 'COLOR_DODGE'+ | 'OVERLAY'+ | 'SOFT_LIGHT'+ | 'HARD_LIGHT'+ | 'DIFFERENCE'+ | 'EXCLUSION'+ | 'HUE'+ | 'SATURATION'+ | 'COLOR'+ | 'LUMINOSITY'+ | 'PASS_THROUGH'+export type ImageScaleMode = 'FILL' | 'FIT' | 'CROP' | 'TILE'++export interface GradientStop {+ color: Color+ position: number+}++export type GradientTransform = Matrix++export interface Fill {+ type: FillType+ color: Color+ opacity: number+ visible: boolean+ blendMode?: BlendMode+ gradientStops?: GradientStop[]+ gradientTransform?: GradientTransform+ imageHash?: string+ imageScaleMode?: ImageScaleMode+ imageTransform?: GradientTransform+}++export type StrokeCap = 'NONE' | 'ROUND' | 'SQUARE' | 'ARROW_LINES' | 'ARROW_EQUILATERAL'+export type StrokeJoin = 'MITER' | 'BEVEL' | 'ROUND'++export interface Stroke {+ color: Color+ weight: number+ opacity: number+ visible: boolean+ align: 'INSIDE' | 'CENTER' | 'OUTSIDE'+ cap?: StrokeCap+ join?: StrokeJoin+ dashPattern?: number[]+}++export interface Effect {+ type: 'DROP_SHADOW' | 'INNER_SHADOW' | 'LAYER_BLUR' | 'BACKGROUND_BLUR' | 'FOREGROUND_BLUR'+ color: Color+ offset: { x: number; y: number }+ radius: number+ spread: number+ visible: boolean+ blendMode?: BlendMode+}++export type ConstraintType = 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'SCALE'+export type TextAutoResize = 'NONE' | 'HEIGHT' | 'WIDTH_AND_HEIGHT' | 'TRUNCATE'+export type TextAlignVertical = 'TOP' | 'CENTER' | 'BOTTOM'+export type TextCase = 'ORIGINAL' | 'UPPER' | 'LOWER' | 'TITLE'+export type TextDecoration = 'NONE' | 'UNDERLINE' | 'STRIKETHROUGH'++export interface ArcData {+ startingAngle: number+ endingAngle: number+ innerRadius: number+}++export type LayoutMode = 'NONE' | 'HORIZONTAL' | 'VERTICAL'+export type LayoutSizing = 'FIXED' | 'HUG' | 'FILL'+export type LayoutAlign = 'MIN' | 'CENTER' | 'MAX' | 'SPACE_BETWEEN'+export type LayoutCounterAlign = 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'BASELINE'+export type LayoutWrap = 'NO_WRAP' | 'WRAP'++export interface SceneNode {+ id: string+ type: NodeType+ name: string+ parentId: string | null+ childIds: string[]++ x: number+ y: number+ width: number+ height: number+ rotation: number++ fills: Fill[]+ strokes: Stroke[]+ effects: Effect[]+ opacity: number++ cornerRadius: number+ topLeftRadius: number+ topRightRadius: number+ bottomRightRadius: number+ bottomLeftRadius: number+ independentCorners: boolean+ cornerSmoothing: number++ visible: boolean+ locked: boolean+ clipsContent: boolean++ blendMode: BlendMode++ text: string+ fontSize: number+ fontFamily: string+ fontWeight: number+ textAlignHorizontal: 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED'+ textAlignVertical: TextAlignVertical+ textAutoResize: TextAutoResize+ textCase: TextCase+ textDecoration: TextDecoration+ lineHeight: number | null+ letterSpacing: number+ maxLines: number | null++ horizontalConstraint: ConstraintType+ verticalConstraint: ConstraintType++ layoutMode: LayoutMode+ layoutWrap: LayoutWrap+ primaryAxisAlign: LayoutAlign+ counterAxisAlign: LayoutCounterAlign+ primaryAxisSizing: LayoutSizing+ counterAxisSizing: LayoutSizing+ itemSpacing: number+ counterAxisSpacing: number+ paddingTop: number+ paddingRight: number+ paddingBottom: number+ paddingLeft: number++ layoutPositioning: 'AUTO' | 'ABSOLUTE'+ layoutGrow: number+ layoutAlignSelf: 'AUTO' | 'STRETCH'++ vectorNetwork: VectorNetwork | null++ arcData: ArcData | null++ strokeCap: StrokeCap+ strokeJoin: StrokeJoin+ dashPattern: number[]++ borderTopWeight: number+ borderRightWeight: number+ borderBottomWeight: number+ borderLeftWeight: number+ independentStrokeWeights: boolean++ pointCount: number+ starInnerRadius: number++ componentId: string | null+ overrides: Record<string, unknown>+}++let nextLocalID = 1++function generateId(): string {+ return `0:${nextLocalID++}`+}++function createDefaultNode(type: NodeType, overrides: Partial<SceneNode> = {}): SceneNode {+ return {+ id: generateId(),+ type,+ name: type.charAt(0) + type.slice(1).toLowerCase(),+ parentId: null,+ childIds: [],+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ rotation: 0,+ fills: [],+ strokes: [],+ effects: [],+ opacity: 1,+ cornerRadius: 0,+ topLeftRadius: 0,+ topRightRadius: 0,+ bottomRightRadius: 0,+ bottomLeftRadius: 0,+ independentCorners: false,+ cornerSmoothing: 0,+ visible: true,+ locked: false,+ clipsContent: false,+ text: '',+ fontSize: 14,+ fontFamily: 'Inter',+ fontWeight: 400,+ textAlignHorizontal: 'LEFT',+ lineHeight: null,+ letterSpacing: 0,+ layoutMode: 'NONE',+ layoutWrap: 'NO_WRAP',+ primaryAxisAlign: 'MIN',+ counterAxisAlign: 'MIN',+ primaryAxisSizing: 'FIXED',+ counterAxisSizing: 'FIXED',+ itemSpacing: 0,+ counterAxisSpacing: 0,+ paddingTop: 0,+ paddingRight: 0,+ paddingBottom: 0,+ paddingLeft: 0,+ blendMode: 'PASS_THROUGH',+ layoutPositioning: 'AUTO',+ layoutGrow: 0,+ layoutAlignSelf: 'AUTO',+ vectorNetwork: null,+ arcData: null,+ textAlignVertical: 'TOP',+ textAutoResize: 'NONE',+ textCase: 'ORIGINAL',+ textDecoration: 'NONE',+ maxLines: null,+ horizontalConstraint: 'MIN',+ verticalConstraint: 'MIN',+ strokeCap: 'NONE',+ strokeJoin: 'MITER',+ dashPattern: [],+ borderTopWeight: 0,+ borderRightWeight: 0,+ borderBottomWeight: 0,+ borderLeftWeight: 0,+ independentStrokeWeights: false,+ pointCount: 5,+ starInnerRadius: 0.38,+ componentId: null,+ overrides: {},+ ...overrides+ }+}++const CONTAINER_TYPES = new Set<NodeType>([+ 'CANVAS',+ 'FRAME',+ 'GROUP',+ 'SECTION',+ 'COMPONENT',+ 'COMPONENT_SET',+ 'INSTANCE'+])++export class SceneGraph {+ nodes = new Map<string, SceneNode>()+ images = new Map<string, Uint8Array>()+ rootId: string++ constructor() {+ const root = createDefaultNode('FRAME', {+ name: 'Document',+ width: 0,+ height: 0+ })+ this.rootId = root.id+ this.nodes.set(root.id, root)++ this.addPage('Page 1')+ }++ addPage(name: string): SceneNode {+ return this.createNode('CANVAS', this.rootId, { name, width: 0, height: 0 })+ }++ getPages(): SceneNode[] {+ return this.getChildren(this.rootId).filter((n) => n.type === 'CANVAS')+ }++ getNode(id: string): SceneNode | undefined {+ return this.nodes.get(id)+ }++ getChildren(id: string): SceneNode[] {+ const node = this.nodes.get(id)+ if (!node) return []+ return node.childIds+ .map((cid) => this.nodes.get(cid))+ .filter((n): n is SceneNode => n !== undefined)+ }++ isContainer(id: string): boolean {+ const node = this.nodes.get(id)+ return node ? CONTAINER_TYPES.has(node.type) : false+ }++ isDescendant(childId: string, ancestorId: string): boolean {+ let current = this.nodes.get(childId)+ while (current) {+ if (current.id === ancestorId) return true+ current = current.parentId ? this.nodes.get(current.parentId) : undefined+ }+ return false+ }++ getAbsolutePosition(id: string): { x: number; y: number } {+ let ax = 0+ let ay = 0+ let current = this.nodes.get(id)+ while (current && current.id !== this.rootId && current.type !== 'CANVAS') {+ ax += current.x+ ay += current.y+ current = current.parentId ? this.nodes.get(current.parentId) : undefined+ }+ return { x: ax, y: ay }+ }++ getAbsoluteBounds(id: string): Rect {+ const pos = this.getAbsolutePosition(id)+ const node = this.nodes.get(id)+ return {+ x: pos.x,+ y: pos.y,+ width: node?.width ?? 0,+ height: node?.height ?? 0+ }+ }++ createNode(type: NodeType, parentId: string, overrides: Partial<SceneNode> = {}): SceneNode {+ const node = createDefaultNode(type, overrides)+ node.parentId = parentId+ this.nodes.set(node.id, node)++ const parent = this.nodes.get(parentId)+ if (parent) {+ parent.childIds.push(node.id)+ }++ return node+ }++ updateNode(id: string, changes: Partial<SceneNode>): void {+ const node = this.nodes.get(id)+ if (!node) return+ Object.assign(node, changes)+ }++ reparentNode(nodeId: string, newParentId: string): void {+ const node = this.nodes.get(nodeId)+ if (!node || nodeId === this.rootId) return+ if (this.isDescendant(newParentId, nodeId)) return++ const oldParent = node.parentId ? this.nodes.get(node.parentId) : undefined+ const newParent = this.nodes.get(newParentId)+ if (!newParent) return+ if (node.parentId === newParentId) return++ // Convert absolute position+ const absPos = this.getAbsolutePosition(nodeId)+ const newParentNode = this.nodes.get(newParentId)+ const newParentAbs =+ newParentId === this.rootId || newParentNode?.type === 'CANVAS'+ ? { x: 0, y: 0 }+ : this.getAbsolutePosition(newParentId)++ // Remove from old parent+ if (oldParent) {+ oldParent.childIds = oldParent.childIds.filter((cid) => cid !== nodeId)+ }++ // Add to new parent+ node.parentId = newParentId+ newParent.childIds.push(nodeId)++ // Adjust position so node stays in same visual place+ node.x = absPos.x - newParentAbs.x+ node.y = absPos.y - newParentAbs.y+ }++ reorderChild(nodeId: string, parentId: string, insertIndex: number): void {+ const node = this.nodes.get(nodeId)+ if (!node) return++ const oldParent = node.parentId ? this.nodes.get(node.parentId) : undefined+ const newParent = this.nodes.get(parentId)+ if (!newParent) return++ // Remove from old parent+ if (oldParent) {+ oldParent.childIds = oldParent.childIds.filter((cid) => cid !== nodeId)+ }++ // If same parent, adjust index since we removed the item+ let idx = insertIndex+ if (+ oldParent === newParent &&+ idx > (oldParent.childIds.indexOf(nodeId) === -1 ? idx : oldParent.childIds.length)+ ) {+ // Already removed above, no adjustment needed+ }++ node.parentId = parentId+ idx = Math.min(idx, newParent.childIds.length)+ newParent.childIds.splice(idx, 0, nodeId)+ }++ deleteNode(id: string): void {+ const node = this.nodes.get(id)+ if (!node || id === this.rootId) return++ if (node.parentId) {+ const parent = this.nodes.get(node.parentId)+ if (parent) {+ parent.childIds = parent.childIds.filter((cid) => cid !== id)+ }+ }++ for (const childId of Array.from(node.childIds)) {+ this.deleteNode(childId)+ }++ this.nodes.delete(id)+ }++ hitTest(px: number, py: number, scopeId?: string): SceneNode | null {+ const scope = scopeId ?? this.rootId+ return this.hitTestChildren(px, py, scope, 0, 0, false)+ }++ hitTestDeep(px: number, py: number, scopeId?: string): SceneNode | null {+ const scope = scopeId ?? this.rootId+ return this.hitTestChildren(px, py, scope, 0, 0, true)+ }++ private static readonly OPAQUE_CONTAINER_TYPES = new Set<NodeType>(['COMPONENT', 'INSTANCE'])++ private hitTestChildren(+ px: number,+ py: number,+ parentId: string,+ offsetX: number,+ offsetY: number,+ deep = false+ ): SceneNode | null {+ const parent = this.nodes.get(parentId)+ if (!parent) return null++ // Reverse order = topmost first+ for (let i = parent.childIds.length - 1; i >= 0; i--) {+ const childId = parent.childIds[i]+ const child = this.nodes.get(childId)+ if (!child || !child.visible) continue++ const ax = offsetX + child.x+ const ay = offsetY + child.y++ // Components/instances: don't recurse unless in deep mode (double-click)+ if (SceneGraph.OPAQUE_CONTAINER_TYPES.has(child.type) && !deep) {+ if (px >= ax && px <= ax + child.width && py >= ay && py <= ay + child.height) {+ return child+ }+ continue+ }++ // Check children first (deeper hit)+ if (CONTAINER_TYPES.has(child.type)) {+ const deepHit = this.hitTestChildren(px, py, childId, ax, ay, deep)+ if (deepHit) return deepHit+ }++ if (px >= ax && px <= ax + child.width && py >= ay && py <= ay + child.height) {+ return child+ }+ }+ return null+ }++ hitTestFrame(+ px: number,+ py: number,+ excludeIds: Set<string>,+ scopeId?: string+ ): SceneNode | null {+ return this.hitTestFrameChildren(px, py, scopeId ?? this.rootId, 0, 0, excludeIds)+ }++ private hitTestFrameChildren(+ px: number,+ py: number,+ parentId: string,+ offsetX: number,+ offsetY: number,+ excludeIds: Set<string>+ ): SceneNode | null {+ const parent = this.nodes.get(parentId)+ if (!parent) return null++ // Deepest matching frame wins+ let best: SceneNode | null = null++ for (const childId of parent.childIds) {+ if (excludeIds.has(childId)) continue+ const child = this.nodes.get(childId)+ if (!child || !child.visible) continue++ const ax = offsetX + child.x+ const ay = offsetY + child.y++ if (!CONTAINER_TYPES.has(child.type)) continue+ if (px < ax || px > ax + child.width || py < ay || py > ay + child.height) continue++ best = child++ const deeper = this.hitTestFrameChildren(px, py, childId, ax, ay, excludeIds)+ if (deeper) best = deeper+ }++ return best+ }++ cloneTree(+ sourceId: string,+ parentId: string,+ overrides: Partial<SceneNode> = {}+ ): SceneNode | null {+ const src = this.nodes.get(sourceId)+ if (!src) return null++ const { id: _srcId, parentId: _srcParent, childIds: _srcChildren, ...rest } = src+ const clone = this.createNode(src.type, parentId, { ...rest, ...overrides })++ for (const childId of src.childIds) {+ this.cloneTree(childId, clone.id)+ }++ return clone+ }++ private static readonly INSTANCE_SYNC_PROPS: (keyof SceneNode)[] = [+ 'width',+ 'height',+ 'fills',+ 'strokes',+ 'effects',+ 'opacity',+ 'cornerRadius',+ 'topLeftRadius',+ 'topRightRadius',+ 'bottomRightRadius',+ 'bottomLeftRadius',+ 'independentCorners',+ 'layoutMode',+ 'layoutWrap',+ 'primaryAxisAlign',+ 'counterAxisAlign',+ 'primaryAxisSizing',+ 'counterAxisSizing',+ 'itemSpacing',+ 'counterAxisSpacing',+ 'paddingTop',+ 'paddingRight',+ 'paddingBottom',+ 'paddingLeft',+ 'clipsContent'+ ]++ private static copyProp<K extends keyof SceneNode>(+ target: Partial<SceneNode> | SceneNode,+ source: SceneNode,+ key: K+ ): void {+ const val = source[key]+ target[key] = (Array.isArray(val) ? structuredClone(val) : val) as SceneNode[K]+ }++ createInstance(+ componentId: string,+ parentId: string,+ overrides: Partial<SceneNode> = {}+ ): SceneNode | null {+ const component = this.nodes.get(componentId)+ if (!component || component.type !== 'COMPONENT') return null++ const props: Partial<SceneNode> = { name: component.name, componentId }+ for (const key of SceneGraph.INSTANCE_SYNC_PROPS) {+ SceneGraph.copyProp(props, component, key)+ }++ const instance = this.createNode('INSTANCE', parentId, { ...props, ...overrides })++ this.cloneChildrenWithMapping(component.id, instance.id)++ return instance+ }++ private cloneChildrenWithMapping(sourceParentId: string, destParentId: string): void {+ const sourceParent = this.nodes.get(sourceParentId)+ if (!sourceParent) return++ for (const childId of sourceParent.childIds) {+ const src = this.nodes.get(childId)+ if (!src) continue++ const { id: _, parentId: _p, childIds: _c, ...rest } = src+ const clone = this.createNode(src.type, destParentId, {+ ...rest,+ componentId: childId+ })++ if (src.childIds.length > 0) {+ this.cloneChildrenWithMapping(childId, clone.id)+ }+ }+ }++ syncInstances(componentId: string): void {+ const component = this.nodes.get(componentId)+ if (!component || component.type !== 'COMPONENT') return++ for (const instance of this.getInstances(componentId)) {+ // Sync instance-level props (unless overridden)+ for (const key of SceneGraph.INSTANCE_SYNC_PROPS) {+ if (key in instance.overrides) continue+ SceneGraph.copyProp(instance, component, key)+ }++ // Sync children: match by componentId+ this.syncChildren(component.id, instance.id, instance.overrides)+ }+ }++ private syncChildren(+ compParentId: string,+ instParentId: string,+ overrides: Record<string, unknown>+ ): void {+ const compParent = this.nodes.get(compParentId)+ const instParent = this.nodes.get(instParentId)+ if (!compParent || !instParent) return++ const instChildMap = new Map<string, SceneNode>()+ for (const childId of instParent.childIds) {+ const child = this.nodes.get(childId)+ if (child?.componentId) instChildMap.set(child.componentId, child)+ }++ // Add new children from component that don't exist in instance+ for (const compChildId of compParent.childIds) {+ if (!instChildMap.has(compChildId)) {+ const src = this.nodes.get(compChildId)+ if (!src) continue+ const { id: _, parentId: _p, childIds: _c, ...rest } = src+ const clone = this.createNode(src.type, instParentId, {+ ...rest,+ componentId: compChildId+ })+ if (src.childIds.length > 0) {+ this.cloneChildrenWithMapping(compChildId, clone.id)+ }+ instChildMap.set(compChildId, clone)+ }+ }++ // Sync existing children+ for (const compChildId of compParent.childIds) {+ const compChild = this.nodes.get(compChildId)+ const instChild = instChildMap.get(compChildId)+ if (!compChild || !instChild) continue++ for (const key of SceneGraph.INSTANCE_SYNC_PROPS) {+ const overrideKey = `${instChild.id}:${key}`+ if (overrideKey in overrides) continue+ SceneGraph.copyProp(instChild, compChild, key)+ }++ for (const key of ['name', 'text', 'fontSize', 'fontWeight', 'fontFamily'] as const) {+ const overrideKey = `${instChild.id}:${key}`+ if (overrideKey in overrides) continue+ SceneGraph.copyProp(instChild, compChild, key)+ }++ if (compChild.childIds.length > 0) {+ this.syncChildren(compChildId, instChild.id, overrides)+ }+ }++ // Reorder instance children to match component order+ const compChildOrder = compParent.childIds+ instParent.childIds.sort((a, b) => {+ const nodeA = this.nodes.get(a)+ const nodeB = this.nodes.get(b)+ const idxA = nodeA?.componentId ? compChildOrder.indexOf(nodeA.componentId) : -1+ const idxB = nodeB?.componentId ? compChildOrder.indexOf(nodeB.componentId) : -1+ return idxA - idxB+ })+ }++ detachInstance(instanceId: string): void {+ const node = this.nodes.get(instanceId)+ if (!node || node.type !== 'INSTANCE') return+ node.type = 'FRAME'+ node.componentId = null+ node.overrides = {}+ }++ getMainComponent(instanceId: string): SceneNode | undefined {+ const node = this.nodes.get(instanceId)+ if (!node?.componentId) return undefined+ return this.nodes.get(node.componentId)+ }++ getInstances(componentId: string): SceneNode[] {+ const instances: SceneNode[] = []+ for (const node of this.nodes.values()) {+ if (node.type === 'INSTANCE' && node.componentId === componentId) {+ instances.push(node)+ }+ }+ return instances+ }++ flattenTree(parentId?: string, depth = 0): Array<{ node: SceneNode; depth: number }> {+ const id = parentId ?? this.rootId+ const parent = this.nodes.get(id)+ if (!parent) return []++ const result: Array<{ node: SceneNode; depth: number }> = []+ for (const childId of parent.childIds) {+ const child = this.nodes.get(childId)+ if (!child) continue+ result.push({ node: child, depth })+ if (child.childIds.length > 0) {+ result.push(...this.flattenTree(childId, depth + 1))+ }+ }+ return result+ }+}diff --git a/packages/core/src/snap.ts b/packages/core/src/snap.tsnew file mode 100644index 000000000..b5d53036d--- /dev/null+++ b/packages/core/src/snap.ts@@ -0,0 +1,169 @@+import type { SceneNode } from './scene-graph'+import type { Rect } from './types'++const SNAP_THRESHOLD = 5++export interface SnapGuide {+ axis: 'x' | 'y'+ position: number+ from: number+ to: number+}++export interface SnapResult {+ dx: number+ dy: number+ guides: SnapGuide[]+}++function getEdges(node: SceneNode) {+ if (node.rotation === 0) {+ return {+ left: node.x,+ right: node.x + node.width,+ centerX: node.x + node.width / 2,+ top: node.y,+ bottom: node.y + node.height,+ centerY: node.y + node.height / 2+ }+ }++ const cx = node.x + node.width / 2+ const cy = node.y + node.height / 2+ const rad = (node.rotation * Math.PI) / 180+ const cos = Math.cos(rad)+ const sin = Math.sin(rad)+ const hw = node.width / 2+ const hh = node.height / 2++ const corners = [+ { 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 }+ ]++ let left = Infinity,+ right = -Infinity,+ top = Infinity,+ bottom = -Infinity+ for (const c of corners) {+ left = Math.min(left, c.x)+ right = Math.max(right, c.x)+ top = Math.min(top, c.y)+ bottom = Math.max(bottom, c.y)+ }++ return {+ left,+ right,+ centerX: (left + right) / 2,+ top,+ bottom,+ centerY: (top + bottom) / 2+ }+}++export function computeSnap(+ movingIds: Set<string>,+ movingBounds: Rect,+ allNodes: SceneNode[]+): SnapResult {+ const targets = allNodes.filter((n) => !movingIds.has(n.id))+ if (targets.length === 0) return { dx: 0, dy: 0, guides: [] }++ const m = {+ left: movingBounds.x,+ right: movingBounds.x + movingBounds.width,+ centerX: movingBounds.x + movingBounds.width / 2,+ top: movingBounds.y,+ bottom: movingBounds.y + movingBounds.height,+ centerY: movingBounds.y + movingBounds.height / 2+ }++ let bestDx = Infinity+ let bestDy = Infinity+ const guides: SnapGuide[] = []++ for (const target of targets) {+ const t = getEdges(target)++ // X-axis snapping: left-to-left, left-to-right, right-to-left, right-to-right, center-to-center+ const xPairs: [number, number][] = [+ [m.left, t.left],+ [m.left, t.right],+ [m.right, t.left],+ [m.right, t.right],+ [m.centerX, t.centerX]+ ]++ for (const [mVal, tVal] of xPairs) {+ const d = tVal - mVal+ if (Math.abs(d) < SNAP_THRESHOLD && Math.abs(d) <= Math.abs(bestDx)) {+ if (Math.abs(d) < Math.abs(bestDx)) {+ bestDx = d+ guides.length = guides.filter((g) => g.axis === 'y').length+ ? guides.length+ : guides.length+ // Remove old x guides if we found a closer snap+ for (let i = guides.length - 1; i >= 0; i--) {+ if (guides[i].axis === 'x') guides.splice(i, 1)+ }+ }+ if (Math.abs(d) === Math.abs(bestDx)) {+ const minY = Math.min(m.top, t.top)+ const maxY = Math.max(m.bottom, t.bottom)+ guides.push({ axis: 'x', position: tVal, from: minY, to: maxY })+ }+ }+ }++ // Y-axis snapping+ const yPairs: [number, number][] = [+ [m.top, t.top],+ [m.top, t.bottom],+ [m.bottom, t.top],+ [m.bottom, t.bottom],+ [m.centerY, t.centerY]+ ]++ for (const [mVal, tVal] of yPairs) {+ const d = tVal - mVal+ if (Math.abs(d) < SNAP_THRESHOLD && Math.abs(d) <= Math.abs(bestDy)) {+ if (Math.abs(d) < Math.abs(bestDy)) {+ for (let i = guides.length - 1; i >= 0; i--) {+ if (guides[i].axis === 'y') guides.splice(i, 1)+ }+ bestDy = d+ }+ if (Math.abs(d) === Math.abs(bestDy)) {+ const minX = Math.min(m.left, t.left)+ const maxX = Math.max(m.right, t.right)+ guides.push({ axis: 'y', position: tVal, from: minX, to: maxX })+ }+ }+ }+ }++ return {+ dx: Math.abs(bestDx) <= SNAP_THRESHOLD ? bestDx : 0,+ dy: Math.abs(bestDy) <= SNAP_THRESHOLD ? bestDy : 0,+ guides+ }+}++export function computeSelectionBounds(nodes: SceneNode[]): Rect | null {+ if (nodes.length === 0) return null+ let minX = Infinity+ let minY = Infinity+ let maxX = -Infinity+ let maxY = -Infinity+ for (const n of nodes) {+ const edges = getEdges(n)+ minX = Math.min(minX, edges.left)+ minY = Math.min(minY, edges.top)+ maxX = Math.max(maxX, edges.right)+ maxY = Math.max(maxY, edges.bottom)+ }+ return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }+}diff --git a/packages/core/src/types.ts b/packages/core/src/types.tsnew file mode 100644index 000000000..14ea3f5c4--- /dev/null+++ b/packages/core/src/types.ts@@ -0,0 +1,32 @@+export interface GUID {+ sessionID: number+ localID: number+}++export interface Color {+ r: number+ g: number+ b: number+ a: number+}++export interface Vector {+ x: number+ y: number+}++export interface Matrix {+ m00: number+ m01: number+ m02: number+ m10: number+ m11: number+ m12: number+}++export interface Rect {+ x: number+ y: number+ width: number+ height: number+}diff --git a/packages/core/src/undo.ts b/packages/core/src/undo.tsnew file mode 100644index 000000000..cc8141a3f--- /dev/null+++ b/packages/core/src/undo.ts@@ -0,0 +1,110 @@+import type { SceneNode } from './scene-graph'++export interface UndoEntry {+ label: string+ forward: () => void+ inverse: () => void+}++export class UndoManager {+ private undoStack: UndoEntry[] = []+ private redoStack: UndoEntry[] = []+ private batchEntries: UndoEntry[] | null = null+ private batchLabel = ''++ apply(entry: UndoEntry): void {+ entry.forward()+ if (this.batchEntries) {+ this.batchEntries.push(entry)+ } else {+ this.undoStack.push(entry)+ this.redoStack = []+ }+ }++ push(entry: UndoEntry): void {+ if (this.batchEntries) {+ this.batchEntries.push(entry)+ } else {+ this.undoStack.push(entry)+ this.redoStack = []+ }+ }++ undo(): string | null {+ const entry = this.undoStack.pop()+ if (!entry) return null+ entry.inverse()+ this.redoStack.push(entry)+ return entry.label+ }++ redo(): string | null {+ const entry = this.redoStack.pop()+ if (!entry) return null+ entry.forward()+ this.undoStack.push(entry)+ return entry.label+ }++ beginBatch(label: string): void {+ this.batchLabel = label+ this.batchEntries = []+ }++ commitBatch(): void {+ if (!this.batchEntries || this.batchEntries.length === 0) {+ this.batchEntries = null+ return+ }+ const entries = this.batchEntries+ const label = this.batchLabel+ this.batchEntries = null++ this.undoStack.push({+ label,+ forward: () => entries.forEach((e) => e.forward()),+ inverse: () => [...entries].reverse().forEach((e) => e.inverse())+ })+ this.redoStack = []+ }++ clear(): void {+ this.undoStack = []+ this.redoStack = []+ this.batchEntries = null+ }++ get canUndo(): boolean {+ return this.undoStack.length > 0+ }++ get canRedo(): boolean {+ return this.redoStack.length > 0+ }++ get undoLabel(): string | null {+ return this.undoStack.at(-1)?.label ?? null+ }++ get redoLabel(): string | null {+ return this.redoStack.at(-1)?.label ?? null+ }+}++export function createPropertyChange(+ node: SceneNode,+ changes: Partial<SceneNode>,+ label: string+): UndoEntry {+ const previous: Partial<SceneNode> = {}+ for (const key of Object.keys(changes) as (keyof SceneNode)[]) {+ ;(previous as Record<string, unknown>)[key] = node[key]+ }++ return {+ label,+ forward: () => Object.assign(node, changes),+ inverse: () => Object.assign(node, previous)+ }+}diff --git a/packages/core/src/vector.ts b/packages/core/src/vector.tsnew file mode 100644index 000000000..8ce6159fd--- /dev/null+++ b/packages/core/src/vector.ts@@ -0,0 +1,333 @@+import type {+ HandleMirroring,+ VectorNetwork,+ VectorRegion,+ VectorSegment,+ VectorVertex,+ WindingRule+} from './scene-graph'+import type { CanvasKit, Path } from 'canvaskit-wasm'++// --- 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()+ const { vertices, segments, regions } = network++ if (regions.length > 0) {+ for (const region of regions) {+ for (const loop of region.loops) {+ addLoopToPath(path, loop, segments, vertices)+ }+ path.setFillType(region.windingRule === 'EVENODD' ? ck.FillType.EvenOdd : ck.FillType.Winding)+ }+ } else {+ // No regions — draw all segments as open paths+ const visited = new Set<number>()+ const chains = buildChains(segments, vertices.length)++ for (const chain of chains) {+ if (chain.length === 0) continue+ const firstSeg = segments[chain[0]]+ path.moveTo(vertices[firstSeg.start].x, vertices[firstSeg.start].y)++ for (const segIdx of chain) {+ visited.add(segIdx)+ addSegmentToPath(path, segments[segIdx], vertices)+ }+ }++ // Any remaining disconnected segments+ for (let i = 0; i < segments.length; i++) {+ if (visited.has(i)) continue+ const seg = segments[i]+ path.moveTo(vertices[seg.start].x, vertices[seg.start].y)+ addSegmentToPath(path, seg, vertices)+ }+ }++ return path+}++function addLoopToPath(+ path: Path,+ loop: number[],+ segments: VectorSegment[],+ vertices: VectorVertex[]+): void {+ if (loop.length === 0) return++ const firstSeg = segments[loop[0]]+ path.moveTo(vertices[firstSeg.start].x, vertices[firstSeg.start].y)++ for (const segIdx of loop) {+ addSegmentToPath(path, segments[segIdx], vertices)+ }++ const lastSeg = segments[loop[loop.length - 1]]+ if (lastSeg.end === firstSeg.start) {+ path.close()+ }+}++function addSegmentToPath(path: Path, seg: VectorSegment, vertices: VectorVertex[]): void {+ const start = vertices[seg.start]+ const end = vertices[seg.end]+ const ts = seg.tangentStart+ const te = seg.tangentEnd++ const isLine = ts.x === 0 && ts.y === 0 && te.x === 0 && te.y === 0+ if (isLine) {+ path.lineTo(end.x, end.y)+ } else {+ // Cubic bezier: control points are tangent offsets from start/end+ path.cubicTo(start.x + ts.x, start.y + ts.y, end.x + te.x, end.y + te.y, end.x, end.y)+ }+}++function buildChains(segments: VectorSegment[], _vertexCount: number): number[][] {+ if (segments.length === 0) return []++ // Build adjacency: for each vertex, which segments connect to it+ const adj = new Map<number, number[]>()+ for (let i = 0; i < segments.length; i++) {+ const s = segments[i]+ if (!adj.has(s.start)) adj.set(s.start, [])+ if (!adj.has(s.end)) adj.set(s.end, [])+ adj.get(s.start)?.push(i)+ adj.get(s.end)?.push(i)+ }++ const visited = new Set<number>()+ const chains: number[][] = []++ // Start from degree-1 vertices (endpoints) or any unvisited+ const degree1 = [...adj.entries()].filter(([, segs]) => segs.length === 1).map(([v]) => v)++ const startVertices = degree1.length > 0 ? degree1 : [segments[0].start]++ for (const startVertex of startVertices) {+ let current = startVertex+ const chain: number[] = []++ while (true) {+ const segs = adj.get(current)+ if (!segs) break++ const nextSeg = segs.find((s) => !visited.has(s))+ if (nextSeg === undefined) break++ visited.add(nextSeg)+ chain.push(nextSeg)++ const seg = segments[nextSeg]+ current = seg.start === current ? seg.end : seg.start+ }++ if (chain.length > 0) chains.push(chain)+ }++ return chains+}++export function computeVectorBounds(network: VectorNetwork): {+ x: number+ y: number+ width: number+ height: number+} {+ if (network.vertices.length === 0) {+ return { x: 0, y: 0, width: 0, height: 0 }+ }++ let minX = Infinity+ let minY = Infinity+ let maxX = -Infinity+ let maxY = -Infinity++ for (const v of network.vertices) {+ minX = Math.min(minX, v.x)+ minY = Math.min(minY, v.y)+ maxX = Math.max(maxX, v.x)+ maxY = Math.max(maxY, v.y)+ }++ // Also consider bezier control points for tighter bounds+ for (const seg of network.segments) {+ const start = network.vertices[seg.start]+ const end = network.vertices[seg.end]+ const cp1x = start.x + seg.tangentStart.x+ const cp1y = start.y + seg.tangentStart.y+ const cp2x = end.x + seg.tangentEnd.x+ const cp2y = end.y + seg.tangentEnd.y++ minX = Math.min(minX, cp1x, cp2x)+ minY = Math.min(minY, cp1y, cp2y)+ maxX = Math.max(maxX, cp1x, cp2x)+ maxY = Math.max(maxY, cp1y, cp2y)+ }++ return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }+}diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.jsonnew file mode 100644index 000000000..32f2561ce--- /dev/null+++ b/packages/core/tsconfig.json@@ -0,0 +1,13 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "skipLibCheck": true,+ "declaration": true,+ "outDir": "dist",+ "rootDir": "src"+ },+ "include": ["src"]+}diff --git a/src/constants.ts b/src/constants.tsindex ceafc460a..aafc7733e 100644--- a/src/constants.ts+++ b/src/constants.ts@@ -1,12 +1,63 @@-import type { Fill, Stroke } from './engine/scene-graph'-import type { Color } from './types'--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 COMPONENT_COLOR = { r: 0.592, g: 0.278, b: 1, a: 1 } satisfies Color-export const SNAP_COLOR = { r: 1.0, g: 0.0, b: 0.56, a: 1 } satisfies Color-export const CANVAS_BG_COLOR = { r: 0.96, g: 0.96, b: 0.96, a: 1 } satisfies Color+export {+ IS_TAURI,+ SELECTION_COLOR,+ COMPONENT_COLOR,+ SNAP_COLOR,+ CANVAS_BG_COLOR,+ ROTATION_HANDLE_OFFSET,+ SNAP_THRESHOLD,+ RULER_SIZE,+ RULER_BG_COLOR,+ RULER_TICK_COLOR,+ RULER_TEXT_COLOR,+ RULER_BADGE_HEIGHT,+ RULER_BADGE_PADDING,+ RULER_BADGE_RADIUS,+ RULER_BADGE_EXCLUSION,+ RULER_TEXT_BASELINE,+ RULER_MAJOR_TICK,+ RULER_MINOR_TICK,+ RULER_HIGHLIGHT_ALPHA,+ PEN_HANDLE_RADIUS,+ PEN_VERTEX_RADIUS,+ PEN_CLOSE_RADIUS_BOOST,+ PEN_PATH_STROKE_WIDTH,+ PARENT_OUTLINE_ALPHA,+ PARENT_OUTLINE_DASH,+ DEFAULT_FONT_SIZE,+ LABEL_FONT_SIZE,+ SIZE_FONT_SIZE,+ ROTATION_HANDLE_RADIUS,+ HANDLE_HALF_SIZE,+ LABEL_OFFSET_Y,+ SIZE_PILL_PADDING_X,+ SIZE_PILL_PADDING_Y,+ SIZE_PILL_HEIGHT,+ SIZE_PILL_RADIUS,+ SIZE_PILL_TEXT_OFFSET_Y,+ MARQUEE_FILL_ALPHA,+ SELECTION_DASH_ALPHA,+ DROP_HIGHLIGHT_ALPHA,+ DROP_HIGHLIGHT_STROKE,+ LAYOUT_INDICATOR_STROKE,+ SECTION_CORNER_RADIUS,+ SECTION_TITLE_HEIGHT,+ SECTION_TITLE_PADDING_X,+ SECTION_TITLE_RADIUS,+ SECTION_TITLE_FONT_SIZE,+ SECTION_TITLE_GAP,+ COMPONENT_SET_DASH,+ COMPONENT_SET_DASH_GAP,+ COMPONENT_SET_BORDER_WIDTH,+ COMPONENT_LABEL_FONT_SIZE,+ COMPONENT_LABEL_GAP,+ COMPONENT_LABEL_ICON_SIZE,+ COMPONENT_LABEL_ICON_GAP,+ RULER_TARGET_PIXEL_SPACING,+ RULER_MAJOR_TOLERANCE+} from '@open-pencil/core'++import type { Fill, Stroke } from '@open-pencil/core'export const DEFAULT_SHAPE_FILL: Fill = {type: 'SOLID',@@ -23,69 +74,17 @@ export const DEFAULT_FRAME_FILL: Fill = {}export const HANDLE_SIZE = 6-export const ROTATION_HANDLE_OFFSET = 20-export const SNAP_THRESHOLD = 5export const DRAG_DEAD_ZONE = 4--export const RULER_SIZE = 20-export const RULER_BG_COLOR = { r: 0.14, g: 0.14, b: 0.14, a: 1 } satisfies Color-export const RULER_TICK_COLOR = { r: 0.4, g: 0.4, b: 0.4, a: 1 } satisfies Color-export const RULER_TEXT_COLOR = { r: 0.55, g: 0.55, b: 0.55, a: 1 } satisfies Color-export const RULER_BADGE_HEIGHT = 14-export const RULER_BADGE_PADDING = 3-export const RULER_BADGE_RADIUS = 2-export const RULER_BADGE_EXCLUSION = 30-export const RULER_TEXT_BASELINE = 0.65-export const RULER_MAJOR_TICK = 0.5-export const RULER_MINOR_TICK = 0.25-export const RULER_HIGHLIGHT_ALPHA = 0.3--export const PEN_HANDLE_RADIUS = 3-export const PEN_VERTEX_RADIUS = 4-export const PEN_CLOSE_RADIUS_BOOST = 2-export const PEN_PATH_STROKE_WIDTH = 2export const PEN_CLOSE_THRESHOLD = 8-export const PARENT_OUTLINE_ALPHA = 0.5-export const PARENT_OUTLINE_DASH = 4-export const DEFAULT_FONT_SIZE = 14-export const LABEL_FONT_SIZE = 11-export const SIZE_FONT_SIZE = 10--export const ROTATION_HANDLE_RADIUS = 4export const ROTATION_SNAP_DEGREES = 15export const ROTATION_HIT_OFFSET = 24--export const HANDLE_HALF_SIZE = 3--export const LABEL_OFFSET_Y = 8-export const SIZE_PILL_PADDING_X = 6-export const SIZE_PILL_PADDING_Y = 6-export const SIZE_PILL_HEIGHT = 18-export const SIZE_PILL_RADIUS = 4-export const SIZE_PILL_TEXT_OFFSET_Y = 13--export const MARQUEE_FILL_ALPHA = 0.08-export const SELECTION_DASH_ALPHA = 0.6-export const DROP_HIGHLIGHT_ALPHA = 0.8-export const DROP_HIGHLIGHT_STROKE = 2--export const LAYOUT_INDICATOR_STROKE = 2-export const DEFAULT_TEXT_WIDTH = 200export const DEFAULT_TEXT_HEIGHT = 24-export const AUTO_LAYOUT_BREAK_THRESHOLD = 8export const HANDLE_HIT_RADIUS = 6export const ROTATION_HIT_RADIUS = 8-export const ZOOM_SENSITIVITY = 0.99-export const SECTION_CORNER_RADIUS = 5-export const SECTION_TITLE_HEIGHT = 24-export const SECTION_TITLE_PADDING_X = 8-export const SECTION_TITLE_RADIUS = 5-export const SECTION_TITLE_FONT_SIZE = 12-export const SECTION_TITLE_GAP = 6export const SECTION_DEFAULT_FILL: Fill = {type: 'SOLID',color: { r: 0.37, g: 0.37, b: 0.37, a: 1 },@@ -99,14 +98,3 @@ export const SECTION_DEFAULT_STROKE: Stroke = {visible: true,align: 'INSIDE'}--export const COMPONENT_SET_DASH = 6-export const COMPONENT_SET_DASH_GAP = 4-export const COMPONENT_SET_BORDER_WIDTH = 1.5-export const COMPONENT_LABEL_FONT_SIZE = 11-export const COMPONENT_LABEL_GAP = 6-export const COMPONENT_LABEL_ICON_SIZE = 10-export const COMPONENT_LABEL_ICON_GAP = 4--export const RULER_TARGET_PIXEL_SPACING = 100-export const RULER_MAJOR_TOLERANCE = 0.01diff --git a/src/engine/canvaskit.ts b/src/engine/canvaskit.tsindex f8d58dd6d..92c0ce15a 100644--- a/src/engine/canvaskit.ts+++ b/src/engine/canvaskit.ts@@ -1,11 +1 @@-import CanvasKitInit, { type CanvasKit } from 'canvaskit-wasm'--let instance: CanvasKit | null = null--export async function getCanvasKit(): Promise<CanvasKit> {- if (instance) return instance- instance = await CanvasKitInit({- locateFile: () => '/canvaskit.wasm'- })- return instance-}+export { getCanvasKit, type CanvasKitOptions } from '@open-pencil/core'diff --git a/src/engine/clipboard.ts b/src/engine/clipboard.tsindex f95712f8c..b720b37bb 100644--- a/src/engine/clipboard.ts+++ b/src/engine/clipboard.ts@@ -1,653 +1,8 @@-import { inflateSync, deflateSync } from 'fflate'--import { initCodec, getCompiledSchema, getSchemaBytes } from '@/kiwi/codec'-import { decodeBinarySchema, compileSchema, ByteBuffer } from '@/kiwi/kiwi-schema'--import { decodeVectorNetworkBlob, encodeVectorNetworkBlob } from './vector'--import type {- SceneGraph,- SceneNode,- Fill,- Stroke,- LayoutMode,- LayoutSizing,- LayoutAlign,- LayoutCounterAlign,- VectorNetwork-} from './scene-graph'-import type { NodeChange as KiwiNodeChange } from '@/kiwi/codec'--interface FigmaClipboardMeta {- fileKey: string- pasteID: number- dataType: string-}--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 FIG_KIWI_VERSION = 106-- 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 = ''- for (let i = 0; i < bytes.length; i++) {- binary += String.fromCharCode(bytes[i])- }- return btoa(binary)-}--function base64ToBinary(b64: string): Uint8Array {- const raw = atob(b64)- const bytes = new Uint8Array(raw.length)- for (let i = 0; i < raw.length; i++) {- bytes[i] = raw.charCodeAt(i)- }- return bytes-}--// --- Paste from Figma -----export async function parseFigmaClipboard(- html: string-): 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-- 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 schemaBytes = inflateSync(parsed.schemaDeflated)- const schema = decodeBinarySchema(new ByteBuffer(schemaBytes))- const compiled = compileSchema(schema)- 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, 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(- nodeChanges: KiwiNodeChange[],- graph: SceneGraph,- targetParentId: string,- offsetX = 0,- offsetY = 0,- blobs: Uint8Array[] = []-): string[] {- const guidMap = new Map<string, KiwiNodeChange>()- const parentMap = new Map<string, string>()- for (const nc of nodeChanges) {- if (!nc.guid) continue- const id = `${nc.guid.sessionID}:${nc.guid.localID}`- guidMap.set(id, nc)- if (nc.parentIndex?.guid) {- parentMap.set(id, `${nc.parentIndex.guid.sessionID}:${nc.parentIndex.guid.localID}`)- }- }-- const skipTypes = new Set(['DOCUMENT', 'CANVAS'])- const topLevel: string[] = []- for (const [id, nc] of guidMap) {- if (skipTypes.has(nc.type ?? '')) continue- const parentId = parentMap.get(id)- if (!parentId || !guidMap.has(parentId) || skipTypes.has(guidMap.get(parentId)?.type ?? '')) {- topLevel.push(id)- }- }-- const created = new Map<string, string>()- const createdIds: string[] = []-- function createNode(figmaId: string, ourParentId: string) {- if (created.has(figmaId)) return- const nc = guidMap.get(figmaId)- if (!nc) return-- const x = (nc.transform?.m02 ?? 0) + (ourParentId === targetParentId ? offsetX : 0)- const y = (nc.transform?.m12 ?? 0) + (ourParentId === targetParentId ? offsetY : 0)-- let rotation = 0- if (nc.transform) {- rotation = Math.atan2(nc.transform.m10, nc.transform.m00) * (180 / Math.PI)- }-- const fills: Fill[] = (nc.fillPaints ?? [])- .filter((p) => p.type === 'SOLID' && p.color)- .map((p) => ({- type: 'SOLID' as const,- color: p.color ?? { r: 0, g: 0, b: 0, a: 1 },- opacity: p.opacity ?? 1,- visible: p.visible ?? true- }))-- const strokes: Stroke[] = (nc.strokePaints ?? [])- .filter((p) => p.type === 'SOLID' && p.color)- .map((p) => ({- color: p.color ?? { r: 0, g: 0, b: 0, a: 1 },- weight: nc.strokeWeight ?? 1,- opacity: p.opacity ?? 1,- visible: p.visible ?? true,- align: 'CENTER' as const- }))-- const nodeType = mapNodeType(nc.type)- const node = graph.createNode(nodeType, ourParentId, {- name: nc.name ?? nodeType,- x,- y,- width: nc.size?.x ?? 100,- height: nc.size?.y ?? 100,- rotation,- opacity: nc.opacity ?? 1,- visible: nc.visible ?? true,- fills,- strokes,- cornerRadius: nc.cornerRadius ?? 0,- independentCorners: nc.rectangleCornerRadiiIndependent ?? false,- topLeftRadius: nc.rectangleTopLeftCornerRadius ?? 0,- topRightRadius: nc.rectangleTopRightCornerRadius ?? 0,- bottomLeftRadius: nc.rectangleBottomLeftCornerRadius ?? 0,- bottomRightRadius: nc.rectangleBottomRightCornerRadius ?? 0,- text: nc.textData?.characters ?? '',- fontSize: nc.fontSize ?? 14,- fontFamily: nc.fontName?.family ?? 'Inter',- textAlignHorizontal:- (nc.textAlignHorizontal as 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED') ?? 'LEFT',- layoutMode: mapLayoutMode(nc.stackMode as string),- itemSpacing: (nc.stackSpacing as number) ?? 0,- paddingTop: (nc.stackVerticalPadding as number) ?? (nc.stackPadding as number) ?? 0,- paddingBottom:- (nc.stackPaddingBottom as number) ??- (nc.stackVerticalPadding as number) ??- (nc.stackPadding as number) ??- 0,- paddingLeft: (nc.stackHorizontalPadding as number) ?? (nc.stackPadding as number) ?? 0,- paddingRight:- (nc.stackPaddingRight as number) ??- (nc.stackHorizontalPadding as number) ??- (nc.stackPadding as number) ??- 0,- primaryAxisSizing: mapSizing(nc.stackPrimarySizing as string),- counterAxisSizing: mapSizing(nc.stackCounterSizing as string),- primaryAxisAlign: mapPrimaryAlign(- (nc.stackPrimaryAlignItems as string) ?? (nc.stackJustify as string)- ),- counterAxisAlign: mapCounterAlign(- (nc.stackCounterAlignItems as string) ?? (nc.stackCounterAlign as string)- ),- 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,- vectorNetwork: decodeVectorData(nc, blobs)- })-- created.set(figmaId, node.id)- if (ourParentId === targetParentId) createdIds.push(node.id)-- const children: string[] = []- for (const [childId, pid] of parentMap) {- if (pid === figmaId && !skipTypes.has(guidMap.get(childId)?.type ?? '')) {- children.push(childId)- }- }- children.sort((a, b) => {- const aPos = guidMap.get(a)?.parentIndex?.position ?? ''- const bPos = guidMap.get(b)?.parentIndex?.position ?? ''- return aPos.localeCompare(bPos)- })- for (const childId of children) {- createNode(childId, node.id)- }- }-- for (const id of topLevel) {- createNode(id, targetParentId)- }-- return createdIds-}--function mapLayoutMode(mode?: string): LayoutMode {- if (mode === 'HORIZONTAL') return 'HORIZONTAL'- if (mode === 'VERTICAL') return 'VERTICAL'- return 'NONE'-}--function mapSizing(sizing?: string): LayoutSizing {- if (sizing === 'RESIZE_TO_FIT' || sizing === 'RESIZE_TO_FIT_WITH_IMPLICIT_SIZE') return 'HUG'- if (sizing === 'FILL') return 'FILL'- return 'FIXED'-}--function mapPrimaryAlign(align?: string): LayoutAlign {- if (align === 'CENTER') return 'CENTER'- if (align === 'MAX') return 'MAX'- if (align === 'SPACE_BETWEEN' || align === 'SPACE_EVENLY') return 'SPACE_BETWEEN'- return 'MIN'-}--function mapCounterAlign(align?: string): LayoutCounterAlign {- if (align === 'CENTER') return 'CENTER'- if (align === 'MAX') return 'MAX'- if (align === 'STRETCH') return 'STRETCH'- if (align === 'BASELINE') return 'BASELINE'- return 'MIN'-}--function mapNodeType(type?: string): SceneNode['type'] {- switch (type) {- case 'FRAME':- return 'FRAME'- case 'COMPONENT':- return 'COMPONENT'- case 'COMPONENT_SET':- return 'COMPONENT_SET'- case 'INSTANCE':- return 'INSTANCE'- case 'RECTANGLE':- case 'ROUNDED_RECTANGLE':- return 'RECTANGLE'- case 'ELLIPSE':- return 'ELLIPSE'- case 'TEXT':- return 'TEXT'- case 'LINE':- return 'LINE'- case 'STAR':- return 'STAR'- case 'REGULAR_POLYGON':- return 'POLYGON'- case 'VECTOR':- case 'BOOLEAN_OPERATION':- return 'VECTOR'- case 'GROUP':- return 'GROUP'- case 'SECTION':- return 'SECTION'- default:- return 'RECTANGLE'- }-}--// --- Copy to Figma-compatible fig-kiwi -----function mapToFigmaType(type: SceneNode['type']): string {- switch (type) {- case 'FRAME':- return 'FRAME'- case 'RECTANGLE':- return 'RECTANGLE'- case 'ELLIPSE':- return 'ELLIPSE'- case 'TEXT':- return 'TEXT'- case 'LINE':- return 'LINE'- case 'STAR':- return 'STAR'- case 'POLYGON':- return 'REGULAR_POLYGON'- case 'VECTOR':- return 'VECTOR'- case 'GROUP':- return 'FRAME'- case 'SECTION':- return 'SECTION'- default:- return 'RECTANGLE'- }-}--function fractionalPosition(index: number): string {- const base = '!'- return String.fromCharCode(base.charCodeAt(0) + index)-}--function sceneNodeToKiwi(- node: SceneNode,- parentGuid: { sessionID: number; localID: number },- childIndex: number,- localIdCounter: { value: number },- graph: SceneGraph,- blobs: Uint8Array[]-): KiwiNodeChange[] {- const localID = localIdCounter.value++- const guid = { sessionID: 1, localID }- const cos = Math.cos((node.rotation * Math.PI) / 180)- const sin = Math.sin((node.rotation * Math.PI) / 180)-- const fillPaints = node.fills- .filter((f) => f.type === 'SOLID')- .map((f) => ({- type: 'SOLID' as const,- color: f.color,- opacity: f.opacity,- visible: f.visible,- blendMode: 'NORMAL' as const- }))-- const strokePaints = node.strokes- .filter((s) => s.visible)- .map((s) => ({- type: 'SOLID' as const,- color: s.color,- opacity: s.opacity,- visible: true,- blendMode: 'NORMAL' as const- }))-- const nc: KiwiNodeChange = {- guid,- parentIndex: { guid: parentGuid, position: fractionalPosition(childIndex) },- type: mapToFigmaType(node.type),- name: node.name,- visible: node.visible,- opacity: node.opacity,- phase: 'CREATED',- size: { x: node.width, y: node.height },- transform: { m00: cos, m01: -sin, m02: node.x, m10: sin, m11: cos, m12: node.y },- strokeWeight: node.strokes.length > 0 ? node.strokes[0].weight : 1,- strokeAlign: 'INSIDE'- }-- if (fillPaints.length > 0) nc.fillPaints = fillPaints- if (strokePaints.length > 0) nc.strokePaints = strokePaints-- if (node.cornerRadius > 0) {- nc.cornerRadius = node.cornerRadius- nc.rectangleTopLeftCornerRadius = node.independentCorners- ? node.topLeftRadius- : node.cornerRadius- nc.rectangleTopRightCornerRadius = node.independentCorners- ? node.topRightRadius- : node.cornerRadius- nc.rectangleBottomLeftCornerRadius = node.independentCorners- ? node.bottomLeftRadius- : node.cornerRadius- nc.rectangleBottomRightCornerRadius = node.independentCorners- ? node.bottomRightRadius- : node.cornerRadius- }-- if (node.type === 'TEXT') {- nc.fontSize = node.fontSize- nc.fontName = { family: node.fontFamily, style: 'Regular', postscript: '' }- nc.textData = {- characters: node.text,- lines: [- {- lineType: 'PLAIN',- styleId: 0,- indentationLevel: 0,- sourceDirectionality: 'AUTO',- listStartOffset: 0,- isFirstLineOfList: false- }- ]- }- nc.textAutoResize = 'WIDTH_AND_HEIGHT'- nc.textAlignHorizontal = node.textAlignHorizontal- }-- if (node.type === 'FRAME' || node.type === 'GROUP') {- nc.frameMaskDisabled = node.type === 'GROUP'- }-- if (node.layoutMode !== 'NONE') {- nc.stackMode = node.layoutMode- nc.stackSpacing = node.itemSpacing- nc.stackVerticalPadding = node.paddingTop- nc.stackHorizontalPadding = node.paddingLeft- nc.stackPaddingBottom = node.paddingBottom- nc.stackPaddingRight = node.paddingRight- nc.stackPrimarySizing = node.primaryAxisSizing === 'HUG' ? 'RESIZE_TO_FIT' : 'FIXED'- nc.stackCounterSizing =- node.counterAxisSizing === 'HUG' ? 'RESIZE_TO_FIT_WITH_IMPLICIT_SIZE' : undefined- }-- if (node.layoutPositioning === 'ABSOLUTE') {- nc.stackPositioning = 'ABSOLUTE'- }- if (node.layoutGrow > 0) {- 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, blobs))- }-- return result-}--export function buildFigmaClipboardHTML(nodes: SceneNode[], graph: SceneGraph): string | null {- const compiled = getCompiledSchema()- const schemaDeflated = deflateSync(getSchemaBytes())-- const docGuid = { sessionID: 0, localID: 0 }- const canvasGuid = { sessionID: 0, localID: 1 }- 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 }- }- ]-- const blobs: Uint8Array[] = []- for (let i = 0; i < nodes.length; i++) {- nodeChanges.push(...sceneNodeToKiwi(nodes[i], canvasGuid, i, localIdCounter, graph, blobs))- }-- const msg: Record<string, unknown> = {- type: 'NODE_CHANGES',- sessionID: 0,- ackID: 0,- pasteID: Math.floor(Math.random() * 2147483647),- pasteFileKey: 'openpencil',- 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 as number,- dataType: 'scene'- }- const metaB64 = btoa(JSON.stringify(meta))-- return (- `<meta charset='utf-8'>` +- `<span data-metadata="<!--(figmeta)${metaB64}(/figmeta)-->"></span>` +- `<span data-buffer="<!--(figma)${bufferB64}(/figma)-->"></span>`- )-}--// --- Internal copy/paste (OpenPencil ↔ OpenPencil) -----export function parseOpenPencilClipboard(- html: string-): Array<SceneNode & { children?: SceneNode[] }> | null {- const match = html.match(/<!--\(openpencil\)(.*?)\(\/openpencil\)-->/s)- if (!match) return null-- try {- const decoded = JSON.parse(atob(match[1]))- if (decoded.format === 'openpencil/v1' && Array.isArray(decoded.nodes)) {- return decoded.nodes- }- } catch {- // Not our format- }- return null-}--export function buildOpenPencilClipboardHTML(nodes: SceneNode[], graph: SceneGraph): string {- const data = {- format: 'openpencil/v1',- nodes: collectNodeTree(nodes, graph)- }- return `<!--(openpencil)${btoa(JSON.stringify(data))}(/openpencil)-->`-}--function collectNodeTree(- nodes: SceneNode[],- graph: SceneGraph-): Array<SceneNode & { children?: SceneNode[] }> {- return nodes.map((node) => {- const children = graph.getChildren(node.id)- return {- ...node,- children: children.length > 0 ? collectNodeTree(children, graph) : undefined- }- })-}+export {+ parseFigmaClipboard,+ importClipboardNodes,+ parseOpenPencilClipboard,+ buildFigmaClipboardHTML,+ buildOpenPencilClipboardHTML,+ prefetchFigmaSchema+} from '@open-pencil/core'diff --git a/src/engine/color.ts b/src/engine/color.tsindex ed6ba61c7..1c5caf414 100644--- a/src/engine/color.ts+++ b/src/engine/color.ts@@ -1,48 +1 @@-import { parse, formatHex, converter } from 'culori'--import type { Color } from '@/types'--const toRgb = converter('rgb')--export function parseColor(input: string): Color {- const parsed = parse(input)- if (!parsed) return { r: 0, g: 0, b: 0, a: 1 }- const rgb = toRgb(parsed)- return {- r: rgb?.r ?? 0,- g: rgb?.g ?? 0,- b: rgb?.b ?? 0,- a: parsed.alpha ?? 1- }-}--export function colorToHex(color: Color): string {- return (formatHex({ mode: 'rgb', r: color.r, g: color.g, b: color.b }) ?? '#000000').toUpperCase()-}--export function colorToHexRaw(color: Color): string {- return colorToHex(color).slice(1)-}--export function colorToRgba255(color: Color) {- return {- r: Math.round(color.r * 255),- g: Math.round(color.g * 255),- b: Math.round(color.b * 255),- a: color.a- }-}--export function rgba255ToColor(rgba: { r: number; g: number; b: number; a: number }): Color {- return { r: rgba.r / 255, g: rgba.g / 255, b: rgba.b / 255, a: rgba.a }-}--export function colorToFill(color: string | Color) {- const rgba = typeof color === 'string' ? parseColor(color) : color- return {- type: 'SOLID' as const,- color: { r: rgba.r, g: rgba.g, b: rgba.b, a: rgba.a },- opacity: rgba.a,- visible: true- }-}+export { parseColor, colorToHex, colorToHexRaw, colorToRgba255 } from '@open-pencil/core'diff --git a/src/engine/fig-export.ts b/src/engine/fig-export.tsindex 8cb153425..78027cac5 100644--- a/src/engine/fig-export.ts+++ b/src/engine/fig-export.ts@@ -1,337 +1 @@-import { zipSync, deflateSync } from 'fflate'--import { IS_TAURI } from '@/constants'-import { initCodec, getCompiledSchema, getSchemaBytes } from '@/kiwi/codec'--import { renderThumbnail } from './render-image'-import { encodeVectorNetworkBlob } from './vector'--import type { SkiaRenderer } from './renderer'-import type { SceneGraph, SceneNode } from './scene-graph'-import type { NodeChange, Paint } from '@/kiwi/codec'-import type { CanvasKit } from 'canvaskit-wasm'--const THUMBNAIL_1X1 = Uint8Array.from(- atob(- 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=='- ),- (c) => c.charCodeAt(0)-)--type KiwiNodeChange = NodeChange & Record<string, unknown>--function mapToFigmaType(type: SceneNode['type']): string {- switch (type) {- case 'FRAME':- return 'FRAME'- case 'RECTANGLE':- return 'RECTANGLE'- case 'ROUNDED_RECTANGLE':- return 'ROUNDED_RECTANGLE'- case 'ELLIPSE':- return 'ELLIPSE'- case 'TEXT':- return 'TEXT'- case 'LINE':- return 'LINE'- case 'STAR':- return 'STAR'- case 'POLYGON':- return 'REGULAR_POLYGON'- case 'VECTOR':- return 'VECTOR'- case 'GROUP':- return 'FRAME'- case 'SECTION':- return 'SECTION'- case 'COMPONENT':- return 'COMPONENT'- case 'COMPONENT_SET':- return 'COMPONENT_SET'- case 'INSTANCE':- return 'INSTANCE'- case 'CONNECTOR':- return 'CONNECTOR'- case 'SHAPE_WITH_TEXT':- return 'SHAPE_WITH_TEXT'- default:- return 'RECTANGLE'- }-}--function fractionalPosition(index: number): string {- return String.fromCharCode('!'.charCodeAt(0) + index)-}--function sceneNodeToKiwi(- node: SceneNode,- parentGuid: { sessionID: number; localID: number },- childIndex: number,- localIdCounter: { value: number },- graph: SceneGraph,- blobs: Uint8Array[]-): KiwiNodeChange[] {- const localID = localIdCounter.value++- const guid = { sessionID: 1, localID }- const cos = Math.cos((node.rotation * Math.PI) / 180)- const sin = Math.sin((node.rotation * Math.PI) / 180)-- const fillPaints = node.fills.map((f) => {- const paint: Paint = {- type: f.type,- color: f.color,- opacity: f.opacity,- visible: f.visible,- blendMode: f.blendMode ?? 'NORMAL'- }- if (f.gradientStops) {- paint.stops = f.gradientStops.map((s) => ({ color: s.color, position: s.position }))- }- if (f.gradientTransform) paint.transform = f.gradientTransform- if (f.imageHash) paint.image = { hash: f.imageHash }- if (f.imageScaleMode) paint.imageScaleMode = f.imageScaleMode- if (f.imageTransform) paint.transform = f.imageTransform- return paint- })-- const strokePaints = node.strokes.map((s) => ({- type: 'SOLID' as const,- color: s.color,- opacity: s.opacity,- visible: s.visible,- blendMode: 'NORMAL' as const- }))-- const nc: KiwiNodeChange = {- guid,- parentIndex: { guid: parentGuid, position: fractionalPosition(childIndex) },- type: mapToFigmaType(node.type),- name: node.name,- visible: node.visible,- opacity: node.opacity,- phase: 'CREATED',- size: { x: node.width, y: node.height },- transform: { m00: cos, m01: -sin, m02: node.x, m10: sin, m11: cos, m12: node.y },- strokeWeight: node.strokes.length > 0 ? node.strokes[0].weight : 1,- strokeAlign: 'INSIDE'- }-- if (fillPaints.length > 0) nc.fillPaints = fillPaints- if (strokePaints.length > 0) nc.strokePaints = strokePaints-- if (node.cornerRadius > 0 || node.independentCorners) {- nc.cornerRadius = node.cornerRadius- nc.rectangleCornerRadiiIndependent = node.independentCorners- nc.rectangleTopLeftCornerRadius = node.independentCorners- ? node.topLeftRadius- : node.cornerRadius- nc.rectangleTopRightCornerRadius = node.independentCorners- ? node.topRightRadius- : node.cornerRadius- nc.rectangleBottomLeftCornerRadius = node.independentCorners- ? node.bottomLeftRadius- : node.cornerRadius- nc.rectangleBottomRightCornerRadius = node.independentCorners- ? node.bottomRightRadius- : node.cornerRadius- }-- if (node.cornerSmoothing > 0) {- nc.cornerSmoothing = node.cornerSmoothing- }-- if (node.effects.length > 0) {- nc.effects = node.effects.map((e) => ({- type: e.type,- color: e.color,- offset: e.offset,- radius: e.radius,- spread: e.spread,- visible: e.visible- }))- }-- if (node.type === 'TEXT') {- nc.fontSize = node.fontSize- nc.fontName = {- family: node.fontFamily,- style: node.fontWeight >= 700 ? 'Bold' : 'Regular',- postscript: ''- }- nc.textData = { characters: node.text }- nc.textAutoResize = 'WIDTH_AND_HEIGHT'- nc.textAlignHorizontal = node.textAlignHorizontal- if (node.lineHeight != null) nc.lineHeight = { value: node.lineHeight, units: 'PIXELS' }- if (node.letterSpacing !== 0) nc.letterSpacing = { value: node.letterSpacing, units: 'PIXELS' }- }-- if (node.type === 'FRAME' || node.type === 'GROUP') {- nc.frameMaskDisabled = node.type === 'GROUP'- if (node.clipsContent) nc.clipsContent = true- }-- if (node.layoutMode !== 'NONE') {- nc.stackMode = node.layoutMode- nc.stackSpacing = node.itemSpacing- nc.stackVerticalPadding = node.paddingTop- nc.stackHorizontalPadding = node.paddingLeft- nc.stackPaddingBottom = node.paddingBottom- nc.stackPaddingRight = node.paddingRight- nc.stackPrimarySizing = node.primaryAxisSizing === 'HUG' ? 'RESIZE_TO_FIT' : 'FIXED'- nc.stackCounterSizing = node.counterAxisSizing === 'HUG' ? 'RESIZE_TO_FIT' : 'FIXED'- nc.stackPrimaryAlignItems = node.primaryAxisAlign- nc.stackCounterAlignItems = node.counterAxisAlign- if (node.layoutWrap === 'WRAP') nc.stackWrap = 'WRAP'- if (node.counterAxisSpacing > 0) nc.stackCounterSpacing = node.counterAxisSpacing- }-- if (node.layoutPositioning === 'ABSOLUTE') nc.stackPositioning = 'ABSOLUTE'- if (node.layoutGrow > 0) 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, blobs))- }-- return result-}--function buildFigKiwi(schemaDeflated: Uint8Array, dataCompressed: Uint8Array): Uint8Array {- const FIG_KIWI_VERSION = 106- 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--export async function exportFigFile(- graph: SceneGraph,- ck?: CanvasKit,- renderer?: SkiaRenderer,- pageId?: string-): Promise<Uint8Array> {- await initCodec()- const compiled = getCompiledSchema()- const schemaDeflated = deflateSync(getSchemaBytes())-- 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 blobs: Uint8Array[] = []- const pages = graph.getPages()-- for (let p = 0; p < pages.length; p++) {- const page = pages[p]- const canvasLocalID = localIdCounter.value++- const canvasGuid = { sessionID: 0, localID: canvasLocalID }-- nodeChanges.push({- 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',- backgroundOpacity: 1,- backgroundColor: { r: 0.96, g: 0.96, b: 0.96, a: 1 },- backgroundEnabled: true- })-- const children = graph.getChildren(page.id)- for (let i = 0; i < children.length; i++) {- nodeChanges.push(...sceneNodeToKiwi(children[i], canvasGuid, i, localIdCounter, graph, blobs))- }- }-- const msg: Record<string, unknown> = {- type: 'NODE_CHANGES',- sessionID: 0,- ackID: 0,- nodeChanges- }-- if (blobs.length > 0) {- msg.blobs = blobs.map((bytes) => ({ bytes }))- }-- const kiwiData = compiled.encodeMessage(msg)-- const currentPageId = pageId ?? pages[0]?.id- const thumbnailPng =- (ck && renderer && currentPageId- ? renderThumbnail(ck, renderer, graph, currentPageId, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT)- : null) ?? THUMBNAIL_1X1-- const metaJson = JSON.stringify({- version: 1,- app: 'OpenPencil',- createdAt: new Date().toISOString()- })-- if (IS_TAURI) {- const { invoke } = await import('@tauri-apps/api/core')- return new Uint8Array(- await invoke<number[]>('build_fig_file', {- schemaDeflated: Array.from(schemaDeflated),- kiwiData: Array.from(kiwiData),- thumbnailPng: Array.from(thumbnailPng),- metaJson- })- )- }-- const canvasData = buildFigKiwi(schemaDeflated, deflateSync(kiwiData))- return zipSync({- 'canvas.fig': [canvasData, { level: 0 }],- 'thumbnail.png': [thumbnailPng, { level: 0 }],- 'meta.json': new TextEncoder().encode(metaJson)- })-}+export { exportFigFile } from '@open-pencil/core'diff --git a/src/engine/fonts.ts b/src/engine/fonts.tsindex bce9df6cb..618810238 100644--- a/src/engine/fonts.ts+++ b/src/engine/fonts.ts@@ -1,145 +1 @@-import type { CanvasKit, TypefaceFontProvider } from 'canvaskit-wasm'--export interface FontInfo {- family: string- fullName: string- style: string- postscriptName: string-}--const loadedFamilies = new Map<string, ArrayBuffer>()-let fontProvider: TypefaceFontProvider | null = null--export function initFontService(_canvasKit: CanvasKit, provider: TypefaceFontProvider) {- fontProvider = provider-}--export function getFontProvider(): TypefaceFontProvider | null {- return fontProvider-}--export async function queryFonts(): Promise<FontInfo[]> {- if (!window.queryLocalFonts) return []- try {- const fonts = await window.queryLocalFonts()- const seen = new Set<string>()- const result: FontInfo[] = []- for (const f of fonts) {- const key = `${f.family}|${f.style}`- if (seen.has(key)) continue- seen.add(key)- result.push({- family: f.family,- fullName: f.fullName,- style: f.style,- postscriptName: f.postscriptName- })- }- return result- } catch {- return []- }-}--export async function listFamilies(): Promise<string[]> {- const fonts = await queryFonts()- return [...new Set(fonts.map((f) => f.family))].sort()-}--const BUNDLED_FONTS: Record<string, string> = {- 'Inter|Regular': '/Inter-Regular.ttf'-}--export async function loadFont(family: string, style = 'Regular'): Promise<ArrayBuffer | null> {- const cacheKey = `${family}|${style}`- if (loadedFamilies.has(cacheKey)) {- const cached = loadedFamilies.get(cacheKey)- if (!cached) return null- registerFontInCanvasKit(family, cached)- return cached- }-- // Try local font access API first- if (window.queryLocalFonts) {- try {- const fonts = await window.queryLocalFonts()- const match =- fonts.find((f: FontInfo) => f.family === family && f.style === style) ??- fonts.find((f: FontInfo) => f.family === family)- if (match) {- const blob: Blob = await match.blob()- const buffer = await blob.arrayBuffer()-- loadedFamilies.set(cacheKey, buffer)- registerFontInCanvasKit(family, buffer)- registerFontInBrowser(family, style, buffer)- return buffer- }- } catch {- /* fall through to bundled */- }- }-- // Fall back to bundled font- const bundledUrl = BUNDLED_FONTS[cacheKey]- if (bundledUrl) {- try {- const response = await fetch(bundledUrl)- const buffer = await response.arrayBuffer()-- loadedFamilies.set(cacheKey, buffer)- registerFontInCanvasKit(family, buffer)- registerFontInBrowser(family, style, buffer)- return buffer- } catch {- /* no bundled font available */- }- }-- return null-}--function registerFontInCanvasKit(family: string, data: ArrayBuffer) {- if (!fontProvider) return- fontProvider.registerFont(data, family)-}--function registerFontInBrowser(family: string, style: string, data: ArrayBuffer) {- const weight = styleToWeight(style)- const italic = style.toLowerCase().includes('italic') ? 'italic' : 'normal'- const face = new FontFace(family, data, {- weight: String(weight),- style: italic- })- face.load().then(() => document.fonts.add(face))-}--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-}--export async function ensureNodeFont(family: string, weight: number): Promise<void> {- const style = weightToStyle(weight)- await loadFont(family, style)-}--function weightToStyle(weight: number): string {- if (weight <= 100) return 'Thin'- if (weight <= 200) return 'ExtraLight'- if (weight <= 300) return 'Light'- if (weight <= 400) return 'Regular'- if (weight <= 500) return 'Medium'- if (weight <= 600) return 'SemiBold'- if (weight <= 700) return 'Bold'- if (weight <= 800) return 'ExtraBold'- return 'Black'-}+export { loadFont, listFamilies } from '@open-pencil/core'diff --git a/src/engine/layout.ts b/src/engine/layout.tsindex 5f2216488..0101322c1 100644--- a/src/engine/layout.ts+++ b/src/engine/layout.ts@@ -1,317 +1 @@-import Yoga, {- Align,- Direction,- FlexDirection,- Gutter,- Justify,- Edge,- Wrap,- type Node as YogaNode-} from 'yoga-layout'--import type { SceneGraph, SceneNode } from './scene-graph'--export function computeLayout(graph: SceneGraph, frameId: string): void {- const frame = graph.getNode(frameId)- if (!frame || frame.layoutMode === 'NONE') return-- const yogaRoot = buildYogaTree(graph, frame)- yogaRoot.calculateLayout(undefined, undefined, Direction.LTR)- applyYogaLayout(graph, frame, yogaRoot)- freeYogaTree(yogaRoot)-}--export function computeAllLayouts(graph: SceneGraph): void {- const visited = new Set<string>()- computeLayoutsBottomUp(graph, graph.rootId, visited)-}--function computeLayoutsBottomUp(graph: SceneGraph, nodeId: string, visited: Set<string>): void {- const node = graph.getNode(nodeId)- if (!node || visited.has(nodeId)) return- visited.add(nodeId)-- for (const childId of node.childIds) {- computeLayoutsBottomUp(graph, childId, visited)- }-- if (node.layoutMode !== 'NONE') {- computeLayout(graph, nodeId)- }-}--function buildYogaTree(graph: SceneGraph, frame: SceneNode): YogaNode {- const root = Yoga.Node.create()-- if (frame.primaryAxisSizing === 'FIXED') {- if (frame.layoutMode === 'HORIZONTAL') root.setWidth(frame.width)- else root.setHeight(frame.height)- }- if (frame.counterAxisSizing === 'FIXED') {- if (frame.layoutMode === 'HORIZONTAL') root.setHeight(frame.height)- else root.setWidth(frame.width)- }-- root.setFlexDirection(- frame.layoutMode === 'HORIZONTAL' ? FlexDirection.Row : FlexDirection.Column- )- root.setFlexWrap(frame.layoutWrap === 'WRAP' ? Wrap.Wrap : Wrap.NoWrap)- root.setJustifyContent(mapJustify(frame.primaryAxisAlign))- root.setAlignItems(mapAlign(frame.counterAxisAlign))-- root.setPadding(Edge.Top, frame.paddingTop)- root.setPadding(Edge.Right, frame.paddingRight)- root.setPadding(Edge.Bottom, frame.paddingBottom)- root.setPadding(Edge.Left, frame.paddingLeft)-- root.setGap(- Gutter.Column,- frame.layoutMode === 'HORIZONTAL' ? frame.itemSpacing : frame.counterAxisSpacing- )- root.setGap(- Gutter.Row,- frame.layoutMode === 'HORIZONTAL' ? frame.counterAxisSpacing : frame.itemSpacing- )-- const children = graph.getChildren(frame.id)- for (let i = 0; i < children.length; i++) {- const child = children[i]-- if (child.layoutPositioning === 'ABSOLUTE') continue-- const yogaChild = Yoga.Node.create()-- if (child.layoutMode !== 'NONE') {- configureChildAsAutoLayout(yogaChild, child, frame, graph)- } else {- configureChildAsLeaf(yogaChild, child, frame)- }-- root.insertChild(yogaChild, root.getChildCount())- }-- return root-}--function configureChildAsAutoLayout(- yogaChild: YogaNode,- child: SceneNode,- parent: SceneNode,- graph: SceneGraph-): void {- const isParentRow = parent.layoutMode === 'HORIZONTAL'- const isChildRow = child.layoutMode === 'HORIZONTAL'-- const widthSizing = isChildRow ? child.primaryAxisSizing : child.counterAxisSizing- const heightSizing = isChildRow ? child.counterAxisSizing : child.primaryAxisSizing-- if (isParentRow) {- setSizing(yogaChild, 'width', widthSizing, child.width, child.layoutGrow)- setSizing(yogaChild, 'height', heightSizing, child.height, 0)- } else {- setSizing(yogaChild, 'width', widthSizing, child.width, 0)- setSizing(yogaChild, 'height', heightSizing, child.height, child.layoutGrow)- }-- if (child.layoutAlignSelf === 'STRETCH') {- yogaChild.setAlignSelf(Align.Stretch)- }-- yogaChild.setFlexDirection(- child.layoutMode === 'HORIZONTAL' ? FlexDirection.Row : FlexDirection.Column- )- yogaChild.setFlexWrap(child.layoutWrap === 'WRAP' ? Wrap.Wrap : Wrap.NoWrap)- yogaChild.setJustifyContent(mapJustify(child.primaryAxisAlign))- yogaChild.setAlignItems(mapAlign(child.counterAxisAlign))-- yogaChild.setPadding(Edge.Top, child.paddingTop)- yogaChild.setPadding(Edge.Right, child.paddingRight)- yogaChild.setPadding(Edge.Bottom, child.paddingBottom)- yogaChild.setPadding(Edge.Left, child.paddingLeft)-- yogaChild.setGap(- Gutter.Column,- child.layoutMode === 'HORIZONTAL' ? child.itemSpacing : child.counterAxisSpacing- )- yogaChild.setGap(- Gutter.Row,- child.layoutMode === 'HORIZONTAL' ? child.counterAxisSpacing : child.itemSpacing- )-- const grandchildren = graph.getChildren(child.id)- for (const gc of grandchildren) {- if (gc.layoutPositioning === 'ABSOLUTE') continue- const yogaGC = Yoga.Node.create()- if (gc.layoutMode !== 'NONE') {- configureChildAsAutoLayout(yogaGC, gc, child, graph)- } else {- configureChildAsLeaf(yogaGC, gc, child)- }- yogaChild.insertChild(yogaGC, yogaChild.getChildCount())- }-}--function configureChildAsLeaf(yogaChild: YogaNode, child: SceneNode, parent: SceneNode): void {- const isRow = parent.layoutMode === 'HORIZONTAL'- const stretchCross = child.layoutAlignSelf === 'STRETCH' || parent.counterAxisAlign === 'STRETCH'-- if (child.layoutGrow > 0) {- yogaChild.setFlexGrow(child.layoutGrow)- if (!stretchCross) {- if (isRow) yogaChild.setHeight(child.height)- else yogaChild.setWidth(child.width)- }- } else {- if (isRow) {- yogaChild.setWidth(child.width)- if (!stretchCross) yogaChild.setHeight(child.height)- } else {- yogaChild.setHeight(child.height)- if (!stretchCross) yogaChild.setWidth(child.width)- }- }-- if (child.layoutAlignSelf === 'STRETCH') {- yogaChild.setAlignSelf(Align.Stretch)- }-}--function setSizing(- yogaNode: YogaNode,- axis: 'width' | 'height',- sizing: string,- fixedValue: number,- grow: number-): void {- if (grow > 0) {- yogaNode.setFlexGrow(grow)- yogaNode.setFlexShrink(1)- return- }-- switch (sizing) {- case 'FIXED':- if (axis === 'width') yogaNode.setWidth(fixedValue)- else yogaNode.setHeight(fixedValue)- break- case 'HUG':- break- case 'FILL':- yogaNode.setFlexGrow(1)- yogaNode.setFlexShrink(1)- break- }-}--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 {- if (frame.primaryAxisSizing === 'HUG' || frame.counterAxisSizing === 'HUG') {- const computedW = yogaNode.getComputedWidth()- const computedH = yogaNode.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 = yogaNode.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 freeYogaTree(node: YogaNode): void {- for (let i = node.getChildCount() - 1; i >= 0; i--) {- freeYogaTree(node.getChild(i))- }- node.free()-}--function mapJustify(align: string): Justify {- switch (align) {- case 'CENTER':- return Justify.Center- case 'MAX':- return Justify.FlexEnd- case 'SPACE_BETWEEN':- return Justify.SpaceBetween- default:- return Justify.FlexStart- }-}--function mapAlign(align: string): Align {- switch (align) {- case 'CENTER':- return Align.Center- case 'MAX':- return Align.FlexEnd- case 'STRETCH':- return Align.Stretch- case 'BASELINE':- return Align.Baseline- default:- return Align.FlexStart- }-}+export { computeLayout, computeAllLayouts } from '@open-pencil/core'diff --git a/src/engine/render-image.ts b/src/engine/render-image.tsindex ac731e1db..1e8d09042 100644--- a/src/engine/render-image.ts+++ b/src/engine/render-image.ts@@ -1,158 +1 @@-import type { SkiaRenderer } from './renderer'-import type { SceneGraph } from './scene-graph'-import type { CanvasKit } from 'canvaskit-wasm'--export type ExportFormat = 'PNG' | 'JPG' | 'WEBP'--interface RenderOptions {- scale: number- format: ExportFormat- quality?: number-}--function computeContentBounds(- graph: SceneGraph,- nodeIds: string[]-): { minX: number; minY: number; maxX: number; maxY: number } | null {- let minX = Infinity,- minY = Infinity,- maxX = -Infinity,- maxY = -Infinity-- for (const id of nodeIds) {- const node = graph.getNode(id)- if (!node || !node.visible) continue- const abs = graph.getAbsolutePosition(id)- minX = Math.min(minX, abs.x)- minY = Math.min(minY, abs.y)- maxX = Math.max(maxX, abs.x + node.width)- maxY = Math.max(maxY, abs.y + node.height)- }-- if (!isFinite(minX)) return null- return { minX, minY, maxX, maxY }-}--function renderToSurface(- ck: CanvasKit,- renderer: SkiaRenderer,- graph: SceneGraph,- pageId: string,- width: number,- height: number,- setup: (canvas: import('canvaskit-wasm').Canvas) => void-): Uint8Array | null {- const surface = ck.MakeSurface(width, height)- if (!surface) return null-- try {- const canvas = surface.getCanvas()- setup(canvas)- renderer.renderSceneToCanvas(canvas, graph, pageId)- surface.flush()- const image = surface.makeImageSnapshot()- const encoded = image.encodeToBytes(ck.ImageFormat.PNG, 100)- image.delete()- return encoded ? new Uint8Array(encoded) : null- } finally {- surface.delete()- }-}--function mimeForFormat(format: ExportFormat): string {- switch (format) {- case 'JPG':- return 'image/jpeg'- case 'WEBP':- return 'image/webp'- default:- return 'image/png'- }-}--async function reencodeImage(- pngBytes: Uint8Array,- format: ExportFormat,- quality: number-): Promise<Uint8Array> {- if (format === 'PNG') return pngBytes-- const blob = new Blob([new Uint8Array(pngBytes)], { type: 'image/png' })- const bitmap = await createImageBitmap(blob)- const canvas = new OffscreenCanvas(bitmap.width, bitmap.height)- const ctx = canvas.getContext('2d')- if (!ctx) return pngBytes-- if (format === 'JPG') {- ctx.fillStyle = '#ffffff'- ctx.fillRect(0, 0, bitmap.width, bitmap.height)- }-- ctx.drawImage(bitmap, 0, 0)- bitmap.close()-- const outBlob = await canvas.convertToBlob({- type: mimeForFormat(format),- quality: quality / 100- })- return new Uint8Array(await outBlob.arrayBuffer())-}--export async function renderNodesToImage(- ck: CanvasKit,- renderer: SkiaRenderer,- graph: SceneGraph,- pageId: string,- nodeIds: string[],- options: RenderOptions-): Promise<Uint8Array | null> {- const bounds = computeContentBounds(graph, nodeIds)- if (!bounds) return null-- const contentW = bounds.maxX - bounds.minX- const contentH = bounds.maxY - bounds.minY- if (contentW <= 0 || contentH <= 0) return null-- const pixelW = Math.ceil(contentW * options.scale)- const pixelH = Math.ceil(contentH * options.scale)- if (pixelW <= 0 || pixelH <= 0) return null-- const png = renderToSurface(ck, renderer, graph, pageId, pixelW, pixelH, (canvas) => {- canvas.clear(ck.TRANSPARENT)- canvas.scale(options.scale, options.scale)- canvas.translate(-bounds.minX, -bounds.minY)- })- if (!png) return null-- const quality = options.quality ?? (options.format === 'PNG' ? 100 : 90)- return reencodeImage(png, options.format, quality)-}--export function renderThumbnail(- ck: CanvasKit,- renderer: SkiaRenderer,- graph: SceneGraph,- pageId: string,- width: number,- height: number-): Uint8Array | null {- const page = graph.getNode(pageId)- if (!page || page.childIds.length === 0) return null-- const bounds = computeContentBounds(graph, page.childIds)- if (!bounds) return null-- const contentW = bounds.maxX - bounds.minX- const contentH = bounds.maxY - bounds.minY- if (contentW <= 0 || contentH <= 0) return null-- const scale = Math.min(width / contentW, height / contentH, 2)-- return renderToSurface(ck, renderer, graph, pageId, width, height, (canvas) => {- canvas.clear(ck.Color4f(renderer.pageColor.r, renderer.pageColor.g, renderer.pageColor.b, 1))- const offsetX = (width - contentW * scale) / 2 - bounds.minX * scale- const offsetY = (height - contentH * scale) / 2 - bounds.minY * scale- canvas.translate(offsetX, offsetY)- canvas.scale(scale, scale)- })-}+export { renderNodesToImage, renderThumbnail, type ExportFormat } from '@open-pencil/core'diff --git a/src/engine/renderer.ts b/src/engine/renderer.tsindex 3a0476c21..9d6b979d4 100644--- a/src/engine/renderer.ts+++ b/src/engine/renderer.ts@@ -1,2102 +1 @@-import {- SELECTION_COLOR,- COMPONENT_COLOR,- SNAP_COLOR,- CANVAS_BG_COLOR,- ROTATION_HANDLE_OFFSET,- RULER_SIZE,- RULER_BG_COLOR,- RULER_TICK_COLOR,- RULER_TEXT_COLOR,- RULER_BADGE_HEIGHT,- RULER_BADGE_PADDING,- RULER_BADGE_RADIUS,- RULER_BADGE_EXCLUSION,- RULER_TEXT_BASELINE,- RULER_MAJOR_TICK,- RULER_MINOR_TICK,- RULER_HIGHLIGHT_ALPHA,- PEN_HANDLE_RADIUS,- PEN_VERTEX_RADIUS,- PEN_CLOSE_RADIUS_BOOST,- PEN_PATH_STROKE_WIDTH,- PARENT_OUTLINE_ALPHA,- PARENT_OUTLINE_DASH,- DEFAULT_FONT_SIZE,- LABEL_FONT_SIZE,- SIZE_FONT_SIZE,- ROTATION_HANDLE_RADIUS,- HANDLE_HALF_SIZE,- LABEL_OFFSET_Y,- SIZE_PILL_PADDING_X,- SIZE_PILL_PADDING_Y,- SIZE_PILL_HEIGHT,- SIZE_PILL_RADIUS,- SIZE_PILL_TEXT_OFFSET_Y,- MARQUEE_FILL_ALPHA,- SELECTION_DASH_ALPHA,- DROP_HIGHLIGHT_ALPHA,- DROP_HIGHLIGHT_STROKE,- LAYOUT_INDICATOR_STROKE,- SECTION_CORNER_RADIUS,- SECTION_TITLE_HEIGHT,- SECTION_TITLE_PADDING_X,- SECTION_TITLE_RADIUS,- SECTION_TITLE_FONT_SIZE,- SECTION_TITLE_GAP,- COMPONENT_SET_DASH,- COMPONENT_SET_DASH_GAP,- COMPONENT_SET_BORDER_WIDTH,- COMPONENT_LABEL_FONT_SIZE,- COMPONENT_LABEL_GAP,- COMPONENT_LABEL_ICON_SIZE,- COMPONENT_LABEL_ICON_GAP,- RULER_TARGET_PIXEL_SPACING,- RULER_MAJOR_TOLERANCE-} from '@/constants'--import { vectorNetworkToPath } from './vector'--import type { SceneNode, SceneGraph, Fill } from './scene-graph'-import type { SnapGuide } from './snap'-import type { Rect } from '@/types'-import type { EmbindEnumEntity, Image as CKImage, Path } from 'canvaskit-wasm'-import type {- CanvasKit,- Surface,- Canvas,- Paint,- Font,- FontMgr,- FontWeight,- TypefaceFontProvider-} from 'canvaskit-wasm'--export interface RenderOverlays {- hoveredNodeId?: string | null- editingTextId?: string | null- marquee?: Rect | null- snapGuides?: SnapGuide[]- rotationPreview?: { nodeId: string; angle: number } | null- dropTargetId?: string | null- layoutInsertIndicator?: {- x: number- y: number- length: number- direction: 'HORIZONTAL' | 'VERTICAL'- } | null- penState?: {- vertices: Array<{ x: number; y: number }>- segments: Array<{- start: number- end: number- tangentStart: { x: number; y: number }- tangentEnd: { x: number; y: number }- }>- dragTangent: { x: number; y: number } | null- closingToFirst: boolean- cursorX?: number- cursorY?: number- } | null-}--export class SkiaRenderer {- private ck: CanvasKit- private surface: Surface- private fillPaint: Paint- private strokePaint: Paint- private selectionPaint: Paint- private parentOutlinePaint: Paint- private snapPaint: Paint- private auxFill: Paint- private auxStroke: Paint- private opacityPaint: Paint- private textFont: Font | null = null- private labelFont: Font | null = null- private sizeFont: Font | null = null- private sectionTitleFont: Font | null = null- private componentLabelFont: Font | null = null- private fontMgr: FontMgr | null = null- private fontProvider: TypefaceFontProvider | null = null- private fontsLoaded = false- private imageCache = new Map<string, CKImage>()-- panX = 0- panY = 0- zoom = 1- dpr = 1- viewportWidth = 0- viewportHeight = 0- showRulers = true- pageColor = CANVAS_BG_COLOR- pageId: string | null = null-- private worldViewport = { x: 0, y: 0, w: 0, h: 0 }-- private selColor(alpha = 1) {- return this.ck.Color4f(SELECTION_COLOR.r, SELECTION_COLOR.g, SELECTION_COLOR.b, alpha)- }-- private compColor(alpha = 1) {- return this.ck.Color4f(COMPONENT_COLOR.r, COMPONENT_COLOR.g, COMPONENT_COLOR.b, alpha)- }-- private isComponentType(type: string): boolean {- return type === 'COMPONENT' || type === 'COMPONENT_SET' || type === 'INSTANCE'- }-- constructor(ck: CanvasKit, surface: Surface) {- this.ck = ck- this.surface = surface-- this.fillPaint = new ck.Paint()- this.fillPaint.setStyle(ck.PaintStyle.Fill)- this.fillPaint.setAntiAlias(true)-- this.strokePaint = new ck.Paint()- this.strokePaint.setStyle(ck.PaintStyle.Stroke)- this.strokePaint.setAntiAlias(true)-- this.selectionPaint = new ck.Paint()- this.selectionPaint.setStyle(ck.PaintStyle.Stroke)- this.selectionPaint.setStrokeWidth(1)- this.selectionPaint.setColor(this.selColor())- this.selectionPaint.setAntiAlias(true)-- this.parentOutlinePaint = new ck.Paint()- this.parentOutlinePaint.setStyle(ck.PaintStyle.Stroke)- this.parentOutlinePaint.setStrokeWidth(1)- this.parentOutlinePaint.setColor(this.selColor(PARENT_OUTLINE_ALPHA))- this.parentOutlinePaint.setAntiAlias(true)- this.parentOutlinePaint.setPathEffect(- ck.PathEffect.MakeDash([PARENT_OUTLINE_DASH, PARENT_OUTLINE_DASH], 0)- )-- this.snapPaint = new ck.Paint()- this.snapPaint.setStyle(ck.PaintStyle.Stroke)- this.snapPaint.setStrokeWidth(1)- this.snapPaint.setColor(this.ck.Color4f(SNAP_COLOR.r, SNAP_COLOR.g, SNAP_COLOR.b, 1))- this.snapPaint.setAntiAlias(true)-- this.auxFill = new ck.Paint()- this.auxFill.setStyle(ck.PaintStyle.Fill)- this.auxFill.setAntiAlias(true)-- this.auxStroke = new ck.Paint()- this.auxStroke.setStyle(ck.PaintStyle.Stroke)- this.auxStroke.setAntiAlias(true)-- this.opacityPaint = new ck.Paint()-- this.textFont = new ck.Font(null, DEFAULT_FONT_SIZE)- }-- async loadFonts(): Promise<void> {- this.fontProvider = this.ck.TypefaceFontProvider.Make()-- const { initFontService, loadFont } = await import('./fonts')- initFontService(this.ck, this.fontProvider)-- const fontData = await loadFont('Inter', 'Regular')- if (fontData) {- const typeface = this.ck.Typeface.MakeFreeTypeFaceFromData(fontData)- if (typeface) {- this.textFont?.delete()- this.labelFont?.delete()- this.sizeFont?.delete()- this.sectionTitleFont?.delete()- this.componentLabelFont?.delete()- this.textFont = new this.ck.Font(typeface, DEFAULT_FONT_SIZE)- this.labelFont = new this.ck.Font(typeface, LABEL_FONT_SIZE)- this.sizeFont = new this.ck.Font(typeface, SIZE_FONT_SIZE)- this.sectionTitleFont = new this.ck.Font(typeface, SECTION_TITLE_FONT_SIZE)- this.componentLabelFont = new this.ck.Font(typeface, COMPONENT_LABEL_FONT_SIZE)- }- this.fontMgr = this.ck.FontMgr.FromData(fontData) ?? null- }-- this.fontsLoaded = true- }-- hitTestSectionTitle(graph: SceneGraph, canvasX: number, canvasY: number): SceneNode | null {- if (!this.sectionTitleFont) return null-- const pageNode = graph.getNode(this.pageId ?? graph.rootId)- if (!pageNode) return null-- const font = this.sectionTitleFont- let result: SceneNode | null = null-- const check = (parentId: string, ox: number, oy: number, insideSection: boolean) => {- const parent = graph.getNode(parentId)- if (!parent) return- for (let i = parent.childIds.length - 1; i >= 0; i--) {- if (result) return- const childId = parent.childIds[i]- const child = graph.getNode(childId)- if (!child || !child.visible) continue- const ax = ox + child.x- const ay = oy + child.y- if (child.type === 'SECTION') {- // Compute pill width from font metrics- const glyphIds = font.getGlyphIDs(child.name)- const widths = font.getGlyphWidths(glyphIds)- let textW = 0- for (const w of widths) textW += w- const pillW =- Math.min(textW + SECTION_TITLE_PADDING_X * 2, child.width * this.zoom) / this.zoom- const pillH = SECTION_TITLE_HEIGHT / this.zoom- const gap = SECTION_TITLE_GAP / this.zoom-- let pillX = ax- let pillY: number- if (insideSection) {- pillY = ay + gap- } else {- pillY = ay - pillH - gap- }-- if (- canvasX >= pillX &&- canvasX <= pillX + pillW &&- canvasY >= pillY &&- canvasY <= pillY + pillH- ) {- result = child- return- }-- check(childId, ax, ay, true)- } else if (child.childIds.length > 0) {- check(childId, ax, ay, insideSection)- }- }- }-- check(pageNode.id, 0, 0, false)- return result- }-- hitTestComponentLabel(graph: SceneGraph, canvasX: number, canvasY: number): SceneNode | null {- if (!this.componentLabelFont) return null-- const pageNode = graph.getNode(this.pageId ?? graph.rootId)- if (!pageNode) return null-- const font = this.componentLabelFont- const LABEL_TYPES = new Set(['COMPONENT', 'COMPONENT_SET', 'INSTANCE'])- let result: SceneNode | null = null-- const check = (parentId: string, ox: number, oy: number) => {- const parent = graph.getNode(parentId)- if (!parent) return- for (let i = parent.childIds.length - 1; i >= 0; i--) {- if (result) return- const childId = parent.childIds[i]- const child = graph.getNode(childId)- if (!child || !child.visible) continue- const ax = ox + child.x- const ay = oy + child.y- if (LABEL_TYPES.has(child.type)) {- const glyphIds = font.getGlyphIDs(child.name)- const widths = font.getGlyphWidths(glyphIds)- let textW = 0- for (const w of widths) textW += w- const labelW = (COMPONENT_LABEL_ICON_SIZE + COMPONENT_LABEL_ICON_GAP + textW) / this.zoom- const labelH = COMPONENT_LABEL_FONT_SIZE / this.zoom- const gap = COMPONENT_LABEL_GAP / this.zoom-- const isInsideSet = parent.type === 'COMPONENT_SET'- const labelX = ax- let labelY: number- if (isInsideSet) {- labelY = ay + gap- } else {- labelY = ay - labelH - gap- }-- if (- canvasX >= labelX &&- canvasX <= labelX + labelW &&- canvasY >= labelY &&- canvasY <= labelY + labelH- ) {- result = child- return- }- }- if (child.childIds.length > 0) {- check(childId, ax, ay)- }- }- }-- check(pageNode.id, 0, 0)- return result- }-- renderSceneToCanvas(canvas: Canvas, graph: SceneGraph, pageId: string): void {- // Disable culling for export — render everything- const prevViewport = this.worldViewport- this.worldViewport = { x: -1e9, y: -1e9, w: 2e9, h: 2e9 }- const pageNode = graph.getNode(pageId)- if (pageNode) {- for (const childId of pageNode.childIds) {- this.renderNode(canvas, graph, childId, {})- }- }- this.worldViewport = prevViewport- }-- render(graph: SceneGraph, selectedIds: Set<string>, overlays: RenderOverlays = {}): void {- const canvas = this.surface.getCanvas()- canvas.clear(this.ck.Color4f(this.pageColor.r, this.pageColor.g, this.pageColor.b, 1))-- // Compute world-space viewport for culling- this.worldViewport = {- x: -this.panX / this.zoom,- y: -this.panY / this.zoom,- w: this.viewportWidth / this.zoom,- h: this.viewportHeight / this.zoom- }-- // Scene layer (world coordinates)- canvas.save()- canvas.scale(this.dpr, this.dpr)- canvas.translate(this.panX, this.panY)- canvas.scale(this.zoom, this.zoom)-- const pageNode = graph.getNode(this.pageId ?? graph.rootId)- if (pageNode) {- for (const childId of pageNode.childIds) {- this.renderNode(canvas, graph, childId, overlays, 0, 0)- }- }-- canvas.restore()-- // Section titles + component labels (screen coordinates, zoom-independent)- canvas.save()- canvas.scale(this.dpr, this.dpr)- this.drawSectionTitles(canvas, graph)- this.drawComponentLabels(canvas, graph)- canvas.restore()-- // UI overlay layer (screen coordinates, zoom-independent)- canvas.save()- canvas.scale(this.dpr, this.dpr)-- this.drawSelection(canvas, graph, selectedIds, overlays)- this.drawSnapGuides(canvas, overlays.snapGuides)- this.drawMarquee(canvas, overlays.marquee)- this.drawLayoutInsertIndicator(canvas, overlays.layoutInsertIndicator)- this.drawPenOverlay(canvas, overlays.penState)- if (this.showRulers) this.drawRulers(canvas, graph, selectedIds)-- canvas.restore()- this.surface.flush()- }-- // --- Selection UI ----- private drawSelection(- canvas: Canvas,- graph: SceneGraph,- selectedIds: Set<string>,- overlays: RenderOverlays- ): void {- if (selectedIds.size === 0) return-- this.drawParentFrameOutlines(canvas, graph, selectedIds)-- if (selectedIds.size === 1) {- const id = [...selectedIds][0]- if (overlays.editingTextId === id) return- const node = graph.getNode(id)- if (!node) return-- const useComponentColor = this.isComponentType(node.type)- this.selectionPaint.setColor(useComponentColor ? this.compColor() : this.selColor())- this.selectionPaint.setStrokeWidth(1)-- const rotation =- overlays.rotationPreview?.nodeId === id ? overlays.rotationPreview.angle : node.rotation- this.drawNodeSelection(canvas, node, rotation, graph)- this.drawSelectionLabels(canvas, graph, selectedIds)-- this.selectionPaint.setColor(this.selColor())- return- }-- for (const id of selectedIds) {- const node = graph.getNode(id)- if (!node) continue-- const useComponentColor = this.isComponentType(node.type)- this.selectionPaint.setColor(useComponentColor ? this.compColor() : this.selColor())- this.selectionPaint.setStrokeWidth(1)-- const rotation =- overlays.rotationPreview?.nodeId === id ? overlays.rotationPreview.angle : node.rotation- this.drawNodeOutline(canvas, node, rotation, graph)- }-- this.selectionPaint.setColor(this.selColor())-- const nodes = [...selectedIds]- .map((id) => graph.getNode(id))- .filter((n): n is SceneNode => n !== undefined)- this.drawGroupBounds(canvas, nodes, graph)-- this.drawSelectionLabels(canvas, graph, selectedIds)- }-- private drawNodeSelection(- canvas: Canvas,- node: SceneNode,- rotation: number,- graph: SceneGraph- ): void {- const abs = graph.getAbsolutePosition(node.id)- const cx = (abs.x + node.width / 2) * this.zoom + this.panX- const cy = (abs.y + node.height / 2) * this.zoom + this.panY- const hw = (node.width / 2) * this.zoom- const hh = (node.height / 2) * this.zoom-- canvas.save()- if (rotation !== 0) {- canvas.rotate(rotation, cx, cy)- }-- const x1 = cx - hw- const y1 = cy - hh- const x2 = cx + hw- const y2 = cy + hh-- canvas.drawRect(this.ck.LTRBRect(x1, y1, x2, y2), this.selectionPaint)-- // Corner handles- this.drawHandle(canvas, x1, y1)- this.drawHandle(canvas, x2, y1)- this.drawHandle(canvas, x1, y2)- this.drawHandle(canvas, x2, y2)-- // Edge handles- const mx = (x1 + x2) / 2- const my = (y1 + y2) / 2- this.drawHandle(canvas, mx, y1)- this.drawHandle(canvas, mx, y2)- this.drawHandle(canvas, x1, my)- this.drawHandle(canvas, x2, my)-- // Rotation handle (line extending above + circle)- const rotHandleY = y1 - ROTATION_HANDLE_OFFSET - ROTATION_HANDLE_RADIUS- this.auxStroke.setStrokeWidth(1)- this.auxStroke.setColor(this.selColor())- this.auxStroke.setPathEffect(null)- canvas.drawLine(mx, y1, mx, rotHandleY, this.auxStroke)-- this.auxFill.setColor(this.ck.WHITE)- canvas.drawCircle(mx, rotHandleY, ROTATION_HANDLE_RADIUS, this.auxFill)- canvas.drawCircle(mx, rotHandleY, ROTATION_HANDLE_RADIUS, this.auxStroke)-- canvas.restore()- }-- private drawSelectionLabels(canvas: Canvas, graph: SceneGraph, selectedIds: Set<string>): void {- if (!this.labelFont || !this.sizeFont) return-- // Compute bounding box of all selected nodes- let minX = Infinity- let minY = Infinity- let maxX = -Infinity- let maxY = -Infinity- const nodes: SceneNode[] = []-- for (const id of selectedIds) {- const node = graph.getNode(id)- if (!node) continue- nodes.push(node)- const abs = graph.getAbsolutePosition(id)- minX = Math.min(minX, abs.x)- minY = Math.min(minY, abs.y)- maxX = Math.max(maxX, abs.x + node.width)- maxY = Math.max(maxY, abs.y + node.height)- }-- if (nodes.length === 0) return-- const sx1 = minX * this.zoom + this.panX- const sy1 = minY * this.zoom + this.panY- const sx2 = maxX * this.zoom + this.panX- const sy2 = maxY * this.zoom + this.panY- const smx = (sx1 + sx2) / 2-- if (nodes.length === 1) {- const node = nodes[0]- const parentNode = node.parentId ? graph.getNode(node.parentId) : null- const isTopLevel =- !parentNode || parentNode.type === 'CANVAS' || parentNode.type === 'SECTION'- if (node.type === 'FRAME' && isTopLevel) {- this.auxFill.setColor(this.selColor())- canvas.drawText(node.name, sx1, sy1 - LABEL_OFFSET_Y, this.auxFill, this.labelFont)- }- }-- // Size widget — blue pill below selection- const w = Math.round(maxX - minX)- const h = Math.round(maxY - minY)- const sizeText = `${w} × ${h}`- const glyphIds = this.sizeFont.getGlyphIDs(sizeText)- const widths = this.sizeFont.getGlyphWidths(glyphIds)- let textWidth = 0- for (let i = 0; i < widths.length; i++) textWidth += widths[i]- const pillW = textWidth + SIZE_PILL_PADDING_X * 2- const pillH = SIZE_PILL_HEIGHT- const pillX = smx - pillW / 2- const pillY = sy2 + SIZE_PILL_PADDING_Y-- const allComponents = nodes.length > 0 && nodes.every((n) => this.isComponentType(n.type))- const pillColor = allComponents ? this.compColor() : this.selColor()-- this.auxFill.setColor(pillColor)- const rrect = this.ck.RRectXY(- this.ck.LTRBRect(pillX, pillY, pillX + pillW, pillY + pillH),- SIZE_PILL_RADIUS,- SIZE_PILL_RADIUS- )- canvas.drawRRect(rrect, this.auxFill)-- this.auxFill.setColor(this.ck.WHITE)- canvas.drawText(- sizeText,- pillX + SIZE_PILL_PADDING_X,- pillY + SIZE_PILL_TEXT_OFFSET_Y,- this.auxFill,- this.sizeFont- )- }-- private drawParentFrameOutlines(- canvas: Canvas,- graph: SceneGraph,- selectedIds: Set<string>- ): void {- const drawn = new Set<string>()- for (const id of selectedIds) {- const node = graph.getNode(id)- if (!node?.parentId) continue- const nodeParent = graph.getNode(node.parentId)- if (!nodeParent || nodeParent.type === 'CANVAS') continue- if (drawn.has(node.parentId) || selectedIds.has(node.parentId)) continue-- const parent = nodeParent-- // Skip dashed outline for top-level frames (direct children of page)- const grandparent = parent.parentId ? graph.getNode(parent.parentId) : null- if (!grandparent || grandparent.type === 'CANVAS') continue-- drawn.add(node.parentId)-- const abs = graph.getAbsolutePosition(parent.id)- const x = abs.x * this.zoom + this.panX- const y = abs.y * this.zoom + this.panY- const w = parent.width * this.zoom- const h = parent.height * this.zoom-- canvas.save()- if (parent.rotation !== 0) {- canvas.rotate(parent.rotation, x + w / 2, y + h / 2)- }- canvas.drawRect(this.ck.LTRBRect(x, y, x + w, y + h), this.parentOutlinePaint)- canvas.restore()- }- }-- private drawNodeOutline(- canvas: Canvas,- node: SceneNode,- rotation: number,- graph: SceneGraph- ): void {- const abs = graph.getAbsolutePosition(node.id)- const cx = (abs.x + node.width / 2) * this.zoom + this.panX- const cy = (abs.y + node.height / 2) * this.zoom + this.panY- const hw = (node.width / 2) * this.zoom- const hh = (node.height / 2) * this.zoom-- canvas.save()- if (rotation !== 0) {- canvas.rotate(rotation, cx, cy)- }-- canvas.drawRect(this.ck.LTRBRect(cx - hw, cy - hh, cx + hw, cy + hh), this.selectionPaint)- canvas.restore()- }-- private drawGroupBounds(canvas: Canvas, nodes: SceneNode[], graph: SceneGraph): void {- let minX = Infinity- let minY = Infinity- let maxX = -Infinity- let maxY = -Infinity-- for (const n of nodes) {- const abs = graph.getAbsolutePosition(n.id)- if (n.rotation !== 0) {- const corners = this.getRotatedCorners(n, abs)- for (const c of corners) {- minX = Math.min(minX, c.x)- minY = Math.min(minY, c.y)- maxX = Math.max(maxX, c.x)- maxY = Math.max(maxY, c.y)- }- } else {- const x1 = abs.x * this.zoom + this.panX- const y1 = abs.y * this.zoom + this.panY- const x2 = (abs.x + n.width) * this.zoom + this.panX- const y2 = (abs.y + n.height) * this.zoom + this.panY- minX = Math.min(minX, x1)- minY = Math.min(minY, y1)- maxX = Math.max(maxX, x2)- maxY = Math.max(maxY, y2)- }- }-- // Dashed bounding box- this.auxStroke.setStrokeWidth(1)- this.auxStroke.setColor(this.selColor(SELECTION_DASH_ALPHA))- this.auxStroke.setPathEffect(null)-- canvas.drawRect(this.ck.LTRBRect(minX, minY, maxX, maxY), this.auxStroke)-- // Group resize handles- this.drawHandle(canvas, minX, minY)- this.drawHandle(canvas, maxX, minY)- this.drawHandle(canvas, minX, maxY)- this.drawHandle(canvas, maxX, maxY)- const gmx = (minX + maxX) / 2- const gmy = (minY + maxY) / 2- this.drawHandle(canvas, gmx, minY)- this.drawHandle(canvas, gmx, maxY)- this.drawHandle(canvas, minX, gmy)- this.drawHandle(canvas, maxX, gmy)- }-- private getRotatedCorners(n: SceneNode, abs: { x: number; y: number }) {- const cx = (abs.x + n.width / 2) * this.zoom + this.panX- const cy = (abs.y + n.height / 2) * this.zoom + this.panY- const hw = (n.width / 2) * this.zoom- const hh = (n.height / 2) * this.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 }- ]- }-- private drawHandle(canvas: Canvas, x: number, y: number): void {- this.auxFill.setColor(this.ck.WHITE)- const rect = this.ck.LTRBRect(- x - HANDLE_HALF_SIZE,- y - HANDLE_HALF_SIZE,- x + HANDLE_HALF_SIZE,- y + HANDLE_HALF_SIZE- )- canvas.drawRect(rect, this.auxFill)- canvas.drawRect(rect, this.selectionPaint)- }-- // --- Snap guides ----- private drawSnapGuides(canvas: Canvas, guides?: SnapGuide[]): void {- if (!guides || guides.length === 0) return-- for (const guide of guides) {- if (guide.axis === 'x') {- const x = guide.position * this.zoom + this.panX- const y1 = guide.from * this.zoom + this.panY- const y2 = guide.to * this.zoom + this.panY- canvas.drawLine(x, y1, x, y2, this.snapPaint)- } else {- const y = guide.position * this.zoom + this.panY- const x1 = guide.from * this.zoom + this.panX- const x2 = guide.to * this.zoom + this.panX- canvas.drawLine(x1, y, x2, y, this.snapPaint)- }- }- }-- // --- Marquee ----- private drawMarquee(canvas: Canvas, marquee?: Rect | null): void {- if (!marquee || marquee.width <= 0 || marquee.height <= 0) return-- const x1 = marquee.x * this.zoom + this.panX- const y1 = marquee.y * this.zoom + this.panY- const x2 = (marquee.x + marquee.width) * this.zoom + this.panX- const y2 = (marquee.y + marquee.height) * this.zoom + this.panY- const rect = this.ck.LTRBRect(x1, y1, x2, y2)-- this.auxFill.setColor(this.selColor(MARQUEE_FILL_ALPHA))- canvas.drawRect(rect, this.auxFill)- canvas.drawRect(rect, this.selectionPaint)- }-- // --- Layout insert indicator ----- private drawLayoutInsertIndicator(- canvas: Canvas,- indicator?: RenderOverlays['layoutInsertIndicator']- ): void {- if (!indicator) return-- this.auxStroke.setStrokeWidth(LAYOUT_INDICATOR_STROKE)- this.auxStroke.setColor(this.selColor())- this.auxStroke.setPathEffect(null)-- if (indicator.direction === 'HORIZONTAL') {- const y = indicator.y * this.zoom + this.panY- const x1 = indicator.x * this.zoom + this.panX- const x2 = (indicator.x + indicator.length) * this.zoom + this.panX- canvas.drawLine(x1, y, x2, y, this.auxStroke)- } else {- const x = indicator.x * this.zoom + this.panX- const y1 = indicator.y * this.zoom + this.panY- const y2 = (indicator.y + indicator.length) * this.zoom + this.panY- canvas.drawLine(x, y1, x, y2, this.auxStroke)- }- }-- // --- Scene rendering ----- private renderNode(- canvas: Canvas,- graph: SceneGraph,- nodeId: string,- overlays: RenderOverlays,- parentAbsX = 0,- parentAbsY = 0- ): void {- const node = graph.getNode(nodeId)- if (!node || !node.visible) return-- const absX = parentAbsX + node.x- const absY = parentAbsY + node.y-- // Viewport culling: skip nodes entirely outside the visible area.- // Only cull leaf nodes and clipped containers — unclipped containers- // may have children that extend beyond the parent's bounds.- const canCull =- node.childIds.length === 0 ||- ((node.type === 'FRAME' || node.type === 'COMPONENT' || node.type === 'INSTANCE') &&- node.clipsContent)- if (canCull) {- const vp = this.worldViewport- // Expand bounds for rotation (diagonal is the max extent)- let bw = node.width- let bh = node.height- if (node.rotation !== 0) {- const diag = Math.sqrt(bw * bw + bh * bh)- const cx = absX + bw / 2- const cy = absY + bh / 2- if (- cx - diag / 2 > vp.x + vp.w ||- cy - diag / 2 > vp.y + vp.h ||- cx + diag / 2 < vp.x ||- cy + diag / 2 < vp.y- ) {- return- }- } else if (absX > vp.x + vp.w || absY > vp.y + vp.h || absX + bw < vp.x || absY + bh < vp.y) {- return- }- }-- canvas.save()- canvas.translate(node.x, node.y)-- if (node.opacity < 1) {- this.opacityPaint.setAlphaf(node.opacity)- canvas.saveLayer(this.opacityPaint)- }-- const rotation =- overlays.rotationPreview?.nodeId === nodeId ? overlays.rotationPreview.angle : node.rotation-- if (rotation !== 0) {- canvas.rotate(rotation, node.width / 2, node.height / 2)- }-- if (node.type === 'SECTION') {- this.renderSection(canvas, node, graph)- } else if (node.type === 'COMPONENT_SET') {- this.renderComponentSet(canvas, node, graph)- } else if (overlays.editingTextId !== nodeId) {- this.renderShape(canvas, node, graph)- }-- // Drop target highlight- if (overlays.dropTargetId === nodeId) {- this.auxStroke.setStrokeWidth(DROP_HIGHLIGHT_STROKE / this.zoom)- this.auxStroke.setColor(this.selColor(DROP_HIGHLIGHT_ALPHA))- canvas.drawRect(this.ck.LTRBRect(0, 0, node.width, node.height), this.auxStroke)- }-- // Hover highlight — shape-aware outline- if (overlays.hoveredNodeId === nodeId) {- this.auxStroke.setStrokeWidth(1 / this.zoom)- this.auxStroke.setColor(this.isComponentType(node.type) ? this.compColor() : this.selColor())- this.auxStroke.setPathEffect(null)- this.strokeNodeShape(canvas, node, this.auxStroke)- }-- // Clip + render children for containers- const isClippableContainer =- node.type === 'FRAME' || node.type === 'COMPONENT' || node.type === 'INSTANCE'- if (isClippableContainer && node.clipsContent && node.childIds.length > 0) {- canvas.save()- canvas.clipRect(- this.ck.LTRBRect(0, 0, node.width, node.height),- this.ck.ClipOp.Intersect,- true- )- for (const childId of node.childIds) {- this.renderNode(canvas, graph, childId, overlays, absX, absY)- }- canvas.restore()- } else {- for (const childId of node.childIds) {- this.renderNode(canvas, graph, childId, overlays, absX, absY)- }- }-- if (node.opacity < 1) {- canvas.restore()- }- canvas.restore()- }-- private strokeNodeShape(canvas: Canvas, node: SceneNode, paint: Paint): void {- const rect = this.ck.LTRBRect(0, 0, node.width, node.height)-- switch (node.type) {- case 'ELLIPSE':- canvas.drawOval(rect, paint)- return- case 'VECTOR':- if (node.vectorNetwork) {- const vp = vectorNetworkToPath(this.ck, node.vectorNetwork)- canvas.drawPath(vp, paint)- vp.delete()- }- return- case 'LINE':- canvas.drawLine(0, 0, node.width, node.height, paint)- return- case 'POLYGON':- case 'STAR': {- const path = this.makePolygonPath(node)- canvas.drawPath(path, paint)- path.delete()- return- }- }-- const hasRadius =- node.cornerRadius > 0 ||- (node.independentCorners &&- (node.topLeftRadius > 0 ||- node.topRightRadius > 0 ||- node.bottomRightRadius > 0 ||- node.bottomLeftRadius > 0))-- if (hasRadius) {- if (node.independentCorners) {- const rrect = new Float32Array([- 0,- 0,- node.width,- node.height,- node.topLeftRadius,- node.topLeftRadius,- node.topRightRadius,- node.topRightRadius,- node.bottomRightRadius,- node.bottomRightRadius,- node.bottomLeftRadius,- node.bottomLeftRadius- ])- canvas.drawRRect(rrect, paint)- } else {- canvas.drawRRect(this.ck.RRectXY(rect, node.cornerRadius, node.cornerRadius), paint)- }- } else {- canvas.drawRect(rect, paint)- }- }-- private renderSection(canvas: Canvas, node: SceneNode, graph: SceneGraph): void {- const rect = this.ck.LTRBRect(0, 0, node.width, node.height)- const rrect = this.ck.RRectXY(rect, SECTION_CORNER_RADIUS, SECTION_CORNER_RADIUS)-- // Fill- for (const fill of node.fills) {- if (!fill.visible) continue- this.applyFill(fill, node, graph)- this.fillPaint.setAlphaf(fill.opacity)- canvas.drawRRect(rrect, this.fillPaint)- this.fillPaint.setShader(null)- }-- // Stroke- for (const stroke of node.strokes) {- if (!stroke.visible) continue- this.strokePaint.setColor(- this.ck.Color4f(stroke.color.r, stroke.color.g, stroke.color.b, stroke.color.a)- )- this.strokePaint.setStrokeWidth(stroke.weight)- this.strokePaint.setAlphaf(stroke.opacity)- canvas.drawRRect(rrect, this.strokePaint)- }- }-- private drawSectionTitles(canvas: Canvas, graph: SceneGraph): void {- if (!this.sectionTitleFont) return-- const pageNode = graph.getNode(this.pageId ?? graph.rootId)- if (!pageNode) return-- const sections: { node: SceneNode; absX: number; absY: number; nested: boolean }[] = []- const collectSections = (parentId: string, ox: number, oy: number, insideSection: boolean) => {- const parent = graph.getNode(parentId)- if (!parent) return- for (const childId of parent.childIds) {- const child = graph.getNode(childId)- if (!child || !child.visible) continue- const ax = ox + child.x- const ay = oy + child.y- if (child.type === 'SECTION') {- const vp = this.worldViewport- if (- ax + child.width >= vp.x &&- ay + child.height >= vp.y &&- ax <= vp.x + vp.w &&- ay <= vp.y + vp.h- ) {- sections.push({ node: child, absX: ax, absY: ay, nested: insideSection })- }- collectSections(childId, ax, ay, true)- } else if (child.childIds.length > 0) {- collectSections(childId, ax, ay, insideSection)- }- }- }- collectSections(pageNode.id, 0, 0, false)-- const font = this.sectionTitleFont- const ellipsis = '…'- const ellipsisGlyphs = font.getGlyphIDs(ellipsis)- const ellipsisWidth = font.getGlyphWidths(ellipsisGlyphs)[0]-- for (const { node, absX, absY, nested } of sections) {- const screenX = absX * this.zoom + this.panX- const screenY = absY * this.zoom + this.panY- const screenW = node.width * this.zoom- const maxPillW = Math.max(screenW, 0)-- const glyphIds = font.getGlyphIDs(node.name)- const widths = font.getGlyphWidths(glyphIds)-- let fullTextWidth = 0- for (const w of widths) fullTextWidth += w-- const maxTextW = maxPillW - SECTION_TITLE_PADDING_X * 2- let displayText = node.name- let textWidth = fullTextWidth-- if (textWidth > maxTextW && maxTextW > ellipsisWidth) {- let truncW = 0- let truncIdx = 0- for (let i = 0; i < widths.length; i++) {- if (truncW + widths[i] + ellipsisWidth > maxTextW) break- truncW += widths[i]- truncIdx = i + 1- }- displayText = node.name.slice(0, truncIdx) + ellipsis- textWidth = truncW + ellipsisWidth- } else if (maxTextW <= ellipsisWidth) {- displayText = ellipsis- textWidth = ellipsisWidth- }-- const pillW = Math.min(textWidth + SECTION_TITLE_PADDING_X * 2, maxPillW)- const pillH = SECTION_TITLE_HEIGHT- const pillX = screenX- const pillY = nested ? screenY + SECTION_TITLE_GAP : screenY - pillH - SECTION_TITLE_GAP-- if (node.fills.length > 0 && node.fills[0].visible) {- const c = node.fills[0].color- this.auxFill.setColor(this.ck.Color4f(c.r, c.g, c.b, node.fills[0].opacity))- } else {- this.auxFill.setColor(this.ck.Color4f(0.37, 0.37, 0.37, 1))- }- const pillRect = this.ck.LTRBRect(pillX, pillY, pillX + pillW, pillY + pillH)- canvas.drawRRect(- this.ck.RRectXY(pillRect, SECTION_TITLE_RADIUS, SECTION_TITLE_RADIUS),- this.auxFill- )-- const pillColor =- node.fills.length > 0 && node.fills[0].visible- ? node.fills[0].color- : { r: 0.37, g: 0.37, b: 0.37 }- const lum = 0.299 * pillColor.r + 0.587 * pillColor.g + 0.114 * pillColor.b- this.auxFill.setColor(lum > 0.5 ? this.ck.BLACK : this.ck.WHITE)- const textY = pillY + pillH * 0.7- canvas.drawText(displayText, pillX + SECTION_TITLE_PADDING_X, textY, this.auxFill, font)- }- }-- private drawComponentLabels(canvas: Canvas, graph: SceneGraph): void {- if (!this.componentLabelFont) return-- const pageNode = graph.getNode(this.pageId ?? graph.rootId)- if (!pageNode) return-- const font = this.componentLabelFont- const LABEL_TYPES = new Set(['COMPONENT', 'COMPONENT_SET', 'INSTANCE'])-- const nodes: { node: SceneNode; absX: number; absY: number; inside: boolean }[] = []- const collect = (parentId: string, ox: number, oy: number) => {- const parent = graph.getNode(parentId)- if (!parent) return- for (const childId of parent.childIds) {- const child = graph.getNode(childId)- if (!child || !child.visible) continue- const ax = ox + child.x- const ay = oy + child.y- if (LABEL_TYPES.has(child.type)) {- const vp = this.worldViewport- if (- ax + child.width >= vp.x &&- ay + child.height >= vp.y &&- ax <= vp.x + vp.w &&- ay <= vp.y + vp.h- ) {- const isInsideSet = parent.type === 'COMPONENT_SET'- nodes.push({ node: child, absX: ax, absY: ay, inside: isInsideSet })- }- }- if (child.childIds.length > 0) {- collect(childId, ax, ay)- }- }- }- collect(pageNode.id, 0, 0)-- const compColor = this.compColor()-- // Diamond icon path points (scaled to COMPONENT_LABEL_ICON_SIZE)- const iconS = COMPONENT_LABEL_ICON_SIZE-- for (const { node, absX, absY, inside } of nodes) {- const screenX = absX * this.zoom + this.panX- const screenY = absY * this.zoom + this.panY-- // Position: inside top-left for variants in a set, above top-left otherwise- const labelX = screenX- let labelY: number- if (inside) {- labelY = screenY + COMPONENT_LABEL_GAP + COMPONENT_LABEL_FONT_SIZE- } else {- labelY = screenY - COMPONENT_LABEL_GAP- }-- // Draw diamond icon- const iconX = labelX- const iconY = labelY - COMPONENT_LABEL_FONT_SIZE * 0.75- const iconCx = iconX + iconS / 2- const iconCy = iconY + iconS / 2- const iconR = iconS / 2-- this.auxFill.setColor(compColor)-- if (node.type === 'COMPONENT_SET') {- const s = iconR * 0.45- const gap = iconR * 0.2- const path = new this.ck.Path()- for (const [dx, dy] of [- [-1, -1],- [1, -1],- [-1, 1],- [1, 1]- ]) {- const cx = iconCx + dx * (s + gap)- const cy = iconCy + dy * (s + gap)- path.moveTo(cx, cy - s)- path.lineTo(cx + s, cy)- path.lineTo(cx, cy + s)- path.lineTo(cx - s, cy)- path.close()- }- canvas.drawPath(path, this.auxFill)- path.delete()- } else {- const path = new this.ck.Path()- path.moveTo(iconCx, iconCy - iconR)- path.lineTo(iconCx + iconR, iconCy)- path.lineTo(iconCx, iconCy + iconR)- path.lineTo(iconCx - iconR, iconCy)- path.close()- canvas.drawPath(path, this.auxFill)- path.delete()- }-- canvas.drawText(- node.name,- labelX + iconS + COMPONENT_LABEL_ICON_GAP,- labelY,- this.auxFill,- font- )- }- }-- private renderComponentSet(canvas: Canvas, node: SceneNode, graph: SceneGraph): void {- const rect = this.ck.LTRBRect(0, 0, node.width, node.height)- const rrect = this.ck.RRectXY(rect, 5, 5)-- for (const fill of node.fills) {- if (!fill.visible) continue- this.applyFill(fill, node, graph)- this.fillPaint.setAlphaf(fill.opacity)- canvas.drawRRect(rrect, this.fillPaint)- this.fillPaint.setShader(null)- }-- this.auxStroke.setStrokeWidth(COMPONENT_SET_BORDER_WIDTH / this.zoom)- this.auxStroke.setColor(this.compColor())- this.auxStroke.setPathEffect(- this.ck.PathEffect.MakeDash(- [COMPONENT_SET_DASH / this.zoom, COMPONENT_SET_DASH_GAP / this.zoom],- 0- )- )- canvas.drawRRect(rrect, this.auxStroke)- this.auxStroke.setPathEffect(null)- }-- private renderShape(canvas: Canvas, node: SceneNode, graph: SceneGraph): void {- const rect = this.ck.LTRBRect(0, 0, node.width, node.height)-- const hasRadius =- node.cornerRadius > 0 ||- (node.independentCorners &&- (node.topLeftRadius > 0 ||- node.topRightRadius > 0 ||- node.bottomRightRadius > 0 ||- node.bottomLeftRadius > 0))-- // Fills- for (const fill of node.fills) {- if (!fill.visible) continue- this.applyFill(fill, node, graph)- this.fillPaint.setAlphaf(fill.opacity)-- this.drawNodeFill(canvas, node, rect, hasRadius)- this.fillPaint.setShader(null)- }-- // Effects (behind: drop shadow)- this.renderEffects(canvas, node, rect, hasRadius, 'behind')-- // Strokes- for (const stroke of node.strokes) {- if (!stroke.visible) continue- this.strokePaint.setColor(- this.ck.Color4f(stroke.color.r, stroke.color.g, stroke.color.b, stroke.color.a)- )- this.strokePaint.setStrokeWidth(stroke.weight)- this.strokePaint.setAlphaf(stroke.opacity)-- if (stroke.cap) {- const capMap: Record<string, EmbindEnumEntity> = {- NONE: this.ck.StrokeCap.Butt,- ROUND: this.ck.StrokeCap.Round,- SQUARE: this.ck.StrokeCap.Square- }- this.strokePaint.setStrokeCap(capMap[stroke.cap] ?? this.ck.StrokeCap.Butt)- }- if (stroke.join) {- const joinMap: Record<string, EmbindEnumEntity> = {- MITER: this.ck.StrokeJoin.Miter,- ROUND: this.ck.StrokeJoin.Round,- BEVEL: this.ck.StrokeJoin.Bevel- }- this.strokePaint.setStrokeJoin(joinMap[stroke.join] ?? this.ck.StrokeJoin.Miter)- }- if (stroke.dashPattern && stroke.dashPattern.length > 0) {- this.strokePaint.setPathEffect(this.ck.PathEffect.MakeDash(stroke.dashPattern, 0))- } else {- this.strokePaint.setPathEffect(null)- }-- this.drawNodeStroke(canvas, node, rect, hasRadius)- }-- // Effects (front: inner shadow, blur)- this.renderEffects(canvas, node, rect, hasRadius, 'front')- }-- private drawNodeFill(- canvas: Canvas,- node: SceneNode,- rect: Float32Array,- hasRadius: boolean- ): void {- switch (node.type) {- case 'VECTOR':- if (node.vectorNetwork) {- const vp = vectorNetworkToPath(this.ck, node.vectorNetwork)- canvas.drawPath(vp, this.fillPaint)- vp.delete()- }- break- case 'ELLIPSE':- if (node.arcData) {- this.drawArc(canvas, node, this.fillPaint)- } else {- canvas.drawOval(rect, this.fillPaint)- }- break- case 'TEXT':- this.renderText(canvas, node)- break- case 'LINE':- canvas.drawLine(0, 0, node.width, node.height, this.fillPaint)- break- case 'POLYGON':- case 'STAR': {- const path = this.makePolygonPath(node)- canvas.drawPath(path, this.fillPaint)- path.delete()- break- }- default:- if (hasRadius) {- canvas.drawRRect(this.makeRRect(node), this.fillPaint)- } else {- canvas.drawRect(rect, this.fillPaint)- }- }- }-- private drawNodeStroke(- canvas: Canvas,- node: SceneNode,- rect: Float32Array,- hasRadius: boolean- ): void {- switch (node.type) {- case 'VECTOR':- if (node.vectorNetwork) {- const vp = vectorNetworkToPath(this.ck, node.vectorNetwork)- canvas.drawPath(vp, this.strokePaint)- vp.delete()- }- break- case 'ELLIPSE':- if (node.arcData) {- this.drawArc(canvas, node, this.strokePaint)- } else {- canvas.drawOval(rect, this.strokePaint)- }- break- case 'POLYGON':- case 'STAR': {- const path = this.makePolygonPath(node)- canvas.drawPath(path, this.strokePaint)- path.delete()- break- }- default:- if (hasRadius) {- canvas.drawRRect(this.makeRRect(node), this.strokePaint)- } else {- canvas.drawRect(rect, this.strokePaint)- }- }- }-- private makePolygonPath(node: SceneNode): Path {- const path = new this.ck.Path()- const cx = node.width / 2- const cy = node.height / 2- const rx = node.width / 2- const ry = node.height / 2- const n = Math.max(3, node.pointCount)- const isStar = node.type === 'STAR'- const innerRatio = isStar ? node.starInnerRadius : 1- const totalPoints = isStar ? n * 2 : n- const angleOffset = -Math.PI / 2-- for (let i = 0; i < totalPoints; i++) {- const angle = angleOffset + (2 * Math.PI * i) / totalPoints- const isInner = isStar && i % 2 === 1- const r = isInner ? innerRatio : 1- const px = cx + rx * r * Math.cos(angle)- const py = cy + ry * r * Math.sin(angle)- if (i === 0) path.moveTo(px, py)- else path.lineTo(px, py)- }- path.close()- return path- }-- private makeRRect(node: SceneNode): Float32Array {- if (node.independentCorners) {- return new Float32Array([- 0,- 0,- node.width,- node.height,- node.topLeftRadius,- node.topLeftRadius,- node.topRightRadius,- node.topRightRadius,- node.bottomRightRadius,- node.bottomRightRadius,- node.bottomLeftRadius,- node.bottomLeftRadius- ])- }- return this.ck.RRectXY(- this.ck.LTRBRect(0, 0, node.width, node.height),- node.cornerRadius,- node.cornerRadius- )- }-- private drawArc(canvas: Canvas, node: SceneNode, paint: Paint): void {- const arc = node.arcData- if (!arc) return- const cx = node.width / 2- const cy = node.height / 2- const rx = node.width / 2- const ry = node.height / 2- const innerRx = rx * arc.innerRadius- const innerRy = ry * arc.innerRadius-- const startDeg = arc.startingAngle * (180 / Math.PI)- const endDeg = arc.endingAngle * (180 / Math.PI)- const sweepDeg = endDeg - startDeg-- const path = new this.ck.Path()- const oval = this.ck.LTRBRect(0, 0, node.width, node.height)-- if (arc.innerRadius > 0) {- // Donut shape- path.addArc(oval, startDeg, sweepDeg)- const innerOval = this.ck.LTRBRect(cx - innerRx, cy - innerRy, cx + innerRx, cy + innerRy)- const innerPath = new this.ck.Path()- innerPath.addArc(innerOval, startDeg + sweepDeg, -sweepDeg)- path.addPath(innerPath)- path.close()- innerPath.delete()- } else {- const isFullCircle = Math.abs(sweepDeg) >= 359.99- if (isFullCircle) {- path.addOval(oval)- } else {- path.moveTo(cx, cy)- path.addArc(oval, startDeg, sweepDeg)- path.close()- }- }-- canvas.drawPath(path, paint)- path.delete()- }-- private renderEffects(- canvas: Canvas,- node: SceneNode,- rect: Float32Array,- hasRadius: boolean,- pass: 'behind' | 'front'- ): void {- for (const effect of node.effects) {- if (!effect.visible) continue-- if (pass === 'behind' && effect.type === 'DROP_SHADOW') {- this.auxFill.setColor(- this.ck.Color4f(effect.color.r, effect.color.g, effect.color.b, effect.color.a)- )- this.auxFill.setImageFilter(- this.ck.ImageFilter.MakeBlur(effect.radius, effect.radius, this.ck.TileMode.Decal, null)- )-- canvas.save()- canvas.translate(effect.offset.x, effect.offset.y)- if (node.type === 'ELLIPSE') {- canvas.drawOval(rect, this.auxFill)- } else if (hasRadius) {- canvas.drawRRect(this.makeRRect(node), this.auxFill)- } else {- canvas.drawRect(rect, this.auxFill)- }- canvas.restore()- this.auxFill.setImageFilter(null)- }-- if (pass === 'front' && effect.type === 'LAYER_BLUR') {- // Layer blur applied as save layer with blur filter — already applied via opacity layer- }-- if (pass === 'front' && effect.type === 'INNER_SHADOW') {- // Inner shadow: draw a shadow clipped to the node shape- this.auxFill.setColor(- this.ck.Color4f(effect.color.r, effect.color.g, effect.color.b, effect.color.a)- )- this.auxFill.setImageFilter(- this.ck.ImageFilter.MakeBlur(effect.radius, effect.radius, this.ck.TileMode.Decal, null)- )-- canvas.save()- if (node.type === 'ELLIPSE') {- const path = new this.ck.Path()- path.addOval(rect)- canvas.clipPath(path, this.ck.ClipOp.Intersect, true)- path.delete()- } else if (hasRadius) {- canvas.clipRRect(this.makeRRect(node), this.ck.ClipOp.Intersect, true)- } else {- canvas.clipRect(rect, this.ck.ClipOp.Intersect, true)- }-- // Draw inverted shape offset by shadow offset- const big = this.ck.LTRBRect(- -effect.radius * 2 + effect.offset.x,- -effect.radius * 2 + effect.offset.y,- node.width + effect.radius * 2 + effect.offset.x,- node.height + effect.radius * 2 + effect.offset.y- )- const bigPath = new this.ck.Path()- bigPath.addRect(big)- if (node.type === 'ELLIPSE') {- const innerPath = new this.ck.Path()- const offsetRect = this.ck.LTRBRect(- effect.offset.x,- effect.offset.y,- node.width + effect.offset.x,- node.height + effect.offset.y- )- innerPath.addOval(offsetRect)- bigPath.op(innerPath, this.ck.PathOp.Difference)- innerPath.delete()- } else {- const innerPath = new this.ck.Path()- innerPath.addRect(- this.ck.LTRBRect(- effect.offset.x,- effect.offset.y,- node.width + effect.offset.x,- node.height + effect.offset.y- )- )- bigPath.op(innerPath, this.ck.PathOp.Difference)- innerPath.delete()- }- canvas.drawPath(bigPath, this.auxFill)- bigPath.delete()- canvas.restore()- this.auxFill.setImageFilter(null)- }- }- }-- private renderText(canvas: Canvas, node: SceneNode): void {- const text = node.text- if (!text) return-- if (this.fontsLoaded && this.fontProvider) {- const paraStyle = new this.ck.ParagraphStyle({- textAlign: this.getTextAlign(node.textAlignHorizontal),- textStyle: {- color: this.fillPaint.getColor(),- fontFamilies: [node.fontFamily || 'Inter'],- fontSize: node.fontSize || DEFAULT_FONT_SIZE,- fontStyle: { weight: { value: node.fontWeight || 400 } as FontWeight },- letterSpacing: node.letterSpacing || 0,- heightMultiplier: node.lineHeight- ? node.lineHeight / (node.fontSize || DEFAULT_FONT_SIZE)- : undefined- }- })- const builder = this.ck.ParagraphBuilder.MakeFromFontProvider(paraStyle, this.fontProvider)- builder.addText(text)- const paragraph = builder.build()- paragraph.layout(node.width || 1e6)- canvas.drawParagraph(paragraph, 0, 0)- paragraph.delete()- builder.delete()- } else if (this.textFont) {- canvas.drawText(text, 0, node.fontSize || DEFAULT_FONT_SIZE, this.fillPaint, this.textFont)- }- }-- private getTextAlign(align: string) {- switch (align) {- case 'CENTER':- return this.ck.TextAlign.Center- case 'RIGHT':- return this.ck.TextAlign.Right- case 'JUSTIFIED':- return this.ck.TextAlign.Justify- default:- return this.ck.TextAlign.Left- }- }-- private applyFill(fill: Fill, node: SceneNode, graph: SceneGraph): void {- this.fillPaint.setShader(null)-- if (fill.type === 'SOLID') {- this.fillPaint.setColor(- this.ck.Color4f(fill.color.r, fill.color.g, fill.color.b, fill.color.a)- )- return- }-- if (fill.type.startsWith('GRADIENT') && fill.gradientStops && fill.gradientTransform) {- this.applyGradientFill(fill, node)- return- }-- if (fill.type === 'IMAGE' && fill.imageHash) {- this.applyImageFill(fill, node, graph)- return- }- }-- private applyGradientFill(fill: Fill, node: SceneNode): void {- const stops = fill.gradientStops- const t = fill.gradientTransform- if (!stops || !t) return- const colors = stops.map((s) => this.ck.Color4f(s.color.r, s.color.g, s.color.b, s.color.a))- const positions = stops.map((s) => s.position)-- // Figma gradient transform maps unit square to node bounds- // Convert transform to canvas coordinates- const w = node.width- const h = node.height-- if (fill.type === 'GRADIENT_LINEAR') {- // Start and end points derived from transform- const startX = t.m02 * w- const startY = t.m12 * h- const endX = (t.m00 + t.m02) * w- const endY = (t.m10 + t.m12) * h- const shader = this.ck.Shader.MakeLinearGradient(- [startX, startY],- [endX, endY],- colors,- positions,- this.ck.TileMode.Clamp- )- this.fillPaint.setShader(shader)- } else if (fill.type === 'GRADIENT_RADIAL') {- const cx = t.m02 * w- const cy = t.m12 * h- const radius = Math.sqrt(t.m00 * t.m00 + t.m10 * t.m10) * Math.max(w, h)- const shader = this.ck.Shader.MakeRadialGradient(- [cx, cy],- radius,- colors,- positions,- this.ck.TileMode.Clamp- )- this.fillPaint.setShader(shader)- } else if (fill.type === 'GRADIENT_ANGULAR') {- const cx = t.m02 * w- const cy = t.m12 * h- const shader = this.ck.Shader.MakeSweepGradient(- cx,- cy,- colors,- positions,- this.ck.TileMode.Clamp,- // Figma angular gradients start from right (0°), CanvasKit sweep from right too- undefined- )- this.fillPaint.setShader(shader)- } else if (fill.type === 'GRADIENT_DIAMOND') {- // Diamond gradient approximated as radial- const cx = t.m02 * w- const cy = t.m12 * h- const radius = Math.sqrt(t.m00 * t.m00 + t.m10 * t.m10) * Math.max(w, h)- const shader = this.ck.Shader.MakeRadialGradient(- [cx, cy],- radius,- colors,- positions,- this.ck.TileMode.Clamp- )- this.fillPaint.setShader(shader)- }- }-- private applyImageFill(fill: Fill, node: SceneNode, graph: SceneGraph): void {- const hash = fill.imageHash- if (!hash) return- let img = this.imageCache.get(hash)- if (!img) {- const data = graph.images.get(hash)- if (!data) return- img = this.ck.MakeImageFromEncoded(data) ?? undefined- if (img) this.imageCache.set(hash, img)- else return- }-- const imgW = img.width()- const imgH = img.height()- const scaleMode = fill.imageScaleMode ?? 'FILL'-- let sx: number, sy: number, sw: number, sh: number- if (scaleMode === 'FILL') {- const scale = Math.max(node.width / imgW, node.height / imgH)- sw = node.width / scale- sh = node.height / scale- sx = (imgW - sw) / 2- sy = (imgH - sh) / 2- } else if (scaleMode === 'FIT') {- sw = imgW- sh = imgH- sx = 0- sy = 0- // FIT: image centered within bounds — handled by shader matrix- } else {- sx = 0- sy = 0- sw = imgW- sh = imgH- }-- const shader = img.makeShaderCubic(- this.ck.TileMode.Clamp,- this.ck.TileMode.Clamp,- 1 / 3,- 1 / 3,- this.ck.Matrix.multiply(- this.ck.Matrix.scaled(node.width / sw, node.height / sh),- this.ck.Matrix.translated(-sx, -sy)- )- )- this.fillPaint.setShader(shader)- }-- screenToCanvas(sx: number, sy: number): { x: number; y: number } {- return {- x: (sx - this.panX) / this.zoom,- y: (sy - this.panY) / this.zoom- }- }-- private drawPenOverlay(canvas: Canvas, penState: RenderOverlays['penState']): void {- if (!penState || penState.vertices.length === 0) return-- const { vertices, segments, dragTangent, cursorX, cursorY } = penState- const pathPaint = new this.ck.Paint()- pathPaint.setStyle(this.ck.PaintStyle.Stroke)- pathPaint.setStrokeWidth(PEN_PATH_STROKE_WIDTH)- pathPaint.setColor(this.selColor())- pathPaint.setAntiAlias(true)-- const handlePaint = new this.ck.Paint()- handlePaint.setStyle(this.ck.PaintStyle.Stroke)- handlePaint.setStrokeWidth(1)- handlePaint.setColor(this.selColor(PARENT_OUTLINE_ALPHA))- handlePaint.setAntiAlias(true)-- const vertexFill = new this.ck.Paint()- vertexFill.setStyle(this.ck.PaintStyle.Fill)- vertexFill.setColor(this.ck.WHITE)- vertexFill.setAntiAlias(true)-- const vertexStroke = new this.ck.Paint()- vertexStroke.setStyle(this.ck.PaintStyle.Stroke)- vertexStroke.setStrokeWidth(PEN_PATH_STROKE_WIDTH)- vertexStroke.setColor(this.selColor())- vertexStroke.setAntiAlias(true)-- const toScreen = (x: number, y: number) => ({- x: x * this.zoom + this.panX,- y: y * this.zoom + this.panY- })-- // Draw existing segments- const path = new this.ck.Path()- for (const seg of segments) {- const s = toScreen(vertices[seg.start].x, vertices[seg.start].y)- const e = toScreen(vertices[seg.end].x, vertices[seg.end].y)- path.moveTo(s.x, s.y)-- const isLine =- seg.tangentStart.x === 0 &&- seg.tangentStart.y === 0 &&- seg.tangentEnd.x === 0 &&- seg.tangentEnd.y === 0- if (isLine) {- path.lineTo(e.x, e.y)- } else {- const cp1 = toScreen(- vertices[seg.start].x + seg.tangentStart.x,- vertices[seg.start].y + seg.tangentStart.y- )- const cp2 = toScreen(- vertices[seg.end].x + seg.tangentEnd.x,- vertices[seg.end].y + seg.tangentEnd.y- )- path.cubicTo(cp1.x, cp1.y, cp2.x, cp2.y, e.x, e.y)- }- }-- // Preview line from last vertex to cursor- if (vertices.length > 0 && cursorX != null && cursorY != null) {- const last = toScreen(vertices[vertices.length - 1].x, vertices[vertices.length - 1].y)- const cursor = toScreen(cursorX, cursorY)- path.moveTo(last.x, last.y)- if (dragTangent) {- const cp1 = toScreen(- vertices[vertices.length - 1].x + dragTangent.x,- vertices[vertices.length - 1].y + dragTangent.y- )- path.cubicTo(cp1.x, cp1.y, cursor.x, cursor.y, cursor.x, cursor.y)- } else {- path.lineTo(cursor.x, cursor.y)- }- }-- canvas.drawPath(path, pathPaint)- path.delete()-- // Draw tangent handle lines- for (const seg of segments) {- const ts = seg.tangentStart- const te = seg.tangentEnd- if (ts.x !== 0 || ts.y !== 0) {- const s = toScreen(vertices[seg.start].x, vertices[seg.start].y)- const cp = toScreen(vertices[seg.start].x + ts.x, vertices[seg.start].y + ts.y)- canvas.drawLine(s.x, s.y, cp.x, cp.y, handlePaint)- canvas.drawCircle(cp.x, cp.y, PEN_HANDLE_RADIUS, vertexFill)- canvas.drawCircle(cp.x, cp.y, PEN_HANDLE_RADIUS, handlePaint)- }- if (te.x !== 0 || te.y !== 0) {- const e = toScreen(vertices[seg.end].x, vertices[seg.end].y)- const cp = toScreen(vertices[seg.end].x + te.x, vertices[seg.end].y + te.y)- canvas.drawLine(e.x, e.y, cp.x, cp.y, handlePaint)- canvas.drawCircle(cp.x, cp.y, PEN_HANDLE_RADIUS, vertexFill)- canvas.drawCircle(cp.x, cp.y, PEN_HANDLE_RADIUS, handlePaint)- }- }-- // Draw current drag tangent handles- if (dragTangent && vertices.length > 0) {- const last = vertices[vertices.length - 1]- const cp1 = toScreen(last.x + dragTangent.x, last.y + dragTangent.y)- const cp2 = toScreen(last.x - dragTangent.x, last.y - dragTangent.y)- canvas.drawLine(cp2.x, cp2.y, cp1.x, cp1.y, handlePaint)- canvas.drawCircle(cp1.x, cp1.y, PEN_HANDLE_RADIUS, vertexFill)- canvas.drawCircle(cp1.x, cp1.y, PEN_HANDLE_RADIUS, handlePaint)- canvas.drawCircle(cp2.x, cp2.y, PEN_HANDLE_RADIUS, vertexFill)- canvas.drawCircle(cp2.x, cp2.y, PEN_HANDLE_RADIUS, handlePaint)- }-- // Draw vertices- for (let i = 0; i < vertices.length; i++) {- const v = toScreen(vertices[i].x, vertices[i].y)- const radius =- i === 0 && penState.closingToFirst- ? PEN_VERTEX_RADIUS + PEN_CLOSE_RADIUS_BOOST- : PEN_VERTEX_RADIUS- canvas.drawCircle(v.x, v.y, radius, vertexFill)- canvas.drawCircle(v.x, v.y, radius, vertexStroke)- }-- pathPaint.delete()- handlePaint.delete()- vertexFill.delete()- vertexStroke.delete()- }-- // --- Rulers ----- private drawRulers(canvas: Canvas, graph: SceneGraph, selectedIds: Set<string>): void {- const R = RULER_SIZE- const vw = this.viewportWidth- const vh = this.viewportHeight- if (vw === 0 || vh === 0) return-- const bg = RULER_BG_COLOR- const bgPaint = new this.ck.Paint()- bgPaint.setColor(this.ck.Color4f(bg.r, bg.g, bg.b, 1))-- canvas.drawRect(this.ck.LTRBRect(0, 0, vw, R), bgPaint)- canvas.drawRect(this.ck.LTRBRect(0, R, R, vh), bgPaint)-- // Corner square- canvas.drawRect(this.ck.LTRBRect(0, 0, R, R), bgPaint)-- const tickPaint = new this.ck.Paint()- tickPaint.setColor(- this.ck.Color4f(RULER_TICK_COLOR.r, RULER_TICK_COLOR.g, RULER_TICK_COLOR.b, 1)- )- tickPaint.setStrokeWidth(1)- tickPaint.setAntiAlias(true)-- const textColor = RULER_TEXT_COLOR- const textPaint = new this.ck.Paint()- textPaint.setColor(this.ck.Color4f(textColor.r, textColor.g, textColor.b, 1))- textPaint.setAntiAlias(true)-- const font = this.sizeFont ?? this.textFont- if (!font) {- bgPaint.delete()- tickPaint.delete()- textPaint.delete()- return- }-- const step = this.rulerStep()- const minorStep = step / 5-- // Compute selection bounds for badge exclusion zones- let sx1 = -Infinity,- sx2 = -Infinity,- sy1 = -Infinity,- sy2 = -Infinity- const selNodes = [...selectedIds]- .map((id) => graph.getNode(id))- .filter((n): n is SceneNode => n !== undefined)- if (selNodes.length > 0) {- 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)- }- sx1 = minX * this.zoom + this.panX- sx2 = maxX * this.zoom + this.panX- sy1 = minY * this.zoom + this.panY- sy2 = maxY * this.zoom + this.panY- }-- const badgeW = RULER_BADGE_EXCLUSION-- // Horizontal ruler (clipped)- canvas.save()- canvas.clipRect(this.ck.LTRBRect(R, 0, vw, R), this.ck.ClipOp.Intersect, false)- const worldLeft = -this.panX / this.zoom- const worldRight = (vw - this.panX) / this.zoom- const startX = Math.floor(worldLeft / step) * step-- for (let wx = startX; wx <= worldRight; wx += minorStep) {- const sx = wx * this.zoom + this.panX- if (sx < R) continue- const isMajor = Math.abs(wx % step) < RULER_MAJOR_TOLERANCE- const tickLen = isMajor ? R * RULER_MAJOR_TICK : R * RULER_MINOR_TICK- canvas.drawLine(sx, R - tickLen, sx, R, tickPaint)-- if (isMajor && selNodes.length > 0) {- const tooClose = Math.abs(sx - sx1) < badgeW || Math.abs(sx - sx2) < badgeW- if (!tooClose) {- canvas.drawText(this.rulerLabel(wx), sx + 2, R * RULER_TEXT_BASELINE, textPaint, font)- }- } else if (isMajor) {- canvas.drawText(this.rulerLabel(wx), sx + 2, R * RULER_TEXT_BASELINE, textPaint, font)- }- }- canvas.restore()-- // Vertical ruler (clipped)- canvas.save()- canvas.clipRect(this.ck.LTRBRect(0, R, R, vh), this.ck.ClipOp.Intersect, false)- const worldTop = -this.panY / this.zoom- const worldBottom = (vh - this.panY) / this.zoom- const startY = Math.floor(worldTop / step) * step-- for (let wy = startY; wy <= worldBottom; wy += minorStep) {- const sy = wy * this.zoom + this.panY- if (sy < R) continue- const isMajor = Math.abs(wy % step) < RULER_MAJOR_TOLERANCE- const tickLen = isMajor ? R * RULER_MAJOR_TICK : R * RULER_MINOR_TICK- canvas.drawLine(R - tickLen, sy, R, sy, tickPaint)-- if (isMajor && selNodes.length > 0) {- const tooClose = Math.abs(sy - sy1) < badgeW || Math.abs(sy - sy2) < badgeW- if (!tooClose) {- canvas.save()- canvas.translate(R * RULER_TEXT_BASELINE, sy - 2)- canvas.rotate(-90, 0, 0)- canvas.drawText(this.rulerLabel(wy), 0, 3, textPaint, font)- canvas.restore()- }- } else if (isMajor) {- canvas.save()- canvas.translate(R * RULER_TEXT_BASELINE, sy - 2)- canvas.rotate(-90, 0, 0)- canvas.drawText(this.rulerLabel(wy), 0, 3, textPaint, font)- canvas.restore()- }- }- canvas.restore()-- // Selection highlight + badges- if (selNodes.length > 0) {- const hlPaint = new this.ck.Paint()- hlPaint.setColor(this.selColor(RULER_HIGHLIGHT_ALPHA))-- canvas.drawRect(this.ck.LTRBRect(Math.max(R, sx1), 0, sx2, R), hlPaint)- canvas.drawRect(this.ck.LTRBRect(0, Math.max(R, sy1), R, sy2), hlPaint)-- this.drawRulerBadge(- canvas,- font,- Math.round((sx1 - this.panX) / this.zoom).toString(),- Math.max(R, sx1),- 0,- 'horizontal'- )- this.drawRulerBadge(- canvas,- font,- Math.round((sx2 - this.panX) / this.zoom).toString(),- sx2,- 0,- 'horizontal'- )- this.drawRulerBadge(- canvas,- font,- Math.round((sy1 - this.panY) / this.zoom).toString(),- 0,- Math.max(R, sy1),- 'vertical'- )- this.drawRulerBadge(- canvas,- font,- Math.round((sy2 - this.panY) / this.zoom).toString(),- 0,- sy2,- 'vertical'- )-- hlPaint.delete()- }-- bgPaint.delete()- tickPaint.delete()- textPaint.delete()- }-- private drawRulerBadge(- canvas: Canvas,- font: InstanceType<CanvasKit['Font']>,- label: string,- x: number,- y: number,- axis: 'horizontal' | 'vertical'- ): void {- const R = RULER_SIZE- const glyphIds = font.getGlyphIDs(label)- const widths = font.getGlyphWidths(glyphIds)- const textW = widths.reduce((s, w) => s + w, 0)- const pad = RULER_BADGE_PADDING- const h = RULER_BADGE_HEIGHT-- const badgePaint = new this.ck.Paint()- badgePaint.setColor(this.selColor())- const labelPaint = new this.ck.Paint()- labelPaint.setColor(this.ck.Color4f(1, 1, 1, 1))- labelPaint.setAntiAlias(true)-- if (axis === 'horizontal') {- const bx = x - (textW + pad * 2) / 2- const by = (R - h) / 2- canvas.drawRRect(- this.ck.RRectXY(- this.ck.LTRBRect(bx, by, bx + textW + pad * 2, by + h),- RULER_BADGE_RADIUS,- RULER_BADGE_RADIUS- ),- badgePaint- )- canvas.drawText(label, bx + pad, R * RULER_TEXT_BASELINE, labelPaint, font)- } else {- const bw = textW + pad * 2- const bx = (R - h) / 2- const by = y - bw / 2- canvas.save()- canvas.translate(bx + h / 2, by + bw / 2)- canvas.rotate(-90, 0, 0)- canvas.drawRRect(- this.ck.RRectXY(- this.ck.LTRBRect(-bw / 2, -h / 2, bw / 2, h / 2),- RULER_BADGE_RADIUS,- RULER_BADGE_RADIUS- ),- badgePaint- )- canvas.drawText(label, -bw / 2 + pad, h / 2 - 3, labelPaint, font)- canvas.restore()- }-- badgePaint.delete()- labelPaint.delete()- }-- private rulerStep(): number {- const pixelsPerUnit = this.zoom- const rawStep = RULER_TARGET_PIXEL_SPACING / pixelsPerUnit- const magnitude = Math.pow(10, Math.floor(Math.log10(rawStep)))- const normalized = rawStep / magnitude-- if (normalized <= 1) return magnitude- if (normalized <= 2) return 2 * magnitude- if (normalized <= 5) return 5 * magnitude- return 10 * magnitude- }-- private rulerLabel(value: number): string {- return Math.round(value).toString()- }-- destroy(): void {- for (const img of this.imageCache.values()) img.delete()- this.imageCache.clear()- this.fillPaint.delete()- this.strokePaint.delete()- this.selectionPaint.delete()- this.snapPaint.delete()- this.auxFill.delete()- this.auxStroke.delete()- this.opacityPaint.delete()- this.textFont?.delete()- this.labelFont?.delete()- this.sizeFont?.delete()- this.fontMgr?.delete()- this.fontProvider?.delete()- this.surface.delete()- }-}+export { SkiaRenderer, type RenderOverlays } from '@open-pencil/core'diff --git a/src/engine/scene-graph.ts b/src/engine/scene-graph.tsindex 0a859b86a..5095d8ed2 100644--- a/src/engine/scene-graph.ts+++ b/src/engine/scene-graph.ts@@ -1,802 +1,34 @@-export type { GUID, Color } from '@/types'--export type HandleMirroring = 'NONE' | 'ANGLE' | 'ANGLE_AND_LENGTH'-export type WindingRule = 'NONZERO' | 'EVENODD'--export interface VectorVertex {- x: number- y: number- strokeCap?: string- strokeJoin?: string- cornerRadius?: number- handleMirroring?: HandleMirroring-}--export interface VectorSegment {- start: number- end: number- tangentStart: { x: number; y: number }- tangentEnd: { x: number; y: number }-}--export interface VectorRegion {- windingRule: WindingRule- loops: number[][]-}--export interface VectorNetwork {- vertices: VectorVertex[]- segments: VectorSegment[]- regions: VectorRegion[]-}--export type NodeType =- | 'CANVAS'- | 'FRAME'- | 'RECTANGLE'- | 'ROUNDED_RECTANGLE'- | 'ELLIPSE'- | 'TEXT'- | 'LINE'- | 'STAR'- | 'POLYGON'- | 'VECTOR'- | 'GROUP'- | 'SECTION'- | 'COMPONENT'- | 'COMPONENT_SET'- | 'INSTANCE'- | 'CONNECTOR'- | 'SHAPE_WITH_TEXT'--import type { Color, Matrix, Rect } from '@/types'--export type FillType =- | 'SOLID'- | 'GRADIENT_LINEAR'- | 'GRADIENT_RADIAL'- | 'GRADIENT_ANGULAR'- | 'GRADIENT_DIAMOND'- | 'IMAGE'-export type BlendMode =- | 'NORMAL'- | 'DARKEN'- | 'MULTIPLY'- | 'COLOR_BURN'- | 'LIGHTEN'- | 'SCREEN'- | 'COLOR_DODGE'- | 'OVERLAY'- | 'SOFT_LIGHT'- | 'HARD_LIGHT'- | 'DIFFERENCE'- | 'EXCLUSION'- | 'HUE'- | 'SATURATION'- | 'COLOR'- | 'LUMINOSITY'- | 'PASS_THROUGH'-export type ImageScaleMode = 'FILL' | 'FIT' | 'CROP' | 'TILE'--export interface GradientStop {- color: Color- position: number-}--export type GradientTransform = Matrix--export interface Fill {- type: FillType- color: Color- opacity: number- visible: boolean- blendMode?: BlendMode- gradientStops?: GradientStop[]- gradientTransform?: GradientTransform- imageHash?: string- imageScaleMode?: ImageScaleMode- imageTransform?: GradientTransform-}--export type StrokeCap = 'NONE' | 'ROUND' | 'SQUARE' | 'ARROW_LINES' | 'ARROW_EQUILATERAL'-export type StrokeJoin = 'MITER' | 'BEVEL' | 'ROUND'--export interface Stroke {- color: Color- weight: number- opacity: number- visible: boolean- align: 'INSIDE' | 'CENTER' | 'OUTSIDE'- cap?: StrokeCap- join?: StrokeJoin- dashPattern?: number[]-}--export interface Effect {- type: 'DROP_SHADOW' | 'INNER_SHADOW' | 'LAYER_BLUR' | 'BACKGROUND_BLUR' | 'FOREGROUND_BLUR'- color: Color- offset: { x: number; y: number }- radius: number- spread: number- visible: boolean- blendMode?: BlendMode-}--export type ConstraintType = 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'SCALE'-export type TextAutoResize = 'NONE' | 'HEIGHT' | 'WIDTH_AND_HEIGHT' | 'TRUNCATE'-export type TextAlignVertical = 'TOP' | 'CENTER' | 'BOTTOM'-export type TextCase = 'ORIGINAL' | 'UPPER' | 'LOWER' | 'TITLE'-export type TextDecoration = 'NONE' | 'UNDERLINE' | 'STRIKETHROUGH'--export interface ArcData {- startingAngle: number- endingAngle: number- innerRadius: number-}--export type LayoutMode = 'NONE' | 'HORIZONTAL' | 'VERTICAL'-export type LayoutSizing = 'FIXED' | 'HUG' | 'FILL'-export type LayoutAlign = 'MIN' | 'CENTER' | 'MAX' | 'SPACE_BETWEEN'-export type LayoutCounterAlign = 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'BASELINE'-export type LayoutWrap = 'NO_WRAP' | 'WRAP'--export interface SceneNode {- id: string- type: NodeType- name: string- parentId: string | null- childIds: string[]-- x: number- y: number- width: number- height: number- rotation: number-- fills: Fill[]- strokes: Stroke[]- effects: Effect[]- opacity: number-- cornerRadius: number- topLeftRadius: number- topRightRadius: number- bottomRightRadius: number- bottomLeftRadius: number- independentCorners: boolean- cornerSmoothing: number-- visible: boolean- locked: boolean- clipsContent: boolean-- blendMode: BlendMode-- text: string- fontSize: number- fontFamily: string- fontWeight: number- textAlignHorizontal: 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED'- textAlignVertical: TextAlignVertical- textAutoResize: TextAutoResize- textCase: TextCase- textDecoration: TextDecoration- lineHeight: number | null- letterSpacing: number- maxLines: number | null-- horizontalConstraint: ConstraintType- verticalConstraint: ConstraintType-- layoutMode: LayoutMode- layoutWrap: LayoutWrap- primaryAxisAlign: LayoutAlign- counterAxisAlign: LayoutCounterAlign- primaryAxisSizing: LayoutSizing- counterAxisSizing: LayoutSizing- itemSpacing: number- counterAxisSpacing: number- paddingTop: number- paddingRight: number- paddingBottom: number- paddingLeft: number-- layoutPositioning: 'AUTO' | 'ABSOLUTE'- layoutGrow: number- layoutAlignSelf: 'AUTO' | 'STRETCH'-- vectorNetwork: VectorNetwork | null-- arcData: ArcData | null-- strokeCap: StrokeCap- strokeJoin: StrokeJoin- dashPattern: number[]-- borderTopWeight: number- borderRightWeight: number- borderBottomWeight: number- borderLeftWeight: number- independentStrokeWeights: boolean-- pointCount: number- starInnerRadius: number-- componentId: string | null- overrides: Record<string, unknown>-}--let nextLocalID = 1--function generateId(): string {- return `0:${nextLocalID++}`-}--function createDefaultNode(type: NodeType, overrides: Partial<SceneNode> = {}): SceneNode {- return {- id: generateId(),- type,- name: type.charAt(0) + type.slice(1).toLowerCase(),- parentId: null,- childIds: [],- x: 0,- y: 0,- width: 100,- height: 100,- rotation: 0,- fills: [],- strokes: [],- effects: [],- opacity: 1,- cornerRadius: 0,- topLeftRadius: 0,- topRightRadius: 0,- bottomRightRadius: 0,- bottomLeftRadius: 0,- independentCorners: false,- cornerSmoothing: 0,- visible: true,- locked: false,- clipsContent: false,- text: '',- fontSize: 14,- fontFamily: 'Inter',- fontWeight: 400,- textAlignHorizontal: 'LEFT',- lineHeight: null,- letterSpacing: 0,- layoutMode: 'NONE',- layoutWrap: 'NO_WRAP',- primaryAxisAlign: 'MIN',- counterAxisAlign: 'MIN',- primaryAxisSizing: 'FIXED',- counterAxisSizing: 'FIXED',- itemSpacing: 0,- counterAxisSpacing: 0,- paddingTop: 0,- paddingRight: 0,- paddingBottom: 0,- paddingLeft: 0,- blendMode: 'PASS_THROUGH',- layoutPositioning: 'AUTO',- layoutGrow: 0,- layoutAlignSelf: 'AUTO',- vectorNetwork: null,- arcData: null,- textAlignVertical: 'TOP',- textAutoResize: 'NONE',- textCase: 'ORIGINAL',- textDecoration: 'NONE',- maxLines: null,- horizontalConstraint: 'MIN',- verticalConstraint: 'MIN',- strokeCap: 'NONE',- strokeJoin: 'MITER',- dashPattern: [],- borderTopWeight: 0,- borderRightWeight: 0,- borderBottomWeight: 0,- borderLeftWeight: 0,- independentStrokeWeights: false,- pointCount: 5,- starInnerRadius: 0.38,- componentId: null,- overrides: {},- ...overrides- }-}--const CONTAINER_TYPES = new Set<NodeType>([- 'CANVAS',- 'FRAME',- 'GROUP',- 'SECTION',- 'COMPONENT',- 'COMPONENT_SET',- 'INSTANCE'-])--export class SceneGraph {- nodes = new Map<string, SceneNode>()- images = new Map<string, Uint8Array>()- rootId: string-- constructor() {- const root = createDefaultNode('FRAME', {- name: 'Document',- width: 0,- height: 0- })- this.rootId = root.id- this.nodes.set(root.id, root)-- this.addPage('Page 1')- }-- addPage(name: string): SceneNode {- return this.createNode('CANVAS', this.rootId, { name, width: 0, height: 0 })- }-- getPages(): SceneNode[] {- return this.getChildren(this.rootId).filter((n) => n.type === 'CANVAS')- }-- getNode(id: string): SceneNode | undefined {- return this.nodes.get(id)- }-- getChildren(id: string): SceneNode[] {- const node = this.nodes.get(id)- if (!node) return []- return node.childIds- .map((cid) => this.nodes.get(cid))- .filter((n): n is SceneNode => n !== undefined)- }-- isContainer(id: string): boolean {- const node = this.nodes.get(id)- return node ? CONTAINER_TYPES.has(node.type) : false- }-- isDescendant(childId: string, ancestorId: string): boolean {- let current = this.nodes.get(childId)- while (current) {- if (current.id === ancestorId) return true- current = current.parentId ? this.nodes.get(current.parentId) : undefined- }- return false- }-- getAbsolutePosition(id: string): { x: number; y: number } {- let ax = 0- let ay = 0- let current = this.nodes.get(id)- while (current && current.id !== this.rootId && current.type !== 'CANVAS') {- ax += current.x- ay += current.y- current = current.parentId ? this.nodes.get(current.parentId) : undefined- }- return { x: ax, y: ay }- }-- getAbsoluteBounds(id: string): Rect {- const pos = this.getAbsolutePosition(id)- const node = this.nodes.get(id)- return {- x: pos.x,- y: pos.y,- width: node?.width ?? 0,- height: node?.height ?? 0- }- }-- createNode(type: NodeType, parentId: string, overrides: Partial<SceneNode> = {}): SceneNode {- const node = createDefaultNode(type, overrides)- node.parentId = parentId- this.nodes.set(node.id, node)-- const parent = this.nodes.get(parentId)- if (parent) {- parent.childIds.push(node.id)- }-- return node- }-- updateNode(id: string, changes: Partial<SceneNode>): void {- const node = this.nodes.get(id)- if (!node) return- Object.assign(node, changes)- }-- reparentNode(nodeId: string, newParentId: string): void {- const node = this.nodes.get(nodeId)- if (!node || nodeId === this.rootId) return- if (this.isDescendant(newParentId, nodeId)) return-- const oldParent = node.parentId ? this.nodes.get(node.parentId) : undefined- const newParent = this.nodes.get(newParentId)- if (!newParent) return- if (node.parentId === newParentId) return-- // Convert absolute position- const absPos = this.getAbsolutePosition(nodeId)- const newParentNode = this.nodes.get(newParentId)- const newParentAbs =- newParentId === this.rootId || newParentNode?.type === 'CANVAS'- ? { x: 0, y: 0 }- : this.getAbsolutePosition(newParentId)-- // Remove from old parent- if (oldParent) {- oldParent.childIds = oldParent.childIds.filter((cid) => cid !== nodeId)- }-- // Add to new parent- node.parentId = newParentId- newParent.childIds.push(nodeId)-- // Adjust position so node stays in same visual place- node.x = absPos.x - newParentAbs.x- node.y = absPos.y - newParentAbs.y- }-- reorderChild(nodeId: string, parentId: string, insertIndex: number): void {- const node = this.nodes.get(nodeId)- if (!node) return-- const oldParent = node.parentId ? this.nodes.get(node.parentId) : undefined- const newParent = this.nodes.get(parentId)- if (!newParent) return-- // Remove from old parent- if (oldParent) {- oldParent.childIds = oldParent.childIds.filter((cid) => cid !== nodeId)- }-- // If same parent, adjust index since we removed the item- let idx = insertIndex- if (- oldParent === newParent &&- idx > (oldParent.childIds.indexOf(nodeId) === -1 ? idx : oldParent.childIds.length)- ) {- // Already removed above, no adjustment needed- }-- node.parentId = parentId- idx = Math.min(idx, newParent.childIds.length)- newParent.childIds.splice(idx, 0, nodeId)- }-- deleteNode(id: string): void {- const node = this.nodes.get(id)- if (!node || id === this.rootId) return-- if (node.parentId) {- const parent = this.nodes.get(node.parentId)- if (parent) {- parent.childIds = parent.childIds.filter((cid) => cid !== id)- }- }-- for (const childId of Array.from(node.childIds)) {- this.deleteNode(childId)- }-- this.nodes.delete(id)- }-- hitTest(px: number, py: number, scopeId?: string): SceneNode | null {- const scope = scopeId ?? this.rootId- return this.hitTestChildren(px, py, scope, 0, 0, false)- }-- hitTestDeep(px: number, py: number, scopeId?: string): SceneNode | null {- const scope = scopeId ?? this.rootId- return this.hitTestChildren(px, py, scope, 0, 0, true)- }-- private static readonly OPAQUE_CONTAINER_TYPES = new Set<NodeType>(['COMPONENT', 'INSTANCE'])-- private hitTestChildren(- px: number,- py: number,- parentId: string,- offsetX: number,- offsetY: number,- deep = false- ): SceneNode | null {- const parent = this.nodes.get(parentId)- if (!parent) return null-- // Reverse order = topmost first- for (let i = parent.childIds.length - 1; i >= 0; i--) {- const childId = parent.childIds[i]- const child = this.nodes.get(childId)- if (!child || !child.visible) continue-- const ax = offsetX + child.x- const ay = offsetY + child.y-- // Components/instances: don't recurse unless in deep mode (double-click)- if (SceneGraph.OPAQUE_CONTAINER_TYPES.has(child.type) && !deep) {- if (px >= ax && px <= ax + child.width && py >= ay && py <= ay + child.height) {- return child- }- continue- }-- // Check children first (deeper hit)- if (CONTAINER_TYPES.has(child.type)) {- const deepHit = this.hitTestChildren(px, py, childId, ax, ay, deep)- if (deepHit) return deepHit- }-- if (px >= ax && px <= ax + child.width && py >= ay && py <= ay + child.height) {- return child- }- }- return null- }-- hitTestFrame(- px: number,- py: number,- excludeIds: Set<string>,- scopeId?: string- ): SceneNode | null {- return this.hitTestFrameChildren(px, py, scopeId ?? this.rootId, 0, 0, excludeIds)- }-- private hitTestFrameChildren(- px: number,- py: number,- parentId: string,- offsetX: number,- offsetY: number,- excludeIds: Set<string>- ): SceneNode | null {- const parent = this.nodes.get(parentId)- if (!parent) return null-- // Deepest matching frame wins- let best: SceneNode | null = null-- for (const childId of parent.childIds) {- if (excludeIds.has(childId)) continue- const child = this.nodes.get(childId)- if (!child || !child.visible) continue-- const ax = offsetX + child.x- const ay = offsetY + child.y-- if (!CONTAINER_TYPES.has(child.type)) continue- if (px < ax || px > ax + child.width || py < ay || py > ay + child.height) continue-- best = child-- const deeper = this.hitTestFrameChildren(px, py, childId, ax, ay, excludeIds)- if (deeper) best = deeper- }-- return best- }-- cloneTree(- sourceId: string,- parentId: string,- overrides: Partial<SceneNode> = {}- ): SceneNode | null {- const src = this.nodes.get(sourceId)- if (!src) return null-- const { id: _srcId, parentId: _srcParent, childIds: _srcChildren, ...rest } = src- const clone = this.createNode(src.type, parentId, { ...rest, ...overrides })-- for (const childId of src.childIds) {- this.cloneTree(childId, clone.id)- }-- return clone- }-- private static readonly INSTANCE_SYNC_PROPS: (keyof SceneNode)[] = [- 'width',- 'height',- 'fills',- 'strokes',- 'effects',- 'opacity',- 'cornerRadius',- 'topLeftRadius',- 'topRightRadius',- 'bottomRightRadius',- 'bottomLeftRadius',- 'independentCorners',- 'layoutMode',- 'layoutWrap',- 'primaryAxisAlign',- 'counterAxisAlign',- 'primaryAxisSizing',- 'counterAxisSizing',- 'itemSpacing',- 'counterAxisSpacing',- 'paddingTop',- 'paddingRight',- 'paddingBottom',- 'paddingLeft',- 'clipsContent'- ]-- private static copyProp<K extends keyof SceneNode>(- target: Partial<SceneNode> | SceneNode,- source: SceneNode,- key: K- ): void {- const val = source[key]- target[key] = (Array.isArray(val) ? structuredClone(val) : val) as SceneNode[K]- }-- createInstance(- componentId: string,- parentId: string,- overrides: Partial<SceneNode> = {}- ): SceneNode | null {- const component = this.nodes.get(componentId)- if (!component || component.type !== 'COMPONENT') return null-- const props: Partial<SceneNode> = { name: component.name, componentId }- for (const key of SceneGraph.INSTANCE_SYNC_PROPS) {- SceneGraph.copyProp(props, component, key)- }-- const instance = this.createNode('INSTANCE', parentId, { ...props, ...overrides })-- this.cloneChildrenWithMapping(component.id, instance.id)-- return instance- }-- private cloneChildrenWithMapping(sourceParentId: string, destParentId: string): void {- const sourceParent = this.nodes.get(sourceParentId)- if (!sourceParent) return-- for (const childId of sourceParent.childIds) {- const src = this.nodes.get(childId)- if (!src) continue-- const { id: _, parentId: _p, childIds: _c, ...rest } = src- const clone = this.createNode(src.type, destParentId, {- ...rest,- componentId: childId- })-- if (src.childIds.length > 0) {- this.cloneChildrenWithMapping(childId, clone.id)- }- }- }-- syncInstances(componentId: string): void {- const component = this.nodes.get(componentId)- if (!component || component.type !== 'COMPONENT') return-- for (const instance of this.getInstances(componentId)) {- // Sync instance-level props (unless overridden)- for (const key of SceneGraph.INSTANCE_SYNC_PROPS) {- if (key in instance.overrides) continue- SceneGraph.copyProp(instance, component, key)- }-- // Sync children: match by componentId- this.syncChildren(component.id, instance.id, instance.overrides)- }- }-- private syncChildren(- compParentId: string,- instParentId: string,- overrides: Record<string, unknown>- ): void {- const compParent = this.nodes.get(compParentId)- const instParent = this.nodes.get(instParentId)- if (!compParent || !instParent) return-- const instChildMap = new Map<string, SceneNode>()- for (const childId of instParent.childIds) {- const child = this.nodes.get(childId)- if (child?.componentId) instChildMap.set(child.componentId, child)- }-- // Add new children from component that don't exist in instance- for (const compChildId of compParent.childIds) {- if (!instChildMap.has(compChildId)) {- const src = this.nodes.get(compChildId)- if (!src) continue- const { id: _, parentId: _p, childIds: _c, ...rest } = src- const clone = this.createNode(src.type, instParentId, {- ...rest,- componentId: compChildId- })- if (src.childIds.length > 0) {- this.cloneChildrenWithMapping(compChildId, clone.id)- }- instChildMap.set(compChildId, clone)- }- }-- // Sync existing children- for (const compChildId of compParent.childIds) {- const compChild = this.nodes.get(compChildId)- const instChild = instChildMap.get(compChildId)- if (!compChild || !instChild) continue-- for (const key of SceneGraph.INSTANCE_SYNC_PROPS) {- const overrideKey = `${instChild.id}:${key}`- if (overrideKey in overrides) continue- SceneGraph.copyProp(instChild, compChild, key)- }-- for (const key of ['name', 'text', 'fontSize', 'fontWeight', 'fontFamily'] as const) {- const overrideKey = `${instChild.id}:${key}`- if (overrideKey in overrides) continue- SceneGraph.copyProp(instChild, compChild, key)- }-- if (compChild.childIds.length > 0) {- this.syncChildren(compChildId, instChild.id, overrides)- }- }-- // Reorder instance children to match component order- const compChildOrder = compParent.childIds- instParent.childIds.sort((a, b) => {- const nodeA = this.nodes.get(a)- const nodeB = this.nodes.get(b)- const idxA = nodeA?.componentId ? compChildOrder.indexOf(nodeA.componentId) : -1- const idxB = nodeB?.componentId ? compChildOrder.indexOf(nodeB.componentId) : -1- return idxA - idxB- })- }-- detachInstance(instanceId: string): void {- const node = this.nodes.get(instanceId)- if (!node || node.type !== 'INSTANCE') return- node.type = 'FRAME'- node.componentId = null- node.overrides = {}- }-- getMainComponent(instanceId: string): SceneNode | undefined {- const node = this.nodes.get(instanceId)- if (!node?.componentId) return undefined- return this.nodes.get(node.componentId)- }-- getInstances(componentId: string): SceneNode[] {- const instances: SceneNode[] = []- for (const node of this.nodes.values()) {- if (node.type === 'INSTANCE' && node.componentId === componentId) {- instances.push(node)- }- }- return instances- }-- flattenTree(parentId?: string, depth = 0): Array<{ node: SceneNode; depth: number }> {- const id = parentId ?? this.rootId- const parent = this.nodes.get(id)- if (!parent) return []-- const result: Array<{ node: SceneNode; depth: number }> = []- for (const childId of parent.childIds) {- const child = this.nodes.get(childId)- if (!child) continue- result.push({ node: child, depth })- if (child.childIds.length > 0) {- result.push(...this.flattenTree(childId, depth + 1))- }- }- return result- }-}+export { SceneGraph } from '@open-pencil/core'+export type {+ GUID,+ Color,+ SceneNode,+ NodeType,+ Fill,+ FillType,+ Stroke,+ StrokeCap,+ StrokeJoin,+ Effect,+ BlendMode,+ ImageScaleMode,+ GradientStop,+ GradientTransform,+ LayoutMode,+ LayoutSizing,+ LayoutAlign,+ LayoutCounterAlign,+ LayoutWrap,+ ConstraintType,+ TextAutoResize,+ TextAlignVertical,+ TextCase,+ TextDecoration,+ ArcData,+ VectorNetwork,+ VectorVertex,+ VectorSegment,+ VectorRegion,+ HandleMirroring,+ WindingRule+} from '@open-pencil/core'diff --git a/src/engine/snap.ts b/src/engine/snap.tsindex d4eabb941..dcfb884b7 100644--- a/src/engine/snap.ts+++ b/src/engine/snap.ts@@ -1,169 +1 @@-import type { SceneNode } from './scene-graph'-import type { Rect } from '@/types'--const SNAP_THRESHOLD = 5--export interface SnapGuide {- axis: 'x' | 'y'- position: number- from: number- to: number-}--export interface SnapResult {- dx: number- dy: number- guides: SnapGuide[]-}--function getEdges(node: SceneNode) {- if (node.rotation === 0) {- return {- left: node.x,- right: node.x + node.width,- centerX: node.x + node.width / 2,- top: node.y,- bottom: node.y + node.height,- centerY: node.y + node.height / 2- }- }-- const cx = node.x + node.width / 2- const cy = node.y + node.height / 2- const rad = (node.rotation * Math.PI) / 180- const cos = Math.cos(rad)- const sin = Math.sin(rad)- const hw = node.width / 2- const hh = node.height / 2-- const corners = [- { 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 }- ]-- let left = Infinity,- right = -Infinity,- top = Infinity,- bottom = -Infinity- for (const c of corners) {- left = Math.min(left, c.x)- right = Math.max(right, c.x)- top = Math.min(top, c.y)- bottom = Math.max(bottom, c.y)- }-- return {- left,- right,- centerX: (left + right) / 2,- top,- bottom,- centerY: (top + bottom) / 2- }-}--export function computeSnap(- movingIds: Set<string>,- movingBounds: Rect,- allNodes: SceneNode[]-): SnapResult {- const targets = allNodes.filter((n) => !movingIds.has(n.id))- if (targets.length === 0) return { dx: 0, dy: 0, guides: [] }-- const m = {- left: movingBounds.x,- right: movingBounds.x + movingBounds.width,- centerX: movingBounds.x + movingBounds.width / 2,- top: movingBounds.y,- bottom: movingBounds.y + movingBounds.height,- centerY: movingBounds.y + movingBounds.height / 2- }-- let bestDx = Infinity- let bestDy = Infinity- const guides: SnapGuide[] = []-- for (const target of targets) {- const t = getEdges(target)-- // X-axis snapping: left-to-left, left-to-right, right-to-left, right-to-right, center-to-center- const xPairs: [number, number][] = [- [m.left, t.left],- [m.left, t.right],- [m.right, t.left],- [m.right, t.right],- [m.centerX, t.centerX]- ]-- for (const [mVal, tVal] of xPairs) {- const d = tVal - mVal- if (Math.abs(d) < SNAP_THRESHOLD && Math.abs(d) <= Math.abs(bestDx)) {- if (Math.abs(d) < Math.abs(bestDx)) {- bestDx = d- guides.length = guides.filter((g) => g.axis === 'y').length- ? guides.length- : guides.length- // Remove old x guides if we found a closer snap- for (let i = guides.length - 1; i >= 0; i--) {- if (guides[i].axis === 'x') guides.splice(i, 1)- }- }- if (Math.abs(d) === Math.abs(bestDx)) {- const minY = Math.min(m.top, t.top)- const maxY = Math.max(m.bottom, t.bottom)- guides.push({ axis: 'x', position: tVal, from: minY, to: maxY })- }- }- }-- // Y-axis snapping- const yPairs: [number, number][] = [- [m.top, t.top],- [m.top, t.bottom],- [m.bottom, t.top],- [m.bottom, t.bottom],- [m.centerY, t.centerY]- ]-- for (const [mVal, tVal] of yPairs) {- const d = tVal - mVal- if (Math.abs(d) < SNAP_THRESHOLD && Math.abs(d) <= Math.abs(bestDy)) {- if (Math.abs(d) < Math.abs(bestDy)) {- for (let i = guides.length - 1; i >= 0; i--) {- if (guides[i].axis === 'y') guides.splice(i, 1)- }- bestDy = d- }- if (Math.abs(d) === Math.abs(bestDy)) {- const minX = Math.min(m.left, t.left)- const maxX = Math.max(m.right, t.right)- guides.push({ axis: 'y', position: tVal, from: minX, to: maxX })- }- }- }- }-- return {- dx: Math.abs(bestDx) <= SNAP_THRESHOLD ? bestDx : 0,- dy: Math.abs(bestDy) <= SNAP_THRESHOLD ? bestDy : 0,- guides- }-}--export function computeSelectionBounds(nodes: SceneNode[]): Rect | null {- if (nodes.length === 0) return null- let minX = Infinity- let minY = Infinity- let maxX = -Infinity- let maxY = -Infinity- for (const n of nodes) {- const edges = getEdges(n)- minX = Math.min(minX, edges.left)- minY = Math.min(minY, edges.top)- maxX = Math.max(maxX, edges.right)- maxY = Math.max(maxY, edges.bottom)- }- return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }-}+export { computeSelectionBounds, computeSnap, type SnapGuide } from '@open-pencil/core'diff --git a/src/engine/undo.ts b/src/engine/undo.tsindex cc8141a3f..efd7af07b 100644--- a/src/engine/undo.ts+++ b/src/engine/undo.ts@@ -1,110 +1 @@-import type { SceneNode } from './scene-graph'--export interface UndoEntry {- label: string- forward: () => void- inverse: () => void-}--export class UndoManager {- private undoStack: UndoEntry[] = []- private redoStack: UndoEntry[] = []- private batchEntries: UndoEntry[] | null = null- private batchLabel = ''-- apply(entry: UndoEntry): void {- entry.forward()- if (this.batchEntries) {- this.batchEntries.push(entry)- } else {- this.undoStack.push(entry)- this.redoStack = []- }- }-- push(entry: UndoEntry): void {- if (this.batchEntries) {- this.batchEntries.push(entry)- } else {- this.undoStack.push(entry)- this.redoStack = []- }- }-- undo(): string | null {- const entry = this.undoStack.pop()- if (!entry) return null- entry.inverse()- this.redoStack.push(entry)- return entry.label- }-- redo(): string | null {- const entry = this.redoStack.pop()- if (!entry) return null- entry.forward()- this.undoStack.push(entry)- return entry.label- }-- beginBatch(label: string): void {- this.batchLabel = label- this.batchEntries = []- }-- commitBatch(): void {- if (!this.batchEntries || this.batchEntries.length === 0) {- this.batchEntries = null- return- }- const entries = this.batchEntries- const label = this.batchLabel- this.batchEntries = null-- this.undoStack.push({- label,- forward: () => entries.forEach((e) => e.forward()),- inverse: () => [...entries].reverse().forEach((e) => e.inverse())- })- this.redoStack = []- }-- clear(): void {- this.undoStack = []- this.redoStack = []- this.batchEntries = null- }-- get canUndo(): boolean {- return this.undoStack.length > 0- }-- get canRedo(): boolean {- return this.redoStack.length > 0- }-- get undoLabel(): string | null {- return this.undoStack.at(-1)?.label ?? null- }-- get redoLabel(): string | null {- return this.redoStack.at(-1)?.label ?? null- }-}--export function createPropertyChange(- node: SceneNode,- changes: Partial<SceneNode>,- label: string-): UndoEntry {- const previous: Partial<SceneNode> = {}- for (const key of Object.keys(changes) as (keyof SceneNode)[]) {- ;(previous as Record<string, unknown>)[key] = node[key]- }-- return {- label,- forward: () => Object.assign(node, changes),- inverse: () => Object.assign(node, previous)- }-}+export { UndoManager } from '@open-pencil/core'diff --git a/src/engine/vector.ts b/src/engine/vector.tsindex 8ce6159fd..38e483a6a 100644--- a/src/engine/vector.ts+++ b/src/engine/vector.ts@@ -1,333 +1 @@-import type {- HandleMirroring,- VectorNetwork,- VectorRegion,- VectorSegment,- VectorVertex,- WindingRule-} from './scene-graph'-import type { CanvasKit, Path } from 'canvaskit-wasm'--// --- 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()- const { vertices, segments, regions } = network-- if (regions.length > 0) {- for (const region of regions) {- for (const loop of region.loops) {- addLoopToPath(path, loop, segments, vertices)- }- path.setFillType(region.windingRule === 'EVENODD' ? ck.FillType.EvenOdd : ck.FillType.Winding)- }- } else {- // No regions — draw all segments as open paths- const visited = new Set<number>()- const chains = buildChains(segments, vertices.length)-- for (const chain of chains) {- if (chain.length === 0) continue- const firstSeg = segments[chain[0]]- path.moveTo(vertices[firstSeg.start].x, vertices[firstSeg.start].y)-- for (const segIdx of chain) {- visited.add(segIdx)- addSegmentToPath(path, segments[segIdx], vertices)- }- }-- // Any remaining disconnected segments- for (let i = 0; i < segments.length; i++) {- if (visited.has(i)) continue- const seg = segments[i]- path.moveTo(vertices[seg.start].x, vertices[seg.start].y)- addSegmentToPath(path, seg, vertices)- }- }-- return path-}--function addLoopToPath(- path: Path,- loop: number[],- segments: VectorSegment[],- vertices: VectorVertex[]-): void {- if (loop.length === 0) return-- const firstSeg = segments[loop[0]]- path.moveTo(vertices[firstSeg.start].x, vertices[firstSeg.start].y)-- for (const segIdx of loop) {- addSegmentToPath(path, segments[segIdx], vertices)- }-- const lastSeg = segments[loop[loop.length - 1]]- if (lastSeg.end === firstSeg.start) {- path.close()- }-}--function addSegmentToPath(path: Path, seg: VectorSegment, vertices: VectorVertex[]): void {- const start = vertices[seg.start]- const end = vertices[seg.end]- const ts = seg.tangentStart- const te = seg.tangentEnd-- const isLine = ts.x === 0 && ts.y === 0 && te.x === 0 && te.y === 0- if (isLine) {- path.lineTo(end.x, end.y)- } else {- // Cubic bezier: control points are tangent offsets from start/end- path.cubicTo(start.x + ts.x, start.y + ts.y, end.x + te.x, end.y + te.y, end.x, end.y)- }-}--function buildChains(segments: VectorSegment[], _vertexCount: number): number[][] {- if (segments.length === 0) return []-- // Build adjacency: for each vertex, which segments connect to it- const adj = new Map<number, number[]>()- for (let i = 0; i < segments.length; i++) {- const s = segments[i]- if (!adj.has(s.start)) adj.set(s.start, [])- if (!adj.has(s.end)) adj.set(s.end, [])- adj.get(s.start)?.push(i)- adj.get(s.end)?.push(i)- }-- const visited = new Set<number>()- const chains: number[][] = []-- // Start from degree-1 vertices (endpoints) or any unvisited- const degree1 = [...adj.entries()].filter(([, segs]) => segs.length === 1).map(([v]) => v)-- const startVertices = degree1.length > 0 ? degree1 : [segments[0].start]-- for (const startVertex of startVertices) {- let current = startVertex- const chain: number[] = []-- while (true) {- const segs = adj.get(current)- if (!segs) break-- const nextSeg = segs.find((s) => !visited.has(s))- if (nextSeg === undefined) break-- visited.add(nextSeg)- chain.push(nextSeg)-- const seg = segments[nextSeg]- current = seg.start === current ? seg.end : seg.start- }-- if (chain.length > 0) chains.push(chain)- }-- return chains-}--export function computeVectorBounds(network: VectorNetwork): {- x: number- y: number- width: number- height: number-} {- if (network.vertices.length === 0) {- return { x: 0, y: 0, width: 0, height: 0 }- }-- let minX = Infinity- let minY = Infinity- let maxX = -Infinity- let maxY = -Infinity-- for (const v of network.vertices) {- minX = Math.min(minX, v.x)- minY = Math.min(minY, v.y)- maxX = Math.max(maxX, v.x)- maxY = Math.max(maxY, v.y)- }-- // Also consider bezier control points for tighter bounds- for (const seg of network.segments) {- const start = network.vertices[seg.start]- const end = network.vertices[seg.end]- const cp1x = start.x + seg.tangentStart.x- const cp1y = start.y + seg.tangentStart.y- const cp2x = end.x + seg.tangentEnd.x- const cp2y = end.y + seg.tangentEnd.y-- minX = Math.min(minX, cp1x, cp2x)- minY = Math.min(minY, cp1y, cp2y)- maxX = Math.max(maxX, cp1x, cp2x)- maxY = Math.max(maxY, cp1y, cp2y)- }-- return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }-}+export { vectorNetworkToPath, decodeVectorNetworkBlob, encodeVectorNetworkBlob, computeVectorBounds } from '@open-pencil/core'diff --git a/src/kiwi/fig-file.ts b/src/kiwi/fig-file.tsindex eefd45527..50c326c0f 100644--- a/src/kiwi/fig-file.ts+++ b/src/kiwi/fig-file.ts@@ -1,109 +1 @@-import { unzipSync, inflateSync } from 'fflate'-import { decompress as zstdDecompress } from 'fzstd'--import { importNodeChanges } from './fig-import'-import { decodeBinarySchema, compileSchema, ByteBuffer } from './kiwi-schema'-import { isZstdCompressed } from './protocol'--import type { FigmaMessage } from './codec'-import type { SceneGraph } from '@/engine/scene-graph'--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)-- 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 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[])- )-- 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)-}--/**- * Read a .fig File object and parse it- */-export async function readFigFile(file: File): Promise<SceneGraph> {- const buffer = await file.arrayBuffer()- return parseFigFile(buffer)-}+export { readFigFile } from '@open-pencil/core'diff --git a/src/kiwi/fig-import.ts b/src/kiwi/fig-import.tsindex a8f2933f8..d2a226672 100644--- a/src/kiwi/fig-import.ts+++ b/src/kiwi/fig-import.ts@@ -1,491 +1 @@-import { SceneGraph } from '@/engine/scene-graph'-import { decodeVectorNetworkBlob } from '@/engine/vector'--import type { NodeChange, Paint, Effect as KiwiEffect, GUID } from './codec'-import type {- NodeType,- Fill,- FillType,- Stroke,- Effect,- Color,- BlendMode,- ImageScaleMode,- GradientTransform,- StrokeCap,- StrokeJoin,- LayoutMode,- LayoutSizing,- LayoutAlign,- LayoutCounterAlign,- ConstraintType,- TextAutoResize,- TextAlignVertical,- TextCase,- TextDecoration,- ArcData,- VectorNetwork-} from '@/engine/scene-graph'--function ext(nc: NodeChange): Record<string, unknown> {- return nc as unknown as Record<string, unknown>-}--function guidToString(guid: GUID): string {- return `${guid.sessionID}:${guid.localID}`-}--function convertColor(color?: { r: number; g: number; b: number; a: number }): Color {- if (!color) return { r: 0, g: 0, b: 0, a: 1 }- return { r: color.r, g: color.g, b: color.b, a: color.a }-}--function imageHashToString(hash: Record<string, number>): string {- const bytes = Object.keys(hash)- .sort((a, b) => Number(a) - Number(b))- .map((k) => hash[Number(k)])- return bytes.map((b) => b.toString(16).padStart(2, '0')).join('')-}--function convertGradientTransform(t?: {- m00: number- m01: number- m02: number- m10: number- m11: number- m12: number-}): GradientTransform | undefined {- if (!t) return undefined- return { m00: t.m00, m01: t.m01, m02: t.m02, m10: t.m10, m11: t.m11, m12: t.m12 }-}--function convertFills(paints?: Paint[]): Fill[] {- if (!paints) return []- return paints.map((p) => {- const base: Fill = {- type: (p.type ?? 'SOLID') as FillType,- color: convertColor(p.color),- opacity: p.opacity ?? 1,- visible: p.visible ?? true,- blendMode: (p.blendMode ?? 'NORMAL') as BlendMode- }-- if (p.type?.startsWith('GRADIENT') && p.stops) {- base.gradientStops = p.stops.map((s) => ({- color: convertColor(s.color),- position: s.position- }))- if (p.transform) {- base.gradientTransform = convertGradientTransform(p.transform)- }- }-- if (p.type === 'IMAGE') {- if (p.image && typeof p.image === 'object') {- const img = p.image as { hash: string | Record<string, number> }- if (typeof img.hash === 'object') {- base.imageHash = imageHashToString(img.hash)- } else if (typeof img.hash === 'string') {- base.imageHash = img.hash- }- }- base.imageScaleMode = (p.imageScaleMode as ImageScaleMode) ?? 'FILL'- if (p.transform) {- base.imageTransform = convertGradientTransform(p.transform)- }- }-- return base- })-}--function convertStrokes(- paints?: Paint[],- weight?: number,- align?: string,- cap?: string,- join?: string,- dashPattern?: number[]-): Stroke[] {- if (!paints) return []- return paints.map((p) => ({- color: convertColor(p.color),- weight: weight ?? 1,- opacity: p.opacity ?? 1,- visible: p.visible ?? true,- align: (align === 'INSIDE'- ? 'INSIDE'- : align === 'OUTSIDE'- ? 'OUTSIDE'- : 'CENTER') as Stroke['align'],- cap: (cap ?? 'NONE') as StrokeCap,- join: (join ?? 'MITER') as StrokeJoin,- dashPattern: dashPattern ?? []- }))-}--function convertEffects(effects?: KiwiEffect[]): Effect[] {- if (!effects) return []- return effects.map((e) => ({- type: e.type as Effect['type'],- color: convertColor(e.color),- offset: e.offset ?? { x: 0, y: 0 },- radius: e.radius ?? 0,- spread: e.spread ?? 0,- visible: e.visible ?? true,- blendMode: (e.blendMode as BlendMode) ?? 'NORMAL'- }))-}--function mapNodeType(type?: string): NodeType | 'DOCUMENT' {- switch (type) {- case 'DOCUMENT':- return 'DOCUMENT'- case 'CANVAS':- return 'CANVAS'- case 'FRAME':- return 'FRAME'- case 'RECTANGLE':- return 'RECTANGLE'- case 'ROUNDED_RECTANGLE':- return 'ROUNDED_RECTANGLE'- case 'ELLIPSE':- return 'ELLIPSE'- case 'TEXT':- return 'TEXT'- case 'LINE':- return 'LINE'- case 'STAR':- return 'STAR'- case 'REGULAR_POLYGON':- return 'POLYGON'- case 'VECTOR':- return 'VECTOR'- case 'GROUP':- return 'GROUP'- case 'SECTION':- return 'SECTION'- case 'COMPONENT':- return 'COMPONENT'- case 'COMPONENT_SET':- return 'COMPONENT_SET'- case 'INSTANCE':- return 'INSTANCE'- case 'SYMBOL':- return 'COMPONENT'- case 'CONNECTOR':- return 'CONNECTOR'- case 'SHAPE_WITH_TEXT':- return 'SHAPE_WITH_TEXT'- default:- return 'RECTANGLE'- }-}--function mapStackMode(mode?: string): LayoutMode {- switch (mode) {- case 'HORIZONTAL':- return 'HORIZONTAL'- case 'VERTICAL':- return 'VERTICAL'- default:- return 'NONE'- }-}--function mapStackSizing(sizing?: string): LayoutSizing {- switch (sizing) {- case 'RESIZE_TO_FIT':- case 'RESIZE_TO_FIT_WITH_IMPLICIT_SIZE':- return 'HUG'- case 'FILL':- return 'FILL'- default:- return 'FIXED'- }-}--function mapStackJustify(justify?: string): LayoutAlign {- switch (justify) {- case 'CENTER':- return 'CENTER'- case 'MAX':- return 'MAX'- case 'SPACE_BETWEEN':- case 'SPACE_EVENLY':- return 'SPACE_BETWEEN'- default:- return 'MIN'- }-}--function mapStackCounterAlign(align?: string): LayoutCounterAlign {- switch (align) {- case 'CENTER':- return 'CENTER'- case 'MAX':- return 'MAX'- case 'STRETCH':- return 'STRETCH'- case 'BASELINE':- return 'BASELINE'- default:- return 'MIN'- }-}--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) {- case 'CENTER':- return 'CENTER'- case 'MAX':- return 'MAX'- case 'STRETCH':- return 'STRETCH'- case 'SCALE':- return 'SCALE'- default:- return 'MIN'- }-}--function mapTextDecoration(d?: string): TextDecoration {- switch (d) {- case 'UNDERLINE':- return 'UNDERLINE'- case 'STRIKETHROUGH':- return 'STRIKETHROUGH'- default:- return 'NONE'- }-}--function mapArcData(data?: Record<string, number>): ArcData | null {- if (!data) return null- return {- startingAngle: data.startingAngle ?? 0,- endingAngle: data.endingAngle ?? 2 * Math.PI,- innerRadius: data.innerRadius ?? 0- }-}--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[] = [],- images?: Map<string, Uint8Array>-): SceneGraph {- const graph = new SceneGraph()-- if (images) {- for (const [hash, data] of images) {- graph.images.set(hash, data)- }- }-- // Remove the default page created by constructor — we'll create pages from the file- for (const page of graph.getPages()) {- graph.deleteNode(page.id)- }-- const changeMap = new Map<string, NodeChange>()- const parentMap = new Map<string, string>()-- for (const nc of nodeChanges) {- if (!nc.guid) continue- if (nc.phase === 'REMOVED') continue- const id = guidToString(nc.guid)- changeMap.set(id, nc)-- if (nc.parentIndex?.guid) {- parentMap.set(id, guidToString(nc.parentIndex.guid))- }- }-- function getChildren(ncId: string): string[] {- const children: string[] = []- for (const [childId, pid] of parentMap) {- if (pid === ncId) children.push(childId)- }- children.sort((a, b) => {- const aPos = changeMap.get(a)?.parentIndex?.position ?? ''- const bPos = changeMap.get(b)?.parentIndex?.position ?? ''- return aPos.localeCompare(bPos)- })- return children- }-- const created = new Set<string>()-- function createSceneNode(ncId: string, graphParentId: string) {- if (created.has(ncId)) return- created.add(ncId)-- const nc = changeMap.get(ncId)- if (!nc) return-- const nodeType = mapNodeType(nc.type)- if (nodeType === 'DOCUMENT') return-- const x = nc.transform?.m02 ?? 0- const y = nc.transform?.m12 ?? 0- const width = nc.size?.x ?? 100- const height = nc.size?.y ?? 100-- let rotation = 0- if (nc.transform) {- rotation = Math.atan2(nc.transform.m10, nc.transform.m00) * (180 / Math.PI)- }-- const dashPattern = (ext(nc).dashPattern as number[]) ?? []-- const node = graph.createNode(nodeType, graphParentId, {- name: nc.name ?? nodeType,- x,- y,- width,- height,- rotation,- opacity: nc.opacity ?? 1,- visible: nc.visible ?? true,- locked: nc.locked ?? false,- blendMode: (ext(nc).blendMode as Fill['blendMode']) ?? 'PASS_THROUGH',- fills: convertFills(nc.fillPaints),- strokes: convertStrokes(- nc.strokePaints,- nc.strokeWeight,- nc.strokeAlign,- nc.strokeCap,- nc.strokeJoin,- dashPattern- ),- effects: convertEffects(nc.effects),- cornerRadius: nc.cornerRadius ?? 0,- topLeftRadius: nc.rectangleTopLeftCornerRadius ?? nc.cornerRadius ?? 0,- topRightRadius: nc.rectangleTopRightCornerRadius ?? nc.cornerRadius ?? 0,- bottomRightRadius: nc.rectangleBottomRightCornerRadius ?? nc.cornerRadius ?? 0,- bottomLeftRadius: nc.rectangleBottomLeftCornerRadius ?? nc.cornerRadius ?? 0,- independentCorners: nc.rectangleCornerRadiiIndependent ?? false,- cornerSmoothing: nc.cornerSmoothing ?? 0,- text: nc.textData?.characters ?? '',- fontSize: nc.fontSize ?? 14,- fontFamily: nc.fontName?.family ?? 'Inter',- fontWeight: mapFontWeight(nc.fontName?.style),- textAlignHorizontal:- (nc.textAlignHorizontal as 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED') ?? 'LEFT',- textAlignVertical: (ext(nc).textAlignVertical as TextAlignVertical) ?? 'TOP',- textAutoResize: (ext(nc).textAutoResize as TextAutoResize) ?? 'NONE',- textCase: (ext(nc).textCase as TextCase) ?? 'ORIGINAL',- textDecoration: mapTextDecoration(ext(nc).textDecoration as string),- lineHeight: nc.lineHeight?.value ?? null,- letterSpacing: nc.letterSpacing?.value ?? 0,- maxLines: (ext(nc).maxLines as number) ?? null,- horizontalConstraint: mapConstraint(ext(nc).horizontalConstraint as string),- verticalConstraint: mapConstraint(ext(nc).verticalConstraint as string),- layoutMode: mapStackMode(nc.stackMode),- itemSpacing: nc.stackSpacing ?? 0,- paddingTop: nc.stackVerticalPadding ?? nc.stackPadding ?? 0,- paddingBottom: nc.stackPaddingBottom ?? nc.stackVerticalPadding ?? nc.stackPadding ?? 0,- paddingLeft: nc.stackHorizontalPadding ?? nc.stackPadding ?? 0,- paddingRight: nc.stackPaddingRight ?? nc.stackHorizontalPadding ?? nc.stackPadding ?? 0,- primaryAxisSizing: mapStackSizing(nc.stackPrimarySizing),- counterAxisSizing: mapStackSizing(nc.stackCounterSizing),- primaryAxisAlign: mapStackJustify(nc.stackPrimaryAlignItems ?? nc.stackJustify),- counterAxisAlign: mapStackCounterAlign(nc.stackCounterAlignItems ?? nc.stackCounterAlign),- 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,- vectorNetwork: resolveVectorNetwork(nc, blobs),- arcData: mapArcData(ext(nc).arcData as Record<string, number> | undefined),- strokeCap: (nc.strokeCap ?? 'NONE') as StrokeCap,- strokeJoin: (nc.strokeJoin ?? 'MITER') as StrokeJoin,- dashPattern,- borderTopWeight: (ext(nc).borderTopWeight as number) ?? 0,- borderRightWeight: (ext(nc).borderRightWeight as number) ?? 0,- borderBottomWeight: (ext(nc).borderBottomWeight as number) ?? 0,- borderLeftWeight: (ext(nc).borderLeftWeight as number) ?? 0,- independentStrokeWeights: (ext(nc).borderStrokeWeightsIndependent as boolean) ?? false- })-- for (const childId of getChildren(ncId)) {- createSceneNode(childId, node.id)- }- }-- // Find the document node (type=DOCUMENT or guid 0:0)- let docId: string | null = null- for (const [id, nc] of changeMap) {- if (nc.type === 'DOCUMENT' || id === '0:0') {- docId = id- break- }- }-- if (docId) {- // Import pages (CANVAS nodes) and their children- for (const canvasId of getChildren(docId)) {- const canvasNc = changeMap.get(canvasId)- if (!canvasNc) continue- if (canvasNc.type === 'CANVAS') {- const page = graph.addPage(canvasNc.name ?? 'Page')- created.add(canvasId)- for (const childId of getChildren(canvasId)) {- createSceneNode(childId, page.id)- }- } else {- createSceneNode(canvasId, graph.getPages()[0]?.id ?? graph.rootId)- }- }- } else {- // No document structure — treat all roots as children of the first page- const roots: string[] = []- for (const [id] of changeMap) {- const pid = parentMap.get(id)- if (!pid || !changeMap.has(pid)) roots.push(id)- }- const page = graph.getPages()[0] ?? graph.addPage('Page 1')- for (const rootId of roots) {- createSceneNode(rootId, page.id)- }- }-- // Ensure at least one page exists- if (graph.getPages().length === 0) {- graph.addPage('Page 1')- }-- return graph-}+export { importNodeChanges } from '@open-pencil/core'diff --git a/src/types.ts b/src/types.tsindex 14ea3f5c4..7ed93f197 100644--- a/src/types.ts+++ b/src/types.ts@@ -1,32 +1 @@-export interface GUID {- sessionID: number- localID: number-}--export interface Color {- r: number- g: number- b: number- a: number-}--export interface Vector {- x: number- y: number-}--export interface Matrix {- m00: number- m01: number- m02: number- m10: number- m11: number- m12: number-}--export interface Rect {- x: number- y: number- width: number- height: number-}+export type { GUID, Color, Vector, Matrix, Rect } from '@open-pencil/core'