Skip to content

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

chore: update instance linkage with master

Danila Poyarkovca17b2ac5570
diff --cc packages/fig/src/clipboard/import.ts
index 000000000,75de28884..bb2c07f45
mode 000000,100644..100644
--- a/packages/fig/src/clipboard/import.ts
+++ b/packages/fig/src/clipboard/import.ts
@@@ -1,0 -1,293 +1,300 @@@
+ import { inflateSync } from 'fflate'
+ import { decode as decodeText, toUint8Array, isValid } from 'js-base64'
+
+ import type { NodeChange as KiwiNodeChange } from '@open-pencil/kiwi/fig/codec'
+ import { decodeBinarySchema, compileSchema, ByteBuffer } from '@open-pencil/kiwi/schema-runtime'
+ import type { SceneGraph } from '@open-pencil/scene-graph'
+
+ import { populateAndApplyOverrides, type InstanceNodeChange } from '../instance-overrides'
+ import {
+ nodeChangeToProps,
++ linkImportedInstanceChildren,
+ shouldImportTextAsAutoSize,
+ sortChildren,
+ parseFigKiwiChunks,
+ decompressFigKiwiDataAsync
+ } from '../node-change'
+
+ function decodeBase64(value: string): Uint8Array {
+ if (!isValid(value)) throw new TypeError('Invalid Base64 string')
+ return toUint8Array(value)
+ }
+ function decodeBase64Text(value: string): string {
+ if (!isValid(value)) throw new TypeError('Invalid Base64 string')
+ return decodeText(value)
+ }
+
+ interface FigmaClipboardMeta {
+ fileKey: string
+ pasteID: number
+ dataType: string
+ }
+
+ 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(decodeBase64Text(metaMatch[1]))
+ const binary = decodeBase64(bufMatch[1])
+
+ try {
+ const chunks = parseFigKiwiChunks(binary)
+ if (!chunks) return null
+
+ const schemaBytes = inflateSync(chunks[0])
+ const schema = decodeBinarySchema(new ByteBuffer(schemaBytes))
+ const compiled = compileSchema(schema)
+ if (!compiled.decodeMessage) return null
+ const dataRaw = await decompressFigKiwiDataAsync(chunks[1])
+ const msg = compiled.decodeMessage(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))
+ )
+
+ return { nodes: msg.nodeChanges ?? [], meta, blobs }
+ } catch {
+ return null
+ }
+ }
+
+ const NON_VISUAL_TYPES = new Set([
+ 'DOCUMENT',
+ 'CANVAS',
+ 'VARIABLE_SET',
+ 'VARIABLE',
+ 'VARIABLE_COLLECTION',
+ 'STYLE',
+ 'STYLE_SET',
+ 'INTERNAL_ONLY_NODE',
+ 'WIDGET',
+ 'STAMP',
+ 'STICKY',
+ 'SHAPE_WITH_TEXT',
+ 'CONNECTOR',
+ 'CODE_BLOCK',
+ 'TABLE_NODE',
+ 'TABLE_CELL',
+ 'SECTION_OVERLAY',
+ 'SLIDE'
+ ])
+
+ function isChildOfVisualNode(nc: KiwiNodeChange, parentTypes: Map<string, string>): boolean {
+ const parentId = nc.parentIndex?.guid
+ ? `${nc.parentIndex.guid.sessionID}:${nc.parentIndex.guid.localID}`
+ : null
+ return (
+ !!parentId &&
+ parentTypes.has(parentId) &&
+ !NON_VISUAL_TYPES.has(parentTypes.get(parentId) ?? '')
+ )
+ }
+
+ export function figmaNodesBounds(
+ nodeChanges: KiwiNodeChange[]
+ ): { x: number; y: number; w: number; h: number } | null {
+ let minX = Infinity
+ let minY = Infinity
+ let maxX = -Infinity
+ let maxY = -Infinity
+
+ const parentTypes = new Map<string, string>()
+ for (const nc of nodeChanges) {
+ if (!nc.guid) continue
+ const id = `${nc.guid.sessionID}:${nc.guid.localID}`
+ parentTypes.set(id, nc.type ?? '')
+ }
+
+ for (const nc of nodeChanges) {
+ if (!nc.type || NON_VISUAL_TYPES.has(nc.type)) continue
+ if (isChildOfVisualNode(nc, parentTypes)) continue
+
+ const x = nc.transform?.m02 ?? 0
+ const y = nc.transform?.m12 ?? 0
+ const w = nc.size?.x ?? 0
+ const h = nc.size?.y ?? 0
+ minX = Math.min(minX, x)
+ minY = Math.min(minY, y)
+ maxX = Math.max(maxX, x + w)
+ maxY = Math.max(maxY, y + h)
+ }
+
+ if (minX === Infinity) return null
+ return { x: minX, y: minY, w: maxX - minX, h: maxY - minY }
+ }
+
+ interface ClipboardImportMaps {
+ guidMap: Map<string, KiwiNodeChange>
+ parentMap: Map<string, string>
+ childMap: Map<string, string[]>
+ }
+
+ function buildClipboardMaps(nodeChanges: KiwiNodeChange[]): ClipboardImportMaps {
+ const guidMap = new Map<string, KiwiNodeChange>()
+ const parentMap = new Map<string, string>()
+ const childMap = 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) {
+ const parentId = `${nc.parentIndex.guid.sessionID}:${nc.parentIndex.guid.localID}`
+ parentMap.set(id, parentId)
+ const siblings = childMap.get(parentId)
+ if (siblings) siblings.push(id)
+ else childMap.set(parentId, [id])
+ }
+ }
+ return { guidMap, parentMap, childMap }
+ }
+
+ function findInternalNodeIds(
+ guidMap: Map<string, KiwiNodeChange>,
+ childMap: Map<string, string[]>
+ ): { internalCanvasIds: Set<string>; internalFigmaIds: Set<string> } {
+ const internalCanvasIds = new Set<string>()
+ for (const [id, nc] of guidMap) {
+ if (nc.type === 'CANVAS' && nc.internalOnly) {
+ internalCanvasIds.add(id)
+ }
+ }
+
+ const internalFigmaIds = new Set<string>()
+ function markInternal(id: string) {
+ internalFigmaIds.add(id)
+ for (const childId of childMap.get(id) ?? []) {
+ if (!internalFigmaIds.has(childId)) markInternal(childId)
+ }
+ }
+ for (const canvasId of internalCanvasIds) markInternal(canvasId)
+
+ return { internalCanvasIds, internalFigmaIds }
+ }
+
+ function classifyTopLevelNodes(
+ guidMap: Map<string, KiwiNodeChange>,
+ parentMap: Map<string, string>,
+ internalCanvasIds: Set<string>
+ ): { topLevel: string[]; internalTopLevel: string[] } {
+ const topLevel: string[] = []
+ const internalTopLevel: string[] = []
+ for (const [id, nc] of guidMap) {
+ if (NON_VISUAL_TYPES.has(nc.type ?? '')) continue
+ const parentId = parentMap.get(id)
+ if (
+ !parentId ||
+ !guidMap.has(parentId) ||
+ NON_VISUAL_TYPES.has(guidMap.get(parentId)?.type ?? '')
+ ) {
+ if (parentId && internalCanvasIds.has(parentId)) {
+ internalTopLevel.push(id)
+ } else {
+ topLevel.push(id)
+ }
+ }
+ }
+ return { topLevel, internalTopLevel }
+ }
+
+ function remapComponentIds(created: Map<string, string>, graph: SceneGraph): void {
+ for (const [, ourId] of created) {
+ const node = graph.getNode(ourId)
+ if (node?.type !== 'INSTANCE' || !node.componentId) continue
+ const ourComponentId = created.get(node.componentId)
+ if (ourComponentId) graph.updateNode(ourId, { componentId: ourComponentId })
+ }
+ }
+
+ function detachOrphanedInstances(created: Map<string, string>, graph: SceneGraph): void {
+ for (const [, ourId] of created) {
+ const node = graph.getNode(ourId)
+ if (node?.type !== 'INSTANCE') continue
+ if (node.childIds.length === 0 && (!node.componentId || !graph.getNode(node.componentId))) {
+ graph.updateNode(ourId, { type: 'FRAME', componentId: '' })
+ }
+ }
+ }
+
+ export function importClipboardNodes(
+ nodeChanges: KiwiNodeChange[],
+ graph: SceneGraph,
+ targetParentId: string,
+ offsetX = 0,
+ offsetY = 0,
+ blobs: Uint8Array[] = []
+ ): string[] {
+ const { guidMap, parentMap, childMap } = buildClipboardMaps(nodeChanges)
+ const { internalCanvasIds, internalFigmaIds } = findInternalNodeIds(guidMap, childMap)
+ const { topLevel, internalTopLevel } = classifyTopLevelNodes(
+ guidMap,
+ parentMap,
+ internalCanvasIds
+ )
+
+ 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 { nodeType, ...props } = nodeChangeToProps(nc, blobs)
+ if (nodeType === 'DOCUMENT' || nodeType === 'VARIABLE') return
+ if (shouldImportTextAsAutoSize(nc, guidMap.get(parentMap.get(figmaId) ?? ''))) {
+ props.textAutoResize = 'WIDTH_AND_HEIGHT'
+ }
+
+ if (ourParentId === targetParentId) {
+ props.x = (props.x ?? 0) + offsetX
+ props.y = (props.y ?? 0) + offsetY
+ }
+
+ const node = graph.createNode(nodeType, ourParentId, props)
+
+ created.set(figmaId, node.id)
+ if (ourParentId === targetParentId && !internalFigmaIds.has(figmaId)) createdIds.push(node.id)
+
+ const children = (childMap.get(figmaId) ?? []).filter(
+ (childId) => !NON_VISUAL_TYPES.has(guidMap.get(childId)?.type ?? '')
+ )
+ sortChildren(children, nc, guidMap)
+ for (const childId of children) {
+ createNode(childId, node.id)
+ }
+ }
+
+ for (const id of internalTopLevel) {
+ createNode(id, targetParentId)
+ }
+ for (const id of topLevel) {
+ createNode(id, targetParentId)
+ }
+
+ remapComponentIds(created, graph)
+
+ graph.preserveSourceMetadataDuring(() => {
+ populateAndApplyOverrides(graph, guidMap as Map<string, InstanceNodeChange>, created, blobs)
+ })
+
+ for (const figmaId of internalTopLevel) {
+ const ourId = created.get(figmaId)
+ if (ourId) graph.deleteNode(ourId)
+ }
+
+ detachOrphanedInstances(created, graph)
+
++ const pastedInstanceIds = new Set<string>()
++ for (const ourId of created.values()) {
++ if (graph.getNode(ourId)?.type === 'INSTANCE') pastedInstanceIds.add(ourId)
++ }
++ if (pastedInstanceIds.size > 0) linkImportedInstanceChildren(graph, pastedInstanceIds)
++
+ return createdIds
+ }