@pairdraw/scene-graph 0.20.0 → 0.21.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/color/index.d.ts +28 -7
- package/dist/color/index.d.ts.map +1 -1
- package/dist/color/index.js +40 -15
- package/dist/color/index.js.map +1 -1
- package/dist/color/management.d.ts +19 -6
- package/dist/color/management.d.ts.map +1 -1
- package/dist/color/management.js +56 -1
- package/dist/color/management.js.map +1 -1
- package/dist/color/profile.d.ts +32 -0
- package/dist/color/profile.d.ts.map +1 -0
- package/dist/color/profile.js +140 -0
- package/dist/color/profile.js.map +1 -0
- package/dist/comments/index.d.ts +2 -2
- package/dist/comments/index.js +2 -2
- package/dist/comments/merge.d.ts.map +1 -1
- package/dist/comments/merge.js +1 -0
- package/dist/comments/merge.js.map +1 -1
- package/dist/comments/schema.d.ts +3 -1
- package/dist/comments/schema.d.ts.map +1 -1
- package/dist/comments/schema.js +19 -2
- package/dist/comments/schema.js.map +1 -1
- package/dist/comments/threads.d.ts +3 -1
- package/dist/comments/threads.d.ts.map +1 -1
- package/dist/comments/threads.js +2 -1
- package/dist/comments/threads.js.map +1 -1
- package/dist/components/properties.d.ts.map +1 -1
- package/dist/components/properties.js +7 -7
- package/dist/components/properties.js.map +1 -1
- package/dist/css/shadows.d.ts +2 -2
- package/dist/css/shadows.d.ts.map +1 -1
- package/dist/css/shadows.js +4 -4
- package/dist/css/shadows.js.map +1 -1
- package/dist/css/values.d.ts +7 -2
- package/dist/css/values.d.ts.map +1 -1
- package/dist/css/values.js +8 -4
- package/dist/css/values.js.map +1 -1
- package/dist/empty-values.js +9 -0
- package/dist/empty-values.js.map +1 -1
- package/dist/graph.d.ts +4 -0
- package/dist/graph.d.ts.map +1 -1
- package/dist/graph.js +11 -2
- package/dist/graph.js.map +1 -1
- package/dist/images.d.ts +3 -2
- package/dist/images.d.ts.map +1 -1
- package/dist/images.js +18 -2
- package/dist/images.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/instances/copies.js +2 -1
- package/dist/instances/copies.js.map +1 -1
- package/dist/instances/index.d.ts.map +1 -1
- package/dist/instances/index.js +12 -11
- package/dist/instances/index.js.map +1 -1
- package/dist/instances/overrides.d.ts +15 -1
- package/dist/instances/overrides.d.ts.map +1 -1
- package/dist/instances/overrides.js +37 -1
- package/dist/instances/overrides.js.map +1 -1
- package/dist/instances/swap-overrides.js +3 -3
- package/dist/instances/swap-overrides.js.map +1 -1
- package/dist/instances/sync.js +9 -7
- package/dist/instances/sync.js.map +1 -1
- package/dist/node-defaults.js +2 -2
- package/dist/node-defaults.js.map +1 -1
- package/dist/plugin-data/fields.d.ts +15 -0
- package/dist/plugin-data/fields.d.ts.map +1 -1
- package/dist/plugin-data/fields.js +15 -23
- package/dist/plugin-data/fields.js.map +1 -1
- package/dist/plugin-data/index.d.ts +2 -2
- package/dist/plugin-data/index.js +2 -2
- package/dist/plugin-data/schema.d.ts +6 -1
- package/dist/plugin-data/schema.d.ts.map +1 -1
- package/dist/plugin-data/schema.js +24 -1
- package/dist/plugin-data/schema.js.map +1 -1
- package/dist/shaders/animation.d.ts +21 -0
- package/dist/shaders/animation.d.ts.map +1 -0
- package/dist/shaders/animation.js +25 -0
- package/dist/shaders/animation.js.map +1 -0
- package/dist/shaders/index.d.ts +2 -1
- package/dist/shaders/index.js +2 -1
- package/dist/slots/content.d.ts.map +1 -1
- package/dist/slots/content.js +4 -4
- package/dist/slots/content.js.map +1 -1
- package/dist/statuses/index.d.ts +2 -2
- package/dist/statuses/index.js +2 -2
- package/dist/statuses/workflow.d.ts +3 -1
- package/dist/statuses/workflow.d.ts.map +1 -1
- package/dist/statuses/workflow.js +6 -2
- package/dist/statuses/workflow.js.map +1 -1
- package/dist/transfer/variables.d.ts.map +1 -1
- package/dist/transfer/variables.js +1 -1
- package/dist/transfer/variables.js.map +1 -1
- package/dist/types.d.ts +34 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/variables/bindings.d.ts +6 -5
- package/dist/variables/bindings.d.ts.map +1 -1
- package/dist/variables/bindings.js +24 -16
- package/dist/variables/bindings.js.map +1 -1
- package/dist/variables/formula/index.d.ts.map +1 -1
- package/dist/variables/formula/index.js +12 -6
- package/dist/variables/formula/index.js.map +1 -1
- package/dist/variables/index.d.ts +14 -1
- package/dist/variables/index.d.ts.map +1 -1
- package/dist/variables/index.js +38 -10
- package/dist/variables/index.js.map +1 -1
- package/dist/variables/paints.d.ts +9 -8
- package/dist/variables/paints.d.ts.map +1 -1
- package/dist/variables/paints.js +35 -26
- package/dist/variables/paints.js.map +1 -1
- package/dist/variables/resolver.d.ts +45 -0
- package/dist/variables/resolver.d.ts.map +1 -0
- package/dist/variables/resolver.js +106 -0
- package/dist/variables/resolver.js.map +1 -0
- package/package.json +1 -1
- package/src/color/index.ts +43 -9
- package/src/color/management.ts +54 -1
- package/src/color/profile.ts +131 -0
- package/src/comments/merge.ts +3 -0
- package/src/comments/schema.ts +32 -2
- package/src/comments/threads.ts +5 -2
- package/src/components/properties.ts +13 -7
- package/src/css/shadows.ts +8 -5
- package/src/css/values.ts +12 -5
- package/src/empty-values.ts +16 -0
- package/src/graph.ts +13 -1
- package/src/images.ts +27 -3
- package/src/instances/copies.ts +2 -1
- package/src/instances/index.ts +19 -11
- package/src/instances/overrides.ts +49 -0
- package/src/instances/swap-overrides.ts +3 -2
- package/src/instances/sync.ts +11 -7
- package/src/node-defaults.ts +2 -2
- package/src/plugin-data/fields.ts +16 -31
- package/src/plugin-data/index.ts +1 -0
- package/src/plugin-data/schema.ts +30 -0
- package/src/shaders/animation.ts +39 -0
- package/src/shaders/index.ts +1 -0
- package/src/slots/content.ts +8 -4
- package/src/statuses/workflow.ts +6 -4
- package/src/transfer/variables.ts +2 -1
- package/src/types.ts +30 -1
- package/src/variables/bindings.ts +35 -18
- package/src/variables/formula/index.ts +19 -18
- package/src/variables/index.ts +49 -10
- package/src/variables/paints.ts +64 -29
- package/src/variables/resolver.ts +178 -0
package/dist/graph.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph.js","names":["Variables.createVariable","Variables.createCollection","Variables.createMode","Variables.getActiveModeId","Variables.getNodeVariableModeId","Variables.resolveVariable","Variables.resolveColorVariable","Variables.resolveNumberVariable","Variables.resolveColorVariableForNode","Variables.resolveNumberVariableForNode","Variables.resolveVariableForNode","Variables.resolveStringVariableForNode","Variables.getVariablesForCollection","Variables.getVariablesByType","HitTest.hitTest","HitTest.hitTestDeep","HitTest.hitTestSelectable","HitTest.hitTestOpenContainer","HitTest.isOpenContainer","HitTest.isPointInNode","HitTest.hitTestDropTarget","Instances.createInstance","Instances.getMainComponent","Instances.getInstances"],"sources":["../src/graph.ts"],"sourcesContent":["/* eslint-disable max-lines -- SceneGraph is the facade over the domain modules */\nimport { omitBy, pick } from 'es-toolkit/object'\nimport { isEmptyObject, isUndefined } from 'es-toolkit/predicate'\n\nimport { removeStaleBindings } from './bindings'\nimport { BufferedSceneEmitter } from './buffered-events'\nimport { assertPageLayout, finiteGeometry, pageLayoutOverrides } from './canvas-layout'\nimport {\n getAbsolutePosition,\n getNodeLocalMatrix,\n getParentWorldMatrix,\n isTranslationOnly,\n localTransformFromWorld\n} from './coordinate'\nimport { cloneNodeProps, type NodeCloneMode } from './copy'\nimport { normalizeEffects } from './effects'\nimport { shareEmptyNodeValues } from './empty-values'\nimport { bindNodeEvents } from './events'\nimport { TRANSFORM_FIELDS } from './fields/geometry'\nimport { LAYOUT_AFFECTING_KEYS } from './fields/layout'\nimport { withGeneratedFrameSize } from './generated'\nimport { gridLayoutChanges } from './grid-values'\nimport * as HitTest from './hit-test'\nimport { generateId } from './ids'\nimport * as Instances from './instances'\nimport { LayoutWrites } from './layout/writes'\nimport Matrix from './matrix'\nimport { CONTAINER_TYPES, createDefaultNode } from './node-defaults'\nimport { withPluginData } from './plugin-data/field'\nimport { PAIRDRAW_PLUGIN_DATA } from './plugin-data/fields'\nimport { updateNodePreview, type NodePreviewObserver } from './preview'\nimport type { Color, Rect, Vector } from './primitives'\n/* eslint-disable max-lines -- SceneGraph is the facade over the domain modules */\nimport { slotPropertyId } from './slots/frames'\nimport { markSourceFieldsEdited } from './source-metadata'\nimport { strokeLineChanges } from './strokes'\nimport { invalidateTextCaches } from './text/picture'\nimport type {\n DocumentColorSpace,\n DocumentKind,\n EnabledLibraryBinding,\n NodeChangeObserver,\n NodeType,\n SceneGraphEventHandlers,\n SceneNode,\n Variable,\n VariableCollection,\n VariableType,\n VariableValue,\n VariableLiteral\n} from './types'\nimport * as Variables from './variables'\nimport type { VariableModeFallback } from './variables'\nimport { normalizeVectorNetwork } from './vector-network'\n\n/** Scopes that graph methods check while a caller's callback runs; scopes nest. */\ntype GraphScope =\n | 'preview'\n | 'sourceMetadata'\n | 'importedState'\n | 'layout'\n | 'derivedLayout'\n | 'componentDerived'\n\nexport class SceneGraph {\n nodes = new Map<string, SceneNode>()\n images = new Map<string, Uint8Array>()\n variables = new Map<string, Variable>()\n variableCollections = new Map<string, VariableCollection>()\n activeMode = new Map<string, string>()\n rootId: string\n figKiwiVersion: number | null = null\n /** Deflated kiwi schema bytes from the original .fig file, preserved for roundtrip fidelity. */\n figSchemaDeflated: Uint8Array | null = null\n documentColorSpace: DocumentColorSpace = 'srgb'\n documentKind: DocumentKind = 'design'\n enabledLibraries = new Map<string, EnabledLibraryBinding>()\n readonly emitter = new BufferedSceneEmitter()\n private absPosCache = new Map<string, Vector>()\n private readonly scopeDepths: Record<GraphScope, number> = {\n preview: 0,\n sourceMetadata: 0,\n importedState: 0,\n layout: 0,\n derivedLayout: 0,\n componentDerived: 0\n }\n private previewObservers: NodePreviewObserver[] = []\n /** Edited-field marks added since the last undo step, which that step takes back when undone. */\n private pendingSourceMarks: Array<[string, string]> = []\n private readonly observeSourceMark = (id: string, field: string) => {\n this.pendingSourceMarks.push([id, field])\n }\n private readonly changeObservers = new Set<NodeChangeObserver>()\n /** How many waits outside the edit each recorder is paused for. */\n private readonly outsideWaits = new Map<NodeChangeObserver, number>()\n private importedIdGenerator: (() => string) | undefined\n private layoutWrites: LayoutWrites | null = null\n positionPreviewVersion = 0\n instanceIndex = new Map<string, Set<string>>()\n /** Every connector in the graph, so routing need not scan every layer. */\n connectorIds = new Set<string>()\n\n constructor(private readonly idGenerator: () => string = generateId) {\n const root = createDefaultNode(this.idGenerator, 'FRAME', {\n name: 'Document',\n width: 0,\n height: 0\n })\n this.rootId = root.id\n this.nodes.set(root.id, root)\n\n this.addPage('Page 1')\n }\n addPage(name: string): SceneNode {\n return this.createNode('CANVAS', this.rootId, { name, width: 0, height: 0 })\n }\n\n getPages(includeInternal = false): SceneNode[] {\n return this.getChildren(this.rootId).filter(\n (n) => n.type === 'CANVAS' && (includeInternal || !n.internalOnly)\n )\n }\n getAllNodes(): Iterable<SceneNode> {\n return this.nodes.values()\n }\n getNode(id: string): SceneNode | undefined {\n return this.nodes.get(id)\n }\n onNodeEvents(handlers: SceneGraphEventHandlers): () => void {\n return bindNodeEvents(this.emitter, handlers)\n }\n\n /**\n * Tells `observer` about each node an edit adds and, before it changes, each node it is about\n * to change, so a recorder can keep the node as it was. Unlike node events these are never\n * buffered. Graph methods report the nodes they change; code that writes into a node directly\n * reports it with `willChangeNode` first.\n */\n observeNodeChanges(observer: NodeChangeObserver): () => void {\n this.changeObservers.add(observer)\n return () => this.changeObservers.delete(observer)\n }\n\n /**\n /**\n * Runs `write`, a change someone else makes, such as a page the reader worker loaded or a\n * collaborator's arriving, outside every edit in progress: the recorders open now do not see\n * it, so none records it as its own. A recorder opened while the write runs is not paused.\n */\n runOutsideEdits<T>(write: () => T): T {\n const paused = [...this.changeObservers]\n for (const observer of paused) this.changeObservers.delete(observer)\n try {\n return write()\n } finally {\n for (const observer of paused) this.changeObservers.add(observer)\n }\n }\n\n /**\n * Waits for `promise`, such as a font or an image download an edit needs, outside the edit in\n * progress: what changes meanwhile, such as the user's or a collaborator's edit, is not recorded\n * as the waiting edit's. Only for code that writes nothing itself until the wait ends.\n */\n async waitOutsideEdit<T>(promise: Promise<T>): Promise<T> {\n // A wait pauses the recorders open when it starts, and only those: a recorder opened by a\n // later edit carries its own waits.\n const waiting = [...this.changeObservers]\n for (const observer of waiting) {\n const waits = this.outsideWaits.get(observer) ?? 0\n if (waits === 0) observer.pause?.()\n this.outsideWaits.set(observer, waits + 1)\n }\n try {\n return await promise\n } finally {\n for (const observer of waiting) {\n const waits = (this.outsideWaits.get(observer) ?? 1) - 1\n if (waits > 0) {\n this.outsideWaits.set(observer, waits)\n continue\n }\n this.outsideWaits.delete(observer)\n if (this.changeObservers.has(observer)) observer.resume?.()\n }\n }\n }\n\n /** Tells `observeNodeChanges` observers that `node` is about to change. */\n willChangeNode(node: SceneNode | undefined): void {\n if (!node) return\n for (const observer of this.changeObservers) observer.before(node)\n }\n\n countDescendants(nodeId: string): number {\n const node = this.nodes.get(nodeId)\n if (!node) return 0\n let count = 0\n const stack = [...node.childIds]\n while (stack.length > 0) {\n const id = stack.pop()\n if (id === undefined) break\n count++\n const child = this.nodes.get(id)\n if (child) {\n for (const childId of child.childIds) {\n stack.push(childId)\n }\n }\n }\n return count\n }\n addVariable(variable: Variable): void {\n Variables.addVariable(this, variable)\n }\n removeVariable(id: string): void {\n Variables.removeVariable(this, id)\n }\n addCollection(collection: VariableCollection): void {\n Variables.addCollection(this, collection)\n }\n createVariable(\n name: string,\n type: VariableType,\n collectionId: string,\n value?: VariableValue\n ): Variable {\n return Variables.createVariable(\n this,\n () => this.generateEntityId(),\n name,\n type,\n collectionId,\n value\n )\n }\n\n createCollection(name: string): VariableCollection {\n // The collection and its default mode are both created before either is registered.\n const issued = new Set<string>()\n return Variables.createCollection(this, () => this.generateEntityId(issued), name)\n }\n\n createMode(collectionId: string, name: string, sourceModeId?: string): string | undefined {\n return Variables.createMode(\n this,\n () => this.generateEntityId(),\n collectionId,\n name,\n sourceModeId\n )\n }\n\n /**\n * Mints IDs from this graph's generator for variables, collections, and modes built outside\n * it, such as a paste's: none is in use, and none repeats one this minter gave.\n */\n entityIdMinter(): () => string {\n const issued = new Set<string>()\n return () => this.generateEntityId(issued)\n }\n\n removeCollection(id: string): void {\n Variables.removeCollection(this, id)\n }\n\n getActiveModeId(collectionId: string): string {\n return Variables.getActiveModeId(this, collectionId)\n }\n\n getNodeVariableModeId(nodeId: string, collectionId: string): string {\n return Variables.getNodeVariableModeId(this, nodeId, collectionId)\n }\n\n setActiveMode(collectionId: string, modeId: string): void {\n Variables.setActiveMode(this, collectionId, modeId)\n }\n\n addMode(collectionId: string, modeId: string, name: string, sourceMode?: string): void {\n Variables.addMode(this, collectionId, modeId, name, sourceMode)\n }\n\n removeMode(collectionId: string, modeId: string): void {\n Variables.removeMode(this, collectionId, modeId)\n }\n\n renameMode(collectionId: string, modeId: string, name: string): void {\n Variables.renameMode(this, collectionId, modeId, name)\n }\n\n setDefaultMode(collectionId: string, modeId: string): void {\n Variables.setDefaultMode(this, collectionId, modeId)\n }\n\n resolveVariable(\n variableId: string,\n modeId?: string,\n visited?: Set<string>\n ): VariableLiteral | undefined {\n return Variables.resolveVariable(this, variableId, modeId, visited)\n }\n\n resolveColorVariable(variableId: string): Color | undefined {\n return Variables.resolveColorVariable(this, variableId)\n }\n\n resolveNumberVariable(variableId: string): number | undefined {\n return Variables.resolveNumberVariable(this, variableId)\n }\n\n resolveColorVariableForNode(\n nodeId: string,\n variableId: string,\n fallback?: VariableModeFallback\n ): Color | undefined {\n return Variables.resolveColorVariableForNode(this, nodeId, variableId, fallback)\n }\n\n resolveNumberVariableForNode(\n nodeId: string,\n variableId: string,\n fallback?: VariableModeFallback\n ): number | undefined {\n return Variables.resolveNumberVariableForNode(this, nodeId, variableId, fallback)\n }\n\n resolveVariableForNode(\n nodeId: string,\n variableId: string,\n fallback?: VariableModeFallback\n ): VariableLiteral | undefined {\n return Variables.resolveVariableForNode(this, nodeId, variableId, fallback)\n }\n\n resolveStringVariableForNode(\n nodeId: string,\n variableId: string,\n fallback?: VariableModeFallback\n ): string | undefined {\n return Variables.resolveStringVariableForNode(this, nodeId, variableId, fallback)\n }\n\n getVariablesForCollection(collectionId: string): Variable[] {\n return Variables.getVariablesForCollection(this, collectionId)\n }\n\n getVariablesByType(type: VariableType): Variable[] {\n return Variables.getVariablesByType(this, type)\n }\n\n bindVariable(nodeId: string, field: string, variableId: string): void {\n Variables.bindVariable(this, nodeId, field, variableId)\n }\n\n unbindVariable(nodeId: string, field: string): void {\n Variables.unbindVariable(this, nodeId, field)\n }\n\n getChildren(id: string): SceneNode[] {\n const node = this.nodes.get(id)\n if (!node) return []\n return node.childIds\n .map((cid) => this.nodes.get(cid))\n .filter((n): n is SceneNode => n !== undefined)\n }\n\n isContainer(id: string): boolean {\n const node = this.nodes.get(id)\n return node ? CONTAINER_TYPES.has(node.type) : false\n }\n\n isDescendant(childId: string, ancestorId: string): boolean {\n return this.closest(childId, (node) => node.id === ancestorId) !== undefined\n }\n\n /**\n * The node itself or its nearest ancestor that matches. The walk visits at most as many nodes\n * as the graph holds, so a parent cycle in bad data cannot hang it.\n */\n closest(id: string, match: (node: SceneNode) => boolean): SceneNode | undefined {\n let current = this.nodes.get(id)\n for (let steps = 0; current && steps < this.nodes.size; steps++) {\n if (match(current)) return current\n current = current.parentId ? this.nodes.get(current.parentId) : undefined\n }\n return undefined\n }\n\n /**\n * The page a node is on: the node itself for a page, its nearest page ancestor otherwise, and\n * null for the document root or a node on no page.\n */\n pageOf(id: string): string | null {\n return this.closest(id, (node) => node.type === 'CANVAS')?.id ?? null\n }\n\n clearAbsPosCache(): void {\n this.absPosCache.clear()\n }\n\n getAbsolutePosition(id: string): Vector {\n const cached = this.absPosCache.get(id)\n if (cached) return cached\n\n const node = this.getNode(id)\n if (!node) return { x: 0, y: 0 }\n\n const result = getAbsolutePosition(node, this)\n this.absPosCache.set(id, result)\n return result\n }\n\n getAbsoluteBounds(id: string): Rect {\n const pos = this.getAbsolutePosition(id)\n const node = this.nodes.get(id)\n return {\n x: pos.x,\n y: pos.y,\n width: node?.width ?? 0,\n height: node?.height ?? 0\n }\n }\n /**\n * An ID no entity uses; `issued` also excludes IDs handed out earlier in the same creation.\n * A generator that returns more taken IDs than the graph holds must be repeating itself, so\n * it counts as exhausted then; a fixed cap would reject a sequence walking past a large import.\n */\n private generateEntityId(issued?: Set<string>): string {\n let limit = Infinity\n for (let attempt = 0; attempt < limit; attempt++) {\n const id = (this.importedIdGenerator ?? this.idGenerator)()\n if (this.isEntityIdTaken(id) || issued?.has(id)) {\n if (limit === Infinity) limit = this.entityIdCount() + (issued?.size ?? 0) + 1\n continue\n }\n issued?.add(id)\n return id\n }\n throw new Error('The ID generator only returned IDs that are in use')\n }\n private entityIdCount(): number {\n let count = this.nodes.size + this.variables.size + this.variableCollections.size\n for (const collection of this.variableCollections.values()) count += collection.modes.length\n return count\n }\n /** Whether a node, variable, collection, or mode has this id. */\n isEntityIdTaken(id: string): boolean {\n if (this.nodes.has(id) || this.variables.has(id) || this.variableCollections.has(id))\n return true\n // Callers replace collection maps and edit `modes` in place (history snapshots, transfer,\n // undo), so an index of mode IDs would go stale; walk them without allocating instead.\n for (const collection of this.variableCollections.values()) {\n for (const mode of collection.modes) if (mode.modeId === id) return true\n }\n return false\n }\n private indexInstance(componentId: string, instanceId: string): void {\n let set = this.instanceIndex.get(componentId)\n if (!set) {\n set = new Set()\n this.instanceIndex.set(componentId, set)\n }\n set.add(instanceId)\n }\n private unindexInstance(componentId: string, instanceId: string): void {\n this.instanceIndex.get(componentId)?.delete(instanceId)\n }\n /**\n * The index lists instances by component, so a change of either, such as undoing a detach that\n * turns a frame back into an instance, moves the layer in it.\n */\n private reindexInstance(node: SceneNode, changes: Partial<SceneNode>): void {\n const indexedBefore = node.type === 'INSTANCE' ? node.componentId : null\n const componentAfter =\n 'componentId' in changes ? (changes.componentId ?? null) : node.componentId\n const indexedAfter = (changes.type ?? node.type) === 'INSTANCE' ? componentAfter : null\n if (indexedBefore === indexedAfter) return\n if (indexedBefore) this.unindexInstance(indexedBefore, node.id)\n if (indexedAfter) this.indexInstance(indexedAfter, node.id)\n }\n private registerNode(node: SceneNode, parentId: string | null): SceneNode {\n node.parentId = parentId\n this.nodes.set(node.id, node)\n if (node.type === 'CONNECTOR') this.connectorIds.add(node.id)\n for (const observer of this.changeObservers) observer.created(node)\n if (node.type === 'INSTANCE' && node.componentId) this.indexInstance(node.componentId, node.id)\n this.emitter.emit('node:created', node)\n return node\n }\n /** Publish synchronous graph events only after the supplied mutation succeeds. */\n withBufferedEvents<T>(action: () => T): T {\n return this.emitter.batch(action)\n }\n\n createNode(type: NodeType, parentId: string, overrides: Partial<SceneNode> = {}): SceneNode {\n const parent = this.nodes.get(parentId)\n if (!parent) throw new Error(`Parent \"${parentId}\" does not exist`)\n const node = createDefaultNode(\n () => this.generateEntityId(),\n type,\n pageLayoutOverrides(type, gridLayoutChanges(overrides))\n )\n Object.assign(node, strokeLineChanges(node, overrides))\n this.willChangeNode(parent)\n parent.childIds.push(node.id)\n return this.registerNode(node, parentId)\n }\n createNodeWithId(\n id: string,\n type: NodeType,\n parentId: string | null,\n overrides: Partial<SceneNode> = {}\n ): SceneNode {\n // A caller restoring or importing a layer must know it brings a new one: replacing a layer\n // that already has the ID would drop it, and its children, from the document.\n if (this.nodes.has(id)) throw new Error(`Node \"${id}\" already exists`)\n if (parentId === id) throw new Error(`Node \"${id}\" cannot be its own parent`)\n const parent = parentId === null ? undefined : this.nodes.get(parentId)\n if (parentId !== null && !parent) throw new Error(`Parent \"${parentId}\" does not exist`)\n const node = createDefaultNode(\n () => id,\n type,\n pageLayoutOverrides(type, gridLayoutChanges(overrides))\n )\n // `overrides` may be another node's snapshot, ID included.\n node.id = id\n if (parent && !parent.childIds.includes(id)) {\n this.willChangeNode(parent)\n parent.childIds.push(id)\n }\n return this.registerNode(node, parentId)\n }\n\n private withScope<T>(scope: GraphScope, fn: () => T): T {\n this.scopeDepths[scope]++\n try {\n return fn()\n } finally {\n this.scopeDepths[scope]--\n }\n }\n\n runPreviewUpdates(fn: () => void, beforeUpdate?: NodePreviewObserver): void {\n if (beforeUpdate) this.previewObservers.push(beforeUpdate)\n try {\n this.withScope('preview', fn)\n } finally {\n if (beforeUpdate) this.previewObservers.pop()\n }\n }\n preserveSourceMetadataDuring<T>(fn: () => T): T {\n return this.withScope('sourceMetadata', fn)\n }\n get isPreservingSourceMetadata(): boolean {\n return this.scopeDepths.sourceMetadata > 0\n }\n\n /** The edited-field marks added since the last call, which that undo step takes back. */\n takeSourceMarks(): Array<[string, string]> {\n const marks = this.pendingSourceMarks\n this.pendingSourceMarks = []\n return marks\n }\n\n /** Marks fields as edited again, for redo of a step that marked them. */\n addSourceMarks(id: string, fields: readonly string[]): void {\n const node = this.nodes.get(id)\n if (node) markSourceFieldsEdited(node, [...fields])\n }\n\n /** Takes back the marks a step added, for undo of that step. */\n removeSourceMarks(id: string, fields: readonly string[]): void {\n const node = this.nodes.get(id)\n if (!node) return\n const removed = new Set(fields)\n const kept = node.source.editedFields.filter((field) => !removed.has(field))\n if (kept.length !== node.source.editedFields.length) node.source.editedFields = kept\n }\n\n applyImportedStateDuring<T>(fn: () => T, idGenerator?: () => string): T {\n const previousGenerator = this.importedIdGenerator\n this.importedIdGenerator = idGenerator ?? previousGenerator\n try {\n return this.withScope('importedState', () => this.preserveSourceMetadataDuring(fn))\n } finally {\n this.importedIdGenerator = previousGenerator\n }\n }\n\n get isApplyingImportedState(): boolean {\n return this.scopeDepths.importedState > 0\n }\n\n /**\n * Lays out what the document already holds: a page as it loads, or again once its fonts\n * arrive. What this writes derives from the document; an edit's own layout is not this.\n */\n applyDerivedLayoutDuring(fn: () => void): void {\n this.withScope('derivedLayout', fn)\n }\n\n /**\n * Runs `fn` as values a copy takes from its component, such as the bound paints of a layer an\n * instance copies, refreshed for it. Source metadata is preserved, and a save leaves them to the\n * component rather than writing them as edits of the copy.\n */\n applyComponentDerivedDuring(fn: () => void): void {\n this.withScope('componentDerived', () => this.preserveSourceMetadataDuring(fn))\n }\n\n get isApplyingComponentDerived(): boolean {\n return this.scopeDepths.componentDerived > 0\n }\n\n get isApplyingDerivedLayout(): boolean {\n return this.scopeDepths.derivedLayout > 0\n }\n\n /**\n * Runs `fn` as layout. Its updates are published once the outermost layout ends, still as\n * layout, and without values a pass changed and a later pass put back (`LayoutWrites`). Outside\n * derived layout, the positions and sizes it publishes count as edited, so formats save them.\n */\n withLayoutMutations(fn: () => void): void {\n const outermost = this.scopeDepths.layout === 0\n this.scopeDepths.layout++\n if (outermost) this.layoutWrites = new LayoutWrites()\n try {\n fn()\n } finally {\n try {\n if (outermost) this.publishLayoutUpdates()\n } finally {\n this.scopeDepths.layout--\n }\n }\n }\n\n private publishLayoutUpdates(): void {\n const writes = this.layoutWrites\n this.layoutWrites = null\n if (!writes) return\n for (const [node, changes, edited] of writes.updates((nodeId) => this.nodes.get(nodeId))) {\n markSourceFieldsEdited(node, edited, this.observeSourceMark)\n this.emitter.emit('node:updated', node.id, changes)\n }\n }\n get isApplyingLayout(): boolean {\n return this.scopeDepths.layout > 0\n }\n updateNodePositionPreview(id: string, x: number, y: number): void {\n this.updateNodePreview(id, { x, y })\n }\n updateNodePreview(id: string, changes: Partial<SceneNode>): void {\n const node = this.nodes.get(id)\n if (node) {\n assertPageLayout(node, changes)\n changes = this.impliedChanges(node, finiteGeometry(changes))\n }\n const appliedChanges = updateNodePreview(this, id, changes, (node, applied) => {\n for (const observe of this.previewObservers) observe(node, applied)\n })\n if (appliedChanges) this.emitter.emit('node:previewUpdated', id, appliedChanges)\n }\n\n /**\n * Writes fields as given. Edits detach the shared styles whose fields they change before\n * they get here (`styleDetachmentChanges`); resolving bindings or loading a file does not.\n */\n updateNode(id: string, changes: Partial<SceneNode>): void {\n if (this.scopeDepths.preview > 0) {\n this.updateNodePreview(id, changes)\n return\n }\n\n const node = this.nodes.get(id)\n if (!node) return\n const given = gridLayoutChanges(finiteGeometry(omitBy(changes, isUndefined)))\n assertPageLayout(node, given)\n this.applyNodeChanges(node, this.impliedChanges(node, given))\n }\n\n /**\n * `changes` with what they also set: a size from outside layout on a generated frame, and\n * strokes and the layer's line fields kept in agreement (`strokeLineChanges`).\n */\n private impliedChanges(node: SceneNode, changes: Partial<SceneNode>): Partial<SceneNode> {\n const sized = this.isApplyingLayout ? changes : withGeneratedFrameSize(node, changes)\n const lines = strokeLineChanges(node, sized)\n return isEmptyObject(lines) ? sized : { ...sized, ...lines }\n }\n\n /** Replay captured properties without dropping explicit undefined values or absent keys. */\n restoreNodeProperties(\n id: string,\n changes: Partial<SceneNode>,\n absent: readonly (keyof SceneNode)[]\n ): void {\n const node = this.nodes.get(id)\n if (node) this.applyNodeChanges(node, changes, absent)\n }\n\n private applyNodeChanges(\n node: SceneNode,\n changes: Partial<SceneNode>,\n absent: readonly (keyof SceneNode)[] = []\n ): void {\n const { id } = node\n this.willChangeNode(node)\n // Include removed keys in cache invalidation and update notifications.\n if (absent.length) {\n changes = { ...changes }\n for (const key of absent) Reflect.set(changes, key, undefined)\n }\n\n // Only clear absPosCache when layout-affecting properties change.\n // Fills, strokes, effects, plugin data changes do NOT affect absolute position.\n const affectsLayout = Object.keys(changes).some((k) => LAYOUT_AFFECTING_KEYS.has(k))\n if (affectsLayout) this.absPosCache.clear()\n this.reindexInstance(node, changes)\n if (node.type === 'TEXT') invalidateTextCaches(node, changes)\n if (this.scopeDepths.sourceMetadata === 0 && !this.isApplyingLayout) {\n markSourceFieldsEdited(node, Object.keys(changes), this.observeSourceMark)\n }\n if (changes.vectorNetwork) {\n changes = { ...changes, vectorNetwork: normalizeVectorNetwork(changes.vectorNetwork) }\n }\n if (changes.effects) {\n changes = { ...changes, effects: normalizeEffects(changes.effects) }\n }\n this.layoutWrites?.record(\n node,\n changes,\n this.scopeDepths.sourceMetadata === 0 && !this.isApplyingDerivedLayout\n )\n Object.assign(node, changes)\n shareEmptyNodeValues(node, Object.keys(changes))\n if (changes.fills) removeStaleBindings(node, 'fills', changes)\n if (changes.strokes) removeStaleBindings(node, 'strokes', changes)\n // A bound paint written keeps what it was given until its variable's color changes.\n if ((changes.fills || changes.strokes) && !this.isApplyingImportedState)\n Variables.recordWrittenBoundPaints(this, node, changes)\n for (const key of absent) Reflect.deleteProperty(node, key)\n this.publishNodeUpdate(id, changes)\n }\n\n /** Marks fields an edit changed, unless metadata is being restored or layout is writing them. */\n private markEdited(node: SceneNode, keys: string[]): void {\n if (this.scopeDepths.sourceMetadata === 0 && !this.isApplyingLayout) {\n markSourceFieldsEdited(node, keys, this.observeSourceMark)\n }\n }\n\n /** Publishes an update now, or leaves it to the running layout, which publishes once it ends. */\n private publishNodeUpdate(id: string, changes: Partial<SceneNode>): void {\n if (!this.layoutWrites) this.emitter.emit('node:updated', id, changes)\n }\n\n /** Whether moving `node` under `parentId` would put an instance inside the component it draws. */\n private movesIntoInstanceOutsideSlot(parentId: string): boolean {\n let current = this.nodes.get(parentId)\n while (current) {\n if (slotPropertyId(current)) return false\n if (current.type === 'INSTANCE') return true\n current = current.parentId ? this.nodes.get(current.parentId) : undefined\n }\n return false\n }\n\n private movesInstanceIntoItsComponent(node: SceneNode, parentId: string): boolean {\n const stack = [node]\n while (stack.length > 0) {\n const current = stack.pop()\n if (!current) continue\n const componentId = current.componentId\n if (componentId && this.closest(parentId, (candidate) => candidate.id === componentId))\n return true\n for (const childId of current.childIds) {\n const child = this.nodes.get(childId)\n if (child) stack.push(child)\n }\n }\n return false\n }\n\n reparentNode(nodeId: string, newParentId: string): void {\n const node = this.nodes.get(nodeId)\n if (!node || nodeId === this.rootId) return\n // A page is never a layer: it holds the document's layers and cannot move inside one.\n if (node.type === 'CANVAS') return\n if (this.isDescendant(newParentId, nodeId)) return\n\n const oldParent = node.parentId ? this.nodes.get(node.parentId) : undefined\n const newParent = this.nodes.get(newParentId)\n if (!newParent) return\n if (node.parentId === newParentId) return\n\n // An instance inside the component it draws would sync itself forever, so Figma keeps it\n // out: the move is refused, as a move into the layer's own subtree is.\n if (this.movesInstanceIntoItsComponent(node, newParentId)) return\n // An instance's contents are its component's copies; only a slot takes the document's own\n // layers, so a layer moved anywhere else inside one would have nothing to correspond to.\n if (this.movesIntoInstanceOutsideSlot(newParentId)) return\n\n const oldParentId = node.parentId\n this.willChangeNode(node)\n this.willChangeNode(oldParent)\n this.willChangeNode(newParent)\n this.absPosCache.clear()\n\n const oldParentWorld = getParentWorldMatrix(oldParent, this)\n const newParentWorld = getParentWorldMatrix(newParent, this)\n\n if (oldParent) {\n oldParent.childIds = oldParent.childIds.filter((cid) => cid !== nodeId)\n }\n\n node.parentId = newParentId\n newParent.childIds.push(nodeId)\n\n const before = pick(node, TRANSFORM_FIELDS)\n if (isTranslationOnly(oldParentWorld) && isTranslationOnly(newParentWorld)) {\n node.x += oldParentWorld[2] - newParentWorld[2]\n node.y += oldParentWorld[5] - newParentWorld[5]\n } else {\n const world = Matrix.multiply(oldParentWorld, getNodeLocalMatrix(node))\n const local = localTransformFromWorld(node, world, newParentWorld)\n if (local) Object.assign(node, local)\n }\n // The node keeps its place on the canvas by new coordinates, which a save must write.\n this.markEdited(\n node,\n TRANSFORM_FIELDS.filter((key) => node[key] !== before[key])\n )\n\n this.emitter.emit('node:reparented', nodeId, oldParentId, newParentId)\n // Bound paints show their variables in the modes the layer now sits in.\n Variables.refreshMovedBoundPaints(this, nodeId, oldParentId)\n }\n\n /**\n * Moves a node to `index` among `parentId`'s children, from wherever it was, without changing\n * its own coordinates. An index past the end appends; a move into the node itself or one of\n * its descendants is ignored.\n */\n insertChildAt(childId: string, parentId: string, index: number): void {\n const node = this.nodes.get(childId)\n const newParent = this.nodes.get(parentId)\n if (!node || !newParent || this.isDescendant(parentId, childId)) return\n const previousParentId = node.parentId\n const oldParent = previousParentId ? this.nodes.get(previousParentId) : undefined\n this.willChangeNode(node)\n this.willChangeNode(oldParent)\n this.willChangeNode(newParent)\n if (oldParent) {\n oldParent.childIds = oldParent.childIds.filter((id) => id !== childId)\n }\n newParent.childIds = newParent.childIds.filter((id) => id !== childId)\n const at = Math.min(index, newParent.childIds.length)\n newParent.childIds.splice(at, 0, childId)\n node.parentId = parentId\n this.absPosCache.clear()\n this.emitter.emit('node:reordered', childId, parentId, at, previousParentId)\n if (previousParentId !== parentId)\n Variables.refreshMovedBoundPaints(this, childId, previousParentId)\n }\n\n deleteNode(id: string): void {\n const node = this.nodes.get(id)\n if (!node || id === this.rootId) return\n this.willChangeNode(node)\n\n if (node.parentId) {\n const parent = this.nodes.get(node.parentId)\n this.willChangeNode(parent)\n if (parent) {\n parent.childIds = parent.childIds.filter((cid) => cid !== id)\n }\n }\n\n this.deleteSubtree(node)\n }\n\n /**\n * Deletes `node` and its layers, children first. Their parent goes with them, so its child\n * list is emptied once instead of being filtered for each child, which kept deleting a frame\n * of thousands of layers quadratic. The list is emptied before the children go, so a listener\n * of a child's deletion never finds it still listed.\n */\n private deleteSubtree(node: SceneNode): void {\n const { id, childIds } = node\n node.childIds = []\n for (const childId of childIds) {\n const child = this.nodes.get(childId)\n if (!child) continue\n this.willChangeNode(child)\n this.deleteSubtree(child)\n }\n\n if (node.type === 'INSTANCE' && node.componentId) this.unindexInstance(node.componentId, id)\n // An override names a layer of its instance: one left naming a deleted layer would be written\n // as a claim for nothing, and reopening would restore a layer the document no longer has.\n for (let owner = node.parentId ? this.nodes.get(node.parentId) : undefined; owner;) {\n if (owner.type === 'INSTANCE') owner.instanceOverrides.descendants.delete(id)\n owner = owner.parentId ? this.nodes.get(owner.parentId) : undefined\n }\n this.connectorIds.delete(id)\n this.nodes.delete(id)\n this.emitter.emit('node:deleted', id, node.parentId)\n }\n\n hitTest(px: number, py: number, scopeId?: string): SceneNode | null {\n return HitTest.hitTest(this, px, py, scopeId)\n }\n\n /** `pad`, in canvas units, grows each shape's box, as Figma takes clicks just outside one. */\n hitTestDeep(px: number, py: number, scopeId?: string, pad = 0): SceneNode | null {\n return HitTest.hitTestDeep(this, px, py, scopeId, pad)\n }\n\n /**\n * The layer a press selects at the point; `locked` hits locked layers too, as a right-click does.\n */\n hitTestSelectable(\n px: number,\n py: number,\n scopeId: string,\n selectedIds: ReadonlySet<string>,\n pad = 0,\n locked = false\n ): SceneNode | null {\n return HitTest.hitTestSelectable(this, px, py, scopeId, selectedIds, pad, locked)\n }\n\n hitTestOpenContainer(px: number, py: number, scopeId: string): SceneNode | null {\n return HitTest.hitTestOpenContainer(this, px, py, scopeId)\n }\n\n isOpenContainer(nodeId: string): boolean {\n return HitTest.isOpenContainer(this, nodeId)\n }\n\n isPointInNode(nodeId: string, px: number, py: number): boolean {\n return HitTest.isPointInNode(this, nodeId, px, py)\n }\n\n hitTestDropTarget(\n px: number,\n py: number,\n excludeIds: ReadonlySet<string>,\n scopeId?: string,\n options?: HitTest.DropTargetOptions\n ): SceneNode | null {\n return HitTest.hitTestDropTarget(this, px, py, excludeIds, scopeId, options)\n }\n\n cloneTree(\n sourceId: string,\n parentId: string,\n overrides: Partial<SceneNode> = {}\n ): SceneNode | null {\n const copies = new Map<string, string>()\n const clone = this.cloneSubtree(sourceId, parentId, overrides, copies)\n // A copied instance records the overrides of its own layers, which are the cloned ones.\n Instances.retargetCopiedOverrides(this, copies)\n // A copy placed in other modes than its source shows its bound paints there, as a move does.\n if (clone) Variables.refreshMovedBoundPaints(this, clone.id, this.nodes.get(sourceId)?.parentId)\n return clone\n }\n\n private cloneSubtree(\n sourceId: string,\n parentId: string,\n overrides: Partial<SceneNode>,\n copies: Map<string, string>\n ): SceneNode | null {\n const src = this.nodes.get(sourceId)\n if (!src) return null\n\n const props = cloneNodeProps(src, null)\n // Null out Figma source identifiers so the clone is treated as local.\n if (props.source) props.source = { ...props.source, id: null, orderKey: null }\n // A copy is a new design nobody has reviewed: Figma's duplicate and clone() drop the status.\n props.status = null\n // A stand-in mark names one layer's place in a version of a design; a copy is not that.\n if (props.pluginData) {\n props.pluginData = withPluginData(\n props.pluginData,\n PAIRDRAW_PLUGIN_DATA.variationStandIn,\n undefined\n )\n }\n const clone = this.createNode(src.type, parentId, { ...props, ...overrides })\n Variables.copyAppliedBoundPaints(src, clone)\n copies.set(src.id, clone.id)\n if (src.status) markSourceFieldsEdited(clone, ['status'])\n\n for (const childId of src.childIds) {\n this.cloneSubtree(childId, clone.id, {}, copies)\n }\n\n return clone\n }\n\n createInstance(\n componentId: string,\n parentId: string,\n overrides: Partial<SceneNode> = {}\n ): SceneNode | null {\n return Instances.createInstance(this, componentId, parentId, overrides)\n }\n\n populateInstanceChildren(\n instanceId: string,\n componentId: string,\n mode: NodeCloneMode = 'deep'\n ): void {\n Instances.populateInstanceChildren(this, instanceId, componentId, mode)\n }\n\n swapInstanceComponent(\n instanceId: string,\n componentId: string,\n options?: Instances.SwapInstanceOptions\n ): void {\n Instances.swapInstanceComponent(this, instanceId, componentId, options)\n }\n\n syncInstances(componentId: string): void {\n Instances.syncInstances(this, componentId)\n }\n\n syncInstancesTogether(componentIds: Iterable<string>): void {\n Instances.syncInstancesTogether(this, componentIds)\n }\n\n syncInstance(instanceId: string): void {\n Instances.syncInstance(this, instanceId)\n }\n\n detachInstance(instanceId: string): void {\n Instances.detachInstance(this, instanceId)\n }\n\n getMainComponent(instanceId: string): SceneNode | undefined {\n return Instances.getMainComponent(this, instanceId)\n }\n\n getInstances(componentId: string): SceneNode[] {\n return Instances.getInstances(this, componentId)\n }\n\n /**\n * The descendants of a layer in depth-first order with their depths. Each layer with children is\n * walked once, so a cycle or repeated links in bad data cannot hang it or repeat its subtree.\n */\n flattenTree(parentId?: string, depth = 0): Array<{ node: SceneNode; depth: number }> {\n const id = parentId ?? this.rootId\n const parent = this.nodes.get(id)\n if (!parent) return []\n const result: Array<{ node: SceneNode; depth: number }> = []\n const pending = [{ node: parent, depth, index: 0 }]\n const walked = new Set([parent])\n while (pending.length > 0) {\n const frame = pending.at(-1)\n if (!frame) break\n if (frame.index >= frame.node.childIds.length) {\n pending.pop()\n continue\n }\n const child = this.nodes.get(frame.node.childIds[frame.index++])\n if (!child) continue\n const container = child.childIds.length > 0\n if (container && walked.has(child)) continue\n result.push({ node: child, depth: frame.depth })\n if (container) {\n walked.add(child)\n pending.push({ node: child, depth: frame.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AAK,MAAM,IAAI,MAAM,KAAK,SAAS,MAAM,QAAQ;GAC/D,IAAI,CAAC,OAAO;GACZ,MAAM,YAAY,MAAM,SAAS,SAAS;GAC1C,IAAI,aAAa,OAAO,IAAI,KAAK,GAAG;GACpC,OAAO,KAAK;IAAE,MAAM;IAAO,OAAO,MAAM;GAAM,CAAC;GAC/C,IAAI,WAAW;IACb,OAAO,IAAI,KAAK;IAChB,QAAQ,KAAK;KAAE,MAAM;KAAO,OAAO,MAAM,QAAQ;KAAG,OAAO;IAAE,CAAC;GAChE;EACF;EACA,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"graph.js","names":["Variables.createVariable","Variables.createCollection","Variables.createMode","Variables.getActiveModeId","Variables.getNodeVariableModeId","Variables.resolveVariable","Variables.resolveColorVariable","Variables.resolveNumberVariable","Variables.resolveColorVariableForNode","Variables.resolveNumberVariableForNode","Variables.resolveVariableForNode","Variables.resolveStringVariableForNode","Variables.getVariablesForCollection","Variables.getVariablesByType","Variables.liveVariables","Variables.liveCollections","HitTest.hitTest","HitTest.hitTestDeep","HitTest.hitTestSelectable","HitTest.hitTestOpenContainer","HitTest.isOpenContainer","HitTest.isPointInNode","HitTest.hitTestDropTarget","Instances.createInstance","Instances.getMainComponent","Instances.getInstances"],"sources":["../src/graph.ts"],"sourcesContent":["/* eslint-disable max-lines -- SceneGraph is the facade over the domain modules */\nimport { omitBy, pick } from 'es-toolkit/object'\nimport { isEmptyObject, isUndefined } from 'es-toolkit/predicate'\n\nimport { removeStaleBindings } from './bindings'\nimport { BufferedSceneEmitter } from './buffered-events'\nimport { assertPageLayout, finiteGeometry, pageLayoutOverrides } from './canvas-layout'\nimport {\n getAbsolutePosition,\n getNodeLocalMatrix,\n getParentWorldMatrix,\n isTranslationOnly,\n localTransformFromWorld\n} from './coordinate'\nimport { cloneNodeProps, type NodeCloneMode } from './copy'\nimport { normalizeEffects } from './effects'\nimport { shareEmptyNodeValues } from './empty-values'\nimport { bindNodeEvents } from './events'\nimport { TRANSFORM_FIELDS } from './fields/geometry'\nimport { LAYOUT_AFFECTING_KEYS } from './fields/layout'\nimport { withGeneratedFrameSize } from './generated'\nimport { gridLayoutChanges } from './grid-values'\nimport * as HitTest from './hit-test'\nimport { generateId } from './ids'\nimport * as Instances from './instances'\nimport { ownInstanceOverrides } from './instances/overrides'\nimport { LayoutWrites } from './layout/writes'\nimport Matrix from './matrix'\nimport { CONTAINER_TYPES, createDefaultNode } from './node-defaults'\nimport { withPluginData } from './plugin-data/field'\nimport { PAIRDRAW_PLUGIN_DATA } from './plugin-data/fields'\nimport { updateNodePreview, type NodePreviewObserver } from './preview'\nimport type { Color, Rect, Vector } from './primitives'\n/* eslint-disable max-lines -- SceneGraph is the facade over the domain modules */\nimport { slotPropertyId } from './slots/frames'\nimport { markSourceFieldsEdited } from './source-metadata'\nimport { strokeLineChanges } from './strokes'\nimport { invalidateTextCaches } from './text/picture'\nimport type {\n DocumentColorSpace,\n DocumentKind,\n EnabledLibraryBinding,\n NodeChangeObserver,\n NodeType,\n SceneGraphEventHandlers,\n SceneNode,\n Variable,\n VariableCollection,\n VariableType,\n VariableValue,\n VariableLiteral\n} from './types'\nimport * as Variables from './variables'\nimport type { VariableModeFallback } from './variables'\nimport { normalizeVectorNetwork } from './vector-network'\n\n/** Scopes that graph methods check while a caller's callback runs; scopes nest. */\ntype GraphScope =\n | 'preview'\n | 'sourceMetadata'\n | 'importedState'\n | 'layout'\n | 'derivedLayout'\n | 'componentDerived'\n\nexport class SceneGraph {\n nodes = new Map<string, SceneNode>()\n images = new Map<string, Uint8Array>()\n variables = new Map<string, Variable>()\n variableCollections = new Map<string, VariableCollection>()\n activeMode = new Map<string, string>()\n rootId: string\n figKiwiVersion: number | null = null\n /** Deflated kiwi schema bytes from the original .fig file, preserved for roundtrip fidelity. */\n figSchemaDeflated: Uint8Array | null = null\n documentColorSpace: DocumentColorSpace = 'srgb'\n documentKind: DocumentKind = 'design'\n enabledLibraries = new Map<string, EnabledLibraryBinding>()\n readonly emitter = new BufferedSceneEmitter()\n private absPosCache = new Map<string, Vector>()\n private readonly scopeDepths: Record<GraphScope, number> = {\n preview: 0,\n sourceMetadata: 0,\n importedState: 0,\n layout: 0,\n derivedLayout: 0,\n componentDerived: 0\n }\n private previewObservers: NodePreviewObserver[] = []\n /** Edited-field marks added since the last undo step, which that step takes back when undone. */\n private pendingSourceMarks: Array<[string, string]> = []\n private readonly observeSourceMark = (id: string, field: string) => {\n this.pendingSourceMarks.push([id, field])\n }\n private readonly changeObservers = new Set<NodeChangeObserver>()\n /** How many waits outside the edit each recorder is paused for. */\n private readonly outsideWaits = new Map<NodeChangeObserver, number>()\n private importedIdGenerator: (() => string) | undefined\n private layoutWrites: LayoutWrites | null = null\n positionPreviewVersion = 0\n instanceIndex = new Map<string, Set<string>>()\n /** Every connector in the graph, so routing need not scan every layer. */\n connectorIds = new Set<string>()\n\n constructor(private readonly idGenerator: () => string = generateId) {\n const root = createDefaultNode(this.idGenerator, 'FRAME', {\n name: 'Document',\n width: 0,\n height: 0\n })\n this.rootId = root.id\n this.nodes.set(root.id, root)\n\n this.addPage('Page 1')\n }\n addPage(name: string): SceneNode {\n return this.createNode('CANVAS', this.rootId, { name, width: 0, height: 0 })\n }\n\n getPages(includeInternal = false): SceneNode[] {\n return this.getChildren(this.rootId).filter(\n (n) => n.type === 'CANVAS' && (includeInternal || !n.internalOnly)\n )\n }\n getAllNodes(): Iterable<SceneNode> {\n return this.nodes.values()\n }\n getNode(id: string): SceneNode | undefined {\n return this.nodes.get(id)\n }\n onNodeEvents(handlers: SceneGraphEventHandlers): () => void {\n return bindNodeEvents(this.emitter, handlers)\n }\n\n /**\n * Tells `observer` about each node an edit adds and, before it changes, each node it is about\n * to change, so a recorder can keep the node as it was. Unlike node events these are never\n * buffered. Graph methods report the nodes they change; code that writes into a node directly\n * reports it with `willChangeNode` first.\n */\n observeNodeChanges(observer: NodeChangeObserver): () => void {\n this.changeObservers.add(observer)\n return () => this.changeObservers.delete(observer)\n }\n\n /**\n /**\n * Runs `write`, a change someone else makes, such as a page the reader worker loaded or a\n * collaborator's arriving, outside every edit in progress: the recorders open now do not see\n * it, so none records it as its own. A recorder opened while the write runs is not paused.\n */\n runOutsideEdits<T>(write: () => T): T {\n const paused = [...this.changeObservers]\n for (const observer of paused) this.changeObservers.delete(observer)\n try {\n return write()\n } finally {\n for (const observer of paused) this.changeObservers.add(observer)\n }\n }\n\n /**\n * Waits for `promise`, such as a font or an image download an edit needs, outside the edit in\n * progress: what changes meanwhile, such as the user's or a collaborator's edit, is not recorded\n * as the waiting edit's. Only for code that writes nothing itself until the wait ends.\n */\n async waitOutsideEdit<T>(promise: Promise<T>): Promise<T> {\n // A wait pauses the recorders open when it starts, and only those: a recorder opened by a\n // later edit carries its own waits.\n const waiting = [...this.changeObservers]\n for (const observer of waiting) {\n const waits = this.outsideWaits.get(observer) ?? 0\n if (waits === 0) observer.pause?.()\n this.outsideWaits.set(observer, waits + 1)\n }\n try {\n return await promise\n } finally {\n for (const observer of waiting) {\n const waits = (this.outsideWaits.get(observer) ?? 1) - 1\n if (waits > 0) {\n this.outsideWaits.set(observer, waits)\n continue\n }\n this.outsideWaits.delete(observer)\n if (this.changeObservers.has(observer)) observer.resume?.()\n }\n }\n }\n\n /** Tells `observeNodeChanges` observers that `node` is about to change. */\n willChangeNode(node: SceneNode | undefined): void {\n if (!node) return\n for (const observer of this.changeObservers) observer.before(node)\n }\n\n countDescendants(nodeId: string): number {\n const node = this.nodes.get(nodeId)\n if (!node) return 0\n let count = 0\n const stack = [...node.childIds]\n while (stack.length > 0) {\n const id = stack.pop()\n if (id === undefined) break\n count++\n const child = this.nodes.get(id)\n if (child) {\n for (const childId of child.childIds) {\n stack.push(childId)\n }\n }\n }\n return count\n }\n addVariable(variable: Variable): void {\n Variables.addVariable(this, variable)\n }\n removeVariable(id: string): void {\n Variables.removeVariable(this, id)\n }\n addCollection(collection: VariableCollection): void {\n Variables.addCollection(this, collection)\n }\n createVariable(\n name: string,\n type: VariableType,\n collectionId: string,\n value?: VariableValue\n ): Variable {\n return Variables.createVariable(\n this,\n () => this.generateEntityId(),\n name,\n type,\n collectionId,\n value\n )\n }\n\n createCollection(name: string): VariableCollection {\n // The collection and its default mode are both created before either is registered.\n const issued = new Set<string>()\n return Variables.createCollection(this, () => this.generateEntityId(issued), name)\n }\n\n createMode(collectionId: string, name: string, sourceModeId?: string): string | undefined {\n return Variables.createMode(\n this,\n () => this.generateEntityId(),\n collectionId,\n name,\n sourceModeId\n )\n }\n\n /**\n * Mints IDs from this graph's generator for variables, collections, and modes built outside\n * it, such as a paste's: none is in use, and none repeats one this minter gave.\n */\n entityIdMinter(): () => string {\n const issued = new Set<string>()\n return () => this.generateEntityId(issued)\n }\n\n removeCollection(id: string): void {\n Variables.removeCollection(this, id)\n }\n\n getActiveModeId(collectionId: string): string {\n return Variables.getActiveModeId(this, collectionId)\n }\n\n getNodeVariableModeId(nodeId: string, collectionId: string): string {\n return Variables.getNodeVariableModeId(this, nodeId, collectionId)\n }\n\n setActiveMode(collectionId: string, modeId: string): void {\n Variables.setActiveMode(this, collectionId, modeId)\n }\n\n addMode(collectionId: string, modeId: string, name: string, sourceMode?: string): void {\n Variables.addMode(this, collectionId, modeId, name, sourceMode)\n }\n\n removeMode(collectionId: string, modeId: string): void {\n Variables.removeMode(this, collectionId, modeId)\n }\n\n renameMode(collectionId: string, modeId: string, name: string): void {\n Variables.renameMode(this, collectionId, modeId, name)\n }\n\n setDefaultMode(collectionId: string, modeId: string): void {\n Variables.setDefaultMode(this, collectionId, modeId)\n }\n\n resolveVariable(\n variableId: string,\n modeId?: string,\n visited?: Set<string>\n ): VariableLiteral | undefined {\n return Variables.resolveVariable(this, variableId, modeId, visited)\n }\n\n resolveColorVariable(variableId: string): Color | undefined {\n return Variables.resolveColorVariable(this, variableId)\n }\n\n resolveNumberVariable(variableId: string): number | undefined {\n return Variables.resolveNumberVariable(this, variableId)\n }\n\n resolveColorVariableForNode(\n nodeId: string,\n variableId: string,\n fallback?: VariableModeFallback\n ): Color | undefined {\n return Variables.resolveColorVariableForNode(this, nodeId, variableId, fallback)\n }\n\n resolveNumberVariableForNode(\n nodeId: string,\n variableId: string,\n fallback?: VariableModeFallback\n ): number | undefined {\n return Variables.resolveNumberVariableForNode(this, nodeId, variableId, fallback)\n }\n\n resolveVariableForNode(\n nodeId: string,\n variableId: string,\n fallback?: VariableModeFallback\n ): VariableLiteral | undefined {\n return Variables.resolveVariableForNode(this, nodeId, variableId, fallback)\n }\n\n resolveStringVariableForNode(\n nodeId: string,\n variableId: string,\n fallback?: VariableModeFallback\n ): string | undefined {\n return Variables.resolveStringVariableForNode(this, nodeId, variableId, fallback)\n }\n\n getVariablesForCollection(collectionId: string): Variable[] {\n return Variables.getVariablesForCollection(this, collectionId)\n }\n\n getVariablesByType(type: VariableType): Variable[] {\n return Variables.getVariablesByType(this, type)\n }\n\n /** Every variable but the deleted ones, which only their bindings still reach. */\n getLiveVariables(): Variable[] {\n return Variables.liveVariables(this)\n }\n\n /** Every collection but the deleted ones. */\n getLiveCollections(): VariableCollection[] {\n return Variables.liveCollections(this)\n }\n\n bindVariable(nodeId: string, field: string, variableId: string): void {\n Variables.bindVariable(this, nodeId, field, variableId)\n }\n\n unbindVariable(nodeId: string, field: string): void {\n Variables.unbindVariable(this, nodeId, field)\n }\n\n getChildren(id: string): SceneNode[] {\n const node = this.nodes.get(id)\n if (!node) return []\n return node.childIds\n .map((cid) => this.nodes.get(cid))\n .filter((n): n is SceneNode => n !== undefined)\n }\n\n isContainer(id: string): boolean {\n const node = this.nodes.get(id)\n return node ? CONTAINER_TYPES.has(node.type) : false\n }\n\n isDescendant(childId: string, ancestorId: string): boolean {\n return this.closest(childId, (node) => node.id === ancestorId) !== undefined\n }\n\n /**\n * The node itself or its nearest ancestor that matches. The walk visits at most as many nodes\n * as the graph holds, so a parent cycle in bad data cannot hang it.\n */\n closest(id: string, match: (node: SceneNode) => boolean): SceneNode | undefined {\n let current = this.nodes.get(id)\n for (let steps = 0; current && steps < this.nodes.size; steps++) {\n if (match(current)) return current\n current = current.parentId ? this.nodes.get(current.parentId) : undefined\n }\n return undefined\n }\n\n /**\n * The page a node is on: the node itself for a page, its nearest page ancestor otherwise, and\n * null for the document root or a node on no page.\n */\n pageOf(id: string): string | null {\n return this.closest(id, (node) => node.type === 'CANVAS')?.id ?? null\n }\n\n clearAbsPosCache(): void {\n this.absPosCache.clear()\n }\n\n getAbsolutePosition(id: string): Vector {\n const cached = this.absPosCache.get(id)\n if (cached) return cached\n\n const node = this.getNode(id)\n if (!node) return { x: 0, y: 0 }\n\n const result = getAbsolutePosition(node, this)\n this.absPosCache.set(id, result)\n return result\n }\n\n getAbsoluteBounds(id: string): Rect {\n const pos = this.getAbsolutePosition(id)\n const node = this.nodes.get(id)\n return {\n x: pos.x,\n y: pos.y,\n width: node?.width ?? 0,\n height: node?.height ?? 0\n }\n }\n /**\n * An ID no entity uses; `issued` also excludes IDs handed out earlier in the same creation.\n * A generator that returns more taken IDs than the graph holds must be repeating itself, so\n * it counts as exhausted then; a fixed cap would reject a sequence walking past a large import.\n */\n private generateEntityId(issued?: Set<string>): string {\n let limit = Infinity\n for (let attempt = 0; attempt < limit; attempt++) {\n const id = (this.importedIdGenerator ?? this.idGenerator)()\n if (this.isEntityIdTaken(id) || issued?.has(id)) {\n if (limit === Infinity) limit = this.entityIdCount() + (issued?.size ?? 0) + 1\n continue\n }\n issued?.add(id)\n return id\n }\n throw new Error('The ID generator only returned IDs that are in use')\n }\n private entityIdCount(): number {\n let count = this.nodes.size + this.variables.size + this.variableCollections.size\n for (const collection of this.variableCollections.values()) count += collection.modes.length\n return count\n }\n /** Whether a node, variable, collection, or mode has this id. */\n isEntityIdTaken(id: string): boolean {\n if (this.nodes.has(id) || this.variables.has(id) || this.variableCollections.has(id))\n return true\n // Callers replace collection maps and edit `modes` in place (history snapshots, transfer,\n // undo), so an index of mode IDs would go stale; walk them without allocating instead.\n for (const collection of this.variableCollections.values()) {\n for (const mode of collection.modes) if (mode.modeId === id) return true\n }\n return false\n }\n private indexInstance(componentId: string, instanceId: string): void {\n let set = this.instanceIndex.get(componentId)\n if (!set) {\n set = new Set()\n this.instanceIndex.set(componentId, set)\n }\n set.add(instanceId)\n }\n private unindexInstance(componentId: string, instanceId: string): void {\n this.instanceIndex.get(componentId)?.delete(instanceId)\n }\n /**\n * The index lists instances by component, so a change of either, such as undoing a detach that\n * turns a frame back into an instance, moves the layer in it.\n */\n private reindexInstance(node: SceneNode, changes: Partial<SceneNode>): void {\n const indexedBefore = node.type === 'INSTANCE' ? node.componentId : null\n const componentAfter =\n 'componentId' in changes ? (changes.componentId ?? null) : node.componentId\n const indexedAfter = (changes.type ?? node.type) === 'INSTANCE' ? componentAfter : null\n if (indexedBefore === indexedAfter) return\n if (indexedBefore) this.unindexInstance(indexedBefore, node.id)\n if (indexedAfter) this.indexInstance(indexedAfter, node.id)\n }\n private registerNode(node: SceneNode, parentId: string | null): SceneNode {\n node.parentId = parentId\n this.nodes.set(node.id, node)\n if (node.type === 'CONNECTOR') this.connectorIds.add(node.id)\n for (const observer of this.changeObservers) observer.created(node)\n if (node.type === 'INSTANCE' && node.componentId) this.indexInstance(node.componentId, node.id)\n this.emitter.emit('node:created', node)\n return node\n }\n /** Publish synchronous graph events only after the supplied mutation succeeds. */\n withBufferedEvents<T>(action: () => T): T {\n return this.emitter.batch(action)\n }\n\n createNode(type: NodeType, parentId: string, overrides: Partial<SceneNode> = {}): SceneNode {\n const parent = this.nodes.get(parentId)\n if (!parent) throw new Error(`Parent \"${parentId}\" does not exist`)\n const node = createDefaultNode(\n () => this.generateEntityId(),\n type,\n pageLayoutOverrides(type, gridLayoutChanges(overrides))\n )\n Object.assign(node, strokeLineChanges(node, overrides))\n this.willChangeNode(parent)\n parent.childIds.push(node.id)\n return this.registerNode(node, parentId)\n }\n createNodeWithId(\n id: string,\n type: NodeType,\n parentId: string | null,\n overrides: Partial<SceneNode> = {}\n ): SceneNode {\n // A caller restoring or importing a layer must know it brings a new one: replacing a layer\n // that already has the ID would drop it, and its children, from the document.\n if (this.nodes.has(id)) throw new Error(`Node \"${id}\" already exists`)\n if (parentId === id) throw new Error(`Node \"${id}\" cannot be its own parent`)\n const parent = parentId === null ? undefined : this.nodes.get(parentId)\n if (parentId !== null && !parent) throw new Error(`Parent \"${parentId}\" does not exist`)\n const node = createDefaultNode(\n () => id,\n type,\n pageLayoutOverrides(type, gridLayoutChanges(overrides))\n )\n // `overrides` may be another node's snapshot, ID included.\n node.id = id\n if (parent && !parent.childIds.includes(id)) {\n this.willChangeNode(parent)\n parent.childIds.push(id)\n }\n return this.registerNode(node, parentId)\n }\n\n private withScope<T>(scope: GraphScope, fn: () => T): T {\n this.scopeDepths[scope]++\n try {\n return fn()\n } finally {\n this.scopeDepths[scope]--\n }\n }\n\n runPreviewUpdates(fn: () => void, beforeUpdate?: NodePreviewObserver): void {\n if (beforeUpdate) this.previewObservers.push(beforeUpdate)\n try {\n this.withScope('preview', fn)\n } finally {\n if (beforeUpdate) this.previewObservers.pop()\n }\n }\n preserveSourceMetadataDuring<T>(fn: () => T): T {\n return this.withScope('sourceMetadata', fn)\n }\n get isPreservingSourceMetadata(): boolean {\n return this.scopeDepths.sourceMetadata > 0\n }\n\n /** The edited-field marks added since the last call, which that undo step takes back. */\n takeSourceMarks(): Array<[string, string]> {\n const marks = this.pendingSourceMarks\n this.pendingSourceMarks = []\n return marks\n }\n\n /** Marks fields as edited again, for redo of a step that marked them. */\n addSourceMarks(id: string, fields: readonly string[]): void {\n const node = this.nodes.get(id)\n if (node) markSourceFieldsEdited(node, [...fields])\n }\n\n /** Takes back the marks a step added, for undo of that step. */\n removeSourceMarks(id: string, fields: readonly string[]): void {\n const node = this.nodes.get(id)\n if (!node) return\n const removed = new Set(fields)\n const kept = node.source.editedFields.filter((field) => !removed.has(field))\n if (kept.length !== node.source.editedFields.length) node.source.editedFields = kept\n }\n\n applyImportedStateDuring<T>(fn: () => T, idGenerator?: () => string): T {\n const previousGenerator = this.importedIdGenerator\n this.importedIdGenerator = idGenerator ?? previousGenerator\n try {\n return this.withScope('importedState', () => this.preserveSourceMetadataDuring(fn))\n } finally {\n this.importedIdGenerator = previousGenerator\n }\n }\n\n get isApplyingImportedState(): boolean {\n return this.scopeDepths.importedState > 0\n }\n\n /**\n * Lays out what the document already holds: a page as it loads, or again once its fonts\n * arrive. What this writes derives from the document; an edit's own layout is not this.\n */\n applyDerivedLayoutDuring(fn: () => void): void {\n this.withScope('derivedLayout', fn)\n }\n\n /**\n * Runs `fn` as values a copy takes from its component, such as the bound paints of a layer an\n * instance copies, refreshed for it. Source metadata is preserved, and a save leaves them to the\n * component rather than writing them as edits of the copy.\n */\n applyComponentDerivedDuring(fn: () => void): void {\n this.withScope('componentDerived', () => this.preserveSourceMetadataDuring(fn))\n }\n\n get isApplyingComponentDerived(): boolean {\n return this.scopeDepths.componentDerived > 0\n }\n\n get isApplyingDerivedLayout(): boolean {\n return this.scopeDepths.derivedLayout > 0\n }\n\n /**\n * Runs `fn` as layout. Its updates are published once the outermost layout ends, still as\n * layout, and without values a pass changed and a later pass put back (`LayoutWrites`). Outside\n * derived layout, the positions and sizes it publishes count as edited, so formats save them.\n */\n withLayoutMutations(fn: () => void): void {\n const outermost = this.scopeDepths.layout === 0\n this.scopeDepths.layout++\n if (outermost) this.layoutWrites = new LayoutWrites()\n try {\n fn()\n } finally {\n try {\n if (outermost) this.publishLayoutUpdates()\n } finally {\n this.scopeDepths.layout--\n }\n }\n }\n\n private publishLayoutUpdates(): void {\n const writes = this.layoutWrites\n this.layoutWrites = null\n if (!writes) return\n for (const [node, changes, edited] of writes.updates((nodeId) => this.nodes.get(nodeId))) {\n markSourceFieldsEdited(node, edited, this.observeSourceMark)\n this.emitter.emit('node:updated', node.id, changes)\n }\n }\n get isApplyingLayout(): boolean {\n return this.scopeDepths.layout > 0\n }\n updateNodePositionPreview(id: string, x: number, y: number): void {\n this.updateNodePreview(id, { x, y })\n }\n updateNodePreview(id: string, changes: Partial<SceneNode>): void {\n const node = this.nodes.get(id)\n if (node) {\n assertPageLayout(node, changes)\n changes = this.impliedChanges(node, finiteGeometry(changes))\n }\n const appliedChanges = updateNodePreview(this, id, changes, (node, applied) => {\n for (const observe of this.previewObservers) observe(node, applied)\n })\n if (appliedChanges) this.emitter.emit('node:previewUpdated', id, appliedChanges)\n }\n\n /**\n * Writes fields as given. Edits detach the shared styles whose fields they change before\n * they get here (`styleDetachmentChanges`); resolving bindings or loading a file does not.\n */\n updateNode(id: string, changes: Partial<SceneNode>): void {\n if (this.scopeDepths.preview > 0) {\n this.updateNodePreview(id, changes)\n return\n }\n\n const node = this.nodes.get(id)\n if (!node) return\n const given = gridLayoutChanges(finiteGeometry(omitBy(changes, isUndefined)))\n assertPageLayout(node, given)\n this.applyNodeChanges(node, this.impliedChanges(node, given))\n }\n\n /**\n * `changes` with what they also set: a size from outside layout on a generated frame, and\n * strokes and the layer's line fields kept in agreement (`strokeLineChanges`).\n */\n private impliedChanges(node: SceneNode, changes: Partial<SceneNode>): Partial<SceneNode> {\n const sized = this.isApplyingLayout ? changes : withGeneratedFrameSize(node, changes)\n const lines = strokeLineChanges(node, sized)\n return isEmptyObject(lines) ? sized : { ...sized, ...lines }\n }\n\n /** Replay captured properties without dropping explicit undefined values or absent keys. */\n restoreNodeProperties(\n id: string,\n changes: Partial<SceneNode>,\n absent: readonly (keyof SceneNode)[]\n ): void {\n const node = this.nodes.get(id)\n if (node) this.applyNodeChanges(node, changes, absent)\n }\n\n private applyNodeChanges(\n node: SceneNode,\n changes: Partial<SceneNode>,\n absent: readonly (keyof SceneNode)[] = []\n ): void {\n const { id } = node\n this.willChangeNode(node)\n // Include removed keys in cache invalidation and update notifications.\n if (absent.length) {\n changes = { ...changes }\n for (const key of absent) Reflect.set(changes, key, undefined)\n }\n\n // Only clear absPosCache when layout-affecting properties change.\n // Fills, strokes, effects, plugin data changes do NOT affect absolute position.\n const affectsLayout = Object.keys(changes).some((k) => LAYOUT_AFFECTING_KEYS.has(k))\n if (affectsLayout) this.absPosCache.clear()\n this.reindexInstance(node, changes)\n if (node.type === 'TEXT') invalidateTextCaches(node, changes)\n if (this.scopeDepths.sourceMetadata === 0 && !this.isApplyingLayout) {\n markSourceFieldsEdited(node, Object.keys(changes), this.observeSourceMark)\n }\n if (changes.vectorNetwork) {\n changes = { ...changes, vectorNetwork: normalizeVectorNetwork(changes.vectorNetwork) }\n }\n if (changes.effects) {\n changes = { ...changes, effects: normalizeEffects(changes.effects) }\n }\n this.layoutWrites?.record(\n node,\n changes,\n this.scopeDepths.sourceMetadata === 0 && !this.isApplyingDerivedLayout\n )\n Object.assign(node, changes)\n shareEmptyNodeValues(node, Object.keys(changes))\n if (changes.fills) removeStaleBindings(node, 'fills', changes)\n if (changes.strokes) removeStaleBindings(node, 'strokes', changes)\n // A bound paint written keeps what it was given until its variable's color changes.\n if ((changes.fills || changes.strokes) && !this.isApplyingImportedState)\n Variables.recordWrittenBoundPaints(this, node, changes)\n for (const key of absent) Reflect.deleteProperty(node, key)\n this.publishNodeUpdate(id, changes)\n }\n\n /** Marks fields an edit changed, unless metadata is being restored or layout is writing them. */\n private markEdited(node: SceneNode, keys: string[]): void {\n if (this.scopeDepths.sourceMetadata === 0 && !this.isApplyingLayout) {\n markSourceFieldsEdited(node, keys, this.observeSourceMark)\n }\n }\n\n /** Publishes an update now, or leaves it to the running layout, which publishes once it ends. */\n private publishNodeUpdate(id: string, changes: Partial<SceneNode>): void {\n if (!this.layoutWrites) this.emitter.emit('node:updated', id, changes)\n }\n\n /** Whether moving `node` under `parentId` would put an instance inside the component it draws. */\n private movesIntoInstanceOutsideSlot(parentId: string): boolean {\n let current = this.nodes.get(parentId)\n while (current) {\n if (slotPropertyId(current)) return false\n if (current.type === 'INSTANCE') return true\n current = current.parentId ? this.nodes.get(current.parentId) : undefined\n }\n return false\n }\n\n private movesInstanceIntoItsComponent(node: SceneNode, parentId: string): boolean {\n const stack = [node]\n while (stack.length > 0) {\n const current = stack.pop()\n if (!current) continue\n const componentId = current.componentId\n if (componentId && this.closest(parentId, (candidate) => candidate.id === componentId))\n return true\n for (const childId of current.childIds) {\n const child = this.nodes.get(childId)\n if (child) stack.push(child)\n }\n }\n return false\n }\n\n reparentNode(nodeId: string, newParentId: string): void {\n const node = this.nodes.get(nodeId)\n if (!node || nodeId === this.rootId) return\n // A page is never a layer: it holds the document's layers and cannot move inside one.\n if (node.type === 'CANVAS') return\n if (this.isDescendant(newParentId, nodeId)) return\n\n const oldParent = node.parentId ? this.nodes.get(node.parentId) : undefined\n const newParent = this.nodes.get(newParentId)\n if (!newParent) return\n if (node.parentId === newParentId) return\n\n // An instance inside the component it draws would sync itself forever, so Figma keeps it\n // out: the move is refused, as a move into the layer's own subtree is.\n if (this.movesInstanceIntoItsComponent(node, newParentId)) return\n // An instance's contents are its component's copies; only a slot takes the document's own\n // layers, so a layer moved anywhere else inside one would have nothing to correspond to.\n if (this.movesIntoInstanceOutsideSlot(newParentId)) return\n\n const oldParentId = node.parentId\n this.willChangeNode(node)\n this.willChangeNode(oldParent)\n this.willChangeNode(newParent)\n this.absPosCache.clear()\n\n const oldParentWorld = getParentWorldMatrix(oldParent, this)\n const newParentWorld = getParentWorldMatrix(newParent, this)\n\n if (oldParent) {\n oldParent.childIds = oldParent.childIds.filter((cid) => cid !== nodeId)\n }\n\n node.parentId = newParentId\n newParent.childIds.push(nodeId)\n\n const before = pick(node, TRANSFORM_FIELDS)\n if (isTranslationOnly(oldParentWorld) && isTranslationOnly(newParentWorld)) {\n node.x += oldParentWorld[2] - newParentWorld[2]\n node.y += oldParentWorld[5] - newParentWorld[5]\n } else {\n const world = Matrix.multiply(oldParentWorld, getNodeLocalMatrix(node))\n const local = localTransformFromWorld(node, world, newParentWorld)\n if (local) Object.assign(node, local)\n }\n // The node keeps its place on the canvas by new coordinates, which a save must write.\n this.markEdited(\n node,\n TRANSFORM_FIELDS.filter((key) => node[key] !== before[key])\n )\n\n this.emitter.emit('node:reparented', nodeId, oldParentId, newParentId)\n // Bound paints show their variables in the modes the layer now sits in.\n Variables.refreshMovedBoundPaints(this, nodeId, oldParentId)\n }\n\n /**\n * Moves a node to `index` among `parentId`'s children, from wherever it was, without changing\n * its own coordinates. An index past the end appends; a move into the node itself or one of\n * its descendants is ignored.\n */\n insertChildAt(childId: string, parentId: string, index: number): void {\n const node = this.nodes.get(childId)\n const newParent = this.nodes.get(parentId)\n if (!node || !newParent || this.isDescendant(parentId, childId)) return\n const previousParentId = node.parentId\n const oldParent = previousParentId ? this.nodes.get(previousParentId) : undefined\n this.willChangeNode(node)\n this.willChangeNode(oldParent)\n this.willChangeNode(newParent)\n if (oldParent) {\n oldParent.childIds = oldParent.childIds.filter((id) => id !== childId)\n }\n newParent.childIds = newParent.childIds.filter((id) => id !== childId)\n const at = Math.min(index, newParent.childIds.length)\n newParent.childIds.splice(at, 0, childId)\n node.parentId = parentId\n this.absPosCache.clear()\n this.emitter.emit('node:reordered', childId, parentId, at, previousParentId)\n if (previousParentId !== parentId)\n Variables.refreshMovedBoundPaints(this, childId, previousParentId)\n }\n\n deleteNode(id: string): void {\n const node = this.nodes.get(id)\n if (!node || id === this.rootId) return\n this.willChangeNode(node)\n\n if (node.parentId) {\n const parent = this.nodes.get(node.parentId)\n this.willChangeNode(parent)\n if (parent) {\n parent.childIds = parent.childIds.filter((cid) => cid !== id)\n }\n }\n\n this.deleteSubtree(node)\n }\n\n /**\n * Deletes `node` and its layers, children first. Their parent goes with them, so its child\n * list is emptied once instead of being filtered for each child, which kept deleting a frame\n * of thousands of layers quadratic. The list is emptied before the children go, so a listener\n * of a child's deletion never finds it still listed.\n */\n private deleteSubtree(node: SceneNode): void {\n const { id, childIds } = node\n node.childIds = []\n for (const childId of childIds) {\n const child = this.nodes.get(childId)\n if (!child) continue\n this.willChangeNode(child)\n this.deleteSubtree(child)\n }\n\n if (node.type === 'INSTANCE' && node.componentId) this.unindexInstance(node.componentId, id)\n // An override names a layer of its instance: one left naming a deleted layer would be written\n // as a claim for nothing, and reopening would restore a layer the document no longer has.\n for (let owner = node.parentId ? this.nodes.get(node.parentId) : undefined; owner;) {\n if (owner.type === 'INSTANCE' && owner.instanceOverrides.descendants.has(id))\n ownInstanceOverrides(owner).descendants.delete(id)\n owner = owner.parentId ? this.nodes.get(owner.parentId) : undefined\n }\n this.connectorIds.delete(id)\n this.nodes.delete(id)\n this.emitter.emit('node:deleted', id, node.parentId)\n }\n\n hitTest(px: number, py: number, scopeId?: string): SceneNode | null {\n return HitTest.hitTest(this, px, py, scopeId)\n }\n\n /** `pad`, in canvas units, grows each shape's box, as Figma takes clicks just outside one. */\n hitTestDeep(px: number, py: number, scopeId?: string, pad = 0): SceneNode | null {\n return HitTest.hitTestDeep(this, px, py, scopeId, pad)\n }\n\n /**\n * The layer a press selects at the point; `locked` hits locked layers too, as a right-click does.\n */\n hitTestSelectable(\n px: number,\n py: number,\n scopeId: string,\n selectedIds: ReadonlySet<string>,\n pad = 0,\n locked = false\n ): SceneNode | null {\n return HitTest.hitTestSelectable(this, px, py, scopeId, selectedIds, pad, locked)\n }\n\n hitTestOpenContainer(px: number, py: number, scopeId: string): SceneNode | null {\n return HitTest.hitTestOpenContainer(this, px, py, scopeId)\n }\n\n isOpenContainer(nodeId: string): boolean {\n return HitTest.isOpenContainer(this, nodeId)\n }\n\n isPointInNode(nodeId: string, px: number, py: number): boolean {\n return HitTest.isPointInNode(this, nodeId, px, py)\n }\n\n hitTestDropTarget(\n px: number,\n py: number,\n excludeIds: ReadonlySet<string>,\n scopeId?: string,\n options?: HitTest.DropTargetOptions\n ): SceneNode | null {\n return HitTest.hitTestDropTarget(this, px, py, excludeIds, scopeId, options)\n }\n\n cloneTree(\n sourceId: string,\n parentId: string,\n overrides: Partial<SceneNode> = {}\n ): SceneNode | null {\n const copies = new Map<string, string>()\n const clone = this.cloneSubtree(sourceId, parentId, overrides, copies)\n // A copied instance records the overrides of its own layers, which are the cloned ones.\n Instances.retargetCopiedOverrides(this, copies)\n // A copy placed in other modes than its source shows its bound paints there, as a move does.\n if (clone) Variables.refreshMovedBoundPaints(this, clone.id, this.nodes.get(sourceId)?.parentId)\n return clone\n }\n\n private cloneSubtree(\n sourceId: string,\n parentId: string,\n overrides: Partial<SceneNode>,\n copies: Map<string, string>\n ): SceneNode | null {\n const src = this.nodes.get(sourceId)\n if (!src) return null\n\n const props = cloneNodeProps(src, null)\n // Null out Figma source identifiers so the clone is treated as local.\n if (props.source) props.source = { ...props.source, id: null, orderKey: null }\n // A copy is a new design nobody has reviewed: Figma's duplicate and clone() drop the status.\n props.status = null\n // A stand-in mark names one layer's place in a version of a design; a copy is not that.\n if (props.pluginData) {\n props.pluginData = withPluginData(\n props.pluginData,\n PAIRDRAW_PLUGIN_DATA.variationStandIn,\n undefined\n )\n }\n const clone = this.createNode(src.type, parentId, { ...props, ...overrides })\n Variables.copyAppliedBoundPaints(src, clone)\n copies.set(src.id, clone.id)\n if (src.status) markSourceFieldsEdited(clone, ['status'])\n\n for (const childId of src.childIds) {\n this.cloneSubtree(childId, clone.id, {}, copies)\n }\n\n return clone\n }\n\n createInstance(\n componentId: string,\n parentId: string,\n overrides: Partial<SceneNode> = {}\n ): SceneNode | null {\n return Instances.createInstance(this, componentId, parentId, overrides)\n }\n\n populateInstanceChildren(\n instanceId: string,\n componentId: string,\n mode: NodeCloneMode = 'deep'\n ): void {\n Instances.populateInstanceChildren(this, instanceId, componentId, mode)\n }\n\n swapInstanceComponent(\n instanceId: string,\n componentId: string,\n options?: Instances.SwapInstanceOptions\n ): void {\n Instances.swapInstanceComponent(this, instanceId, componentId, options)\n }\n\n syncInstances(componentId: string): void {\n Instances.syncInstances(this, componentId)\n }\n\n syncInstancesTogether(componentIds: Iterable<string>): void {\n Instances.syncInstancesTogether(this, componentIds)\n }\n\n syncInstance(instanceId: string): void {\n Instances.syncInstance(this, instanceId)\n }\n\n detachInstance(instanceId: string): void {\n Instances.detachInstance(this, instanceId)\n }\n\n getMainComponent(instanceId: string): SceneNode | undefined {\n return Instances.getMainComponent(this, instanceId)\n }\n\n getInstances(componentId: string): SceneNode[] {\n return Instances.getInstances(this, componentId)\n }\n\n /**\n * The descendants of a layer in depth-first order with their depths. Each layer with children is\n * walked once, so a cycle or repeated links in bad data cannot hang it or repeat its subtree.\n */\n flattenTree(parentId?: string, depth = 0): Array<{ node: SceneNode; depth: number }> {\n const id = parentId ?? this.rootId\n const parent = this.nodes.get(id)\n if (!parent) return []\n const result: Array<{ node: SceneNode; depth: number }> = []\n const pending = [{ node: parent, depth, index: 0 }]\n const walked = new Set([parent])\n while (pending.length > 0) {\n const frame = pending.at(-1)\n if (!frame) break\n if (frame.index >= frame.node.childIds.length) {\n pending.pop()\n continue\n }\n const child = this.nodes.get(frame.node.childIds[frame.index++])\n if (!child) continue\n const container = child.childIds.length > 0\n if (container && walked.has(child)) continue\n result.push({ node: child, depth: frame.depth })\n if (container) {\n walked.add(child)\n pending.push({ node: child, depth: frame.depth + 1, index: 0 })\n }\n }\n return result\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA,IAAa,aAAb,MAAwB;CAuCO;CAtC7B,wBAAQ,IAAI,IAAuB;CACnC,yBAAS,IAAI,IAAwB;CACrC,4BAAY,IAAI,IAAsB;CACtC,sCAAsB,IAAI,IAAgC;CAC1D,6BAAa,IAAI,IAAoB;CACrC;CACA,iBAAgC;;CAEhC,oBAAuC;CACvC,qBAAyC;CACzC,eAA6B;CAC7B,mCAAmB,IAAI,IAAmC;CAC1D,UAAmB,IAAI,qBAAqB;CAC5C,8BAAsB,IAAI,IAAoB;CAC9C,cAA2D;EACzD,SAAS;EACT,gBAAgB;EAChB,eAAe;EACf,QAAQ;EACR,eAAe;EACf,kBAAkB;CACpB;CACA,mBAAkD,CAAC;;CAEnD,qBAAsD,CAAC;CACvD,qBAAsC,IAAY,UAAkB;EAClE,KAAK,mBAAmB,KAAK,CAAC,IAAI,KAAK,CAAC;CAC1C;CACA,kCAAmC,IAAI,IAAwB;;CAE/D,+BAAgC,IAAI,IAA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AA0B;EACrC,aAAuB,MAAM,UAAU;CACzC;CAEA,eAAe,YAA0B;EACvC,eAAyB,MAAM,UAAU;CAC3C;CAEA,iBAAiB,YAA2C;EAC1D,OAAOC,iBAA2B,MAAM,UAAU;CACpD;CAEA,aAAa,aAAkC;EAC7C,OAAOC,aAAuB,MAAM,WAAW;CACjD;;;;;CAMA,YAAY,UAAmB,QAAQ,GAA8C;EACnF,MAAM,KAAK,YAAY,KAAK;EAC5B,MAAM,SAAS,KAAK,MAAM,IAAI,EAAE;EAChC,IAAI,CAAC,QAAQ,OAAO,CAAC;EACrB,MAAM,SAAoD,CAAC;EAC3D,MAAM,UAAU,CAAC;GAAE,MAAM;GAAQ;GAAO,OAAO;EAAE,CAAC;EAClD,MAAM,yBAAS,IAAI,IAAI,CAAC,MAAM,CAAC;EAC/B,OAAO,QAAQ,SAAS,GAAG;GACzB,MAAM,QAAQ,QAAQ,GAAG,EAAE;GAC3B,IAAI,CAAC,OAAO;GACZ,IAAI,MAAM,SAAS,MAAM,KAAK,SAAS,QAAQ;IAC7C,QAAQ,IAAI;IACZ;GACF;GACA,MAAM,QAAQ,KAAK,MAAM,IAAI,MAAM,KAAK,SAAS,MAAM,QAAQ;GAC/D,IAAI,CAAC,OAAO;GACZ,MAAM,YAAY,MAAM,SAAS,SAAS;GAC1C,IAAI,aAAa,OAAO,IAAI,KAAK,GAAG;GACpC,OAAO,KAAK;IAAE,MAAM;IAAO,OAAO,MAAM;GAAM,CAAC;GAC/C,IAAI,WAAW;IACb,OAAO,IAAI,KAAK;IAChB,QAAQ,KAAK;KAAE,MAAM;KAAO,OAAO,MAAM,QAAQ;KAAG,OAAO;IAAE,CAAC;GAChE;EACF;EACA,OAAO;CACT;AACF"}
|
package/dist/images.d.ts
CHANGED
|
@@ -6,7 +6,7 @@ import { Matrix, Size } from "./primitives/index.js";
|
|
|
6
6
|
* hold images under other names; anything that hands images to Figma still checks.
|
|
7
7
|
*/
|
|
8
8
|
declare function computeImageHash(data: Uint8Array): string;
|
|
9
|
-
type ImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp';
|
|
9
|
+
type ImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | 'image/avif';
|
|
10
10
|
/** The raster types a dropped or pasted file can be imported as an image fill from. */
|
|
11
11
|
declare const IMPORTABLE_RASTER_TYPES: ReadonlySet<string>;
|
|
12
12
|
/** Whether a file is an SVG image, which some systems report without a media type. */
|
|
@@ -24,7 +24,8 @@ interface ImageHeader extends Size {
|
|
|
24
24
|
declare function imageHeader(data: Uint8Array): ImageHeader | null;
|
|
25
25
|
/**
|
|
26
26
|
* The media type of encoded image bytes, read from their header, for writing them out as a data
|
|
27
|
-
* URL or file.
|
|
27
|
+
* URL or file. AVIF is read from its ISO media brand, which `image-size` does not decode. Bytes it
|
|
28
|
+
* cannot read are reported as PNG, as image fills began.
|
|
28
29
|
*/
|
|
29
30
|
declare function imageMimeType(data: Uint8Array): ImageMimeType;
|
|
30
31
|
/** An image's size in pixels, read from its header; null for bytes it cannot read. */
|
package/dist/images.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"images.d.ts","names":[],"sources":["../src/images.ts"],"mappings":";;;;;;;iBAWgB,iBAAiB,MAAM;KAI3B;;cAWC,yBAAyB;;iBAStB,UAAU;EAAQ;EAAc;;UAM/B,oBAAoB;EACnC,MAAM;;;;;;iBAOQ,YAAY,MAAM,aAAa
|
|
1
|
+
{"version":3,"file":"images.d.ts","names":[],"sources":["../src/images.ts"],"mappings":";;;;;;;iBAWgB,iBAAiB,MAAM;KAI3B;;cAWC,yBAAyB;;iBAStB,UAAU;EAAQ;EAAc;;UAM/B,oBAAoB;EACnC,MAAM;;;;;;iBAOQ,YAAY,MAAM,aAAa;;;;;;iBAuC/B,cAAc,MAAM,aAAa;;iBAKjC,UAAU,MAAM,aAAa;;;;;iBAS7B,oBACd,eACA,gBACA,oBACA,sBACC"}
|
package/dist/images.js
CHANGED
|
@@ -47,12 +47,28 @@ function imageHeader(data) {
|
|
|
47
47
|
height: header.height
|
|
48
48
|
} : null;
|
|
49
49
|
}
|
|
50
|
+
/** A four-character ISO media brand at `start`, or an empty string when the bytes are short. */
|
|
51
|
+
function isoBrand(data, start) {
|
|
52
|
+
if (start + 4 > data.length) return "";
|
|
53
|
+
return String.fromCharCode(data[start] ?? 0, data[start + 1] ?? 0, data[start + 2] ?? 0, data[start + 3] ?? 0);
|
|
54
|
+
}
|
|
55
|
+
/** Whether bytes are an AVIF image, whose `ftyp` box names the brand or lists it as compatible. */
|
|
56
|
+
function isAVIF(data) {
|
|
57
|
+
if (isoBrand(data, 4) !== "ftyp") return false;
|
|
58
|
+
const size = (data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3]) >>> 0;
|
|
59
|
+
const isAvif = (brand) => brand === "avif" || brand === "avis";
|
|
60
|
+
if (isAvif(isoBrand(data, 8))) return true;
|
|
61
|
+
const end = Math.min(size >= 16 ? size : data.length, data.length);
|
|
62
|
+
for (let start = 16; start + 4 <= end; start += 4) if (isAvif(isoBrand(data, start))) return true;
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
50
65
|
/**
|
|
51
66
|
* The media type of encoded image bytes, read from their header, for writing them out as a data
|
|
52
|
-
* URL or file.
|
|
67
|
+
* URL or file. AVIF is read from its ISO media brand, which `image-size` does not decode. Bytes it
|
|
68
|
+
* cannot read are reported as PNG, as image fills began.
|
|
53
69
|
*/
|
|
54
70
|
function imageMimeType(data) {
|
|
55
|
-
return imageHeader(data)?.type ?? "image/png";
|
|
71
|
+
return imageHeader(data)?.type ?? (isAVIF(data) ? "image/avif" : "image/png");
|
|
56
72
|
}
|
|
57
73
|
/** An image's size in pixels, read from its header; null for bytes it cannot read. */
|
|
58
74
|
function imageSize(data) {
|
package/dist/images.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"images.js","names":["readImageHeader"],"sources":["../src/images.ts"],"sourcesContent":["import { sha1 } from '@noble/hashes/legacy.js'\nimport { bytesToHex } from '@noble/hashes/utils.js'\nimport { imageSize as readImageHeader } from 'image-size'\n\nimport type { Matrix, Size } from './primitives'\n\n/**\n * The name an image's bytes are stored under: the hex SHA-1 of the bytes, as Figma names images,\n * so `.fig` files and the Figma clipboard can carry the name as it is. Documents saved before may\n * hold images under other names; anything that hands images to Figma still checks.\n */\nexport function computeImageHash(data: Uint8Array): string {\n return bytesToHex(sha1(data))\n}\n\nexport type ImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp'\n\n/** The image types documents store, by the name `image-size` gives each format. */\nconst IMAGE_MIME_TYPES: Partial<Record<string, ImageMimeType>> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp'\n}\n\n/** The raster types a dropped or pasted file can be imported as an image fill from. */\nexport const IMPORTABLE_RASTER_TYPES: ReadonlySet<string> = new Set([\n 'image/png',\n 'image/jpeg',\n 'image/webp',\n 'image/gif',\n 'image/avif'\n])\n\n/** Whether a file is an SVG image, which some systems report without a media type. */\nexport function isSVGFile(file: { name: string; type: string }): boolean {\n return (\n file.type === 'image/svg+xml' || (file.type === '' && file.name.toLowerCase().endsWith('.svg'))\n )\n}\n\nexport interface ImageHeader extends Size {\n type: ImageMimeType\n}\n\n/**\n * The type and size of a PNG, JPEG, GIF, or WebP, read from its header by `image-size`; null for\n * bytes it cannot read and for other formats.\n */\nexport function imageHeader(data: Uint8Array): ImageHeader | null {\n let header: ReturnType<typeof readImageHeader>\n try {\n header = readImageHeader(data)\n } catch {\n return null\n }\n const type = header.type === undefined ? undefined : IMAGE_MIME_TYPES[header.type]\n return type ? { type, width: header.width, height: header.height } : null\n}\n\n/**\n * The media type of encoded image bytes, read from their header, for writing them out as a data\n * URL or file. Bytes it cannot read are reported as PNG, as image fills began.\n */\nexport function imageMimeType(data: Uint8Array): ImageMimeType {\n return imageHeader(data)?.type ?? 'image/png'\n}\n\n/** An image's size in pixels, read from its header; null for bytes it cannot read. */\nexport function imageSize(data: Uint8Array): Size | null {\n const header = imageHeader(data)\n return header && { width: header.width, height: header.height }\n}\n\n/**\n * The crop that shows an image as Fill does: scaled to cover a `width` × `height` layer and\n * centred. Figma starts a crop from it, as the image-space window a crop's transform holds.\n */\nexport function coverImageTransform(\n width: number,\n height: number,\n imageWidth: number,\n imageHeight: number\n): Matrix {\n const scale = Math.max(width / imageWidth, height / imageHeight)\n const m00 = width / scale / imageWidth\n const m11 = height / scale / imageHeight\n return { m00, m01: 0, m02: (1 - m00) / 2, m10: 0, m11, m12: (1 - m11) / 2 }\n}\n"],"mappings":";;;;;;;;;AAWA,SAAgB,iBAAiB,MAA0B;CACzD,OAAO,WAAW,KAAK,IAAI,CAAC;AAC9B;;AAKA,MAAM,mBAA2D;CAC/D,KAAK;CACL,KAAK;CACL,KAAK;CACL,MAAM;AACR;;AAGA,MAAa,0CAA+C,IAAI,IAAI;CAClE;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,SAAgB,UAAU,MAA+C;CACvE,OACE,KAAK,SAAS,mBAAoB,KAAK,SAAS,MAAM,KAAK,KAAK,YAAY,CAAC,CAAC,SAAS,MAAM;AAEjG;;;;;AAUA,SAAgB,YAAY,MAAsC;CAChE,IAAI;CACJ,IAAI;EACF,SAASA,YAAgB,IAAI;CAC/B,QAAQ;EACN,OAAO;CACT;CACA,MAAM,OAAO,OAAO,SAAS,KAAA,IAAY,KAAA,IAAY,iBAAiB,OAAO;CAC7E,OAAO,OAAO;EAAE;EAAM,OAAO,OAAO;EAAO,QAAQ,OAAO;CAAO,IAAI;AACvE
|
|
1
|
+
{"version":3,"file":"images.js","names":["readImageHeader"],"sources":["../src/images.ts"],"sourcesContent":["import { sha1 } from '@noble/hashes/legacy.js'\nimport { bytesToHex } from '@noble/hashes/utils.js'\nimport { imageSize as readImageHeader } from 'image-size'\n\nimport type { Matrix, Size } from './primitives'\n\n/**\n * The name an image's bytes are stored under: the hex SHA-1 of the bytes, as Figma names images,\n * so `.fig` files and the Figma clipboard can carry the name as it is. Documents saved before may\n * hold images under other names; anything that hands images to Figma still checks.\n */\nexport function computeImageHash(data: Uint8Array): string {\n return bytesToHex(sha1(data))\n}\n\nexport type ImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | 'image/avif'\n\n/** The image types documents store, by the name `image-size` gives each format. */\nconst IMAGE_MIME_TYPES: Partial<Record<string, ImageMimeType>> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp'\n}\n\n/** The raster types a dropped or pasted file can be imported as an image fill from. */\nexport const IMPORTABLE_RASTER_TYPES: ReadonlySet<string> = new Set([\n 'image/png',\n 'image/jpeg',\n 'image/webp',\n 'image/gif',\n 'image/avif'\n])\n\n/** Whether a file is an SVG image, which some systems report without a media type. */\nexport function isSVGFile(file: { name: string; type: string }): boolean {\n return (\n file.type === 'image/svg+xml' || (file.type === '' && file.name.toLowerCase().endsWith('.svg'))\n )\n}\n\nexport interface ImageHeader extends Size {\n type: ImageMimeType\n}\n\n/**\n * The type and size of a PNG, JPEG, GIF, or WebP, read from its header by `image-size`; null for\n * bytes it cannot read and for other formats.\n */\nexport function imageHeader(data: Uint8Array): ImageHeader | null {\n let header: ReturnType<typeof readImageHeader>\n try {\n header = readImageHeader(data)\n } catch {\n return null\n }\n const type = header.type === undefined ? undefined : IMAGE_MIME_TYPES[header.type]\n return type ? { type, width: header.width, height: header.height } : null\n}\n\n/** A four-character ISO media brand at `start`, or an empty string when the bytes are short. */\nfunction isoBrand(data: Uint8Array, start: number): string {\n if (start + 4 > data.length) return ''\n return String.fromCharCode(\n data[start] ?? 0,\n data[start + 1] ?? 0,\n data[start + 2] ?? 0,\n data[start + 3] ?? 0\n )\n}\n\n/** Whether bytes are an AVIF image, whose `ftyp` box names the brand or lists it as compatible. */\nfunction isAVIF(data: Uint8Array): boolean {\n if (isoBrand(data, 4) !== 'ftyp') return false\n const size = ((data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3]) >>> 0\n const isAvif = (brand: string) => brand === 'avif' || brand === 'avis'\n if (isAvif(isoBrand(data, 8))) return true\n const end = Math.min(size >= 16 ? size : data.length, data.length)\n // The major brand is followed by a minor version, then the compatible brands.\n for (let start = 16; start + 4 <= end; start += 4) if (isAvif(isoBrand(data, start))) return true\n return false\n}\n\n/**\n * The media type of encoded image bytes, read from their header, for writing them out as a data\n * URL or file. AVIF is read from its ISO media brand, which `image-size` does not decode. Bytes it\n * cannot read are reported as PNG, as image fills began.\n */\nexport function imageMimeType(data: Uint8Array): ImageMimeType {\n return imageHeader(data)?.type ?? (isAVIF(data) ? 'image/avif' : 'image/png')\n}\n\n/** An image's size in pixels, read from its header; null for bytes it cannot read. */\nexport function imageSize(data: Uint8Array): Size | null {\n const header = imageHeader(data)\n return header && { width: header.width, height: header.height }\n}\n\n/**\n * The crop that shows an image as Fill does: scaled to cover a `width` × `height` layer and\n * centred. Figma starts a crop from it, as the image-space window a crop's transform holds.\n */\nexport function coverImageTransform(\n width: number,\n height: number,\n imageWidth: number,\n imageHeight: number\n): Matrix {\n const scale = Math.max(width / imageWidth, height / imageHeight)\n const m00 = width / scale / imageWidth\n const m11 = height / scale / imageHeight\n return { m00, m01: 0, m02: (1 - m00) / 2, m10: 0, m11, m12: (1 - m11) / 2 }\n}\n"],"mappings":";;;;;;;;;AAWA,SAAgB,iBAAiB,MAA0B;CACzD,OAAO,WAAW,KAAK,IAAI,CAAC;AAC9B;;AAKA,MAAM,mBAA2D;CAC/D,KAAK;CACL,KAAK;CACL,KAAK;CACL,MAAM;AACR;;AAGA,MAAa,0CAA+C,IAAI,IAAI;CAClE;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,SAAgB,UAAU,MAA+C;CACvE,OACE,KAAK,SAAS,mBAAoB,KAAK,SAAS,MAAM,KAAK,KAAK,YAAY,CAAC,CAAC,SAAS,MAAM;AAEjG;;;;;AAUA,SAAgB,YAAY,MAAsC;CAChE,IAAI;CACJ,IAAI;EAC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5B,MAAM,MAAM,SAAS,QAAQ;CAC7B,OAAO;EAAE;EAAK,KAAK;EAAG,MAAM,IAAI,OAAO;EAAG,KAAK;EAAG;EAAK,MAAM,IAAI,OAAO;CAAE;AAC5E"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { CommittedGraphEventError } from "./buffered-events.js";
|
|
2
2
|
import { SceneGraph } from "./graph.js";
|
|
3
|
-
import { ArcData, AxisSizingMode, BlendMode, BooleanOperation, CODE_SYNTAX_PLATFORMS, CharacterStyleOverride, CodeSyntaxPlatform, CommentReply, CommentThread, ComponentPropertyDefinition, ComponentPropertyReference, ComponentPropertyReferenceField, ComponentPropertyType, ConnectorControlPoint, ConnectorEndpoint, ConnectorLabelPosition, ConnectorLineType, ConnectorMagnet, ConstraintType, DerivedTextGlyph, DocumentColorSpace, DocumentKind, DrawIOEdgeSource, Effect, EnabledLibraryBinding, ExportSetting, FigmaLayoutMetadata, FigmaSourcePayload, Fill, FillType, FontFeature, FontVariation, GeometryPath, GradientStop, GradientTransform, GridPosition, GridTrack, GridTrackSizing, HandleMirroring, HyperlinkTarget, ImageFilters, ImageScaleMode, LayoutAlign, LayoutAlignSelf, LayoutCounterAlign, LayoutDirection, LayoutGrid, LayoutMode, LayoutSizing, LayoutWrap, LeadingTrim, LibraryAssetIdentity, LibraryAssetSource, MODE_ATTRIBUTE_PATTERN, MaskType, MeshGradientPoint, NodeChangeObserver, NodeType, NoiseEffect, NoiseEffectParams, NoiseType, NumericNodeProperty, OverflowDirection, PatternAlignment, PatternTileType, PluginDataEntry, PluginRelaunchDataEntry, PrototypeAction, PrototypeActionType, PrototypeBackAction, PrototypeCloseAction, PrototypeEasingType, PrototypeNavigationType, PrototypeNodeAction, PrototypeOverlayPositionType, PrototypeReaction, PrototypeTransition, PrototypeTransitionType, PrototypeTrigger, PrototypeTriggerType, SceneGraphEventHandlers, SceneGraphEvents, SceneNode, ScrollBehavior, ShaderEffect, ShadowEffect, SharedStyle, SharedStyleKind, SharedStyleType, SlotSettings, SourceLibraryPublication, SourceMetadata, Stroke, StrokeCap, StrokeJoin, StyleRun, SymbolLink, TEXT_BINDABLE_FIELDS, TOKEN_UNITS, TextAlignVertical, TextAutoResize, TextBindableField, TextBoundVariables, TextCase, TextDecoration, TextDecorationStyle, TextDirection, TextLength, TextListType, TextParagraphSpacingField, TextParagraphStyle, TextPathData, TextureEffect, TextureEffectParams, TokenExpression, TokenUnit, VARIABLE_FORMULA_OPERATORS, VARIABLE_SCOPES, Variable, VariableAlias, VariableCollection, VariableCollectionMode, VariableColorExpression, VariableFormula, VariableFormulaNode, VariableFormulaOperation, VariableFormulaOperator, VariableLiteral, VariableModeMap, VariableScope, VariableType, VariableUnsupportedExpression, VariableValue, VariantPropSpec, VectorNetwork, VectorRegion, VectorSegment, VectorVertex, WindingRule, isLibraryCollection, isModeAttributeName } from "./types.js";
|
|
3
|
+
import { ArcData, AxisSizingMode, BlendMode, BooleanOperation, CODE_SYNTAX_PLATFORMS, CharacterStyleOverride, CodeSyntaxPlatform, ColorProfile, CommentRegion, CommentReply, CommentThread, ComponentPropertyDefinition, ComponentPropertyReference, ComponentPropertyReferenceField, ComponentPropertyType, ConnectorControlPoint, ConnectorEndpoint, ConnectorLabelPosition, ConnectorLineType, ConnectorMagnet, ConstraintType, DerivedTextGlyph, DocumentColorSpace, DocumentKind, DrawIOEdgeSource, Effect, EnabledLibraryBinding, ExportSetting, FigmaLayoutMetadata, FigmaSourcePayload, Fill, FillType, FontFeature, FontVariation, GeometryPath, GradientStop, GradientTransform, GridPosition, GridTrack, GridTrackSizing, HandleMirroring, HyperlinkTarget, ImageFilters, ImageScaleMode, LayoutAlign, LayoutAlignSelf, LayoutCounterAlign, LayoutDirection, LayoutGrid, LayoutMode, LayoutSizing, LayoutWrap, LeadingTrim, LibraryAssetIdentity, LibraryAssetSource, MODE_ATTRIBUTE_PATTERN, MaskType, MeshGradientPoint, NodeChangeObserver, NodeType, NoiseEffect, NoiseEffectParams, NoiseType, NumericNodeProperty, OverflowDirection, PatternAlignment, PatternTileType, PluginDataEntry, PluginRelaunchDataEntry, PrototypeAction, PrototypeActionType, PrototypeBackAction, PrototypeCloseAction, PrototypeEasingType, PrototypeNavigationType, PrototypeNodeAction, PrototypeOverlayPositionType, PrototypeReaction, PrototypeTransition, PrototypeTransitionType, PrototypeTrigger, PrototypeTriggerType, SceneGraphEventHandlers, SceneGraphEvents, SceneNode, ScrollBehavior, ShaderEffect, ShadowEffect, SharedStyle, SharedStyleKind, SharedStyleType, SlotSettings, SourceLibraryPublication, SourceMetadata, Stroke, StrokeCap, StrokeJoin, StyleRun, SymbolLink, TEXT_BINDABLE_FIELDS, TOKEN_UNITS, TextAlignVertical, TextAutoResize, TextBindableField, TextBoundVariables, TextCase, TextDecoration, TextDecorationStyle, TextDirection, TextLength, TextListType, TextParagraphSpacingField, TextParagraphStyle, TextPathData, TextureEffect, TextureEffectParams, TokenExpression, TokenUnit, VARIABLE_FORMULA_OPERATORS, VARIABLE_SCOPES, Variable, VariableAlias, VariableCollection, VariableCollectionMode, VariableColorExpression, VariableFormula, VariableFormulaNode, VariableFormulaOperation, VariableFormulaOperator, VariableLiteral, VariableModeMap, VariableScope, VariableType, VariableUnsupportedExpression, VariableValue, VariantPropSpec, VectorNetwork, VectorRegion, VectorSegment, VectorVertex, WindingRule, isLibraryCollection, isModeAttributeName } from "./types.js";
|
|
4
4
|
import { generateId, setIdSession } from "./ids.js";
|
|
5
|
-
export { ArcData, AxisSizingMode, BlendMode, BooleanOperation, CODE_SYNTAX_PLATFORMS, CharacterStyleOverride, CodeSyntaxPlatform, CommentReply, CommentThread, CommittedGraphEventError, ComponentPropertyDefinition, ComponentPropertyReference, ComponentPropertyReferenceField, ComponentPropertyType, ConnectorControlPoint, ConnectorEndpoint, ConnectorLabelPosition, ConnectorLineType, ConnectorMagnet, ConstraintType, DerivedTextGlyph, DocumentColorSpace, DocumentKind, DrawIOEdgeSource, Effect, EnabledLibraryBinding, ExportSetting, FigmaLayoutMetadata, FigmaSourcePayload, Fill, FillType, FontFeature, FontVariation, GeometryPath, GradientStop, GradientTransform, GridPosition, GridTrack, GridTrackSizing, HandleMirroring, HyperlinkTarget, ImageFilters, ImageScaleMode, LayoutAlign, LayoutAlignSelf, LayoutCounterAlign, LayoutDirection, LayoutGrid, LayoutMode, LayoutSizing, LayoutWrap, LeadingTrim, LibraryAssetIdentity, LibraryAssetSource, MODE_ATTRIBUTE_PATTERN, MaskType, MeshGradientPoint, NodeChangeObserver, NodeType, NoiseEffect, NoiseEffectParams, NoiseType, NumericNodeProperty, OverflowDirection, PatternAlignment, PatternTileType, PluginDataEntry, PluginRelaunchDataEntry, PrototypeAction, PrototypeActionType, PrototypeBackAction, PrototypeCloseAction, PrototypeEasingType, PrototypeNavigationType, PrototypeNodeAction, PrototypeOverlayPositionType, PrototypeReaction, PrototypeTransition, PrototypeTransitionType, PrototypeTrigger, PrototypeTriggerType, SceneGraph, SceneGraphEventHandlers, SceneGraphEvents, SceneNode, ScrollBehavior, ShaderEffect, ShadowEffect, SharedStyle, SharedStyleKind, SharedStyleType, SlotSettings, SourceLibraryPublication, SourceMetadata, Stroke, StrokeCap, StrokeJoin, StyleRun, SymbolLink, TEXT_BINDABLE_FIELDS, TOKEN_UNITS, TextAlignVertical, TextAutoResize, TextBindableField, TextBoundVariables, TextCase, TextDecoration, TextDecorationStyle, TextDirection, TextLength, TextListType, TextParagraphSpacingField, TextParagraphStyle, TextPathData, TextureEffect, TextureEffectParams, TokenExpression, TokenUnit, VARIABLE_FORMULA_OPERATORS, VARIABLE_SCOPES, Variable, VariableAlias, VariableCollection, VariableCollectionMode, VariableColorExpression, VariableFormula, VariableFormulaNode, VariableFormulaOperation, VariableFormulaOperator, VariableLiteral, VariableModeMap, VariableScope, VariableType, VariableUnsupportedExpression, VariableValue, VariantPropSpec, VectorNetwork, VectorRegion, VectorSegment, VectorVertex, WindingRule, generateId, isLibraryCollection, isModeAttributeName, setIdSession };
|
|
5
|
+
export { ArcData, AxisSizingMode, BlendMode, BooleanOperation, CODE_SYNTAX_PLATFORMS, CharacterStyleOverride, CodeSyntaxPlatform, ColorProfile, CommentRegion, CommentReply, CommentThread, CommittedGraphEventError, ComponentPropertyDefinition, ComponentPropertyReference, ComponentPropertyReferenceField, ComponentPropertyType, ConnectorControlPoint, ConnectorEndpoint, ConnectorLabelPosition, ConnectorLineType, ConnectorMagnet, ConstraintType, DerivedTextGlyph, DocumentColorSpace, DocumentKind, DrawIOEdgeSource, Effect, EnabledLibraryBinding, ExportSetting, FigmaLayoutMetadata, FigmaSourcePayload, Fill, FillType, FontFeature, FontVariation, GeometryPath, GradientStop, GradientTransform, GridPosition, GridTrack, GridTrackSizing, HandleMirroring, HyperlinkTarget, ImageFilters, ImageScaleMode, LayoutAlign, LayoutAlignSelf, LayoutCounterAlign, LayoutDirection, LayoutGrid, LayoutMode, LayoutSizing, LayoutWrap, LeadingTrim, LibraryAssetIdentity, LibraryAssetSource, MODE_ATTRIBUTE_PATTERN, MaskType, MeshGradientPoint, NodeChangeObserver, NodeType, NoiseEffect, NoiseEffectParams, NoiseType, NumericNodeProperty, OverflowDirection, PatternAlignment, PatternTileType, PluginDataEntry, PluginRelaunchDataEntry, PrototypeAction, PrototypeActionType, PrototypeBackAction, PrototypeCloseAction, PrototypeEasingType, PrototypeNavigationType, PrototypeNodeAction, PrototypeOverlayPositionType, PrototypeReaction, PrototypeTransition, PrototypeTransitionType, PrototypeTrigger, PrototypeTriggerType, SceneGraph, SceneGraphEventHandlers, SceneGraphEvents, SceneNode, ScrollBehavior, ShaderEffect, ShadowEffect, SharedStyle, SharedStyleKind, SharedStyleType, SlotSettings, SourceLibraryPublication, SourceMetadata, Stroke, StrokeCap, StrokeJoin, StyleRun, SymbolLink, TEXT_BINDABLE_FIELDS, TOKEN_UNITS, TextAlignVertical, TextAutoResize, TextBindableField, TextBoundVariables, TextCase, TextDecoration, TextDecorationStyle, TextDirection, TextLength, TextListType, TextParagraphSpacingField, TextParagraphStyle, TextPathData, TextureEffect, TextureEffectParams, TokenExpression, TokenUnit, VARIABLE_FORMULA_OPERATORS, VARIABLE_SCOPES, Variable, VariableAlias, VariableCollection, VariableCollectionMode, VariableColorExpression, VariableFormula, VariableFormulaNode, VariableFormulaOperation, VariableFormulaOperator, VariableLiteral, VariableModeMap, VariableScope, VariableType, VariableUnsupportedExpression, VariableValue, VariantPropSpec, VectorNetwork, VectorRegion, VectorSegment, VectorVertex, WindingRule, generateId, isLibraryCollection, isModeAttributeName, setIdSession };
|
package/dist/instances/copies.js
CHANGED
|
@@ -138,7 +138,8 @@ function removeLeftoverCopies(graph, context, removals) {
|
|
|
138
138
|
const overrides = /* @__PURE__ */ new Map();
|
|
139
139
|
for (const removed of nodes) {
|
|
140
140
|
const fields = context.overrides.descendants.get(removed.id);
|
|
141
|
-
if (fields)
|
|
141
|
+
if (!fields) continue;
|
|
142
|
+
overrides.set(removed.id, new Map(fields));
|
|
142
143
|
context.overrides.descendants.delete(removed.id);
|
|
143
144
|
}
|
|
144
145
|
let copies = store.byInstance.get(context.instanceId);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"copies.js","names":["hasNodeInstanceOverride"],"sources":["../../src/instances/copies.ts"],"sourcesContent":["// How an instance's copies follow the component's layers when its structure changes.\nimport type { SceneGraph } from '../graph'\nimport { ownsSlotContent, slotPropertyId } from '../slots/frames'\nimport type { SceneNode } from '../types'\nimport { DEFAULT_HISTORY_LIMIT } from '../undo'\nimport {\n copiedComponentLayerId,\n hasInstanceOverride as hasNodeInstanceOverride,\n type InstanceOverrideState\n} from './overrides'\nimport { replacedComponentLayerId } from './replacements'\n\n/**\n * One instance's sync: the copies it has matched to the component's layers, the parents it\n * synced, and, built on first need, the copies the instance had before, by the layer they copy.\n * Copies follow their layers when the component's structure changes, as Figma moves them: a\n * layer moved inside the component keeps its copy and the copy's overrides, and a copy whose\n * layer left or was deleted goes.\n */\nexport interface InstanceSyncContext {\n instanceId: string\n overrides: InstanceOverrideState\n matched: Set<string>\n leftovers: Set<string>\n copies?: Map<string, SceneNode[]>\n}\n\nexport function createInstanceSyncContext(\n instanceId: string,\n overrides: InstanceOverrideState\n): InstanceSyncContext {\n return { instanceId, overrides, matched: new Set(), leftovers: new Set() }\n}\n\n/** The component layer a copy in the instance stands for, or a replaced layer stands in for. */\nfunction copiedLayerId(\n graph: SceneGraph,\n node: SceneNode,\n context: InstanceSyncContext\n): string | undefined {\n return (\n replacedComponentLayerId(graph, node) ??\n copiedComponentLayerId(context.overrides, context.instanceId, node)\n )\n}\n\n/** Whether sync goes inside a copy: not into slot content, a swapped instance, or an instance. */\nfunction syncsInside(graph: SceneGraph, node: SceneNode, context: InstanceSyncContext): boolean {\n if (node.type === 'INSTANCE') return false\n if (hasNodeInstanceOverride(context.overrides, context.instanceId, node.id, 'componentId')) {\n return false\n }\n const layer = node.componentId ? graph.nodes.get(node.componentId) : undefined\n return !layer || !ownsSlotContent(graph, node, slotPropertyId(layer))\n}\n\nfunction copiesOf(graph: SceneGraph, context: InstanceSyncContext): Map<string, SceneNode[]> {\n if (context.copies) return context.copies\n const copies = new Map<string, SceneNode[]>()\n const visit = (parent: SceneNode) => {\n for (const id of parent.childIds) {\n const child = graph.nodes.get(id)\n if (!child) continue\n const layerId = copiedLayerId(graph, child, context)\n if (layerId) copies.set(layerId, [...(copies.get(layerId) ?? []), child])\n if (syncsInside(graph, child, context)) visit(child)\n }\n }\n const instance = graph.nodes.get(context.instanceId)\n if (instance) visit(instance)\n context.copies = copies\n return copies\n}\n\n/** A copy of `layerId` the sync has not placed yet, which a moved layer takes along. */\nexport function unplacedCopy(\n graph: SceneGraph,\n context: InstanceSyncContext,\n layerId: string,\n instParentId: string\n): SceneNode | undefined {\n return copiesOf(graph, context)\n .get(layerId)\n ?.find(\n (copy) =>\n !context.matched.has(copy.id) &&\n graph.nodes.has(copy.id) &&\n copy.id !== instParentId &&\n !graph.isDescendant(instParentId, copy.id)\n )\n}\n\n/** Whether any layer in the component subtree at `layerId` already has a copy to move. */\nexport function hasUnplacedCopiesBelow(\n graph: SceneGraph,\n context: InstanceSyncContext,\n layerId: string\n): boolean {\n const copies = copiesOf(graph, context)\n if (copies.size === 0) return false\n const layer = graph.nodes.get(layerId)\n return (layer?.childIds ?? []).some(\n (id) =>\n copies.get(id)?.some((copy) => !context.matched.has(copy.id)) ||\n hasUnplacedCopiesBelow(graph, context, id)\n )\n}\n\n/** The copies one sync of a component's instances removed, by instance and layer. */\nexport interface CopyRemovals {\n keys: Array<[instanceId: string, layerId: string]>\n}\n\n/** A copy the sync removed, kept so the layer coming back, as on undo, brings it back as it was. */\ninterface RemovedCopy {\n /** The copy and everything in it, parents first. */\n nodes: SceneNode[]\n overrides: Map<string, Map<string, unknown>>\n removals: CopyRemovals\n}\n\ninterface RemovedCopyStore {\n /** Removed copies by instance, then by the layer they copied. */\n byInstance: Map<string, Map<string, RemovedCopy>>\n /** Syncs that removed copies, oldest first. */\n removals: CopyRemovals[]\n}\n\nconst removedCopies = new WeakMap<SceneGraph, RemovedCopyStore>()\n\nfunction removedCopyStore(graph: SceneGraph): RemovedCopyStore {\n let store = removedCopies.get(graph)\n if (!store) {\n store = { byInstance: new Map(), removals: [] }\n removedCopies.set(graph, store)\n }\n return store\n}\n\n/**\n * Keeps one edit's removed copies restorable. Only as many edits as undo keeps are kept, so\n * copies no undo can bring back are forgotten, oldest first.\n */\nfunction keepCopyRemovals(graph: SceneGraph, removals: CopyRemovals): void {\n if (removals.keys.length === 0) return\n const store = removedCopyStore(graph)\n store.removals.push(removals)\n while (store.removals.length > DEFAULT_HISTORY_LIMIT) {\n const oldest = store.removals.shift()\n for (const [instanceId, layerId] of oldest?.keys ?? []) {\n const copies = store.byInstance.get(instanceId)\n // A later sync may have removed the same layer's copy again; that one stays.\n if (!copies || copies.get(layerId)?.removals !== oldest) continue\n copies.delete(layerId)\n if (copies.size === 0) store.byInstance.delete(instanceId)\n }\n }\n}\n\nconst activeRemovals = new WeakMap<SceneGraph, CopyRemovals>()\n\n/**\n * Runs `fn` with every copy the syncs inside it remove kept as one group: one edit's syncs, however\n * many components they reach, take one place in the history of removals.\n */\nexport function groupCopyRemovals<T>(graph: SceneGraph, fn: (removals: CopyRemovals) => T): T {\n const active = activeRemovals.get(graph)\n if (active) return fn(active)\n const removals: CopyRemovals = { keys: [] }\n activeRemovals.set(graph, removals)\n try {\n return fn(removals)\n } finally {\n activeRemovals.delete(graph)\n keepCopyRemovals(graph, removals)\n }\n}\n\n/**\n * Brings back the copy of `layerId` the sync removed from this instance, with the same layers\n * and overrides, as Figma restores an instance's override when the layer's deletion is undone.\n */\nexport function restoreRemovedCopy(\n graph: SceneGraph,\n context: InstanceSyncContext,\n layerId: string,\n instParentId: string\n): SceneNode | undefined {\n const store = removedCopyStore(graph)\n const removed = store.byInstance.get(context.instanceId)\n const entry = removed?.get(layerId)\n if (!removed || !entry) return undefined\n removed.delete(layerId)\n if (removed.size === 0) store.byInstance.delete(context.instanceId)\n const root = entry.nodes.at(0)\n if (!root || entry.nodes.some((node) => graph.nodes.has(node.id))) return undefined\n for (const node of entry.nodes) {\n const { id, type, parentId, childIds: _childIds, ...props } = structuredClone(node)\n graph.createNodeWithId(id, type, id === root.id ? instParentId : parentId, props)\n }\n for (const [id, fields] of entry.overrides) context.overrides.descendants.set(id, new Map(fields))\n return graph.nodes.get(root.id)\n}\n\n/**\n * Deletes the copies the sync left over: ones whose layer left the component, was deleted, or\n * now has another copy. Copies the instance owns, such as slot content, are never reached.\n */\nexport function removeLeftoverCopies(\n graph: SceneGraph,\n context: InstanceSyncContext,\n removals: CopyRemovals\n): void {\n const store = removedCopyStore(graph)\n for (const id of context.leftovers) {\n const node = graph.nodes.get(id)\n const layerId = node ? copiedLayerId(graph, node, context) : undefined\n if (!node || !layerId || context.matched.has(id)) continue\n const nodes: SceneNode[] = []\n const collect = (current: SceneNode) => {\n nodes.push(structuredClone(current))\n for (const childId of current.childIds) {\n const child = graph.nodes.get(childId)\n if (child) collect(child)\n }\n }\n collect(node)\n const overrides = new Map<string, Map<string, unknown>>()\n for (const removed of nodes) {\n const fields = context.overrides.descendants.get(removed.id)\n if (fields) overrides.set(removed.id, new Map(fields))\n context.overrides.descendants.delete(removed.id)\n }\n let copies = store.byInstance.get(context.instanceId)\n if (!copies) {\n copies = new Map()\n store.byInstance.set(context.instanceId, copies)\n }\n copies.set(layerId, { nodes, overrides, removals })\n removals.keys.push([context.instanceId, layerId])\n graph.deleteNode(id)\n }\n context.leftovers.clear()\n}\n"],"mappings":";;;;;AA2BA,SAAgB,0BACd,YACA,WACqB;CACrB,OAAO;EAAE;EAAY;EAAW,yBAAS,IAAI,IAAI;EAAG,2BAAW,IAAI,IAAI;CAAE;AAC3E;;AAGA,SAAS,cACP,OACA,MACA,SACoB;CACpB,OACE,yBAAyB,OAAO,IAAI,KACpC,uBAAuB,QAAQ,WAAW,QAAQ,YAAY,IAAI;AAEtE;;AAGA,SAAS,YAAY,OAAmB,MAAiB,SAAuC;CAC9F,IAAI,KAAK,SAAS,YAAY,OAAO;CACrC,IAAIA,oBAAwB,QAAQ,WAAW,QAAQ,YAAY,KAAK,IAAI,aAAa,GACvF,OAAO;CAET,MAAM,QAAQ,KAAK,cAAc,MAAM,MAAM,IAAI,KAAK,WAAW,IAAI,KAAA;CACrE,OAAO,CAAC,SAAS,CAAC,gBAAgB,OAAO,MAAM,eAAe,KAAK,CAAC;AACtE;AAEA,SAAS,SAAS,OAAmB,SAAwD;CAC3F,IAAI,QAAQ,QAAQ,OAAO,QAAQ;CACnC,MAAM,yBAAS,IAAI,IAAyB;CAC5C,MAAM,SAAS,WAAsB;EACnC,KAAK,MAAM,MAAM,OAAO,UAAU;GAChC,MAAM,QAAQ,MAAM,MAAM,IAAI,EAAE;GAChC,IAAI,CAAC,OAAO;GACZ,MAAM,UAAU,cAAc,OAAO,OAAO,OAAO;GACnD,IAAI,SAAS,OAAO,IAAI,SAAS,CAAC,GAAI,OAAO,IAAI,OAAO,KAAK,CAAC,GAAI,KA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AC1B"}
|
|
1
|
+
{"version":3,"file":"copies.js","names":["hasNodeInstanceOverride"],"sources":["../../src/instances/copies.ts"],"sourcesContent":["// How an instance's copies follow the component's layers when its structure changes.\nimport type { SceneGraph } from '../graph'\nimport { ownsSlotContent, slotPropertyId } from '../slots/frames'\nimport type { SceneNode } from '../types'\nimport { DEFAULT_HISTORY_LIMIT } from '../undo'\nimport {\n copiedComponentLayerId,\n hasInstanceOverride as hasNodeInstanceOverride,\n type InstanceOverrideState\n} from './overrides'\nimport { replacedComponentLayerId } from './replacements'\n\n/**\n * One instance's sync: the copies it has matched to the component's layers, the parents it\n * synced, and, built on first need, the copies the instance had before, by the layer they copy.\n * Copies follow their layers when the component's structure changes, as Figma moves them: a\n * layer moved inside the component keeps its copy and the copy's overrides, and a copy whose\n * layer left or was deleted goes.\n */\nexport interface InstanceSyncContext {\n instanceId: string\n overrides: InstanceOverrideState\n matched: Set<string>\n leftovers: Set<string>\n copies?: Map<string, SceneNode[]>\n}\n\nexport function createInstanceSyncContext(\n instanceId: string,\n overrides: InstanceOverrideState\n): InstanceSyncContext {\n return { instanceId, overrides, matched: new Set(), leftovers: new Set() }\n}\n\n/** The component layer a copy in the instance stands for, or a replaced layer stands in for. */\nfunction copiedLayerId(\n graph: SceneGraph,\n node: SceneNode,\n context: InstanceSyncContext\n): string | undefined {\n return (\n replacedComponentLayerId(graph, node) ??\n copiedComponentLayerId(context.overrides, context.instanceId, node)\n )\n}\n\n/** Whether sync goes inside a copy: not into slot content, a swapped instance, or an instance. */\nfunction syncsInside(graph: SceneGraph, node: SceneNode, context: InstanceSyncContext): boolean {\n if (node.type === 'INSTANCE') return false\n if (hasNodeInstanceOverride(context.overrides, context.instanceId, node.id, 'componentId')) {\n return false\n }\n const layer = node.componentId ? graph.nodes.get(node.componentId) : undefined\n return !layer || !ownsSlotContent(graph, node, slotPropertyId(layer))\n}\n\nfunction copiesOf(graph: SceneGraph, context: InstanceSyncContext): Map<string, SceneNode[]> {\n if (context.copies) return context.copies\n const copies = new Map<string, SceneNode[]>()\n const visit = (parent: SceneNode) => {\n for (const id of parent.childIds) {\n const child = graph.nodes.get(id)\n if (!child) continue\n const layerId = copiedLayerId(graph, child, context)\n if (layerId) copies.set(layerId, [...(copies.get(layerId) ?? []), child])\n if (syncsInside(graph, child, context)) visit(child)\n }\n }\n const instance = graph.nodes.get(context.instanceId)\n if (instance) visit(instance)\n context.copies = copies\n return copies\n}\n\n/** A copy of `layerId` the sync has not placed yet, which a moved layer takes along. */\nexport function unplacedCopy(\n graph: SceneGraph,\n context: InstanceSyncContext,\n layerId: string,\n instParentId: string\n): SceneNode | undefined {\n return copiesOf(graph, context)\n .get(layerId)\n ?.find(\n (copy) =>\n !context.matched.has(copy.id) &&\n graph.nodes.has(copy.id) &&\n copy.id !== instParentId &&\n !graph.isDescendant(instParentId, copy.id)\n )\n}\n\n/** Whether any layer in the component subtree at `layerId` already has a copy to move. */\nexport function hasUnplacedCopiesBelow(\n graph: SceneGraph,\n context: InstanceSyncContext,\n layerId: string\n): boolean {\n const copies = copiesOf(graph, context)\n if (copies.size === 0) return false\n const layer = graph.nodes.get(layerId)\n return (layer?.childIds ?? []).some(\n (id) =>\n copies.get(id)?.some((copy) => !context.matched.has(copy.id)) ||\n hasUnplacedCopiesBelow(graph, context, id)\n )\n}\n\n/** The copies one sync of a component's instances removed, by instance and layer. */\nexport interface CopyRemovals {\n keys: Array<[instanceId: string, layerId: string]>\n}\n\n/** A copy the sync removed, kept so the layer coming back, as on undo, brings it back as it was. */\ninterface RemovedCopy {\n /** The copy and everything in it, parents first. */\n nodes: SceneNode[]\n overrides: Map<string, Map<string, unknown>>\n removals: CopyRemovals\n}\n\ninterface RemovedCopyStore {\n /** Removed copies by instance, then by the layer they copied. */\n byInstance: Map<string, Map<string, RemovedCopy>>\n /** Syncs that removed copies, oldest first. */\n removals: CopyRemovals[]\n}\n\nconst removedCopies = new WeakMap<SceneGraph, RemovedCopyStore>()\n\nfunction removedCopyStore(graph: SceneGraph): RemovedCopyStore {\n let store = removedCopies.get(graph)\n if (!store) {\n store = { byInstance: new Map(), removals: [] }\n removedCopies.set(graph, store)\n }\n return store\n}\n\n/**\n * Keeps one edit's removed copies restorable. Only as many edits as undo keeps are kept, so\n * copies no undo can bring back are forgotten, oldest first.\n */\nfunction keepCopyRemovals(graph: SceneGraph, removals: CopyRemovals): void {\n if (removals.keys.length === 0) return\n const store = removedCopyStore(graph)\n store.removals.push(removals)\n while (store.removals.length > DEFAULT_HISTORY_LIMIT) {\n const oldest = store.removals.shift()\n for (const [instanceId, layerId] of oldest?.keys ?? []) {\n const copies = store.byInstance.get(instanceId)\n // A later sync may have removed the same layer's copy again; that one stays.\n if (!copies || copies.get(layerId)?.removals !== oldest) continue\n copies.delete(layerId)\n if (copies.size === 0) store.byInstance.delete(instanceId)\n }\n }\n}\n\nconst activeRemovals = new WeakMap<SceneGraph, CopyRemovals>()\n\n/**\n * Runs `fn` with every copy the syncs inside it remove kept as one group: one edit's syncs, however\n * many components they reach, take one place in the history of removals.\n */\nexport function groupCopyRemovals<T>(graph: SceneGraph, fn: (removals: CopyRemovals) => T): T {\n const active = activeRemovals.get(graph)\n if (active) return fn(active)\n const removals: CopyRemovals = { keys: [] }\n activeRemovals.set(graph, removals)\n try {\n return fn(removals)\n } finally {\n activeRemovals.delete(graph)\n keepCopyRemovals(graph, removals)\n }\n}\n\n/**\n * Brings back the copy of `layerId` the sync removed from this instance, with the same layers\n * and overrides, as Figma restores an instance's override when the layer's deletion is undone.\n */\nexport function restoreRemovedCopy(\n graph: SceneGraph,\n context: InstanceSyncContext,\n layerId: string,\n instParentId: string\n): SceneNode | undefined {\n const store = removedCopyStore(graph)\n const removed = store.byInstance.get(context.instanceId)\n const entry = removed?.get(layerId)\n if (!removed || !entry) return undefined\n removed.delete(layerId)\n if (removed.size === 0) store.byInstance.delete(context.instanceId)\n const root = entry.nodes.at(0)\n if (!root || entry.nodes.some((node) => graph.nodes.has(node.id))) return undefined\n for (const node of entry.nodes) {\n const { id, type, parentId, childIds: _childIds, ...props } = structuredClone(node)\n graph.createNodeWithId(id, type, id === root.id ? instParentId : parentId, props)\n }\n for (const [id, fields] of entry.overrides) context.overrides.descendants.set(id, new Map(fields))\n return graph.nodes.get(root.id)\n}\n\n/**\n * Deletes the copies the sync left over: ones whose layer left the component, was deleted, or\n * now has another copy. Copies the instance owns, such as slot content, are never reached.\n */\nexport function removeLeftoverCopies(\n graph: SceneGraph,\n context: InstanceSyncContext,\n removals: CopyRemovals\n): void {\n const store = removedCopyStore(graph)\n for (const id of context.leftovers) {\n const node = graph.nodes.get(id)\n const layerId = node ? copiedLayerId(graph, node, context) : undefined\n if (!node || !layerId || context.matched.has(id)) continue\n const nodes: SceneNode[] = []\n const collect = (current: SceneNode) => {\n nodes.push(structuredClone(current))\n for (const childId of current.childIds) {\n const child = graph.nodes.get(childId)\n if (child) collect(child)\n }\n }\n collect(node)\n const overrides = new Map<string, Map<string, unknown>>()\n for (const removed of nodes) {\n const fields = context.overrides.descendants.get(removed.id)\n if (!fields) continue\n overrides.set(removed.id, new Map(fields))\n context.overrides.descendants.delete(removed.id)\n }\n let copies = store.byInstance.get(context.instanceId)\n if (!copies) {\n copies = new Map()\n store.byInstance.set(context.instanceId, copies)\n }\n copies.set(layerId, { nodes, overrides, removals })\n removals.keys.push([context.instanceId, layerId])\n graph.deleteNode(id)\n }\n context.leftovers.clear()\n}\n"],"mappings":";;;;;AA2BA,SAAgB,0BACd,YACA,WACqB;CACrB,OAAO;EAAE;EAAY;EAAW,yBAAS,IAAI,IAAI;EAAG,2BAAW,IAAI,IAAI;CAAE;AAC3E;;AAGA,SAAS,cACP,OACA,MACA,SACoB;CACpB,OACE,yBAAyB,OAAO,IAAI,KACpC,uBAAuB,QAAQ,WAAW,QAAQ,YAAY,IAAI;AAEtE;;AAGA,SAAS,YAAY,OAAmB,MAAiB,SAAuC;CAC9F,IAAI,KAAK,SAAS,YAAY,OAAO;CACrC,IAAIA,oBAAwB,QAAQ,WAAW,QA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;EACZ,MAAM,4BAAY,IAAI,IAAkC;EACxD,KAAK,MAAM,WAAW,OAAO;GAC3B,MAAM,SAAS,QAAQ,UAAU,YAAY,IAAI,QAAQ,EAAE;GAC3D,IAAI,CAAC,QAAQ;GACb,UAAU,IAAI,QAAQ,IAAI,IAAI,IAAI,MAAM,CAAC;GACzC,QAAQ,UAAU,YAAY,OAAO,QAAQ,EAAE;EACjD;EACA,IAAI,SAAS,MAAM,WAAW,IAAI,QAAQ,UAAU;EACpD,IAAI,CAAC,QAAQ;GACX,yBAAS,IAAI,IAAI;GACjB,MAAM,WAAW,IAAI,QAAQ,YAAY,MAAM;EACjD;EACA,OAAO,IAAI,SAAS;GAAE;GAAO;GAAW;EAAS,CAAC;EAClD,SAAS,KAAK,KAAK,CAAC,QAAQ,YAAY,OAAO,CAAC;EAChD,MAAM,WAAW,EAAE;CACrB;CACA,QAAQ,UAAU,MAAM;AAC1B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/instances/index.ts"],"mappings":";;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/instances/index.ts"],"mappings":";;;;;;;;;;iBAkEgB,2BAA2B,WAAW,YAAY,QAAQ;iBAiB1D,eACd,OAAO,YACP,qBACA,kBACA,YAAW,QAAQ,aAClB;iBAoBa,yBACd,OAAO,YACP,oBACA,qBACA,OAAM;UAyCS;;;;;;EAMf;;;;;;;EAOA;;iBAGc,sBACd,OAAO,YACP,oBACA,uBACE,UAAkB,qBAA2B;iBA+DjC,cAAc,OAAO,YAAY;;;;;iBAQjC,sBAAsB,OAAO,YAAY,cAAc;;iBAOvD,aAAa,OAAO,YAAY;;;;;;iBAyEhC,wBACd,OAAO,YACP,QAAQ;iBAeM,eAAe,OAAO,YAAY;iBAmElC,iBAAiB,OAAO,YAAY,qBAAqB;iBAMzD,aAAa,OAAO,YAAY,sBAAsB;;iBAYtD,qBAAqB,OAAO,YAAY,iBAAiB;;;;;iBAazD,aAAa,OAAO,YAAY,MAAM;;;;iBAOtC,oBAAoB,OAAO,YAAY,gBAAgB;;;;;iBA2CvD,wBACd,OAAO,YACP,qBACC;;UAMc;EACf;EACA,WAAW;;iBAGG,4BACd,OAAO,YACP,qBACC;iBAOa,+BACd,OAAO,YACP,OAAO;;;;;;iBAYO,yBACd,OAAO,YACP,oBACA,oBACA;;;;;iBAkBc,uBAAuB,MAAM,WAAW,SAAS,QAAQ;iBAMzD,uBACd,OAAO,YACP,gBACA,QAAQ;;iBAsDM,wBAAwB,OAAO,YAAY;;;;;;;;;iBAqB3C,qBACd,OAAO,YACP,kBACA;;;;;iBAmDc,qBAAqB,OAAO,YAAY"}
|
package/dist/instances/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { REPLACED_LAYER_OVERRIDE, assignmentOverrideField, cloneInstanceOverrideState, copiedComponentLayerId, createInstanceOverrideState, getInstanceOverride, hasInstanceOverride as hasInstanceOverride$1, overriddenAssignmentId, setInstanceOverride, variableModeOverrideField } from "./overrides.js";
|
|
1
|
+
import { REPLACED_LAYER_OVERRIDE, assignmentOverrideField, cloneInstanceOverrideState, copiedComponentLayerId, createInstanceOverrideState, getInstanceOverride, hasInstanceOverride as hasInstanceOverride$1, overriddenAssignmentId, ownInstanceOverrides, setInstanceOverride, variableModeOverrideField } from "./overrides.js";
|
|
2
2
|
import { shapeGeometryChanges } from "../resize.js";
|
|
3
3
|
import { instanceMainComponent } from "./main-component.js";
|
|
4
4
|
import { detachOwnedSlotContent, restoreOwnedSlotContent } from "../slots/frames.js";
|
|
@@ -59,9 +59,9 @@ function populateInstanceChildren(graph, instanceId, componentId, mode = "deep")
|
|
|
59
59
|
function recordNestedSwap(graph, instance, componentId) {
|
|
60
60
|
const owner = instance.parentId ? findInstanceAncestor(graph, instance.parentId) : void 0;
|
|
61
61
|
if (!owner) return;
|
|
62
|
-
if (typeof getInstanceOverride(owner.instanceOverrides, owner.id, instance.id, "sourceComponentId") !== "string" && instance.componentId) setInstanceOverride(owner
|
|
63
|
-
setInstanceOverride(owner
|
|
64
|
-
graph.updateNode(owner.id, { instanceOverrides: owner
|
|
62
|
+
if (typeof getInstanceOverride(owner.instanceOverrides, owner.id, instance.id, "sourceComponentId") !== "string" && instance.componentId) setInstanceOverride(ownInstanceOverrides(owner), owner.id, instance.id, "sourceComponentId", instance.componentId);
|
|
63
|
+
setInstanceOverride(ownInstanceOverrides(owner), owner.id, instance.id, "componentId", componentId);
|
|
64
|
+
graph.updateNode(owner.id, { instanceOverrides: ownInstanceOverrides(owner) });
|
|
65
65
|
}
|
|
66
66
|
function swapInstanceComponent(graph, instanceId, componentId, { keepName = false, restoreOverrides = true } = {}) {
|
|
67
67
|
const instance = graph.nodes.get(instanceId);
|
|
@@ -150,8 +150,9 @@ function syncInstancesOf(graph, componentId, instances) {
|
|
|
150
150
|
keepOwnContentSize(graph, updates, instance, source);
|
|
151
151
|
if (updates.width !== void 0 || updates.height !== void 0) Object.assign(updates, shapeGeometryChanges(instance, updates.width ?? instance.width, updates.height ?? instance.height));
|
|
152
152
|
updateSyncedProps(graph, instance, updates, (key) => isProtectedSyncField(instance, key, protectedField));
|
|
153
|
-
const
|
|
154
|
-
|
|
153
|
+
const owned = ownInstanceOverrides(instance);
|
|
154
|
+
const context = createInstanceSyncContext(instance.id, owned);
|
|
155
|
+
syncChildren(graph, component.id, instance.id, owned, context);
|
|
155
156
|
removeLeftoverCopies(graph, context, removals);
|
|
156
157
|
}
|
|
157
158
|
});
|
|
@@ -311,7 +312,7 @@ function restoreAssignmentOverrideState(graph, state) {
|
|
|
311
312
|
function recordAssignmentOverride(graph, instanceId, propertyId, value) {
|
|
312
313
|
const outer = assignmentOverrideOwner(graph, instanceId);
|
|
313
314
|
if (!outer) return;
|
|
314
|
-
setInstanceOverride(outer
|
|
315
|
+
setInstanceOverride(ownInstanceOverrides(outer), outer.id, instanceId, assignmentOverrideField(propertyId), value);
|
|
315
316
|
graph.updateNode(outer.id, { instanceOverrides: outer.instanceOverrides });
|
|
316
317
|
}
|
|
317
318
|
/**
|
|
@@ -349,8 +350,8 @@ function forgetOverridesOf(graph, nodeId) {
|
|
|
349
350
|
if (!parentId) return;
|
|
350
351
|
graph.closest(parentId, (ancestor) => {
|
|
351
352
|
if (ancestor.type !== "INSTANCE") return false;
|
|
352
|
-
const
|
|
353
|
-
if (ids.some((id) => descendants.delete(id))) graph.updateNode(ancestor.id, { instanceOverrides:
|
|
353
|
+
const owned = ownInstanceOverrides(ancestor);
|
|
354
|
+
if (ids.some((id) => owned.descendants.delete(id))) graph.updateNode(ancestor.id, { instanceOverrides: owned });
|
|
354
355
|
return false;
|
|
355
356
|
});
|
|
356
357
|
}
|
|
@@ -400,8 +401,8 @@ function replaceInstanceLayer(graph, targetId, replacementId) {
|
|
|
400
401
|
verticalConstraint: target.verticalConstraint
|
|
401
402
|
});
|
|
402
403
|
graph.deleteNode(target.id);
|
|
403
|
-
setInstanceOverride(owner
|
|
404
|
-
graph.updateNode(owner.id, { instanceOverrides: owner
|
|
404
|
+
setInstanceOverride(ownInstanceOverrides(owner), owner.id, replacementId, REPLACED_LAYER_OVERRIDE, layerId);
|
|
405
|
+
graph.updateNode(owner.id, { instanceOverrides: ownInstanceOverrides(owner) });
|
|
405
406
|
return true;
|
|
406
407
|
}
|
|
407
408
|
/**
|