AI-native design editor. Open-source Figma alternative.
perf(fig): restore large document load performance
Danila Poyarkovdf41f60a261a
diff --git a/packages/core/src/io/formats.ts b/packages/core/src/io/formats.tsindex f16526d09..0b0273a72 100644--- a/packages/core/src/io/formats.ts+++ b/packages/core/src/io/formats.ts@@ -161,7 +161,7 @@ export const figFormat: IOFormatAdapter = {},async readDocument(input) {const data = input.data.slice().buffer- const graph = await parseFigFile(data)+ const graph = await parseFigFile(data, { populate: 'first-page' })return { graph, sourceFormat: 'fig' }},async writeDocument(graph, options?: FigWriteOptions, context?: IOContext) {diff --git a/packages/fig/src/instance-overrides/index.ts b/packages/fig/src/instance-overrides/index.tsindex 1f439324e..a97276514 100644--- a/packages/fig/src/instance-overrides/index.ts+++ b/packages/fig/src/instance-overrides/index.ts@@ -18,7 +18,12 @@ import { isEqual } from 'es-toolkit/predicate'import { guidToString } from '@open-pencil/fig/node-change'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'-import { copyFills, copyStyleRuns } from '@open-pencil/scene-graph/copy'+import {+ copyFills,+ copyStyleRuns,+ hasSameCopySource,+ markCopySource+} from '@open-pencil/scene-graph/copy'import type { JsonObject } from '@open-pencil/scene-graph/primitives'import { applyComponentProperties } from './component-props'@@ -127,34 +132,57 @@ function propagateResolvedChildPlacementClones(graph: SceneGraph): void {}}+function sameDerivedGlyphSource(+ source: SceneNode['figmaDerivedTextGlyphs'],+ target: SceneNode['figmaDerivedTextGlyphs']+): boolean {+ if (source === target) return true+ if (!source || !target) return false+ return hasSameCopySource(source, target)+}+function propagateResolvedTextClones(graph: SceneGraph): void {- for (let pass = 0; pass < 10; pass++) {- let changed = false- for (const node of graph.getAllNodes()) {- if (node.type !== 'TEXT' || !node.componentId) continue- const source = graph.getNode(node.componentId)- if (source?.type !== 'TEXT' || source.text !== node.text) continue- if (- source.width === node.width &&- source.height === node.height &&- isEqual(source.fills, node.fills) &&- isEqual(source.styleRuns, node.styleRuns) &&- isEqual(source.figmaDerivedTextGlyphs, node.figmaDerivedTextGlyphs)- ) {- continue- }- graph.updateNode(node.id, {- width: source.width,- height: source.height,- fills: copyFills(source.fills),- styleRuns: copyStyleRuns(source.styleRuns),- figmaDerivedTextGlyphs: source.figmaDerivedTextGlyphs- ? structuredClone(source.figmaDerivedTextGlyphs)- : undefined- })- changed = true+ const ordered: SceneNode[] = []+ const visited = new Set<string>()+ const visiting = new Set<string>()+ const visit = (node: SceneNode) => {+ if (visited.has(node.id) || visiting.has(node.id)) return+ visiting.add(node.id)+ const source = node.componentId ? graph.getNode(node.componentId) : undefined+ if (source?.type === 'TEXT') visit(source)+ visiting.delete(node.id)+ visited.add(node.id)+ if (node.type === 'TEXT' && node.componentId) ordered.push(node)+ }+ for (const nodeId of graph.nodes.keys()) {+ const node = graph.getNode(nodeId)+ if (node?.type === 'TEXT' && node.componentId) visit(node)+ }++ for (const node of ordered) {+ const source = node.componentId ? graph.getNode(node.componentId) : undefined+ if (source?.type !== 'TEXT' || source.text !== node.text) continue+ if (+ source.width === node.width &&+ source.height === node.height &&+ isEqual(source.fills, node.fills) &&+ isEqual(source.styleRuns, node.styleRuns) &&+ sameDerivedGlyphSource(source.figmaDerivedTextGlyphs, node.figmaDerivedTextGlyphs)+ ) {+ continue}- if (!changed) return+ graph.updateNode(node.id, {+ width: source.width,+ height: source.height,+ fills: copyFills(source.fills),+ styleRuns: copyStyleRuns(source.styleRuns),+ figmaDerivedTextGlyphs: source.figmaDerivedTextGlyphs+ ? markCopySource(+ source.figmaDerivedTextGlyphs,+ structuredClone(source.figmaDerivedTextGlyphs)+ )+ : undefined+ })}}diff --git a/packages/fig/src/instance-overrides/populate.ts b/packages/fig/src/instance-overrides/populate.tsindex 0f227b078..62ccbb4e0 100644--- a/packages/fig/src/instance-overrides/populate.ts+++ b/packages/fig/src/instance-overrides/populate.ts@@ -48,7 +48,7 @@ export function populateInstances(}if (comp.childIds.length > 0 && node.childIds.length === 0) {- graph.populateInstanceChildren(nodeId, node.componentId)+ graph.populateInstanceChildren(nodeId, node.componentId, 'fig-import')}}diff --git a/packages/fig/src/instance-overrides/resolve.ts b/packages/fig/src/instance-overrides/resolve.tsindex bdd96aa00..51b17460b 100644--- a/packages/fig/src/instance-overrides/resolve.ts+++ b/packages/fig/src/instance-overrides/resolve.ts@@ -377,7 +377,7 @@ export function repopulateInstance(ctx: OverrideContext, nodeId: string, compId:}ctx.graph.preserveSourceMetadataDuring(() => ctx.graph.updateNode(nodeId, updates))if (comp && comp.childIds.length > 0) {- ctx.graph.populateInstanceChildren(nodeId, compId)+ ctx.graph.populateInstanceChildren(nodeId, compId, 'fig-import')applyStrokeDescendants(ctx, nodeId, previousStrokes)}ctx.swappedInstances.add(nodeId)diff --git a/packages/fig/src/instance-overrides/sync/clones.ts b/packages/fig/src/instance-overrides/sync/clones.tsindex 41e4ba22a..193c1a897 100644--- a/packages/fig/src/instance-overrides/sync/clones.ts+++ b/packages/fig/src/instance-overrides/sync/clones.ts@@ -16,7 +16,9 @@ export function recloneChildren(for (const childId of Array.from(tgtNode.childIds)) graph.deleteNode(childId)graph.updateNode(tgtNode.id, { name: srcChild.name, componentId: srcChild.componentId })syncNodeProps(graph, srcChild, tgtNode, protections)- if (srcChild.childIds.length > 0) graph.populateInstanceChildren(tgtNode.id, srcChildId)+ if (srcChild.childIds.length > 0) {+ graph.populateInstanceChildren(tgtNode.id, srcChildId, 'fig-import')+ }swappedInstances.add(tgtNode.id)}diff --git a/packages/fig/src/instance-overrides/sync/fields.ts b/packages/fig/src/instance-overrides/sync/fields.tsindex 7bca8673e..0a0ce9807 100644--- a/packages/fig/src/instance-overrides/sync/fields.ts+++ b/packages/fig/src/instance-overrides/sync/fields.ts@@ -1,5 +1,12 @@import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'-import { copyFills, copyStrokes, copyEffects, copyStyleRuns } from '@open-pencil/scene-graph/copy'+import {+ copyEffects,+ copyFills,+ copyStrokes,+ copyStyleRuns,+ hasSameCopySource,+ markCopySource+} from '@open-pencil/scene-graph/copy'import { isFieldProtected } from '../patches'import type { ProtectedField, ProtectionMap } from '../patches'@@ -73,23 +80,23 @@ function assignCopiedUpdate(): void {switch (key) {case 'fills':- updates.fills = copyFills(source.fills)+ updates.fills = markCopySource(source.fills, copyFills(source.fills))breakcase 'strokes':- updates.strokes = copyStrokes(source.strokes)+ updates.strokes = markCopySource(source.strokes, copyStrokes(source.strokes))breakcase 'effects':- updates.effects = copyEffects(source.effects)+ updates.effects = markCopySource(source.effects, copyEffects(source.effects))breakcase 'styleRuns':- updates.styleRuns = copyStyleRuns(source.styleRuns)+ updates.styleRuns = markCopySource(source.styleRuns, copyStyleRuns(source.styleRuns))break}}function copiedSync(key: CopiedSyncKey, field: ProtectedField): SyncFn {return (source, target, updates, protections) => {- if (source[key] !== target[key] && canSync(protections, target.id, field)) {+ if (!hasSameCopySource(source[key], target[key]) && canSync(protections, target.id, field)) {assignCopiedUpdate(key, source, updates)}}diff --git a/packages/fig/src/instance-overrides/sync/propagate.ts b/packages/fig/src/instance-overrides/sync/propagate.tsindex 62393fb9e..a56abb009 100644--- a/packages/fig/src/instance-overrides/sync/propagate.ts+++ b/packages/fig/src/instance-overrides/sync/propagate.ts@@ -78,7 +78,9 @@ export function propagateOverridesTransitively(syncNodeProps(graph, source, node, protections)if (source.childIds.length !== node.childIds.length) {for (const childId of Array.from(node.childIds)) graph.deleteNode(childId)- if (source.childIds.length > 0) graph.populateInstanceChildren(node.id, sourceId)+ if (source.childIds.length > 0) {+ graph.populateInstanceChildren(node.id, sourceId, 'fig-import')+ }} else if (source.childIds.length > 0 && node.childIds.length > 0) {syncChildrenDeep(graph, sourceId, node.id, swappedInstances, skip, protections)}diff --git a/packages/scene-graph/src/copy.ts b/packages/scene-graph/src/copy.tsindex ac606d94f..71613c7f1 100644--- a/packages/scene-graph/src/copy.ts+++ b/packages/scene-graph/src/copy.ts@@ -21,6 +21,7 @@ import type {Stroke,StyleRun} from './'+import { createDefaultSourceMetadata } from './node-defaults'import { cloneVectorNetwork } from './vector-network'// --- Individual copy functions ---@@ -70,6 +71,20 @@ export function copyStyleRun(r: StyleRun): StyleRun {// --- Array copy functions ---+const internalCopySources = new WeakMap<object, object>()++/** Record immutable lineage for an internal deep copy without sharing mutable values. */+export function markCopySource<T extends object>(source: T, copy: T): T {+ internalCopySources.set(copy, internalCopySources.get(source) ?? source)+ return copy+}++/** Compare internal deep copies in O(1) without traversing large paint or text payloads. */+export function hasSameCopySource(left: object, right: object): boolean {+ if (left === right) return true+ return (internalCopySources.get(left) ?? left) === (internalCopySources.get(right) ?? right)+}+export function copyFills(fills: Fill[]): Fill[] {return fills.map(copyFill)}@@ -145,21 +160,38 @@ function copyArcData(a: ArcData): ArcData {* would otherwise share by reference. When adding a mutable SceneNode field,* add its copy behavior here or document why sharing is intentional.*/-export function cloneNodeProps(src: SceneNode, componentId: string | null): Partial<SceneNode> {+export type NodeCloneMode = 'deep' | 'fig-import'++export function cloneNodeProps(+ src: SceneNode,+ componentId: string | null,+ mode: NodeCloneMode = 'deep'+): Partial<SceneNode> {const { id: _, parentId: _p, childIds: _c, ...rest } = src+ if (mode === 'fig-import') {+ return {+ ...rest,+ ...(componentId !== null ? { componentId } : {}),+ source: createDefaultSourceMetadata(),+ boundVariables: { ...src.boundVariables },+ overrides: Object.keys(src.overrides).length > 0 ? structuredClone(src.overrides) : {},+ componentPropertyAssignments: { ...src.componentPropertyAssignments },+ componentPropertyValues: { ...src.componentPropertyValues }+ }+ }return {...rest,...(componentId !== null ? { componentId } : {}),boundVariables: { ...src.boundVariables },overrides: Object.keys(src.overrides).length > 0 ? structuredClone(src.overrides) : {},- fills: copyOpt(src.fills, copyFills),- strokes: copyOpt(src.strokes, copyStrokes),- effects: copyOpt(src.effects, copyEffects),+ fills: copyOpt(src.fills, (value) => markCopySource(value, copyFills(value))),+ strokes: copyOpt(src.strokes, (value) => markCopySource(value, copyStrokes(value))),+ effects: copyOpt(src.effects, (value) => markCopySource(value, copyEffects(value))),layoutGrids: copyOpt(src.layoutGrids, copyLayoutGrids),- styleRuns: copyOpt(src.styleRuns, copyStyleRuns),- // Source metadata preserves opaque raw Figma payloads; use structuredClone instead of- // hand-copying partial known shapes and accidentally sharing nested raw Figma data.- source: structuredClone(src.source),+ styleRuns: copyOpt(src.styleRuns, (value) => markCopySource(value, copyStyleRuns(value))),+ // Generated instance descendants have no independent Figma provenance. Retaining the source+ // component's opaque raw payload here duplicates megabytes of metadata per instance.+ source: componentId === null ? structuredClone(src.source) : createDefaultSourceMetadata(),dashPattern: copyOpt(src.dashPattern, (a) => [...a]),fontVariations: copyOpt(src.fontVariations, (a) => a.map((v) => ({ ...v }))),fontFeatures: copyOpt(src.fontFeatures, (a) => a.map((v) => ({ ...v }))),@@ -181,7 +213,9 @@ export function cloneNodeProps(src: SceneNode, componentId: string | null): PartarcData: src.arcData ? copyArcData(src.arcData) : null,vectorNetwork: src.vectorNetwork ? cloneVectorNetwork(src.vectorNetwork) : null,textPicture: src.textPicture ? new Uint8Array(src.textPicture) : null,- figmaDerivedTextGlyphs: copyGlyphs(src.figmaDerivedTextGlyphs),+ figmaDerivedTextGlyphs: src.figmaDerivedTextGlyphs+ ? markCopySource(src.figmaDerivedTextGlyphs, copyGlyphs(src.figmaDerivedTextGlyphs) ?? [])+ : null,gridPosition: src.gridPosition ? { ...src.gridPosition } : null}}diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.tsindex dda9ef08c..48aea3c4d 100644--- a/packages/scene-graph/src/index.ts+++ b/packages/scene-graph/src/index.ts@@ -547,8 +547,12 @@ export class SceneGraph {return Instances.createInstance(this, componentId, parentId, overrides)}- populateInstanceChildren(instanceId: string, componentId: string): void {- Instances.populateInstanceChildren(this, instanceId, componentId)+ populateInstanceChildren(+ instanceId: string,+ componentId: string,+ mode: Instances.NodeCloneMode = 'deep'+ ): void {+ Instances.populateInstanceChildren(this, instanceId, componentId, mode)}swapInstanceComponent(instanceId: string, componentId: string): void {diff --git a/packages/scene-graph/src/instances.ts b/packages/scene-graph/src/instances.tsindex 5e9fe4bac..4bf4bd854 100644--- a/packages/scene-graph/src/instances.ts+++ b/packages/scene-graph/src/instances.ts@@ -1,5 +1,8 @@import type { SceneGraph, SceneNode } from './'import { cloneNodeProps, copyEffects, copyFills, copyStrokes, copyStyleRuns } from './copy'+import type { NodeCloneMode } from './copy'++export type { NodeCloneMode } from './copy'const INSTANCE_SYNC_PROPS: (keyof SceneNode)[] = ['width',@@ -77,7 +80,8 @@ function copyProp(function cloneChildrenWithMapping(graph: SceneGraph,sourceParentId: string,- destParentId: string+ destParentId: string,+ mode: NodeCloneMode = 'deep'): void {const sourceParent = graph.nodes.get(sourceParentId)if (!sourceParent) return@@ -86,10 +90,10 @@ function cloneChildrenWithMapping(const src = graph.nodes.get(childId)if (!src) continue- const clone = graph.createNode(src.type, destParentId, cloneNodeProps(src, childId))+ const clone = graph.createNode(src.type, destParentId, cloneNodeProps(src, childId, mode))if (src.childIds.length > 0) {- cloneChildrenWithMapping(graph, childId, clone.id)+ cloneChildrenWithMapping(graph, childId, clone.id, mode)}}}@@ -193,12 +197,13 @@ export function createInstance(export function populateInstanceChildren(graph: SceneGraph,instanceId: string,- componentId: string+ componentId: string,+ mode: NodeCloneMode = 'deep'): void {const instance = graph.nodes.get(instanceId)const component = graph.nodes.get(componentId)if (!instance || !component || instance.type !== 'INSTANCE') return- cloneChildrenWithMapping(graph, componentId, instanceId)+ cloneChildrenWithMapping(graph, componentId, instanceId, mode)}export function swapInstanceComponent(diff --git a/packages/scene-graph/src/node-defaults.ts b/packages/scene-graph/src/node-defaults.tsindex 9d68e854d..31975e7c8 100644--- a/packages/scene-graph/src/node-defaults.ts+++ b/packages/scene-graph/src/node-defaults.ts@@ -1,5 +1,25 @@import { BLACK, DEFAULT_FONT_FAMILY, DEFAULT_STROKE_MITER_LIMIT } from './constants'-import type { NodeType, SceneNode } from './types'+import type { NodeType, SceneNode, SourceMetadata } from './types'++export function createDefaultSourceMetadata(): SourceMetadata {+ return {+ format: null,+ id: null,+ orderKey: null,+ editedFields: [],+ fig: {+ rawSize: null,+ rawTransform: null,+ rawNodeFields: {},+ layout: null,+ symbolOverrides: [],+ componentPropAssignments: [],+ derivedSymbolData: [],+ derivedSymbolDataLayoutVersion: null,+ uniformScaleFactor: null+ }+ }+}export function createDefaultNode(generateId: () => string,@@ -17,23 +37,7 @@ export function createDefaultNode(width: 100,height: 100,rotation: 0,- source: {- format: null,- id: null,- orderKey: null,- editedFields: [],- fig: {- rawSize: null,- rawTransform: null,- rawNodeFields: {},- layout: null,- symbolOverrides: [],- componentPropAssignments: [],- derivedSymbolData: [],- derivedSymbolDataLayoutVersion: null,- uniformScaleFactor: null- }- },+ source: createDefaultSourceMetadata(),figmaDerivedLayout: null,fills:type === 'TEXT' ? [{ type: 'SOLID' as const, color: BLACK, opacity: 1, visible: true }] : [],diff --git a/tests/engine/scene-graph/clone/node-props.test.ts b/tests/engine/scene-graph/clone/node-props.test.tsindex 3820c2bd7..ef190d7f2 100644--- a/tests/engine/scene-graph/clone/node-props.test.ts+++ b/tests/engine/scene-graph/clone/node-props.test.ts@@ -137,6 +137,40 @@ describe('cloneNodeProps deep-copies overrides values', () => {})})+describe('cloneNodeProps fig import mode', () => {+ test('shares immutable payloads while resetting provenance and mutable maps', () => {+ const graph = new SceneGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Imported component child',+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, visible: true, opacity: 1 }],+ boundVariables: { 'fills/0/color': 'v1' },+ source: {+ format: 'fig',+ id: 'fig-source',+ orderKey: 'a',+ fig: {+ rawSize: { x: 100, y: 40 },+ rawTransform: null,+ rawNodeFields: { derivedTextData: { large: true } },+ layout: null,+ symbolOverrides: [],+ componentPropAssignments: [],+ derivedSymbolData: [],+ derivedSymbolDataLayoutVersion: null,+ uniformScaleFactor: null+ }+ }+ })++ const cloneProps = cloneNodeProps(node, node.id, 'fig-import')++ expect(cloneProps.fills).toBe(node.fills)+ expect(cloneProps.boundVariables).not.toBe(node.boundVariables)+ expect(cloneProps.source?.format).toBeNull()+ expect(cloneProps.source?.fig.rawNodeFields).toEqual({})+ })+})+describe('cloneNodeProps coverage guard', () => {test('cloneNodeProps does not crash when array fields are undefined', () => {const graph = new SceneGraph()